@openchamber/web 1.5.9 → 1.6.0

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.
@@ -0,0 +1,265 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-Bui932eM.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-BSKxzwkK.js","assets/index-D8WE2_bP.js","assets/index-BlYLID2P.css"])))=>i.map(i=>d[i]);
2
+ import{t as Eh,c as Ih,F as Ph,j as e,R as Th,T as Fh,P as Rh,C as Lh,A as Oh,a as _h,b as $h,d as Bh,e as zh,f as Hh,L as Wh,g as Uh,i as Vh,I as Gh,s as Tt,S as qh,k as Kh,l as ns,m as fs,p as qs,n as Ks,o as Gl,_ as vs,q as i,r as Lm,u as es,v as Jh,w as Om,x as Qh,y as Yh,z as Xh,B as Zh,D as eg,E as tg,G as Ae,H as ql,J as sg,K as rg,M as Ys,N as kc,O as Kl,Q as Vo,U as Wt,V as tr,W as Mt,X as ol,Y as Cc,Z as _m,$ as ng,a0 as en,a1 as og,a2 as Zn,a3 as sr,a4 as lr,a5 as rn,a6 as Ut,a7 as al,a8 as ag,a9 as vn,aa as il,ab as En,ac as jn,ad as Qr,ae as Mc,af as Ls,ag as $m,ah as ig,ai as cg,aj as lg,ak as dg,al as ug,am as mg,an as fg,ao as ka,ap as pg,aq as Wa,ar as Zs,as as tn,at as ks,au as In,av as Vs,aw as eo,ax as ls,ay as Cr,az as hg,aA as gg,aB as Bm,aC as cl,aD as Sn,aE as ll,aF as Mr,aG as zm,aH as to,aI as xg,aJ as mi,aK as Hm,aL as zs,aM as Wm,aN as Nn,aO as kn,aP as Ua,aQ as Ri,aR as yg,aS as nn,aT as Fr,aU as nr,aV as bg,aW as wg,aX as Jl,aY as Dc,aZ as vg,a_ as jg,a$ as Sg,b0 as Ng,b1 as kg,b2 as Cg,b3 as Mg,b4 as Dg,b5 as Ag,b6 as Um,b7 as Li,b8 as Eg,b9 as Dr,ba as Ig,bb as Pg,bc as Tg,bd as Fg,be as Rg,bf as Lg,bg as Og,bh as _g,bi as $g,bj as Bg,bk as zg,bl as Hg,bm as Wg,bn as Ug,bo as Vg,bp as Gg,bq as Rr,br as Va,bs as Ar,bt as jr,bu as qg,bv as fi,bw as Kg,bx as Un,by as Jg,bz as Qg,bA as Yg,bB as so,bC as Xg,bD as Zg,bE as ex,bF as tx,bG as sx,bH as Ca,bI as pi,bJ as rx,bK as nx,bL as Jn,bM as Hn,bN as Vm,bO as ox,bP as ax,bQ as rr,bR as ix,bS as _r,bT as Gm,bU as cx,bV as lx,bW as Ac,bX as qm,bY as Km,bZ as dx,b_ as ux,b$ as mx,c0 as ro,c1 as fx,c2 as Ql,c3 as px,c4 as Ec,c5 as fo,c6 as po,c7 as hx,c8 as gx,c9 as xx,ca as hi,cb as yx,cc as bx,cd as wx,ce as pn,cf as Yl,cg as vx,ch as jx,ci as Sx,cj as Nx,ck as kx,cl as Cx,cm as Mx,cn as Dx,co as Jm,cp as Ge,cq as Qm,cr as ho,cs as Ax,ct as Ex,cu as Ix,cv as Px,cw as Tx,cx as Fx,cy as Ym,cz as Xm,cA as Zm,cB as ef,cC as tf,cD as Rx,cE as sf,cF as rf,cG as nf,cH as Vn,cI as Lx,cJ as Ox,cK as Ic,cL as _x,cM as of,cN as dl,cO as ul,cP as ml,cQ as $x,cR as Bx,cS as zx,cT as Hx,cU as Xl,cV as af,cW as Wx,cX as Ux,cY as Vx,cZ as Gx,c_ as Zl,c$ as ed,d0 as td,d1 as qx,d2 as Fo,d3 as cf,d4 as lf,d5 as yo,d6 as gi,d7 as df,d8 as Kx,d9 as Jx,da as uf,db as Pc,dc as Qx,dd as Yx,de as Xx,df as Zx,dg as ey,dh as ty}from"./vendor-.bun-Bui932eM.js";import{c as sy,g as ry,d as ny,a as oy,r as ay,l as iy,b as cy,u as ly,e as dy,f as uy,h as my,i as fy,j as py,k as hy,m as gy,n as xy}from"./index-D8WE2_bP.js";const ds=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",zt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,mr=()=>typeof window>"u"?!1:!ds()&&!zt(),on=()=>ds()?window.opencodeDesktop??null:null,mf=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const t=window.opencodeDesktop;return t?.getSettings&&t?.updateSettings?{getSettings:t.getSettings.bind(t),updateSettings:t.updateSettings.bind(t)}:null},fl=async()=>{const t=on();if(typeof window<"u"){const r=window.__OPENCHAMBER_HOME__;if(r&&r.length>0)return r}if(!t)return null;if(typeof t.homeDirectory=="string"&&t.homeDirectory.length>0)return t.homeDirectory;try{if(!t.getHomeDirectory)return null;const r=await t.getHomeDirectory();if(r?.success&&typeof r.path=="string"&&r.path.length>0)return r.path}catch(r){console.warn("Failed to obtain desktop home directory:",r)}return null},yy=async()=>{const t=on();if(!t)return null;try{return await t.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},by=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,zr=async()=>{const t=mf();if(!t)return null;try{return await t.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},wy=async t=>{const r=mf();if(!r)return null;try{return await r.updateSettings(t)}catch(s){return console.warn("[desktop] Failed to update desktop settings",s),null}},vy=async t=>{const r=on();if(!r||!r.requestDirectoryAccess)return{success:!0,path:t};try{return await r.requestDirectoryAccess(t)}catch(s){return console.warn("Failed to request directory access",s),{success:!1,error:s instanceof Error?s.message:String(s)}}},jy=async t=>{const r=on();if(!r||!r.startAccessingDirectory)return{success:!0};try{return await r.startAccessingDirectory(t)}catch(s){return console.warn("Failed to start accessing directory",s),{success:!1,error:s instanceof Error?s.message:String(s)}}},Sy=async t=>{const r=on();if(!r||!r.stopAccessingDirectory)return{success:!0};try{return await r.stopAccessingDirectory(t)}catch(s){return console.warn("Failed to stop accessing directory",s),{success:!1,error:s instanceof Error?s.message:String(s)}}},Ny=async()=>{const t=on();if(!t||!t.checkForUpdates)return null;try{return await t.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},ky=async t=>{const r=on();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(t),!0}catch(s){return console.warn("Failed to download update",s),!1}},Cy=async()=>{const t=on();if(!t||!t.restartToUpdate)return!1;try{return await t.restartToUpdate(),!0}catch(r){return console.warn("Failed to restart for update",r),!1}};function R(...t){return Eh(Ih(t))}const ff=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),$s=t=>ff()&&ds()?t.metaKey:t.ctrlKey,Yt=()=>ff()&&ds()?"⌘":"Ctrl",pf=(t,r)=>{const s=t??"",n=Math.max(16,r?.maxLength??45);if(s.length<=n)return s;const o=s.split("/");if(o.length<=1)return s;const a=o.pop()??"";if(!a)return s;const c=Math.max(0,n-(a.length+2));if(c<=0)return`…/${a}`;let l="";for(const d of o){if(!d)continue;const u=l?`${l}/${d}`:d;if(u.length>c)break;l=u}if(!l){const d=o[0]??"";l=d?d.slice(0,c):""}return l?`${l}…/${a}`:`…/${a}`},Ga=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function Yr(t,r){if(!t)return"";const s=Ga(t);if(s==="/")return"/";const n=r?Ga(r):void 0;if(n&&n!=="/"){if(s===n)return"~";if(s.startsWith(`${n}/`)){const o=s.slice(n.length+1);return o?`~/${o}`:"~"}}return s}function sd(t,r){if(!t)return"/";const s=Ga(t);if(!s||s==="/")return"/";const n=r?Ga(r):void 0;return n&&n!=="/"&&s===n?"~":s.split("/").pop()||s||"/"}function Xs(t,r){return r?t?t.toLowerCase().includes(r.toLowerCase())?!0:new Ph([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function My({delayDuration:t=0,...r}){return e.jsx(_h,{"data-slot":"tooltip-provider",delayDuration:t,...r})}function dt({delayDuration:t=0,...r}){return e.jsx(My,{delayDuration:t,children:e.jsx(Th,{"data-slot":"tooltip",...r})})}function ut({...t}){return e.jsx(Fh,{"data-slot":"tooltip-trigger",...t})}function lt({className:t,sideOffset:r=0,children:s,...n}){return e.jsx(Rh,{children:e.jsxs(Lh,{"data-slot":"tooltip-content",sideOffset:r,className:R("bg-muted text-muted-foreground 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 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",t),...n,children:[s,e.jsx(Oh,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}function ts({...t}){return e.jsx($h,{"data-slot":"dropdown-menu",...t})}function ss({...t}){return e.jsx(Bh,{"data-slot":"dropdown-menu-trigger",...t})}function rs({className:t,sideOffset:r=4,...s}){return e.jsx(zh,{children:e.jsx(Hh,{"data-slot":"dropdown-menu-content",sideOffset:r,className:R("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",t),...s})})}function kt({className:t,inset:r,variant:s="default",...n}){return e.jsx(Kh,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":s,className:R("hover:bg-muted data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",t),...n})}function qa({...t}){return e.jsx(Uh,{"data-slot":"dropdown-menu-radio-group",...t})}function Ka({className:t,children:r,...s}){return e.jsxs(Vh,{"data-slot":"dropdown-menu-radio-item",className:R("relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-muted [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",t),...s,children:[e.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:e.jsx(Gh,{children:e.jsx(Tt,{className:"size-3"})})}),r]})}function Lr({className:t,inset:r,...s}){return e.jsx(Wh,{"data-slot":"dropdown-menu-label","data-inset":r,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",t),...s})}function Ds({className:t,...r}){return e.jsx(qh,{"data-slot":"dropdown-menu-separator",className:R("bg-border -mx-1 my-0.5 h-px",t),...r})}let Oi=null;const rd=()=>{const t=new Map;return{getItem:r=>t.get(r)??null,setItem:(r,s)=>{t.set(r,s)},removeItem:r=>{t.delete(r)},clear:()=>{t.clear()},key:r=>Array.from(t.keys())[r]??null,get length(){return t.size}}},Dy=()=>{if(typeof window>"u"||!window.localStorage)return rd();const t=window.localStorage,r=rd();let s=!0;const n=()=>{s=!1};return{getItem:u=>{if(s)try{const m=t.getItem(u);if(m!==null)return m}catch{n()}return r.getItem(u)},setItem:(u,m)=>{if(s)try{t.setItem(u,m),r.removeItem(u);return}catch{n()}r.setItem(u,m)},removeItem:u=>{if(s)try{t.removeItem(u)}catch{n()}r.removeItem(u)},clear:()=>{if(s)try{t.clear()}catch{n()}r.clear()},key:u=>{if(s)try{return t.key(u)}catch{n()}return r.key(u)},get length(){if(s)try{return t.length+r.length}catch{n()}return r.length}}},js=()=>(Oi||(Oi=Dy()),Oi),pl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Ay={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function nd(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Or={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},Ma={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Or.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ma.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Or.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ma.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Or.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ma.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Or.tool.inline})},Me=ns()(fs(qs((t,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",mainTabGuard:null,pendingDiffFile:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,showTextJustificationActivity:!1,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,memoryLimitHistorical:90,memoryLimitViewport:120,memoryLimitActiveSession:180,toolCallExpansion:"collapsed",fontSize:100,padding:100,cornerRadius:12,inputBarOffset:0,favoriteModels:[],recentModels:[],diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"stacked",isTimelineDialogOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",setTheme:s=>{t({theme:s}),r().applyTheme()},toggleSidebar:()=>{t(s=>{const n=!s.isSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:n,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:n}})},setSidebarOpen:s=>{t(()=>{if(s&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:s,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:s}})},setSidebarWidth:s=>{t({sidebarWidth:s,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:s=>{t({isSessionSwitcherOpen:s})},setMainTabGuard:s=>{t({mainTabGuard:s})},setActiveMainTab:s=>{const n=r().mainTabGuard;n&&!n(s)||t({activeMainTab:s})},setPendingDiffFile:s=>{t({pendingDiffFile:s})},navigateToDiff:s=>{const n=r().mainTabGuard;n&&!n("diff")||t({pendingDiffFile:s,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:s}=r();return s&&t({pendingDiffFile:null}),s},setIsMobile:s=>{t({isMobile:s})},toggleCommandPalette:()=>{t(s=>({isCommandPaletteOpen:!s.isCommandPaletteOpen}))},setCommandPaletteOpen:s=>{t({isCommandPaletteOpen:s})},toggleHelpDialog:()=>{t(s=>({isHelpDialogOpen:!s.isHelpDialogOpen}))},setHelpDialogOpen:s=>{t({isHelpDialogOpen:s})},setAboutDialogOpen:s=>{t({isAboutDialogOpen:s})},setSessionCreateDialogOpen:s=>{t({isSessionCreateDialogOpen:s})},setSettingsDialogOpen:s=>{t({isSettingsDialogOpen:s})},setModelSelectorOpen:s=>{t({isModelSelectorOpen:s})},setSidebarSection:s=>{t({sidebarSection:s})},setEventStreamStatus:(s,n)=>{t({eventStreamStatus:s,eventStreamHint:n??null})},setShowReasoningTraces:s=>{t({showReasoningTraces:s})},setShowTextJustificationActivity:s=>{t({showTextJustificationActivity:s})},setAutoDeleteEnabled:s=>{t({autoDeleteEnabled:s})},setAutoDeleteAfterDays:s=>{const n=Math.max(1,Math.min(365,s));t({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:s=>{t({autoDeleteLastRunAt:s})},setMemoryLimitHistorical:s=>{const n=Math.max(10,Math.min(500,Math.round(s)));t({memoryLimitHistorical:n})},setMemoryLimitViewport:s=>{const n=Math.max(20,Math.min(500,Math.round(s)));t({memoryLimitViewport:n})},setMemoryLimitActiveSession:s=>{const n=Math.max(30,Math.min(1e3,Math.round(s)));t({memoryLimitActiveSession:n})},setToolCallExpansion:s=>{t({toolCallExpansion:s})},setFontSize:s=>{const n=Math.max(50,Math.min(200,s));t({fontSize:n}),r().applyTypography()},setPadding:s=>{const n=Math.max(50,Math.min(200,s));t({padding:n}),r().applyPadding()},setCornerRadius:s=>{t({cornerRadius:s})},applyTypography:()=>{const{fontSize:s}=r(),n=document.documentElement,o=s/100,a=Object.entries(pl);if(o===1){for(const[c]of a)n.style.removeProperty(nd(c));return}for(const[c,l]of a){const d=parseFloat(l);Number.isFinite(d)&&n.style.setProperty(nd(c),`${d*o}rem`)}},applyPadding:()=>{const{padding:s}=r(),n=document.documentElement,o=s/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);n.style.setProperty("--padding-scale",a.toString());const c=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*c).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*c).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*c).toFixed(3)),n.style.setProperty("--line-height-loose",(2*c).toFixed(3))},setDiffLayoutPreference:s=>{t({diffLayoutPreference:s})},setDiffFileLayout:(s,n)=>{t(o=>({diffFileLayout:{...o.diffFileLayout,[s]:n}}))},setDiffWrapLines:s=>{t({diffWrapLines:s})},setDiffViewMode:s=>{t({diffViewMode:s})},setInputBarOffset:s=>{t({inputBarOffset:s})},setKeyboardOpen:s=>{t({isKeyboardOpen:s})},toggleFavoriteModel:(s,n)=>{t(o=>o.favoriteModels.some(c=>c.providerID===s&&c.modelID===n)?{favoriteModels:o.favoriteModels.filter(c=>!(c.providerID===s&&c.modelID===n))}:{favoriteModels:[{providerID:s,modelID:n},...o.favoriteModels]})},isFavoriteModel:(s,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===s&&a.modelID===n)},addRecentModel:(s,n)=>{t(o=>{const a=o.recentModels.filter(c=>!(c.providerID===s&&c.modelID===n));return{recentModels:[{providerID:s,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||t(s=>{const n={};return s.isSidebarOpen&&!s.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:s}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),s==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(s)},setMultiRunLauncherOpen:s=>{t(n=>({isMultiRunLauncherOpen:s,multiRunLauncherPrefillPrompt:s?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:s=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:s,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:s=>{t({isTimelineDialogOpen:s})},setNativeNotificationsEnabled:s=>{t({nativeNotificationsEnabled:s})},setNotificationMode:s=>{t({notificationMode:s})}}),{name:"ui-store",storage:Ks(()=>js()),partialize:t=>({theme:t.theme,isSidebarOpen:t.isSidebarOpen,sidebarWidth:t.sidebarWidth,isSessionSwitcherOpen:t.isSessionSwitcherOpen,activeMainTab:t.activeMainTab,sidebarSection:t.sidebarSection,isSessionCreateDialogOpen:t.isSessionCreateDialogOpen,isSettingsDialogOpen:t.isSettingsDialogOpen,showReasoningTraces:t.showReasoningTraces,showTextJustificationActivity:t.showTextJustificationActivity,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,autoDeleteLastRunAt:t.autoDeleteLastRunAt,memoryLimitHistorical:t.memoryLimitHistorical,memoryLimitViewport:t.memoryLimitViewport,memoryLimitActiveSession:t.memoryLimitActiveSession,toolCallExpansion:t.toolCallExpansion,fontSize:t.fontSize,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,recentModels:t.recentModels,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,diffViewMode:t.diffViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode})}),{name:"ui-store"}));async function Ey(){try{const t=await fetch("/api/openchamber/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Server responded with ${t.status}`);const r=await t.json();return{available:r.available??!1,version:r.version,currentVersion:r.currentVersion??"unknown",body:r.body,packageManager:r.packageManager,updateCommand:r.updateCommand}}catch(t){return console.warn("Failed to check for web updates:",t),null}}function Iy(){return ds()?"desktop":mr()?"web":null}const od={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},xi=ns()((t,r)=>({...od,checkForUpdates:async()=>{const s=Iy();if(s){t({checking:!0,error:null,runtimeType:s});try{let n=null;s==="desktop"?n=await Ny():s==="web"&&(n=await Ey()),t({checking:!1,available:n?.available??!1,info:n,lastChecked:Date.now()})}catch(n){t({checking:!1,error:n instanceof Error?n.message:"Failed to check for updates"})}}},downloadUpdate:async()=>{const{available:s,runtimeType:n}=r();if(!(n!=="desktop"||!s)){t({downloading:!0,error:null,progress:null});try{await ky(o=>{t({progress:o})}),t({downloading:!1,downloaded:!0})}catch(o){t({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:s,runtimeType:n}=r();if(!(n!=="desktop"||!s))try{await Cy()}catch(o){t({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{t({available:!1,downloaded:!1,info:null})},reset:()=>{t(od)}})),Py="/api",Ty=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Fy=t=>{const r=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(Ty.test(r)||typeof window>"u")return r;const s=window.location?.href||window.location?.origin;if(!s)return r;try{return new URL(r,s).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),r}},Ry=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_DESKTOP_SERVER__,r=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!t||!r)return null;const s=typeof t.origin=="string"&&t.origin.length>0?t.origin:null;return s?`${s}/api`:null},ea=t=>t.replace(/\\/g,"/"),_i=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class Ly{client;baseUrl;scopedClients=new Map;sseAbortControllers=new Map;currentDirectory=void 0;globalSseAbortController=null;globalSseTask=null;globalSseLastEventId;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;constructor(r=Py){const n=Ry()||r;this.baseUrl=Fy(n),this.client=Gl({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}getScopedApiClient(r){const s=this.normalizeCandidatePath(r)??r,n=s||"",o=this.scopedClients.get(n);if(o)return o;const a=Gl({baseUrl:this.baseUrl,directory:s});return this.scopedClients.set(n,a),a}normalizeCandidatePath(r){if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const n=s.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const s=r.match(/^([A-Za-z]:)(?:\/|$)/);if(s){const a=s[1],l=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return l.length>=2?{homeDirectory:`${a}/${l[0]}/${l[1]}`,username:l[1]}:l.length===1?{homeDirectory:`${a}/${l[0]}`,username:l[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,s){if(r==null)return s();const n=this.currentDirectory;this.currentDirectory=r;try{return await s()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,s=o=>{const a=this.normalizeCandidatePath(o);a&&r.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(s(a.directory),s(a.worktree),s(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!r.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);s(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>s(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(s(this.currentDirectory),typeof window<"u")try{s(window.localStorage.getItem("lastDirectory")),s(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&s(process.cwd()),!r.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(r);return this.deriveHomeDirectory(n)}async probeDirectory(r){const s=this.normalizeCandidatePath(r);if(!s)return!1;try{const o=(await this.client.path.get({directory:s})).data,a=typeof o?.directory=="string"?o.directory:null;return!!(a&&a.trim().length>0)}catch{return!1}}async listSessions(){const r=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(r.data)?r.data:[]}async createSession(r){const s=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!s.data)throw new Error("Failed to create session");return s.data}async getSession(r){const s=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!s.data)throw new Error("Session not found");return s.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,s){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:s});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r,s){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof s=="number"?{limit:s}:{}})).data||[]}async getSessionTodos(r){try{const s=this.baseUrl.replace(/\/$/,""),n=new URL(`${s}/session/${encodeURIComponent(r)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(r){if(!r)return!1;const s=r.toLowerCase();return s.startsWith("text/")&&s!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript"].includes(s)}isHeicMime(r){if(!r)return!1;const s=r.toLowerCase();return s==="image/heic"||s==="image/heif"}async compressImage(r,s,n=.8,o=2048){return typeof document>"u"?r:new Promise(a=>{const c=new Image;c.onload=()=>{let l=c.width,d=c.height;(l>o||d>o)&&(l>d?(d=Math.round(d*(o/l)),l=o):(l=Math.round(l*(o/d)),d=o));const u=document.createElement("canvas");u.width=l,u.height=d;const m=u.getContext("2d");if(!m){a(r);return}m.drawImage(c,0,0,l,d);let f=s;s==="image/png"&&r.length>2.5*1024*1024&&(f="image/jpeg");try{a(u.toDataURL(f,n))}catch{a(r)}},c.onerror=()=>a(r),c.src=r})}async convertHeicToJpeg(r){try{const s=(await vs(async()=>{const{default:f}=await import("./vendor-.bun-Bui932eM.js").then(p=>p.h);return{default:f}},__vite__mapDeps([0,1]))).default,n=r.url.indexOf(",");if(n===-1)return r;const o=r.url.substring(n+1),a=atob(o),c=new Uint8Array(a.length);for(let f=0;f<a.length;f++)c[f]=a.charCodeAt(f);const l=new Blob([c],{type:r.mime}),d=await s({blob:l,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const h=new FileReader;h.onload=()=>f(h.result),h.onerror=p,h.readAsDataURL(d)});let m=r.filename;return m&&(m=m.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:m,url:u}}catch(s){return console.warn("Failed to convert HEIC to JPEG:",s),r}}async normalizeFilePart(r){if(this.isHeicMime(r.mime))return this.convertHeicToJpeg(r);if(r.mime.startsWith("image/")&&(r.mime==="image/jpeg"||r.mime==="image/png"||r.mime==="image/webp")&&r.url.length>1.33*1024*1024){const n=await this.compressImage(r.url,r.mime),o=n.startsWith("data:image/jpeg")?"image/jpeg":r.mime;return{...r,mime:o,url:n}}if(!this.shouldNormalizeToTextPlain(r.mime))return r;let s=r.url;if(r.url.startsWith("data:")){const n=r.url.indexOf(",");if(n!==-1){const o=r.url.substring(5,n),a=r.url.substring(n);s=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:s}}async sendMessage(r){const s=Date.now(),n=r.messageId??`temp_${s}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.prefaceText&&r.prefaceText.trim()&&o.push({type:"text",text:r.prefaceText,synthetic:r.prefaceTextSynthetic!==!1}),r.text&&r.text.trim()){const a={type:"text",text:r.text};o.push(a)}if(r.files&&r.files.length>0)for(const a of r.files){const c=await this.normalizeFilePart(a),l={type:"file",mime:c.mime,filename:c.filename,url:c.url};o.push(l)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text,...a.synthetic?{synthetic:!0}:{}}),a.files&&a.files.length>0)for(const c of a.files){const l=await this.normalizeFilePart(c),d={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,variant:r.variant,parts:o}),n}async abortSession(r){return!!(await this.client.session.abort({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(r,s,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:s,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const s=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!s.data)throw new Error("Failed to unrevert session");return s.data}async forkSession(r,s){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:s});if(!n.data)throw new Error("Failed to fork session");return n.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(r){try{const s=this.baseUrl.replace(/\/$/,""),n=new URL(`${s}/session/status`),o=typeof r=="string"?r.trim():"";o.length>0&&n.searchParams.set("directory",o);const a=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const c=await a.json().catch(()=>null);return!c||typeof c!="object"?{}:c}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async getWebServerSessionActivity(){try{const r=await fetch("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return null;const s=await r.json().catch(()=>null);return!s||typeof s!="object"?null:s}catch{return null}}async listToolIds(r){try{const s=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(s?{directory:s}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(r,s,n){return(await this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:s,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async replyToQuestion(r,s){const n=!Array.isArray(s)||s.length===0?[]:Array.isArray(s[0])?s:[s];return(await this.client.question.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},answers:n})).data||!1}async rejectQuestion(r){return(await this.client.question.reject({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async listPendingQuestions(r){const s=[],n=async d=>{try{const u=typeof d=="string"?d.trim():"";return(await this.client.question.list(u?{directory:u}:void 0)).data||[]}catch{return[]}};s.push(n(null));const o=new Set;for(const d of r?.directories??[]){const u=this.normalizeCandidatePath(d??null);u&&o.add(u)}for(const d of o)s.push(n(d));const a=await Promise.all(s),c=[],l=new Set;for(const d of a)for(const u of d){if(!u||typeof u!="object")continue;const m=u.id;typeof m!="string"||m.length===0||l.has(m)||(l.add(m),c.push(u))}return c}async getConfig(){const r=await this.client.config.get();if(!r.data)throw new Error("Failed to get config");return r.data}async updateConfig(r){const s=`${this.baseUrl}/config`,n=await fetch(s,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(r){const s=await this.getConfig(),n=r(s);return await this.updateConfig(n)}async getProviders(){const r=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!r.data)throw new Error("Failed to get providers");return r.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]}catch{return[]}}parseSseBlock(r){if(!r)return null;const s=r.split(`
3
+ `),n=[];let o;for(const c of s)if(c.startsWith("data:"))n.push(c.slice(5).replace(/^\s/,""));else if(c.startsWith("id:")){const l=c.slice(3).trim();l&&(o=l)}if(n.length===0)return null;const a=n.join(`
4
+ `).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const s=r,n=typeof s.directory=="string"?s.directory:typeof s.properties=="object"&&s.properties!==null?s.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof s.type=="string")return{directory:o&&o.length>0?o:"global",payload:s};const a=s.payload;if(a&&typeof a=="object"){const c=a;if(typeof c.type=="string")return{directory:o&&o.length>0?o:"global",payload:c}}return null}emitGlobalSseEvent(r){for(const s of this.globalSseListeners)try{s(r)}catch(n){console.warn("[OpencodeClient] Global SSE listener error:",n)}}notifyGlobalSseOpen(){for(const r of this.globalSseOpenListeners)try{r()}catch(s){console.warn("[OpencodeClient] Global SSE open handler error:",s)}}notifyGlobalSseError(r){for(const s of this.globalSseErrorListeners)try{s(r)}catch(n){console.warn("[OpencodeClient] Global SSE error handler failed:",n)}}ensureGlobalSseStarted(){if(this.globalSseTask)return;const r=new AbortController;this.globalSseAbortController=r,this.globalSseTask=this.runGlobalSseLoop(r).catch(s=>{s?.name==="AbortError"||r.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",s)}).finally(()=>{this.globalSseAbortController===r&&(this.globalSseAbortController=null),this.globalSseTask=null,this.globalSseIsConnected=!1})}maybeStopGlobalSse(){this.globalSseListeners.size>0||(this.globalSseAbortController&&!this.globalSseAbortController.signal.aborted&&this.globalSseAbortController.abort(),this.globalSseAbortController=null)}async runGlobalSseLoop(r){const s=`${this.baseUrl.replace(/\/+$/,"")}/global/event`;let n=0;for(;!r.signal.aborted;){try{const a={Accept:"text/event-stream","Cache-Control":"no-cache"};this.globalSseLastEventId&&(a["Last-Event-ID"]=this.globalSseLastEventId);const c=await fetch(s,{method:"GET",headers:a,signal:r.signal});if(!c.ok||!c.body)throw new Error(`Global SSE connect failed with status ${c.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const l=c.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await l.read();if(f||r.signal.aborted)break;if(!p||p.length===0)continue;u+=d.decode(p,{stream:!0}).replace(/\r\n/g,`
5
+ `);const h=u.split(`
6
+
7
+ `);u=h.pop()??"";for(const g of h){const x=this.parseSseBlock(g);if(!x)continue;x.id&&(this.globalSseLastEventId=x.id);const b=this.normalizeRoutedSsePayload(x.data);b&&this.emitGlobalSseEvent(b)}}const m=u.trim();if(m&&!r.signal.aborted){const f=this.parseSseBlock(m);f?.id&&(this.globalSseLastEventId=f.id);const p=f?this.normalizeRoutedSsePayload(f.data):null;p&&this.emitGlobalSseEvent(p)}this.globalSseIsConnected=!1}catch(a){if(this.globalSseIsConnected=!1,a?.name==="AbortError"||r.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",a),this.notifyGlobalSseError(a)}if(r.signal.aborted)break;n+=1;const o=Math.min(3e3*Math.pow(2,n),3e4);await new Promise(a=>setTimeout(a,o))}}subscribeToGlobalEvents(r,s,n,o){const a=this.normalizeCandidatePath(o?.directory??null),c=l=>{a&&l.directory!==a||r(l)};return this.globalSseListeners.add(c),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(l){console.warn("[OpencodeClient] Global SSE open handler error:",l)}},0)),s&&this.globalSseErrorListeners.add(s),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(c),n&&this.globalSseOpenListeners.delete(n),s&&this.globalSseErrorListeners.delete(s),this.maybeStopGlobalSse()}}subscribeToEvents(r,s,n,o,a){const c=a?.key??"default",l=a?.scope??"directory",d=this.sseAbortControllers.get(c);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(c,u);let m;if(l==="global"){let p=null;const h=x=>{if(x.directory==="global")return x.payload;const b=x.payload,y=typeof b.properties=="object"&&b.properties!==null?b.properties:{};return y.directory===x.directory?x.payload:{...b,properties:{...y,directory:x.directory}}},g=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(c)===u&&this.sseAbortControllers.delete(c)};return u.signal.addEventListener("abort",g,{once:!0}),p=this.subscribeToGlobalEvents(x=>{u.signal.aborted||r(h(x))},s?x=>{u.signal.aborted||s(x)}:void 0,n?()=>{u.signal.aborted||n()}:void 0),()=>{g(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const h=p;if(typeof h.type=="string")return h;const g=h.payload;if(g&&typeof g=="object"){const x=g;if(typeof x.type=="string"){if(typeof h.directory=="string"&&h.directory.length>0){const y={...(typeof x.properties=="object"&&x.properties!==null?x.properties:null)??{},directory:h.directory};return{...x,properties:y}}return x}}return null};return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const p=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",p??"default");const h=async g=>{try{const x=p?{directory:p}:void 0,b={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:v=>{v instanceof Error&&v.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",v),s&&!u.signal.aborted&&s(v))},onSseEvent:v=>{if(u.signal.aborted)return;v.id&&typeof v.id=="string"&&(m=v.id);const S=v.data,C=f(S);C&&r(C)}};m&&(b.headers={...b.headers||{},"Last-Event-ID":m});const y=await this.client.event.subscribe(x,b);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const v of y.stream)if(u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(x){if(x?.name==="AbortError"||u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",x),s&&s(x);const b=Math.min(3e3*Math.pow(2,g),3e4);await new Promise(y=>setTimeout(y,b)),u.signal.aborted||await h(g+1);return}if(!u.signal.aborted){const x=Math.min(3e3*Math.pow(2,g),3e4);await new Promise(b=>setTimeout(b,x)),await h(g+1)}};try{await h(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(c)===u&&this.sseAbortControllers.delete(c)}})(),()=>{this.sseAbortControllers.get(c)===u&&this.sseAbortControllers.delete(c),u.abort()}}async readFile(r){try{const s=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,directory:this.currentDirectory})});if(!s.ok)throw new Error(`Failed to read file: ${s.statusText}`);return await s.text()}catch{return`// Content of ${r}
8
+ // This would be loaded from the server`}}async listFiles(r){try{const s=r||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:s})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(s=>({name:s.name,description:s.description,agent:s.agent,model:s.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(s=>({name:s.name,description:s.description,agent:s.agent,model:s.model,template:s.template,subtask:s.subtask}))}catch{return[]}}async getCommandDetails(r){try{const s=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(s.data){const n=s.data.find(o=>o.name===r);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{let r;const s=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;s==="/api"?r="/health":s.endsWith("/api")?r=`${s.slice(0,-4)}/health`:r=`${s}/health`;const n=await fetch(r);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(r){const s=_i();if(s?.createDirectory)try{return await s.createDirectory(r)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}const n=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!n.ok){const a=await n.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await n.json()}async listLocalDirectory(r,s){const n=_i();if(n)try{const o=await n.listDirectory(r||"",s);return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:ea(a.path),isDirectory:!!a.isDirectory,isFile:!a.isDirectory,isSymbolicLink:!1}))}catch(o){throw console.error("Failed to list directory contents:",o),o}try{const o=new URLSearchParams;r&&r.trim().length>0&&o.set("path",r),s?.respectGitignore&&o.set("respectGitignore","true");const a=o.toString(),c=await fetch(`${this.baseUrl}/fs/list${a?`?${a}`:""}`);if(!c.ok){const d=await c.json().catch(()=>({})),u=typeof d.error=="string"?d.error:"Failed to list directory";throw new Error(u)}const l=await c.json();return!l||!Array.isArray(l.entries)?[]:l.entries}catch(o){throw console.error("Failed to list directory contents:",o),o}}async searchFiles(r,s){const n=_i(),o=typeof s?.directory=="string"&&s.directory.trim().length>0?s.directory.trim():this.currentDirectory,a=o?ea(o):null;if(n)try{const m=await n.search({directory:o||"",query:r,maxResults:s?.limit,includeHidden:s?.includeHidden,respectGitignore:s?.respectGitignore});return Array.isArray(m)?m.map(f=>{const p=ea(f.path),h=p.split("/").filter(Boolean).pop()||p,g=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?ea(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:g,extension:h.includes(".")?h.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const c=new URLSearchParams;o&&o.length>0&&c.set("directory",o),typeof r=="string"&&c.set("q",r),typeof s?.limit=="number"&&Number.isFinite(s.limit)&&c.set("limit",String(s.limit)),s?.includeHidden&&c.set("includeHidden","true"),s?.respectGitignore===!1&&c.set("respectGitignore","false");const l=`${this.baseUrl}/fs/search${c.toString()?`?${c.toString()}`:""}`,d=await fetch(l,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await fl();if(r)return r;try{const s=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!s.ok){const o=await s.json().catch(()=>({})),a=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(a)}const n=await s.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(s){return console.warn("Failed to resolve filesystem home directory:",s),null}}async setOpenCodeWorkingDirectory(r){if(!r||typeof r!="string"||!r.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",r),null;const s=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",s,"with path:",r);try{const n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})}),o=await n.json().catch(()=>null);if(!n.ok){const a=o??{},c=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(c)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:r}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const Oe=new Ly,Oy=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:Oe},Symbol.toStringTag,{value:"Module"})),Tc=new Set;function yi(t){return Tc.add(t),()=>{Tc.delete(t)}}function Sr(t,r){const s=Array.isArray(t)?t:[t],n=Array.from(new Set(s));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:r?.source,timestamp:Date.now()};for(const a of Tc)try{const c=a(o);c instanceof Promise&&c.catch(l=>{console.error("[ConfigSync] Async listener failed:",l)})}catch(c){console.error("[ConfigSync] Listener threw:",c)}}function Ro(t,r){return t.scopes.includes("all")||t.scopes.includes(r)}const hl="Updating OpenCode configuration...";let Nr=0,sn=hl;const Fc=new Set;function Ja(){const t={isUpdating:Nr>0,message:sn};Fc.forEach(r=>r(t))}function Us(t){Nr+=1,Nr===1?(sn=t||hl,Ja()):t&&(sn=t,Ja())}function _s(){Nr!==0&&(Nr-=1,Nr===0&&(sn=hl,Ja()))}function $r(t){sn===t&&Nr>0||(sn=t,Nr>0&&Ja())}function _y(t){return Fc.add(t),t({isUpdating:Nr>0,message:sn}),()=>{Fc.delete(t)}}function $y(){return{isUpdating:Nr>0,message:sn}}const vr=ns()(fs(qs((t,r)=>({queuedMessages:{},queueModeEnabled:!0,addToQueue:(s,n)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};t(c=>{const l=c.queuedMessages[s]??[];return{queuedMessages:{...c.queuedMessages,[s]:[...l,a]}}})},removeFromQueue:(s,n)=>{t(o=>{const c=(o.queuedMessages[s]??[]).filter(l=>l.id!==n);if(c.length===0){const{[s]:l,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[s]:c}}})},popToInput:(s,n)=>{const c=(r().queuedMessages[s]??[]).find(l=>l.id===n);return c?(t(l=>{const u=(l.queuedMessages[s]??[]).filter(m=>m.id!==n);if(u.length===0){const{[s]:m,...f}=l.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...l.queuedMessages,[s]:u}}}),c):null},clearQueue:s=>{t(n=>{const{[s]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:s=>{t({queueModeEnabled:s}),as({queueModeEnabled:s})},getQueueForSession:s=>r().queuedMessages[s]??[]}),{name:"message-queue-store",storage:Ks(()=>js()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),hf="directoryTreeShowHidden",Rc="directory-show-hidden-change",ad=()=>{if(typeof window>"u")return!0;try{const t=js().getItem(hf);return t===null?!0:t==="true"}catch{return!0}},By=()=>{typeof window>"u"||window.dispatchEvent(new Event(Rc))},gl=(t,r={})=>{if(!(typeof window>"u")){try{js().setItem(hf,t?"true":"false"),By()}catch{}r.persist!==!1&&as({directoryShowHidden:t})}},Go=()=>{const[t,r]=i.useState(ad);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(ad())};return window.addEventListener("storage",s),window.addEventListener(Rc,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Rc,s)}},[]),t},gf="filesViewShowGitignored",Lc="files-view-show-gitignored-change",id=()=>{if(typeof window>"u")return!1;try{return js().getItem(gf)==="true"}catch{return!1}},zy=()=>{typeof window>"u"||window.dispatchEvent(new Event(Lc))},xf=(t,r={})=>{if(!(typeof window>"u")){try{js().setItem(gf,t?"true":"false"),zy()}catch{}r.persist!==!1&&as({filesViewShowGitignored:t})}},bi=()=>{const[t,r]=i.useState(id);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(id())};return window.addEventListener("storage",s),window.addEventListener(Lc,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Lc,s)}},[]),t},cd=t=>{if(!t||typeof t!="object")return null;const r={};return typeof t.showReasoningTraces=="boolean"&&(r.showReasoningTraces=t.showReasoningTraces),Object.keys(r).length>0?r:null},Hy=t=>!t||typeof t!="object"?null:{showReasoningTraces:t.showReasoningTraces},Wy=t=>{const r=Me.getState();typeof t.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(t.showReasoningTraces)},Uy=async()=>{if(typeof window>"u")return null;if(ds()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const s=await r.load();return cd(typeof s=="object"&&s!==null?s:null)}catch(s){return console.warn("Failed to load appearance preferences from desktop storage:",s),null}}const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const r=JSON.parse(t),s=Hy(r);return cd(s)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let yf=null;const ld=t=>{yf=t},Ps=()=>yf,Da=t=>{typeof window>"u"||(t.themeId&&localStorage.setItem("selectedThemeId",t.themeId),t.themeVariant&&localStorage.setItem("selectedThemeVariant",t.themeVariant),t.lightThemeId&&localStorage.setItem("lightThemeId",t.lightThemeId),t.darkThemeId&&localStorage.setItem("darkThemeId",t.darkThemeId),typeof t.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(t.useSystemTheme)),t.lastDirectory&&localStorage.setItem("lastDirectory",t.lastDirectory),t.homeDirectory&&(localStorage.setItem("homeDirectory",t.homeDirectory),window.__OPENCHAMBER_HOME__=t.homeDirectory),Array.isArray(t.projects)&&t.projects.length>0?localStorage.setItem("projects",JSON.stringify(t.projects)):localStorage.removeItem("projects"),t.activeProjectId?localStorage.setItem("activeProjectId",t.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(t.pinnedDirectories)&&t.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(t.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),typeof t.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(t.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof t.directoryShowHidden=="boolean"&&localStorage.setItem("directoryTreeShowHidden",t.directoryShowHidden?"true":"false"),typeof t.filesViewShowGitignored=="boolean"&&localStorage.setItem("filesViewShowGitignored",t.filesViewShowGitignored?"true":"false"))},Vy=t=>{if(!Array.isArray(t))return;const r=[],s=new Set;for(const n of t){if(!n||typeof n!="object")continue;const o=n,a=typeof o.id=="string"?o.id.trim():"",c=typeof o.label=="string"?o.label.trim():"",l=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!c||!l||s.has(a)||(s.add(a),r.push({id:a,label:c,source:l,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},Gy=t=>{if(!Array.isArray(t))return;const r=[],s=new Set,n=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,c=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!c||!l)continue;const d=l==="/"?l:l.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||s.has(c)||n.has(d))continue;s.add(c),n.add(d);const u={id:c,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.baseBranch=="string"&&m.baseBranch.trim()&&(f.baseBranch=m.baseBranch.trim()),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r.length>0?r:void 0},bf=()=>{const t=Me.persist;if(t&&typeof t=="object")return t},wf=()=>Ps()?.settings??null,Aa=t=>{const r=Me.getState(),s=vr.getState();if(typeof t.showReasoningTraces=="boolean"&&t.showReasoningTraces!==r.showReasoningTraces&&r.setShowReasoningTraces(t.showReasoningTraces),typeof t.autoDeleteEnabled=="boolean"&&t.autoDeleteEnabled!==r.autoDeleteEnabled&&r.setAutoDeleteEnabled(t.autoDeleteEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)){const n=Math.max(1,Math.min(365,t.autoDeleteAfterDays));n!==r.autoDeleteAfterDays&&r.setAutoDeleteAfterDays(n)}typeof t.memoryLimitHistorical=="number"&&Number.isFinite(t.memoryLimitHistorical)&&r.setMemoryLimitHistorical(t.memoryLimitHistorical),typeof t.memoryLimitViewport=="number"&&Number.isFinite(t.memoryLimitViewport)&&r.setMemoryLimitViewport(t.memoryLimitViewport),typeof t.memoryLimitActiveSession=="number"&&Number.isFinite(t.memoryLimitActiveSession)&&r.setMemoryLimitActiveSession(t.memoryLimitActiveSession),typeof t.queueModeEnabled=="boolean"&&t.queueModeEnabled!==s.queueModeEnabled&&s.setQueueMode(t.queueModeEnabled),typeof t.showTextJustificationActivity=="boolean"&&t.showTextJustificationActivity!==r.showTextJustificationActivity&&r.setShowTextJustificationActivity(t.showTextJustificationActivity),typeof t.nativeNotificationsEnabled=="boolean"&&t.nativeNotificationsEnabled!==r.nativeNotificationsEnabled&&r.setNativeNotificationsEnabled(t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&t.notificationMode!==r.notificationMode&&r.setNotificationMode(t.notificationMode),typeof t.toolCallExpansion=="string"&&(t.toolCallExpansion==="collapsed"||t.toolCallExpansion==="activity"||t.toolCallExpansion==="detailed")&&t.toolCallExpansion!==r.toolCallExpansion&&r.setToolCallExpansion(t.toolCallExpansion),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&t.fontSize!==r.fontSize&&r.setFontSize(t.fontSize),typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding!==r.padding&&r.setPadding(t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&t.cornerRadius!==r.cornerRadius&&r.setCornerRadius(t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&t.inputBarOffset!==r.inputBarOffset&&r.setInputBarOffset(t.inputBarOffset),typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&t.diffLayoutPreference!==r.diffLayoutPreference&&r.setDiffLayoutPreference(t.diffLayoutPreference),typeof t.diffViewMode=="string"&&(t.diffViewMode==="single"||t.diffViewMode==="stacked")&&t.diffViewMode!==r.diffViewMode&&r.setDiffViewMode(t.diffViewMode),typeof t.directoryShowHidden=="boolean"&&gl(t.directoryShowHidden,{persist:!1}),typeof t.filesViewShowGitignored=="boolean"&&xf(t.filesViewShowGitignored,{persist:!1})},dd=t=>{if(!t||typeof t!="object")return null;const r=t,s={};typeof r.themeId=="string"&&r.themeId.length>0&&(s.themeId=r.themeId),(r.useSystemTheme===!0||r.useSystemTheme===!1)&&(s.useSystemTheme=r.useSystemTheme),typeof r.themeVariant=="string"&&(r.themeVariant==="light"||r.themeVariant==="dark")&&(s.themeVariant=r.themeVariant),typeof r.lightThemeId=="string"&&r.lightThemeId.length>0&&(s.lightThemeId=r.lightThemeId),typeof r.darkThemeId=="string"&&r.darkThemeId.length>0&&(s.darkThemeId=r.darkThemeId),typeof r.lastDirectory=="string"&&r.lastDirectory.length>0&&(s.lastDirectory=r.lastDirectory),typeof r.homeDirectory=="string"&&r.homeDirectory.length>0&&(s.homeDirectory=r.homeDirectory);const n=Gy(r.projects);n&&(s.projects=n),typeof r.activeProjectId=="string"&&r.activeProjectId.length>0&&(s.activeProjectId=r.activeProjectId),Array.isArray(r.approvedDirectories)&&(s.approvedDirectories=r.approvedDirectories.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.securityScopedBookmarks)&&(s.securityScopedBookmarks=r.securityScopedBookmarks.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.pinnedDirectories)&&(s.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(a=>typeof a=="string"&&a.length>0)))),typeof r.showReasoningTraces=="boolean"&&(s.showReasoningTraces=r.showReasoningTraces),typeof r.autoDeleteEnabled=="boolean"&&(s.autoDeleteEnabled=r.autoDeleteEnabled),typeof r.autoDeleteAfterDays=="number"&&Number.isFinite(r.autoDeleteAfterDays)&&(s.autoDeleteAfterDays=r.autoDeleteAfterDays),typeof r.defaultModel=="string"&&r.defaultModel.length>0&&(s.defaultModel=r.defaultModel),typeof r.defaultVariant=="string"&&r.defaultVariant.length>0&&(s.defaultVariant=r.defaultVariant),typeof r.defaultAgent=="string"&&r.defaultAgent.length>0&&(s.defaultAgent=r.defaultAgent),typeof r.autoCreateWorktree=="boolean"&&(s.autoCreateWorktree=r.autoCreateWorktree),typeof r.gitmojiEnabled=="boolean"&&(s.gitmojiEnabled=r.gitmojiEnabled),typeof r.queueModeEnabled=="boolean"&&(s.queueModeEnabled=r.queueModeEnabled),typeof r.showTextJustificationActivity=="boolean"&&(s.showTextJustificationActivity=r.showTextJustificationActivity),typeof r.nativeNotificationsEnabled=="boolean"&&(s.nativeNotificationsEnabled=r.nativeNotificationsEnabled),typeof r.notificationMode=="string"&&(r.notificationMode==="always"||r.notificationMode==="hidden-only")&&(s.notificationMode=r.notificationMode),typeof r.toolCallExpansion=="string"&&(r.toolCallExpansion==="collapsed"||r.toolCallExpansion==="activity"||r.toolCallExpansion==="detailed")&&(s.toolCallExpansion=r.toolCallExpansion),typeof r.fontSize=="number"&&Number.isFinite(r.fontSize)&&(s.fontSize=r.fontSize),typeof r.padding=="number"&&Number.isFinite(r.padding)&&(s.padding=r.padding),typeof r.cornerRadius=="number"&&Number.isFinite(r.cornerRadius)&&(s.cornerRadius=r.cornerRadius),typeof r.inputBarOffset=="number"&&Number.isFinite(r.inputBarOffset)&&(s.inputBarOffset=r.inputBarOffset),typeof r.diffLayoutPreference=="string"&&(r.diffLayoutPreference==="dynamic"||r.diffLayoutPreference==="inline"||r.diffLayoutPreference==="side-by-side")&&(s.diffLayoutPreference=r.diffLayoutPreference),typeof r.diffViewMode=="string"&&(r.diffViewMode==="single"||r.diffViewMode==="stacked")&&(s.diffViewMode=r.diffViewMode),typeof r.directoryShowHidden=="boolean"&&(s.directoryShowHidden=r.directoryShowHidden),typeof r.filesViewShowGitignored=="boolean"&&(s.filesViewShowGitignored=r.filesViewShowGitignored),typeof r.memoryLimitHistorical=="number"&&Number.isFinite(r.memoryLimitHistorical)&&(s.memoryLimitHistorical=r.memoryLimitHistorical),typeof r.memoryLimitViewport=="number"&&Number.isFinite(r.memoryLimitViewport)&&(s.memoryLimitViewport=r.memoryLimitViewport),typeof r.memoryLimitActiveSession=="number"&&Number.isFinite(r.memoryLimitActiveSession)&&(s.memoryLimitActiveSession=r.memoryLimitActiveSession);const o=Vy(r.skillCatalogs);return o&&(s.skillCatalogs=o),s},qy=async()=>{const t=wf();if(t)try{const r=await t.load();return dd(r.settings)}catch(r){console.warn("Failed to load shared settings from runtime settings API:",r)}try{const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return null;const s=await r.json().catch(()=>null);return dd(s)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},vf=async()=>{if(typeof window>"u")return;const t=bf(),r=s=>{Da(s);const n=()=>Aa(s);if(t?.hasHydrated?.())n();else if(n(),t?.onFinishHydration){const o=t.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:s}))};try{const s=ds()?await zr():await qy();s&&r(s)}catch(s){console.warn("Failed to synchronise settings:",s)}},as=async t=>{if(typeof window>"u")return;if(ds()){try{const s=await wy(t);s&&(Da(s),Aa(s))}catch(s){console.warn("Failed to update desktop settings:",s)}return}const r=wf();if(r)try{const s=await r.save(t);s&&(Da(s),Aa(s));return}catch(s){console.warn("Failed to update settings via runtime settings API:",s)}try{const s=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!s.ok){console.warn("Failed to update shared settings via API:",s.status,s.statusText);return}const n=await s.json().catch(()=>null);n&&(Da(n),Aa(n))}catch(s){console.warn("Failed to update shared settings via API:",s)}},jf=async()=>{if(typeof window>"u")return;const t=bf();try{const r=await Uy();if(!r)return;const s=()=>Wy(r);if(t?.hasHydrated?.()){s();return}if(s(),t?.onFinishHydration){const n=t.onFinishHydration(()=>{n?.(),s()})}}catch(r){console.warn("Failed to load appearance preferences:",r)}},Ky=3e4,Jy=40,Qy=60,Yy=(t,r,s,n,o)=>{const a=t.trim(),c=r.trim().toLowerCase();return`${a}::${c}::${s}::${n?"1":"0"}::${o?"1":"0"}`},wi=ns()(fs((t,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,n,o=Qy,a){if(!s||s.trim().length===0)return[];const c=s.trim(),l=typeof n=="string"?n.trim():"",d=!!a?.includeHidden,u=a?.respectGitignore??!0,m=Yy(c,l,o,d,u),f=Date.now(),p=r().cache[m];if(p&&f-p.timestamp<Ky)return p.files;const h=r().inFlight[m];if(h)return h;const g=Oe.searchFiles(l,{directory:c,limit:o,includeHidden:d,respectGitignore:u}).then(x=>(t(b=>{const y={...b.cache,[m]:{files:x,timestamp:Date.now()}},v=b.cacheKeys.filter(S=>S!==m);for(v.push(m);v.length>Jy;){const S=v.shift();S&&delete y[S]}return{cache:y,cacheKeys:v}}),x)).finally(()=>{t(x=>{const b={...x.inFlight};return delete b[m],{inFlight:b}})});return t(x=>({inFlight:{...x.inFlight,[m]:g}})),g},invalidateDirectory(s){if(!s||s.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${s.trim()}::`;t(a=>{const c={...a.cache},l=a.cacheKeys.filter(m=>m.startsWith(o)?(delete c[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:c,cacheKeys:l,inFlight:u}})}}),{name:"file-search-store"})),hs=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var Xy={};let ur=null;const dr=js(),ud=dr.getItem("lastDirectory"),Zy=typeof ud=="string"&&ud.length>0,ta=t=>{try{wi.getState().invalidateDirectory(t)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},Sf=t=>{const r=t.trim();if(!r)return r;const s=r.replace(/\\/g,"/");return s.length>1?s.replace(/\/+$/,""):s},eb=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},Ea=(t,r)=>{const s=eb(t,r);return Sf(s)},Qa=()=>{if(typeof window<"u"){const r=dr.getItem("homeDirectory")||ur||null,s=dr.getItem("lastDirectory");if(s&&!zt())return Ea(s,r);if(ur)return ur;const n=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:window.opencodeDesktop&&typeof window.opencodeDesktop.homeDirectory=="string"?window.opencodeDesktop.homeDirectory:null;if(n&&n.length>0)return ur=n,dr.setItem("homeDirectory",n),n;if(r&&!zt())return ur=r,r}const t=typeof process<"u"&&Xy?.HOME;return t||process?.cwd?.()||"/"},tb=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");if(s.length>1){const n=s.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return s==="/"||s.length===0?null:s},sb=t=>(ur=t,typeof window<"u"&&dr.setItem("homeDirectory",t),as({homeDirectory:t}),t),Nf=async()=>{const t=n=>{const o=tb(n);return o?sb(o):null};try{const n=await Oe.getFilesystemHome(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Oe.getSystemInfo(),o=t(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await fl(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=Qa(),s=t(r);return s||r},rb=()=>{if(!zt())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const r=Sf(t);return r.length>0?r:null},yn=rb()||Qa();yn&&Oe.setDirectory(yn);const nb=!!(yn&&yn!=="/"),vt=ns()(fs((t,r)=>({currentDirectory:yn,directoryHistory:[yn],historyIndex:0,homeDirectory:yn,hasPersistedDirectory:Zy,isHomeReady:nb,isSwitchingDirectory:!1,setDirectory:(s,n)=>{const o=ur||r().homeDirectory||dr.getItem("homeDirectory"),a=Ea(s,o);hs()&&console.log("[DirectoryStore] setDirectory called with path:",a),Oe.setDirectory(a),ta(),t(c=>{const l=[...c.directoryHistory.slice(0,c.historyIndex+1),a];return dr.setItem("lastDirectory",a),as({lastDirectory:a}),{currentDirectory:a,directoryHistory:l,historyIndex:l.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const s=r();if(s.historyIndex>0){const n=s.historyIndex-1,o=s.directoryHistory[n];Oe.setDirectory(o),ta(),dr.setItem("lastDirectory",o),as({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const s=r();if(s.historyIndex<s.directoryHistory.length-1){const n=s.historyIndex+1,o=s.directoryHistory[n];Oe.setDirectory(o),ta(),dr.setItem("lastDirectory",o),as({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:s,setDirectory:n}=r(),o=ur||r().homeDirectory||Qa();if(s===o||s==="/")return;const a=s.endsWith("/")?s.slice(0,-1):s,c=a.lastIndexOf("/");if(c===-1){const l=ur||Qa();n(l)}else n(c===0?"/":a.substring(0,c))},goHome:async()=>{const s=ur||r().homeDirectory||await Nf();r().setDirectory(s)},synchronizeHomeDirectory:s=>{const n=r(),o=s;ur=o;const a=n.homeDirectory!==o,c=dr.getItem("lastDirectory"),l=typeof c=="string"&&c.length>0,d=!l&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||t({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",m=n.currentDirectory?Ea(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(x=>Ea(x,o)),p=f.some((x,b)=>x!==n.directoryHistory[b]),h=!!(m&&m!==n.currentDirectory),g={homeDirectory:o,hasPersistedDirectory:l,isHomeReady:u};if(d?(g.currentDirectory=o,g.directoryHistory=[o],g.historyIndex=0,g.isSwitchingDirectory=!1):(h||p)&&(g.currentDirectory=m,g.directoryHistory=f,g.historyIndex=Math.min(n.historyIndex,f.length-1),g.isSwitchingDirectory=!1),t(()=>g),(d||h)&&u){const x=d?o:m;Oe.setDirectory(x),ta(),dr.setItem("lastDirectory",x),as({lastDirectory:x})}as({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Nf().then(t=>{vt.getState().synchronizeHomeDirectory(t)});const Qn=js(),kf="projects",Oc="activeProjectId",ob=(t,r)=>{const s=t.trim();return!s.startsWith("~")||!r?s:s==="~"?r:s.startsWith("~/")||s.startsWith("~\\")?`${r}${s.slice(1)}`:s},vi=t=>{const r=t.trim();if(!r)return"";const s=Qn.getItem("homeDirectory")||vt.getState().homeDirectory||"",o=ob(r,s).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},Cf=t=>{const r=vi(t);if(!r||r==="/")return"Root";const s=r.split("/").filter(Boolean);return s[s.length-1]||r},ab=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Mf=t=>{if(!Array.isArray(t))return[];const r=[],s=new Set,n=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,c=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!c||!l)continue;const d=vi(l);if(!d||s.has(c)||n.has(d))continue;s.add(c),n.add(d);const u={id:c,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.baseBranch=="string"&&(f.baseBranch=m.baseBranch),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r},ib=()=>{try{const t=Qn.getItem(kf);return t?Mf(JSON.parse(t)):[]}catch{return[]}},cb=()=>{try{const t=Qn.getItem(Oc);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},xl=(t,r)=>{try{Qn.setItem(kf,JSON.stringify(t))}catch{}try{r?Qn.setItem(Oc,r):Qn.removeItem(Oc)}catch{}},Fn=(t,r)=>{xl(t,r),as({projects:t,activeProjectId:r??void 0})},lb=ib(),db=()=>{if(typeof window>"u"||!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode)return null;const r=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof r!="string"||r.trim().length===0)return null;const s=vi(r);if(!s)return null;const n=`vscode:${s}`,o={id:n,path:s,label:Cf(s),addedAt:Date.now(),lastOpenedAt:Date.now()};return hs()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},cr=db(),yl=cr?.projects??lb,Df=cr?.activeProjectId??cb()??yl[0]?.id??null;cr&&xl(yl,Df);const Lt=ns()(fs((t,r)=>({projects:yl,activeProjectId:Df,validateProjectPath:s=>{if(typeof s!="string"||s.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=vi(s);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(s,n)=>{if(cr)return null;const{validateProjectPath:o}=r(),a=o(s);if(!a.ok||!a.normalizedPath)return null;const c=a.normalizedPath,l=r().projects.find(g=>g.path===c);if(l)return r().setActiveProject(l.id),l;const d=Date.now(),u=n?.label?.trim()||Cf(c),m=n?.id?.trim(),p={id:m&&!r().projects.some(g=>g.id===m)?m:ab(),path:c,label:u,addedAt:d,lastOpenedAt:d},h=[...r().projects,p];return t({projects:h}),hs()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:s=>{if(cr)return;const n=r(),o=n.projects.filter(c=>c.id!==s);let a=n.activeProjectId;if(n.activeProjectId===s&&(a=o[0]?.id??null),t({projects:o,activeProjectId:a}),Fn(o,a),a){const c=o.find(l=>l.id===a);c&&(Oe.setDirectory(c.path),vt.getState().setDirectory(c.path,{showOverlay:!1}))}else vt.getState().goHome()},setActiveProject:s=>{if(cr)return;const{projects:n,activeProjectId:o}=r();if(o===s)return;const a=n.find(d=>d.id===s);if(!a)return;const c=Date.now(),l=n.map(d=>d.id===s?{...d,lastOpenedAt:c}:d);t({projects:l,activeProjectId:s}),Fn(l,s),Oe.setDirectory(a.path),vt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:s=>{if(cr)return;const{projects:n,activeProjectId:o}=r();if(o===s||!n.find(d=>d.id===s))return;const c=Date.now(),l=n.map(d=>d.id===s?{...d,lastOpenedAt:c}:d);t({projects:l,activeProjectId:s}),Fn(l,s)},renameProject:(s,n)=>{if(cr)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:c}=r(),l=a.map(d=>d.id===s?{...d,label:o}:d);t({projects:l}),Fn(l,c)},reorderProjects:(s,n)=>{if(cr)return;const{projects:o,activeProjectId:a}=r();if(s<0||s>=o.length||n<0||n>=o.length||s===n)return;const c=[...o],[l]=c.splice(s,1);c.splice(n,0,l),t({projects:c}),Fn(c,a)},synchronizeFromSettings:s=>{if(cr)return;const n=Mf(s.projects??[]),o=typeof s.activeProjectId=="string"&&s.activeProjectId.trim()?s.activeProjectId.trim():null,a=r(),c=JSON.stringify(a.projects)!==JSON.stringify(n),l=a.activeProjectId!==o;if(!(!c&&!l)&&(t({projects:n,activeProjectId:o}),xl(n,o),o)){const d=n.find(u=>u.id===o);d&&(Oe.setDirectory(d.path),vt.getState().setDirectory(d.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:s,activeProjectId:n}=r();return n?s.find(o=>o.id===n)??null:null},updateWorktreeDefaults:(s,n)=>{if(cr)return;const{projects:o,activeProjectId:a}=r(),c=o.find(u=>u.id===s);if(!c)return;const l={...c.worktreeDefaults};n.baseBranch!==void 0&&(n.baseBranch.trim()?l.baseBranch=n.baseBranch.trim():delete l.baseBranch),n.autoCreateWorktree!==void 0&&(l.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===s?{...u,worktreeDefaults:Object.keys(l).length>0?l:void 0}:u);t({projects:d}),Fn(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",t=>{const r=t.detail;r&&typeof r=="object"&&Lt.getState().synchronizeFromSettings(r)});const ub=new Set(["init","review"]),Gn=t=>ub.has(t.name),Mo="useCommandsStore",_c=t=>new Promise(r=>setTimeout(r,t)),sa=()=>{try{const r=Lt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const s=Oe.getDirectory();if(s?.trim())return s.trim()}catch(t){console.warn("[CommandsStore] Error resolving config directory:",t)}return null},mb=2e4,md=300,fd=4,fb=800,pb=200,hb=2e3,an=ns()(fs(qs((t,r)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:s=>{t({selectedCommandName:s})},setCommandDraft:s=>{t({commandDraft:s})},loadCommands:async()=>{t({isLoading:!0});const s=r().commands;let n=null;for(let o=0;o<3;o++)try{const a=sa(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await Oe.withDirectory(a,()=>Oe.listCommandsWithDetails()),d=await Promise.all(l.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${c}`,{headers:{"Cache-Control":"no-cache",...a?{"x-opencode-directory":a}:{}}});if(m.ok){const f=await m.json();let p=f.scope;if(!p&&f.sources){const h=f.sources;p=(h.md?.exists?h.md.scope:void 0)??(h.json?.exists?h.json.scope:void 0)??h.md?.scope??h.json?.scope}return p==="project"||p==="user"?{...u,scope:p}:{...u,scope:void 0}}}catch(m){console.warn(`[CommandsStore] Failed to fetch config for command ${u.name}:`,m)}return u}));return JSON.stringify(s)!==JSON.stringify(d)?t({commands:d,isLoading:!1}):t({isLoading:!1}),!0}catch(a){n=a;const c=200*(o+1);await new Promise(l=>setTimeout(l,c))}return console.error("Failed to load commands:",n),t({commands:s,isLoading:!1}),!1},createCommand:async s=>{Us("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",s.name);const o={template:s.template||""};s.description&&(o.description=s.description),s.agent&&(o.agent=s.agent),s.model&&(o.model=s.model),s.subtask!==void 0&&(o.subtask=s.subtask),s.scope&&(o.scope=s.scope),console.log("[CommandsStore] Command config to save:",o);const a=sa(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(s.name)}${c}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await $i({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&Sr("commands",{source:Mo}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||_s()}},updateCommand:async(s,n)=>{Us("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",s),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const c=sa(),l=c?`?directory=${encodeURIComponent(c)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(s)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...c?{"x-opencode-directory":c}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),u?.requiresReload??!0)return o=!0,await $i({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&Sr("commands",{source:Mo}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||_s()}},deleteCommand:async s=>{Us("Deleting command configuration…");let n=!1;try{const o=sa(),a=o?`?directory=${encodeURIComponent(o)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await c.json().catch(()=>null);if(!c.ok){const m=l?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),l?.requiresReload??!0)return n=!0,await $i({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&Sr("commands",{source:Mo}),r().selectedCommandName===s&&t({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||_s()}},getCommandByName:s=>{const{commands:n}=r();return n.find(o=>o.name===s)}}),{name:"commands-store",storage:Ks(()=>js()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=an);async function gb(t){const r=typeof t=="number"&&t>0?Math.min(t,md):0;r>0&&await _c(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<mb;){n+=1,$r(`Waiting for OpenCode… (attempt ${n})`);try{if(await Oe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-s,c=n<=fd&&a<1200?md:Math.min(fb+Math.max(0,n-fd)*pb,hb);await _c(c)}throw o||new Error("OpenCode did not become ready in time")}async function $i(t={}){const{message:r,delayMs:s}=t;try{$r(r||"Refreshing commands…")}catch{}try{await gb(s),$r("Refreshing commands…"),await an.getState().loadCommands(),Sr("commands",{source:Mo})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),$r("OpenCode refresh failed. Please retry refreshing configuration manually."),await _c(1500)}finally{_s()}}let pd=null;pd||(pd=yi(t=>{if(t.source!==Mo&&Ro(t,"commands")){const{loadCommands:r}=an.getState();r()}}));const Vr=()=>{const t=Oe.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Ia="useSkillsStore",fr=ns()(fs(qs((t,r)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:s=>{t({selectedSkillName:s})},setSkillDraft:s=>{t({skillDraft:s})},loadSkills:async()=>{t({isLoading:!0});const s=r().skills;let n=null;for(let o=0;o<3;o++)try{const a=Vr(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills${c}`);if(!l.ok)throw new Error(`Failed to list skills: ${l.status}`);const m=((await l.json()).skills||[]).map(f=>({name:f.name,path:f.path,scope:f.scope??"user",source:f.source??"opencode",description:f.sources?.md?.description||""}));return t({skills:m,isLoading:!1}),!0}catch(a){n=a;const c=200*(o+1);await new Promise(l=>setTimeout(l,c))}return console.error("Failed to load skills:",n),t({skills:s,isLoading:!1}),!1},getSkillDetail:async s=>{try{const n=Vr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(s)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async s=>{Us("Creating skill...");try{const n={name:s.name,description:s.description};s.instructions&&(n.instructions=s.instructions),s.scope&&(n.scope=s.scope),s.supportingFiles&&(n.supportingFiles=s.supportingFiles);const o=Vr(),a=o?`?directory=${encodeURIComponent(o)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(s.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),l=await c.json().catch(()=>null);if(!c.ok){const u=l?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&Sr("skills",{source:Ia}),d}catch{return!1}finally{_s()}},updateSkill:async(s,n)=>{Us("Updating skill...");try{const o={};n.description!==void 0&&(o.description=n.description),n.instructions!==void 0&&(o.instructions=n.instructions),n.supportingFiles!==void 0&&(o.supportingFiles=n.supportingFiles);const a=Vr(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(s)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&Sr("skills",{source:Ia}),u}catch{return!1}finally{_s()}},deleteSkill:async s=>{Us("Deleting skill...");try{const n=Vr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(s)}${o}`,{method:"DELETE"}),c=await a.json().catch(()=>null);if(!a.ok){const d=c?.error||"Failed to delete skill";throw new Error(d)}const l=await r().loadSkills();return l&&Sr("skills",{source:Ia}),r().selectedSkillName===s&&t({selectedSkillName:null}),l}catch{return!1}finally{_s()}},getSkillByName:s=>{const{skills:n}=r();return n.find(o=>o.name===s)},readSupportingFile:async(s,n)=>{try{const o=Vr(),a=o?`&directory=${encodeURIComponent(o)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return c.ok?(await c.json()).content??null:null}catch{return null}},writeSupportingFile:async(s,n,o)=>{try{const a=Vr(),c=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}${c}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(s,n)=>{try{const o=Vr(),a=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}${a}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:Ks(()=>js()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=fr);let hd=null;hd||(hd=yi(t=>{if(t.source!==Ia&&Ro(t,"skills")){const{loadSkills:r}=fr.getState();r()}}));const gd=[{id:"anthropic",label:"Anthropic",description:"Anthropic's public skills repository",source:"anthropics/skills",defaultSubpath:"skills",sourceType:"github"},{id:"clawdhub",label:"ClawdHub",description:"Community skill registry with vector search",source:"clawdhub:registry",sourceType:"clawdhub"}],ra=()=>{const t=Oe.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},qo=ns()(fs((t,r)=>({sources:gd,itemsBySource:{},selectedSourceId:gd[0]?.id??null,pageInfoBySource:{},loadedSourceIds:{},clawdhubHasMoreBySource:{},isLoadingCatalog:!1,isLoadingSource:!1,isLoadingMore:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:s=>t({selectedSourceId:s}),loadCatalog:async s=>{t({isLoadingCatalog:!0,lastCatalogError:null});const n={sources:r().sources,itemsBySource:r().itemsBySource,pageInfoBySource:r().pageInfoBySource,loadedSourceIds:r().loadedSourceIds,clawdhubHasMoreBySource:r().clawdhubHasMoreBySource};let o=null;try{const a=s?.refresh?"?refresh=true":"",c=new AbortController,l=window.setTimeout(()=>c.abort(),3e3);try{const d=await fetch(`/api/config/skills/catalog${a}`,{method:"GET",headers:{Accept:"application/json"},signal:c.signal}),u=await d.json().catch(()=>null);if(!d.ok||!u?.ok)throw o=u?.error||{kind:"unknown",message:`Failed to load catalog (${d.status})`},new Error(o.message);const m=u.sources&&u.sources.length>0?u.sources:n.sources,f=s?.refresh?{}:r().itemsBySource||{},p=s?.refresh?{}:r().pageInfoBySource||{},h=s?.refresh?{}:r().loadedSourceIds||{},g=s?.refresh?{}:r().clawdhubHasMoreBySource||{},x=r().selectedSourceId,b=x&&m.some(y=>y.id===x)?x:m[0]?.id??null;return t({sources:m,itemsBySource:f,pageInfoBySource:p,loadedSourceIds:h,clawdhubHasMoreBySource:g,selectedSourceId:b}),!0}finally{window.clearTimeout(l)}}catch(a){return o=o||{kind:"unknown",message:a instanceof Error?a.message:String(a)},t({sources:n.sources,itemsBySource:n.itemsBySource,pageInfoBySource:n.pageInfoBySource,loadedSourceIds:n.loadedSourceIds,clawdhubHasMoreBySource:n.clawdhubHasMoreBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{t({isLoadingCatalog:!1})}},loadSource:async(s,n)=>{if(!s)return!1;t({isLoadingSource:!0,lastCatalogError:null});try{const o=ra(),a=n?.refresh?"&refresh=true":"",c=o?`?directory=${encodeURIComponent(o)}&sourceId=${encodeURIComponent(s)}${a}`:`?sourceId=${encodeURIComponent(s)}${a}`,l=await fetch(`/api/config/skills/catalog/source${c}`,{method:"GET",headers:{Accept:"application/json"}}),d=await l.json().catch(()=>null),u=Array.isArray(d?.items);if(!l.ok||!d?.ok&&!u){const p=await fetch(`/api/config/skills/catalog${c}`,{method:"GET",headers:{Accept:"application/json"}}),h=await p.json().catch(()=>null),g=h?.itemsBySource?.[s];return p.ok&&h?.ok&&Array.isArray(g)?(t(x=>({itemsBySource:{...x.itemsBySource,[s]:g},pageInfoBySource:{...x.pageInfoBySource,[s]:{nextCursor:null}},loadedSourceIds:{...x.loadedSourceIds,[s]:!0},clawdhubHasMoreBySource:{...x.clawdhubHasMoreBySource,[s]:!1}})),!0):(t({lastCatalogError:d?.error||{kind:"unknown",message:`Failed to load source (${l.status})`}}),!1)}const m=d?.items||[],f=d?.nextCursor??null;return t(p=>({itemsBySource:{...p.itemsBySource,[s]:m},pageInfoBySource:{...p.pageInfoBySource,[s]:{nextCursor:f}},loadedSourceIds:{...p.loadedSourceIds,[s]:!0},clawdhubHasMoreBySource:{...p.clawdhubHasMoreBySource,[s]:m.length>0}})),!0}catch(o){return t({lastCatalogError:{kind:"unknown",message:o instanceof Error?o.message:String(o)}}),!1}finally{t({isLoadingSource:!1})}},loadMoreClawdHub:async()=>{const s=r().selectedSourceId;if(!s)return!1;const o=r().pageInfoBySource[s]?.nextCursor||null;t({isLoadingMore:!0});try{const a=ra(),c=[`sourceId=${encodeURIComponent(s)}`];a&&c.push(`directory=${encodeURIComponent(a)}`),o&&c.push(`cursor=${encodeURIComponent(o)}`);const l=`?${c.join("&")}`,d=await fetch(`/api/config/skills/catalog/source${l}`,{method:"GET",headers:{Accept:"application/json"}}),u=await d.json().catch(()=>null);if(!d.ok||!u?.ok)return!1;const m=u.nextCursor??null,f=r().itemsBySource[s]||[],p=u.items||[],h=new Map(f.map(b=>[`${b.sourceId}:${b.skillDir}`,b]));let g=0;for(const b of p){const y=`${b.sourceId}:${b.skillDir}`;h.has(y)||(g+=1),h.set(y,b)}const x=p.length===0||g===0;return t(b=>({itemsBySource:{...b.itemsBySource,[s]:Array.from(h.values())},pageInfoBySource:{...b.pageInfoBySource,[s]:{nextCursor:m}},clawdhubHasMoreBySource:{...b.clawdhubHasMoreBySource,[s]:!x}})),!0}catch{return!1}finally{t({isLoadingMore:!1})}},scanRepo:async s=>{t({isScanning:!0,lastScanError:null,scanResults:null});try{const n=ra(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s)}),c=await a.json().catch(()=>null);if(!a.ok||!c){const l=c?.error||{kind:"unknown",message:"Failed to scan repository"};return t({lastScanError:l}),{ok:!1,error:l}}return c.ok?(t({scanResults:c.items||[]}),c):(t({lastScanError:c.error||{kind:"unknown",message:"Failed to scan repository"}}),c)}finally{t({isScanning:!1})}},installSkills:async s=>{t({isInstalling:!0,lastInstallError:null});try{const n=ra(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/install${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s)}),c=await a.json().catch(()=>null);if(!c){const l={kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:l}),{ok:!1,error:l}}if(!a.ok||!c.ok){const l=c.error||{kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:l}),{ok:!1,error:l}}return fr.getState().loadSkills(),c}catch(n){const o={kind:"unknown",message:n instanceof Error?n.message:String(n)};return t({lastInstallError:o}),{ok:!1,error:o}}finally{t({isInstalling:!1})}}}),{name:"skills-catalog-store"})),xb=()=>{const t=Oe.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},na=()=>{try{const r=Lt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const s=Oe.getDirectory();if(s?.trim())return s.trim()}catch(t){console.warn("[AgentsStore] Error resolving config directory:",t)}return null},hn=t=>{const r=t;return r.native===!0||r.builtIn===!0},Af=t=>{const r=t;return r.hidden===!0||r.options?.hidden===!0},Ef=t=>t.filter(r=>!Af(r)),Pa="useAgentsStore",Ya=t=>new Promise(r=>setTimeout(r,t)),yb=2e4,xd=300,yd=4,bb=800,wb=200,vb=2e3,cn=ns()(fs(qs((t,r)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:s=>{t({selectedAgentName:s})},setAgentDraft:s=>{t({agentDraft:s})},loadAgents:async()=>{t({isLoading:!0});const s=r().agents;for(let n=0;n<3;n++)try{const o=na(),a=o?`?directory=${encodeURIComponent(o)}`:"",c=await Oe.withDirectory(o,()=>Oe.listAgents()),l=await Promise.all(c.map(async d=>{try{const u=await fetch(`/api/config/agents/${encodeURIComponent(d.name)}${a}`,{headers:{"Cache-Control":"no-cache",...o?{"x-opencode-directory":o}:{}}});if(u.ok){const m=await u.json();let f=m.scope;if(!f&&m.sources){const p=m.sources;f=(p.md?.exists?p.md.scope:void 0)??(p.json?.exists?p.json.scope:void 0)??p.md?.scope??p.json?.scope}return f==="project"||f==="user"?{...d,scope:f}:{...d,scope:void 0}}}catch(u){console.warn(`[AgentsStore] Failed to fetch config for agent ${d.name}:`,u)}return d}));return JSON.stringify(s)!==JSON.stringify(l)?t({agents:l,isLoading:!1}):t({isLoading:!1}),!0}catch{}return t({isLoading:!1}),!1},createAgent:async s=>{Us("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",s.name);const o={mode:s.mode||"subagent"};s.description&&(o.description=s.description),s.model&&(o.model=s.model),s.temperature!==void 0&&(o.temperature=s.temperature),s.top_p!==void 0&&(o.top_p=s.top_p),s.prompt&&(o.prompt=s.prompt),s.permission&&(o.permission=s.permission),s.disable!==void 0&&(o.disable=s.disable),s.scope&&(o.scope=s.scope),console.log("[AgentsStore] Agent config to save:",o);const a=na(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(s.name)}${c}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await Do({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&Sr("agents",{source:Pa}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||_s()}},updateAgent:async(s,n)=>{Us("Updating agent configuration…");let o=!1;try{const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const c=na(),l=c?`?directory=${encodeURIComponent(c)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(s)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...c?{"x-opencode-directory":c}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update agent";throw new Error(p)}if(u?.requiresReload??!0)return o=!0,await Do({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&Sr("agents",{source:Pa}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||_s()}},deleteAgent:async s=>{Us("Deleting agent configuration…");let n=!1;try{const o=na(),a=o?`?directory=${encodeURIComponent(o)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await c.json().catch(()=>null);if(!c.ok){const m=l?.error||"Failed to delete agent";throw new Error(m)}if(l?.requiresReload??!0)return n=!0,await Do({message:l?.message,delayMs:l?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&Sr("agents",{source:Pa}),r().selectedAgentName===s&&t({selectedAgentName:null}),u}catch{return!1}finally{n||_s()}},getAgentByName:s=>{const{agents:n}=r();return n.find(o=>o.name===s)},getVisibleAgents:()=>{const{agents:s}=r();return Ef(s)}}),{name:"agents-store",storage:Ks(()=>js()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=cn);async function jb(t){const r=typeof t=="number"&&t>0?Math.min(t,xd):0;r>0&&await Ya(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<yb;){n+=1,$r(`Waiting for OpenCode… (attempt ${n})`);try{if(await Oe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-s,c=n<=yd&&a<1200?xd:Math.min(bb+Math.max(0,n-yd)*wb,vb);await Ya(c)}throw o||new Error("OpenCode did not become ready in time")}const Sb=t=>{if(!t||t.length===0)return["all"];const r=Array.from(new Set(t));return r.includes("all")?["all"]:r};async function Nb(t={}){const{message:r,delayMs:s}=t,n=Sb(t.scopes),o=t.mode??(n.includes("all")?"projects":"active");try{$r(r||"Refreshing configuration…")}catch{}try{await jb(s);const a=Je.getState(),c=cn.getState(),l=an.getState(),d=fr.getState(),u=qo.getState(),m=n.includes("all")||n.includes("providers"),f=n.includes("all")||n.includes("agents"),p=n.includes("all")||n.includes("agents"),h=n.includes("all")||n.includes("commands"),g=n.includes("all")||n.includes("skills"),x=xb(),b=o==="projects"?Lt.getState().projects:[],y=Array.from(new Set([...x?[x]:[],...b.map(C=>C.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&Je.setState({directoryScoped:{}});const v=[];for(const C of y)m&&v.push(a.loadProviders({directory:C}).then(()=>{})),f&&v.push(a.loadAgents({directory:C}).then(()=>{}));const S=[];p&&S.push(c.loadAgents().then(()=>{})),h&&S.push(l.loadCommands().then(()=>{})),g&&(S.push(d.loadSkills().then(()=>{})),S.push(u.loadCatalog().then(()=>{}))),$r("Refreshing configuration…"),await Promise.all([...v,...S])}catch{$r("OpenCode refresh failed. Please retry."),await Ya(1500)}finally{_s()}}async function Do(t){await Nb(t)}async function Ao(t){Us(t?.message||"Reloading OpenCode configuration…");try{const r=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),s=await r.json().catch(()=>null);if(!r.ok){const o=s?.error||"Failed to reload configuration";throw new Error(o)}const n={...t,scopes:t?.scopes??["all"],mode:t?.mode??"projects"};s?.requiresReload?await Do({...n,message:s.message,delayMs:s.reloadDelayMs}):await Do(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),$r("Failed to reload configuration. Please try again."),await Ya(2e3),_s(),r}}let bd=null;bd||(bd=yi(t=>{if(t.source!==Pa&&Ro(t,"agents")){const{loadAgents:r}=cn.getState();r()}}));const kb="https://models.dev/api.json",Cb="/api/openchamber/models-metadata",wd="opencode",vd="big-pickle",Mb=async()=>{try{if(ds()){const l=await zr();return{defaultModel:l?.defaultModel,defaultVariant:l?.defaultVariant,defaultAgent:l?.defaultAgent,autoCreateWorktree:l?.autoCreateWorktree,gitmojiEnabled:l?.gitmojiEnabled}}const t=Ps()?.settings;if(t)try{const d=(await t.load())?.settings;if(d){const u=typeof d?.defaultModel=="string"?d.defaultModel.trim():"",m=typeof d?.defaultVariant=="string"?d.defaultVariant.trim():"",f=typeof d?.defaultAgent=="string"?d.defaultAgent.trim():"",p=typeof d?.gitmojiEnabled=="boolean"?d.gitmojiEnabled:void 0;return{defaultModel:u.length>0?u:void 0,defaultVariant:m.length>0?m:void 0,defaultAgent:f.length>0?f:void 0,autoCreateWorktree:typeof d?.autoCreateWorktree=="boolean"?d.autoCreateWorktree:void 0,gitmojiEnabled:p}}}catch{}const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const s=await r.json(),n=typeof s?.defaultModel=="string"?s.defaultModel.trim():"",o=typeof s?.defaultVariant=="string"?s.defaultVariant.trim():"",a=typeof s?.defaultAgent=="string"?s.defaultAgent.trim():"",c=typeof s?.gitmojiEnabled=="boolean"?s.gitmojiEnabled:void 0;return{defaultModel:n.length>0?n:void 0,defaultVariant:o.length>0?o:void 0,defaultAgent:a.length>0?a:void 0,autoCreateWorktree:typeof s?.autoCreateWorktree=="boolean"?s.autoCreateWorktree:void 0,gitmojiEnabled:c}}catch{return{}}},oa=t=>{if(!t||typeof t!="string")return null;const r=t.split("/");return r.length!==2||!r[0]||!r[1]?null:{providerId:r[0],modelId:r[1]}},Db=t=>t?.toLowerCase?.()??"",Ab=t=>t==="primary"||t==="all"||t===void 0||t===null,Lo=t=>typeof t=="object"&&t!==null,Xa=t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),Eb=t=>{if(!Lo(t))return!1;const r=t;if(r.modalities){const{input:s,output:n}=r.modalities;if(s&&!Xa(s)||n&&!Xa(n))return!1}return!0},Ib=t=>{if(!Lo(t))return!1;const r=t;return r.models===void 0||Lo(r.models)},If=(t,r)=>{const s=Db(t);return!s||!r?"":`${s}/${r}`},Pb=t=>{const r=new Map;if(!Lo(t))return r;for(const[s,n]of Object.entries(t)){if(!Ib(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:s,a=n.models;if(!(!a||!Lo(a)))for(const[c,l]of Object.entries(a)){if(!Eb(l))continue;const d=typeof c=="string"&&c.length>0?c:l.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof l.id=="string"&&l.id.length>0?l.id:d,providerId:o,name:typeof l.name=="string"?l.name:void 0,tool_call:typeof l.tool_call=="boolean"?l.tool_call:void 0,reasoning:typeof l.reasoning=="boolean"?l.reasoning:void 0,temperature:typeof l.temperature=="boolean"?l.temperature:void 0,attachment:typeof l.attachment=="boolean"?l.attachment:void 0,modalities:l.modalities?{input:Xa(l.modalities.input)?l.modalities.input:void 0,output:Xa(l.modalities.output)?l.modalities.output:void 0}:void 0,cost:l.cost,limit:l.limit,knowledge:typeof l.knowledge=="string"?l.knowledge:void 0,release_date:typeof l.release_date=="string"?l.release_date:void 0,last_updated:typeof l.last_updated=="string"?l.last_updated:void 0},m=If(o,d);m&&r.set(m,u)}}return r},Tb=async()=>{if(typeof fetch!="function")return new Map;const t=[Cb,kb];for(const r of t){const s=typeof AbortController<"u"?new AbortController:void 0,n=s?setTimeout(()=>s.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),a={signal:s?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const c=await fetch(r,a);if(!c.ok)throw new Error(`Metadata request to ${r} returned status ${c.status}`);const l=await c.json();return Pb(l)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let Bi=null;const Fb=(t,r)=>{t().size>0||Bi||(Bi=Tb().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{Bi=null}))},Rb=t=>new Promise(r=>setTimeout(r,t)),bl="__global__",Yn=t=>{const r=typeof t=="string"?t.trim():"";return r.length>0?r:bl},Rn=t=>t===bl?null:t,Lb=()=>{if(typeof window>"u")return bl;const t=Oe.getDirectory()??vt.getState().currentDirectory;return Yn(t)},Je=ns()(fs(qs((t,r)=>({activeDirectoryKey:Lb(),directoryScoped:{},providers:[],agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultAgent:void 0,settingsAutoCreateWorktree:!1,settingsGitmojiEnabled:!1,activateDirectory:async s=>{const n=Yn(s);t(o=>{const a=o.directoryScoped[n];return a?{activeDirectoryKey:n,providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders}:{activeDirectoryKey:n,providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}}}),r().isConnected&&(await r().loadProviders({directory:Rn(n)}),await r().loadAgents({directory:Rn(n)}))},loadProviders:async s=>{const n=Yn(s?.directory??Rn(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),c=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let l=null;for(let d=0;d<3;d++)try{Fb(()=>r().modelsMetadata,h=>t({modelsMetadata:h}));const u=await Oe.withDirectory(Rn(n),()=>Oe.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(h=>{const g=h.models??{},x=Object.keys(g).map(b=>g[b]);return{...h,models:x}});t(h=>{const x={...h.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:p,defaultProviders:f},b={directoryScoped:{...h.directoryScoped,[n]:x}};if(h.activeDirectoryKey===n&&(b.providers=p,b.defaultProviders=f,!h.currentProviderId&&!h.currentModelId&&h.settingsDefaultModel)){const y=oa(h.settingsDefaultModel);if(y){const v=p.find(S=>S.id===y.providerId);if(v?.models.some(S=>S.id===y.modelId)){const S=v.models.find(N=>N.id===y.modelId),C=h.settingsDefaultVariant&&S?.variants?.[h.settingsDefaultVariant]?h.settingsDefaultVariant:void 0;b.currentProviderId=y.providerId,b.currentModelId=y.modelId,b.currentVariant=C,b.selectedProviderId=y.providerId,x.currentProviderId=y.providerId,x.currentModelId=y.modelId,x.currentVariant=C,x.selectedProviderId=y.providerId}}}return b});return}catch(u){l=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",l),t(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:c},f={directoryScoped:{...d.directoryScoped,[n]:m}};if(d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=c,!d.currentProviderId&&!d.currentModelId&&d.settingsDefaultModel)){const p=oa(d.settingsDefaultModel);if(p){const h=a.find(g=>g.id===p.providerId);if(h?.models.some(g=>g.id===p.modelId)){const g=h.models.find(b=>b.id===p.modelId),x=d.settingsDefaultVariant&&g?.variants?.[d.settingsDefaultVariant]?d.settingsDefaultVariant:void 0;f.currentProviderId=p.providerId,f.currentModelId=p.modelId,f.currentVariant=x,f.selectedProviderId=p.providerId,m.currentProviderId=p.providerId,m.currentModelId=p.modelId,m.currentVariant=x,m.selectedProviderId=p.providerId}}}return f})},setProvider:s=>{const{providers:n}=r(),o=n.find(l=>l.id===s);if(!o)return;const c=o.models[0]?.id||"";t(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentProviderId:s,currentModelId:c,selectedProviderId:s};return{currentProviderId:s,currentModelId:c,selectedProviderId:s,directoryScoped:{...l.directoryScoped,[d]:m}}})},setModel:s=>{t(n=>{const o=n.activeDirectoryKey,c={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentModelId:s};return{currentModelId:s,directoryScoped:{...n.directoryScoped,[o]:c}}})},setCurrentVariant:s=>{t(n=>{if(n.currentVariant===s)return n;const o=n.activeDirectoryKey,c={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentVariant:s};return{currentVariant:s,directoryScoped:{...n.directoryScoped,[o]:c}}})},getCurrentModelVariants:()=>{const n=r().getCurrentModel()?.variants;return n?Object.keys(n):[]},cycleCurrentVariant:()=>{const s=r().getCurrentModelVariants();if(s.length===0)return;const n=r().currentVariant;if(!n){r().setCurrentVariant(s[0]);return}const o=s.indexOf(n);if(o===-1||o===s.length-1){r().setCurrentVariant(void 0);return}r().setCurrentVariant(s[o+1])},setSelectedProvider:s=>{t(n=>{const o=n.activeDirectoryKey,c={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},selectedProviderId:s};return{selectedProviderId:s,directoryScoped:{...n.directoryScoped,[o]:c}}})},saveAgentModelSelection:(s,n,o)=>{t(a=>{const c=a.activeDirectoryKey,l={...a.agentModelSelections,[s]:{providerId:n,modelId:o}},u={...a.directoryScoped[c]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:l};return{agentModelSelections:l,directoryScoped:{...a.directoryScoped,[c]:u}}})},getAgentModelSelection:s=>{const{agentModelSelections:n}=r();return n[s]||null},loadAgents:async s=>{const n=Yn(s?.directory??Rn(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let c=null;for(let l=0;l<3;l++)try{const[d,u]=await Promise.all([Oe.withDirectory(Rn(n),()=>Oe.listAgents()),Mb()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(t(N=>{const D={...N.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},k={settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsGitmojiEnabled:u.gitmojiEnabled??!1,directoryScoped:{...N.directoryScoped,[n]:D}};return N.activeDirectoryKey===n&&(k.agents=m),k}),m.length===0)return t(N=>{const D={...N.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},k={directoryScoped:{...N.directoryScoped,[n]:D}};return N.activeDirectoryKey===n&&(k.currentAgentName=void 0),k}),!0;const p=(N,j)=>{const D=f.find(k=>k.id===N);return D?D.models.some(k=>k.id===j):!1},h=m.filter(N=>Ab(N.mode));let b=h.find(N=>N.name==="build")||h[0]||m[0];const y={};if(u.defaultAgent){const N=m.find(j=>j.name===u.defaultAgent);N?b=N:y.defaultAgent=""}let v,S,C;if(u.defaultModel){const N=oa(u.defaultModel);if(N&&p(N.providerId,N.modelId)){if(v=N.providerId,S=N.modelId,u.defaultVariant){const k=f.find(M=>M.id===N.providerId)?.models.find(M=>M.id===N.modelId)?.variants;k&&Object.prototype.hasOwnProperty.call(k,u.defaultVariant)?C=u.defaultVariant:y.defaultVariant=""}}else y.defaultModel=""}if(!v&&b?.model?.providerID&&b?.model?.modelID){const{providerID:N,modelID:j}=b.model;p(N,j)&&(v=N,S=j)}if(!v)if(p(wd,vd))v=wd,S=vd;else{const N=f[0],j=N?.models[0];N&&j&&(v=N.id,S=j.id)}return t(N=>{const j=N.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},D={...j,providers:f,agents:m,currentAgentName:b.name,currentProviderId:v??j.currentProviderId,currentModelId:S??j.currentModelId,currentVariant:C},k={directoryScoped:{...N.directoryScoped,[n]:D}};return N.activeDirectoryKey===n&&(k.currentAgentName=b.name,v&&S&&(k.currentProviderId=v,k.currentModelId=S,k.currentVariant=C)),k}),Object.keys(y).length>0&&(t({settingsDefaultModel:y.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultVariant:y.defaultVariant!==void 0?void 0:r().settingsDefaultVariant,settingsDefaultAgent:y.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),as(y).catch(()=>{})),!0}catch(d){c=d;const u=200*(l+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",c),t(l=>{const d=l.activeDirectoryKey===n?l.providers:l.directoryScoped[n]?.providers??[],m={...l.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...l.directoryScoped,[n]:m}};return l.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:s=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:c}=r();if(t(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentAgentName:s};return{currentAgentName:s,directoryScoped:{...l.directoryScoped,[d]:m}}}),s&&typeof window<"u"){const l=window.__zustand_session_store__;if(l){const d=l.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&l.setState(h=>{const g=new Map(h.currentAgentContext);return g.set(u,s),{currentAgentContext:g}}),u&&m(u)&&(p(u,s)||f(u,n))}}if(s&&typeof window<"u"){const l=window.__zustand_session_store__;if(l?.getState){const{currentSessionId:m,getAgentModelForSession:f}=l.getState();if(m&&f(m,s))return}if(a){const m=oa(a);if(m&&o.find(p=>p.id===m.providerId)?.models.some(p=>p.id===m.modelId)){t(p=>{const h=p.activeDirectoryKey,g=p.directoryScoped[h]??{providers:p.providers,agents:p.agents,currentProviderId:p.currentProviderId,currentModelId:p.currentModelId,currentVariant:p.currentVariant,currentAgentName:p.currentAgentName,selectedProviderId:p.selectedProviderId,agentModelSelections:p.agentModelSelections,defaultProviders:p.defaultProviders};let x;if(c){const S=o.find(C=>C.id===m.providerId)?.models.find(C=>C.id===m.modelId)?.variants;S&&Object.prototype.hasOwnProperty.call(S,c)&&(x=c)}const b={...g,currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:x};return{currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:x,directoryScoped:{...p.directoryScoped,[h]:b}}});return}}const u=n.find(m=>m.name===s)?.model;if(u?.providerID&&u?.modelID){const{providerID:m,modelID:f}=u;o.find(g=>g.id===m)?.models.find(g=>g.id===f)&&t(g=>{const x=g.activeDirectoryKey,y={...g.directoryScoped[x]??{providers:g.providers,agents:g.agents,currentProviderId:g.currentProviderId,currentModelId:g.currentModelId,currentAgentName:g.currentAgentName,selectedProviderId:g.selectedProviderId,agentModelSelections:g.agentModelSelections,defaultProviders:g.defaultProviders},currentProviderId:m,currentModelId:f,selectedProviderId:m};return{currentProviderId:m,currentModelId:f,selectedProviderId:m,directoryScoped:{...g.directoryScoped,[x]:y}}})}}},setSettingsDefaultModel:s=>{t({settingsDefaultModel:s})},setSettingsDefaultVariant:s=>{t({settingsDefaultVariant:s})},setSettingsDefaultAgent:s=>{t({settingsDefaultAgent:s})},setSettingsAutoCreateWorktree:s=>{t({settingsAutoCreateWorktree:s})},setSettingsGitmojiEnabled:s=>{t({settingsGitmojiEnabled:s})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Oe.checkHealth();return t({isConnected:a}),a}catch(a){o=a,n+=1;const c=400*n;await Rb(c)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),t({isConnected:!1}),!1},initializeApp:async()=>{try{const s=hs();s&&console.log("Starting app initialization...");const n=await r().checkConnection();if(s&&console.log("Connection check result:",n),!n){s&&console.log("Server not connected"),t({isConnected:!1});return}s&&console.log("Initializing app..."),await Oe.initApp(),s&&console.log("Loading providers..."),await r().loadProviders(),s&&console.log("Loading agents..."),await r().loadAgents(),t({isInitialized:!0,isConnected:!0}),s&&console.log("App initialized successfully")}catch(s){console.error("Failed to initialize app:",s),t({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:s,currentProviderId:n}=r();return s.find(o=>o.id===n)},getCurrentModel:()=>{const s=r().getCurrentProvider(),{currentModelId:n}=r();if(s)return s.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:s,currentAgentName:n}=r();if(n)return s.find(o=>o.name===n)},getModelMetadata:(s,n)=>{const o=If(s,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:s}=r();return Ef(s)}}),{name:"config-store",storage:Ks(()=>js()),partialize:t=>({activeDirectoryKey:t.activeDirectoryKey,directoryScoped:t.directoryScoped,currentProviderId:t.currentProviderId,currentModelId:t.currentModelId,currentVariant:t.currentVariant,currentAgentName:t.currentAgentName,selectedProviderId:t.selectedProviderId,agentModelSelections:t.agentModelSelections,defaultProviders:t.defaultProviders,settingsDefaultModel:t.settingsDefaultModel,settingsDefaultVariant:t.settingsDefaultVariant,settingsDefaultAgent:t.settingsDefaultAgent,settingsAutoCreateWorktree:t.settingsAutoCreateWorktree,settingsGitmojiEnabled:t.settingsGitmojiEnabled})})));typeof window<"u"&&(window.__zustand_config_store__=Je);let jd=null;jd||(jd=yi(async t=>{const r=[];if(Ro(t,"agents")){const{loadAgents:s}=Je.getState();r.push(s().then(()=>{}))}if(Ro(t,"providers")){const{loadProviders:s}=Je.getState();r.push(s())}r.length>0&&await Promise.all(r)}));let Sd=null;typeof window<"u"&&!Sd&&(Sd=vt.subscribe((t,r)=>{const s=Yn(t.currentDirectory),n=Yn(r.currentDirectory);s!==n&&Je.getState().activateDirectory(t.currentDirectory)}));const gn={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,HISTORICAL_MESSAGES:90,FETCH_BUFFER:20,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},$c=180,Ta=()=>{const t=Me.getState?.();return t?{...gn,HISTORICAL_MESSAGES:t.memoryLimitHistorical??gn.HISTORICAL_MESSAGES,VIEWPORT_MESSAGES:t.memoryLimitViewport??gn.VIEWPORT_MESSAGES}:gn},Gr=()=>{const t=Me.getState?.();return t?t.memoryLimitActiveSession??$c:$c},Tr=gn,Rs=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function Hr(t){const r=Rs();return r?r.checkIsGitRepository(t):sy(t)}async function Ob(t){const r=Rs();return r?r.getGitStatus(t):ry(t)}async function wl(t){const r=Rs();return r?r.getGitBranches(t):py(t)}async function Bc(t,r){const s=Rs();return s?s.deleteGitBranch(t,r):ny(t,r)}async function Nd(t,r){const s=Rs();return s?s.deleteRemoteBranch(t,r):oy(t,r)}async function _b(t,r){const s=Rs();return s?.generatePullRequestDescription?s.generatePullRequestDescription(t,r):xy(t,r)}async function Pf(t){const r=Rs();return r?r.listGitWorktrees(t):iy(t)}async function Tf(t,r){const s=Rs();return s?s.removeGitWorktree(t,r):ay(t,r)}async function $b(t,r={}){const s=Rs();return s?s.gitFetch(t,r):gy(t,r)}async function Bb(t,r,s){const n=Rs();return n?n.renameBranch(t,r,s):hy(t,r,s)}async function zb(){const t=Rs();return t?t.getGitIdentities():fy()}async function Hb(t){const r=Rs();return r?r.createGitIdentity(t):dy(t)}async function Wb(t,r){const s=Rs();return s?s.updateGitIdentity(t,r):ly(t,r)}async function Ub(t){const r=Rs();return r?r.deleteGitIdentity(t):cy(t)}async function Vb(){const t=Rs();return t?.discoverGitCredentials?t.discoverGitCredentials():uy()}async function Gb(){const t=Rs();return t?.getGlobalGitIdentity?t.getGlobalGitIdentity():my()}const qb="openchamber.json",Kb=".openchamber",Jb=[".config","openchamber"],Qb=[".config","openchamber","projects"],Yb="settings.json",zi=new Map,kd=t=>/^[A-Za-z0-9._-]+$/.test(t),Xb=t=>{let r="";for(const s of t)r+=s.toString(16).padStart(2,"0");return r},Zb=async t=>{try{if(typeof crypto>"u"||!crypto.subtle)return null;const s=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-1",s);return Xb(new Uint8Array(n))}catch{return null}};function ji(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Oo=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},no=(t,r)=>{const s=Oo(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},Ff=t=>no(no(t,Kb),qb),Ko=()=>{const t="/api";return t.startsWith("/"),t},vl=async(t,r)=>{try{const s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return s.ok?{ok:!0,data:await s.json().catch(()=>null)}:{ok:!1,data:null}}catch{return{ok:!1,data:null}}},ew=async t=>{const r=ji();if(r?.createDirectory)try{if((await r.createDirectory(t))?.success)return!0}catch{}return!!(await vl(`${Ko()}/fs/mkdir`,{path:t})).ok},Rf=async t=>{const r=ji();if(r?.readFile)try{const s=await r.readFile(t);return typeof s?.content=="string"?s.content:""}catch{return null}try{const s=await fetch(`${Ko()}/fs/read?path=${encodeURIComponent(t)}`);return s.ok?await s.text():null}catch{return null}},tw=async(t,r)=>{const s=ji();if(s?.writeFile)try{if((await s.writeFile(t,r))?.success)return!0}catch{}return!!(await vl(`${Ko()}/fs/write`,{path:t,content:r})).ok},Lf=async()=>{if(!zt()){const t=await fl().catch(()=>null);if(t&&t.trim().length>0)return Oo(t)}try{const t=await fetch(`${Ko()}/fs/home`);if(!t.ok)return null;const r=await t.json().catch(()=>null),s=typeof r?.home=="string"?r.home.trim():"";return s?Oo(s):null}catch{return null}},sw=async()=>{const t=await Lf();return t?Jb.reduce((r,s)=>no(r,s),t):null},Of=async()=>{const t=await Lf();return t?Qb.reduce((r,s)=>no(r,s),t):null},rw=async()=>{const t=await sw();return t?no(t,Yb):null},nw=async t=>{const r=typeof t?.path=="string"?t.path.trim():"",s=r?Oo(r):"",n=typeof t?.id=="string"?t.id.trim():"";if(n&&kd(n))return n;if(s){const a=zi.get(s);if(a)return a}const o=await rw();if(o&&s){const a=await Rf(o);if(a)try{const c=JSON.parse(a),l=Array.isArray(c?.projects)?c.projects:[];for(const d of l){if(!d||typeof d!="object")continue;const u=d,m=typeof u.id=="string"?u.id.trim():"",f=typeof u.path=="string"?Oo(u.path.trim()):"";if(m&&kd(m)&&f&&f===s)return zi.set(s,m),m}}catch{}}if(s){const a=await Zb(s),c=a?`path_${a}`:`path_${s.replace(/[^A-Za-z0-9._-]+/g,"_")}`;return zi.set(s,c),c}return null},_f=async t=>{const r=await Of();if(!r)return null;const s=await nw(t);return s?no(r,`${s}.json`):null};async function $f(t){const r=typeof t?.path=="string"?t.path.trim():"";if(!r)return null;const s=await _f(t),n=async l=>{const d=await Rf(l);return d===null?null:d},o=l=>{if(typeof l!="string")return null;const d=l.trim();if(!d)return null;try{const u=JSON.parse(d);return!u||typeof u!="object"?null:u}catch{return null}};if(s){const l=o(await n(s));if(l)return l}const a=Ff(r),c=o(await n(a));if(!c)return null;try{await Bf(t,c)&&await iw(r)}catch{}return c}async function Bf(t,r){if(!(typeof t?.path=="string"?t.path.trim():""))return!1;const n=await Of(),o=await _f(t);if(!n||!o)return!1;try{if(!await ew(n))return!1;const c=JSON.stringify(r,null,2);return await tw(o,c)}catch(a){return console.error("Failed to write openchamber config:",a),!1}}async function ow(t,r){const n={...await $f(t)||{},...r};return Bf(t,n)}async function go(t){return(await $f(t))?.["setup-worktree"]??[]}async function zf(t,r){const s=r.filter(n=>n.trim().length>0);return ow(t,{"setup-worktree":s})}function aw(t,r){return t.replace(/\$ROOT_PROJECT_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_PROJECT_PATH\}/g,r.rootWorktreePath).replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}async function iw(t){const r=Ff(t),s=ji();if(s?.delete)try{await s.delete(r);return}catch{}try{await vl(`${Ko()}/fs/delete`,{path:r})}catch{}}const cw=".openchamber",_o=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},lw=t=>t?t.startsWith("refs/heads/")?t.substring(11):t.startsWith("heads/")?t.substring(6):t.startsWith("refs/")?t.substring(5):t:"";async function dw(t){const{projectDirectory:r,path:s,force:n}=t,o=_o(r);await Tf(o,{path:s,force:n})}async function Si(t){const r=_o(t);return Pf(r)}async function Jo(t){const r=_o(t),s=await Ob(r);return{isDirty:!s.isClean,ahead:s.ahead,behind:s.behind,upstream:s.tracking}}function Ni(t,r){const s=_o(t),n=_o(r.worktree),o=`${s}/${cw}/`;return{source:n.startsWith(o)?"legacy":"sdk",path:n,branch:r.branch??"",label:lw(r.branch??""),projectDirectory:s,relativePath:n.startsWith(`${s}/`)?n.slice(s.length+1):n}}const uw=".openchamber",oo=t=>{const r=t.replace(/\\/g,"/");return r==="/"?"/":r.length>1?r.replace(/\/+$/,""):r},mw=(t,r)=>{const s=oo(t),n=oo(r),o=`${s}/${uw}/`;return n.startsWith(o)},fw=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80),pw=t=>{const r=t.trim();return r?`'${r.replace(/'/g,"'\\''")}'`:"''"},Hf=t=>{if(!t||typeof t!="object")return t;const r=t;return"data"in r?r.data:t},hw=t=>{const r=oo(t),s=r.split("/").filter(Boolean);return s[s.length-1]??r},gw=t=>{const r=[],s=typeof t.startPoint=="string"?t.startPoint.trim():"";s&&s!=="HEAD"&&r.push(`git reset --hard ${pw(s)}`);for(const o of t.setupCommands){const a=o.trim();a&&r.push(aw(a,{rootWorktreePath:t.projectDirectory}))}const n=r.filter(Boolean).join(" && ");return n.trim().length>0?n:void 0};async function $o(t){const r=t.path,s=Oe.getScopedApiClient(r),n=[];try{const a=await s.worktree.list(),c=Hf(a),l=Array.isArray(c)?c:[];for(const d of l){if(typeof d!="string"||d.trim().length===0)continue;const u=oo(d),m=hw(u);n.push({source:"sdk",name:m,path:u,projectDirectory:r,branch:`opencode/${m}`,label:m})}}catch{}try{const c=(await Si(r)).map(l=>Ni(r,l)).filter(l=>mw(r,l.path)).map(l=>({...l,source:"legacy"}));n.push(...c)}catch{}const o=new Map;for(const a of n){const c=oo(a.path),l=o.get(c);if(!l){o.set(c,a);continue}l.source!=="sdk"&&a.source==="sdk"&&o.set(c,a)}return Array.from(o.values()).sort((a,c)=>{const l=(a.label||a.branch||a.path).toLowerCase(),d=(c.label||c.branch||c.path).toLowerCase();return l.localeCompare(d)})}async function ki(t,r){const s=t.path,n=Oe.getScopedApiClient(s),a=(typeof r.preferredName=="string"?fw(r.preferredName):"")||void 0,c=Array.isArray(r.setupCommands)?r.setupCommands:[],l=gw({projectDirectory:s,setupCommands:c,startPoint:r.startPoint});let d=null;const u=r.allowSuffix!==!1,m=a&&u?6:1;for(let p=0;p<m;p+=1){const h=a?p===0?a:`${a}-${p+1}`:void 0;try{const g=await n.worktree.create({worktreeCreateInput:{...h?{name:h}:{},...l?{startCommand:l}:{}}}),x=Hf(g);if(!x||typeof x!="object")throw new Error("Invalid worktree.create response");const b=x,y=typeof b.name=="string"?b.name:h,v=typeof b.branch=="string"?b.branch:y?`opencode/${y}`:"",S=typeof b.directory=="string"?b.directory:"";if(!y||!S)throw new Error("Worktree create missing name/directory");return{source:"sdk",name:y,path:oo(S),projectDirectory:s,branch:v,label:y}}catch(g){d=g}}const f=d instanceof Error?d.message:"Failed to create worktree";throw new Error(f)}async function Qo(t,r,s){const n=t.path,o=!!s?.deleteRemoteBranch,a=s?.remoteName;if(r.source==="sdk"){await Oe.getScopedApiClient(n).worktree.remove({worktreeRemoveInput:{directory:r.path}});const m=(r.branch||"").replace(/^refs\/heads\//,"").trim();m&&await Bc(n,{branch:m,force:!0}).catch(()=>{}),o&&m&&await Nd(n,{branch:m,remote:a}).catch(()=>{});return}const c=!!r.status?.isDirty,l=!!(s?.force??c);await Tf(n,{path:r.path,force:l}).catch(async()=>{await dw({projectDirectory:n,path:r.path,force:!0})});const d=(r.branch||"").replace(/^refs\/heads\//,"").trim();d&&await Bc(n,{branch:d,force:!0}).catch(()=>{}),o&&d&&await Nd(n,{branch:d,remote:a}).catch(()=>{})}const Wf=js(),Uf="oc.sessionSelectionByDirectory",Cd=".openchamber",xw=()=>{try{const t=Wf.getItem(Uf);if(!t)return{};const r=JSON.parse(t);return!r||typeof r!="object"?{}:Object.entries(r).reduce((s,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(s[n]=o),s),{})}catch{return{}}};let Fa=null;const jl=()=>(Fa||(Fa=xw()),Fa),Vf=t=>{Fa=t;try{Wf.setItem(Uf,JSON.stringify(t))}catch{}},Gf=t=>{if(!t)return null;const s=jl()[t];return typeof s=="string"?s:null},Ir=(t,r)=>{if(!t)return;const s={...jl()};r?s[t]=r:delete s[t],Vf(s)},yw=(t,r)=>{if(!t)return;const s=Gf(t);if(!s)return;if(!new Set(r).has(s)){const o={...jl()};delete o[t],Vf(o)}},Md=async(t,r)=>{const s=t.status??await Jo(t.path).catch(()=>{}),n=Lt.getState().projects,o=At(t.projectDirectory)??t.projectDirectory,c={id:n.find(l=>At(l.path)===o)?.id??`path:${o}`,path:o};await Qo(c,s?{...t,status:s}:t,{deleteRemoteBranch:r?.deleteRemoteBranch,remoteName:r?.remoteName,force:!!s?.isDirty})},At=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},Dd=()=>{if(typeof window>"u")return null;const t=window.__VSCODE_CONFIG__,r=typeof t?.workspaceFolder=="string"?t.workspaceFolder:null;return At(r)},bw=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,aa=(...t)=>{hs()&&bw()&&console.log("[OpenChamber][VSCode][sessions]",...t)},qr=t=>{const r=new Map;return t.forEach(s=>{if(!s||typeof s.id!="string"||s.id.length===0)return;const n=r.get(s.id);if(!n){r.set(s.id,s);return}const o=n.time?.updated??0;(s.time?.updated??0)>o&&r.set(s.id,s)}),Array.from(r.values())},or=t=>{const r=new Map;t.forEach(s=>{const n=At(s.directory??null);if(!n)return;const o=r.get(n);o?o.push(s):r.set(n,[s])});for(const[s,n]of r.entries())r.set(s,qr(n));return r},Ln=(t,r)=>{const s=t.find(n=>n.id===r);return s?At(s.directory??null):null},ww=async(t,r,s)=>{const n=At(r);if(!n||t.length===0)return null;const o=t.map(u=>({id:u.id,directory:At(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Si(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const m=new Map(s);return o.forEach(({id:f})=>{m.delete(f)&&(u=!0)}),u?m:null}const c=new Map;a.forEach(u=>{const m=Ni(n,u),f=At(m.path)??m.path;f!==n&&c.set(f,m)});let l=!1;const d=new Map(s);return o.forEach(({id:u,directory:m})=>{const f=c.get(m);if(!f){d.delete(u)&&(l=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),l=!0)}),l?d:null},gt=ns()(fs(qs((t,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,loadSessions:async()=>{t({isLoading:!0,error:null});try{const s=vt.getState(),n=Lt.getState(),o=Oe.getApiClient(),a=Dd(),c=!!a;aa("loadSessions:start",{workspace:a,currentDirectory:s.currentDirectory,clientDirectory:Oe.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const l=new Map,d=async F=>{const z=At(F)??F,G=z,oe=l.get(G);if(oe)return oe;try{const O=await o.path.get({directory:F}),Y=At(O.data?.directory??null)??z;return l.set(G,Y),Y}catch{return l.set(G,z),z}},u=(F,z,G)=>{const oe=At(z);if(!oe)return F;const q=G?.includeDescendants===!0?`${oe}/`:null,Y=G?.includeMissingDirectory===!0;return F.filter(Z=>{const B=At(Z.directory??null);return B?!!(B===oe||q&&B.startsWith(q)):Y})},m=(F,z,G)=>{const oe=At(z);if(!oe)return F;const O=At(G??null);if(!O||O===oe)return F.map(Z=>At(Z.directory??null)?Z:{...Z,directory:oe});const q=O==="/"?"/":`${O}/`,Y=oe==="/"?"/":`${oe}/`;return F.map(Z=>{const B=At(Z.directory??null);if(!B)return{...Z,directory:oe};if(B===O)return{...Z,directory:oe};if(q!=="/"&&B.startsWith(q)){const W=B.slice(q.length);return{...Z,directory:`${Y}${W}`}}return Z})},f=async F=>{const z=At(F);if(!z)try{const B=await o.session.list(void 0);return Array.isArray(B.data)?B.data:[]}catch(B){throw console.debug("Failed to list sessions (global):",B),B}const G=await d(z),oe=async()=>{const B=await o.session.list({directory:z});return Array.isArray(B.data)?B.data:[]};let O=[],q=null,Y=!1;try{O=await oe()}catch(B){console.debug("Failed to list sessions for directory:",z,B),q=B,O=[]}if(O.length===0){Y=!0;try{const B=await o.session.list(void 0),W=Array.isArray(B.data)?B.data:[];O=u(W,G,{includeDescendants:c,includeMissingDirectory:!1})}catch(B){throw console.debug("Failed to list sessions (global fallback):",B),q||B}}const Z=u(O,G,{includeDescendants:c,includeMissingDirectory:!Y});return aa("fetchSessionsForDirectory",{requestedDirectory:z,canonicalDirectory:G,fetched:O.length,filtered:Z.length}),m(Z,z,G)},p=At(s.currentDirectory??Oe.getDirectory()??null),h=n.projects.find(F=>F.id===n.activeProjectId)??null,g=At(h?.path??null),x=g??p??null,b=n.projects.length>0?n.projects:x?[{id:"legacy",path:x}]:[];if(b.length===0){t({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}const y=await Promise.all(b.map(async F=>{const z=At(F.path);if(!z)return{projectId:F.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const G=await Hr(z).catch(()=>!1),oe=await f(z||null);aa("projectSessions",{projectId:F.id,projectPath:z,isGitRepo:G,parentSessions:oe.length});const O=[];let q=[];const Y=new Set;if(Y.add(z),G){const B=`${z}/${Cd}`;try{const W=new Set,te=await $o({id:F.id,path:z}).catch(()=>[]);q=te,te.forEach(K=>{K?.path&&W.add(At(K.path)??K.path)}),(await Oe.listLocalDirectory(z)).some(K=>K.isDirectory&&K.name===Cd)&&(await Oe.listLocalDirectory(B)).filter(L=>L.isDirectory).forEach(L=>{const ce=/^([A-Za-z]:)?\//.test(L.path)?L.path:`${B}/${L.name}`,he=At(ce)??ce;W.add(he)}),W.forEach(K=>{const L=At(K)??K;Y.add(L)}),W.size>0&&(await Promise.allSettled(Array.from(W).map(L=>f(L)))).forEach(L=>{L.status==="fulfilled"&&Array.isArray(L.value)&&O.push(...L.value)})}catch{q=[]}}const Z=qr([...oe,...O]);return{projectId:F.id,projectPath:z,sessions:Z,discoveredWorktrees:q,validPaths:Y}})),v=new Map;y.forEach(F=>{F.projectPath&&F.validPaths.forEach(z=>{const G=At(z)??z,oe=F.sessions.filter(O=>(At(O.directory??null)??G)===G);v.set(G,qr(oe))})});const S=qr(Array.from(v.values()).flat()),C=r();let N=C.worktreeMetadata;for(const F of y)if(F.projectPath)try{const z=await ww(F.sessions,F.projectPath,N);z&&(N=z)}catch(z){console.debug("Failed to refresh worktree metadata during session load:",z)}const j=new Map;y.forEach(F=>{F.projectPath&&j.set(F.projectPath,F.discoveredWorktrees)});const D=new Set;y.forEach(F=>{F.validPaths.forEach(z=>{const G=At(z)??z;G&&D.add(G)})});const k=p??g??null,M=k&&D.has(k)?k:g??k,w=M?v.get(M)??[]:S,T=new Set(S.map(F=>F.id));for(const[F,z]of v.entries())yw(F,z.map(G=>G.id));const E=(M??null)!==(C.lastLoadedDirectory??null);let I=C.currentSessionId;if((!I||!T.has(I)||E)&&(I=w[0]?.id??S[0]?.id??null),M){const F=Gf(M);F&&T.has(F)&&(I=F)}const A=(()=>{if(!I)return M??null;const F=N.get(I)?.path;if(F)return At(F)??F;const z=Ln(S,I);return z||(M??null)})();try{Oe.setDirectory(A??void 0)}catch(F){console.warn("Failed to sync OpenCode directory after session load:",F)}const P=g?y.find(F=>F.projectPath===g)?.discoveredWorktrees??[]:[];t({sessions:S,sessionsByDirectory:v,currentSessionId:I,lastLoadedDirectory:M??null,isLoading:!1,worktreeMetadata:N,availableWorktrees:P,availableWorktreesByProject:j}),M&&Ir(M,I),A&&A!==M&&Ir(A,I)}catch(s){t({error:s instanceof Error?s.message:"Failed to load sessions",isLoading:!1})}},createSession:async(s,n,o)=>{t({error:null});const a=vt.getState(),c=At(a.currentDirectory),l=Dd(),d=l??At(n??Oe.getDirectory()??c);aa("createSession:start",{title:s,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:l});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(x=>x.id)),p={id:u,title:s||"New session",parentID:o??void 0,directory:d??null,projectID:m.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(t(x=>{const b=[p,...x.sessions],y=new Map(x.sessionsByDirectory);if(d){const v=y.get(d)??[];y.set(d,qr([p,...v]))}return{sessions:b,sessionsByDirectory:y,currentSessionId:u,webUICreatedSessions:new Set([...x.webUICreatedSessions,u]),isLoading:!1}}),d)try{Oe.setDirectory(d)}catch(x){console.warn("Failed to sync OpenCode directory after session creation:",x)}const h=x=>{const b=d??null,y=b?{...x,directory:b}:x;t(v=>{const S=v.sessions.map(N=>N.id===u?y:N),C=new Map(v.sessionsByDirectory);if(d){const j=(C.get(d)??[]).map(D=>D.id===u?y:D);C.set(d,qr(j))}return{sessions:S,sessionsByDirectory:or(S),currentSessionId:y.id,webUICreatedSessions:new Set([...Array.from(v.webUICreatedSessions).filter(N=>N!==u),y.id])}}),Ir(d??null,y.id)},g=async()=>{const x=Oe.getApiClient(),b=20;for(let y=0;y<b;y+=1){try{const v=await x.session.list(d?{directory:d}:void 0),C=(Array.isArray(v.data)?v.data:[]).find(N=>!(f.has(N.id)||s&&N.title&&N.title!==s));if(C)return C}catch(v){console.debug("Session poll attempt failed:",v)}await new Promise(v=>setTimeout(v,2e3))}return null};try{const x=()=>Oe.createSession({title:s,parentID:o??void 0});let b=null;try{b=d?await Oe.withDirectory(d,x):await x()}catch(y){console.warn("Direct session create failed or timed out, falling back to polling:",y)}return b||(b=await g()),b?(h(b),b):(t(y=>({sessions:y.sessions.filter(v=>v.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(v=>v!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(x){return t(b=>({sessions:b.sessions.filter(y=>y.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(b.webUICreatedSessions).filter(y=>y!==u)),isLoading:!1,error:x instanceof Error?x.message:"Failed to create session"})),null}},deleteSession:async(s,n)=>{t({isLoading:!0,error:null});const o=r().worktreeMetadata.get(s),a=Ln(r().sessions,s),c=o?.path??a;let l=null;try{o&&n?.archiveWorktree&&(await Md(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),l=o);const d=()=>Oe.deleteSession(s);if(!(c?await Oe.withDirectory(c,d):await d()))return t(p=>{const h={isLoading:!1,error:"Failed to delete session"};if(l){const g=new Map(p.worktreeMetadata);g.delete(s),h.worktreeMetadata=g}return h}),!1;let m=null;t(p=>{const h=p.sessions.filter(y=>y.id!==s);m=p.currentSessionId===s?null:p.currentSessionId;const g=new Map(p.worktreeMetadata);g.delete(s);const x=n?.archiveWorktree&&o?p.availableWorktrees.filter(y=>At(y.path)!==At(o.path)):p.availableWorktrees,b=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const y=At(o.projectDirectory)??o.projectDirectory,v=b.get(y)??[];b.set(y,v.filter(S=>At(S.path)!==At(o.path)))}return{sessions:h,sessionsByDirectory:or(h),currentSessionId:m,isLoading:!1,worktreeMetadata:g,availableWorktrees:x,availableWorktreesByProject:b}});const f=c??Oe.getDirectory()??null;return Ir(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return t(l?m=>{const f=new Map(m.worktreeMetadata);return f.delete(s),{worktreeMetadata:f,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(s,n)=>{const o=Array.from(new Set(s.filter(b=>typeof b=="string"&&b.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||t({isLoading:!0,error:null});const c=[],l=[],d=new Set,u=[],m=new Set;for(const b of o)try{const y=r().worktreeMetadata.get(b),v=Ln(r().sessions,b),S=y?.path??v;y&&n?.archiveWorktree&&!m.has(y.path)&&(await Md(y,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(b),u.push({path:y.path,projectDirectory:y.projectDirectory}),m.add(y.path));const C=()=>Oe.deleteSession(b);(S?await Oe.withDirectory(S,C):await C())?(c.push(b),y?.path&&!u.some(j=>j.path===y.path)&&u.push({path:y.path,projectDirectory:y.projectDirectory})):l.push(b)}catch{l.push(b)}const f=vt.getState();u.forEach(({path:b,projectDirectory:y})=>{f.currentDirectory===b&&f.setDirectory(y,{showOverlay:!1})});const p=new Set(c),h=l.length>0?l.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let g=null;t(b=>{const y=b.sessions.filter(j=>!p.has(j.id));b.currentSessionId&&p.has(b.currentSessionId)?g=null:g=b.currentSessionId;const v=new Map(b.worktreeMetadata);for(const j of p)v.delete(j);for(const j of d)v.delete(j);const S=new Set(u.map(j=>At(j.path)).filter(j=>!!j)),C=S.size>0?b.availableWorktrees.filter(j=>!S.has(At(j.path)??j.path)):b.availableWorktrees,N=new Map(b.availableWorktreesByProject);return u.length>0&&u.reduce((D,k)=>{const M=At(k.projectDirectory)??k.projectDirectory,w=At(k.path)??k.path;return D.has(M)||D.set(M,new Set),D.get(M)?.add(w),D},new Map).forEach((D,k)=>{const w=(N.get(k)??[]).filter(T=>!D.has(At(T.path)??T.path));N.set(k,w)}),{sessions:y,sessionsByDirectory:or(y),currentSessionId:g,...a?{}:{isLoading:!1,error:h},worktreeMetadata:v,availableWorktrees:C,availableWorktreesByProject:N}});const x=Oe.getDirectory()??null;return Ir(x,g),{deletedIds:c,failedIds:l}},updateSessionTitle:async(s,n)=>{try{const o=Ln(r().sessions,s),a=r().worktreeMetadata.get(s),c=()=>Oe.updateSession(s,n),l=a?.path??o,d=l?await Oe.withDirectory(l,c):await c();t(u=>{const m=u.sessions.map(f=>f.id===s?d:f);return{sessions:m,sessionsByDirectory:or(m)}})}catch(o){t({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async s=>{try{const n=Ln(r().sessions,s),o=Oe.getApiClient(),c=r().worktreeMetadata.get(s)?.path??n,l=async()=>{const u=n??Oe.getDirectory();return o.session.share({sessionID:s,...u?{directory:u}:{}})},d=c?await Oe.withDirectory(c,l):await l();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:or(m)}}),d.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async s=>{try{const n=Ln(r().sessions,s),o=Oe.getApiClient(),c=r().worktreeMetadata.get(s)?.path??n,l=async()=>{const u=n??Oe.getDirectory();return o.session.unshare({sessionID:s,...u?{directory:u}:{}})},d=c?await Oe.withDirectory(c,l):await l();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:or(m)}}),d.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:s=>{t({currentSessionId:s,error:null});const n=Oe.getDirectory()??null;Ir(n,s)},clearError:()=>{t({error:null})},getSessionsByDirectory:s=>{const n=At(s)??s,{sessionsByDirectory:o,sessions:a}=r(),c=o.get(n);return c||a.filter(l=>(At(l.directory??null)??n)===n)},getDirectoryForSession:s=>{if(!s)return null;const n=r().worktreeMetadata.get(s);if(n?.path)return At(n.path)??n.path;const o=r().sessions.find(c=>c.id===s);return At(o?.directory??null)},applySessionMetadata:(s,n)=>{!s||!n||t(o=>{const a=o.sessions.findIndex(h=>h.id===s);if(a===-1)return o;const c=o.sessions[a],l=n.time?{...c.time,...n.time}:c.time,d=n.summary===void 0?c.summary:n.summary||void 0,u=n.share===void 0?c.share:n.share||void 0,m={...c,...n,time:l,summary:d,share:u},f=m.title!==c.title||m.parentID!==c.parentID||m.directory!==c.directory||m.version!==c.version||m.projectID!==c.projectID||JSON.stringify(m.time)!==JSON.stringify(c.time)||JSON.stringify(m.summary??null)!==JSON.stringify(c.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(c.share??null),p=[...o.sessions];return p[a]=f?m:c,{sessions:p,sessionsByDirectory:or(p)}})},isOpenChamberCreatedSession:s=>{const{webUICreatedSessions:n}=r();return n.has(s)},markSessionAsOpenChamberCreated:s=>{t(n=>{const o=new Set(n.webUICreatedSessions);return o.add(s),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:s=>{const{markSessionAsOpenChamberCreated:n}=r();n(s)},setWorktreeMetadata:(s,n)=>{s&&t(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(s,n):a.delete(s),{worktreeMetadata:a}})},getWorktreeMetadata:s=>{if(s)return r().worktreeMetadata.get(s)},setSessionDirectory:(s,n)=>{if(!s)return;const o=r().sessions,a=o.findIndex(u=>u.id===s);if(a===-1)return;const l=o[a].directory??null,d=n??void 0;l!==(d??null)&&(t(u=>{const m=[...u.sessions],f={...m[a]};return d!==void 0?f.directory=d:delete f.directory,m[a]=f,{sessions:m,sessionsByDirectory:or(m)}}),l&&Ir(l,null),n&&Ir(n,s))},updateSession:s=>{t(n=>{const a=n.sessions.findIndex(l=>l.id===s.id)===-1?[s,...n.sessions]:n.sessions.map(l=>l.id===s.id?s:l),c=qr(a);return{sessions:c,sessionsByDirectory:or(c)}})},removeSessionFromStore:s=>{s&&t(n=>{const o=n.sessions.find(u=>u.id===s),a=At(o?.directory??null),c=n.sessions.filter(u=>u.id!==s);if(c.length===n.sessions.length)return n;const l=new Map(n.worktreeMetadata);l.delete(s);const d=n.currentSessionId===s?null:n.currentSessionId;return a&&Ir(a,null),{sessions:c,sessionsByDirectory:or(c),currentSessionId:d,worktreeMetadata:l}})}}),{name:"session-store",storage:Ks(()=>js()),partialize:t=>({currentSessionId:t.currentSessionId,sessions:t.sessions,lastLoadedDirectory:t.lastLoadedDirectory,webUICreatedSessions:Array.from(t.webUICreatedSessions),worktreeMetadata:Array.from(t.worktreeMetadata.entries()),availableWorktrees:t.availableWorktrees,availableWorktreesByProject:Array.from(t.availableWorktreesByProject.entries())}),merge:(t,r)=>{if(!(p=>typeof p=="object"&&p!==null)(t))return r;const n=Array.isArray(t.sessions)?t.sessions:r.sessions,o=typeof t.currentSessionId=="string"||t.currentSessionId===null?t.currentSessionId:r.currentSessionId,a=Array.isArray(t.webUICreatedSessions)?t.webUICreatedSessions:[],c=Array.isArray(t.worktreeMetadata)?t.worktreeMetadata:[],l=Array.isArray(t.availableWorktrees)?t.availableWorktrees:r.availableWorktrees,d=Array.isArray(t.availableWorktreesByProject)?t.availableWorktreesByProject:[],u=new Map(d),m=typeof t.lastLoadedDirectory=="string"?t.lastLoadedDirectory:r.lastLoadedDirectory??null,f=qr(n);return{...r,...t,sessions:f,sessionsByDirectory:or(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(c),availableWorktrees:l,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),qf="This message comes from an AI assistant in another session. The user wants you to respond according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed. Always clearly state what you understand your task to be, and wait for the user's approval of your conclusions before taking any further actions.",vw="This message bellow comes from an AI agent in another session. I want you to act according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed; if it is a bug description, find the root cause and fix it. Proceed with actions right away based on your understanding of the task. Here is the content of the message: ",Hi=t=>typeof t=="string"&&t.trim()===qf.trim(),Wi=(t,r)=>{const s=Date.now(),n=t.get(r),o=new Map(t);return o.set(r,{phase:"streaming",startedAt:n?.startedAt??s,lastUpdateAt:s}),o},bo=(t,r)=>{const s=Array.from(r);if(!s.some(a=>t.has(a)))return t;const o=new Map(t);return s.forEach(a=>{o.delete(a)}),o},Ad=new Map,Kf=t=>{const r=Ad.get(t);r&&(clearTimeout(r),Ad.delete(t))},ln=t=>{for(const r of t)Kf(r)},Bo=t=>{if(!t)return"";if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>Bo(r)).join("");if(typeof t=="object"){if(typeof t.text=="string")return t.text;if(Array.isArray(t.content))return t.content.map(r=>Bo(r)).join("")}return""},Wn=t=>{if(!t)return"";const r=t;if(typeof r.text=="string")return r.text;if(Array.isArray(r.text))return r.text.map(n=>typeof n=="string"?n:Wn(n)).join("");const s=Bo(r.delta);return s||(typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||Bo(o.delta)||""}return""}).join(""):"")},wo=(t,r)=>{const s={...t};if(s.type=s.type||"text",s.type==="text"){const n=r&&typeof r.text=="string"?r.text:"",o=typeof s.text=="string"?s.text:"",a=Bo(t.delta);o?s.text=o:a?s.text=n?`${n}${a}`:a:n?s.text=n:s.text="",delete s.delta}return s},Ed=50*1024*1024,jw=t=>{const r=(t||"").toLowerCase();switch(r.includes(".")&&r.split(".").pop()||""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";case"bmp":return"image/bmp";case"ico":return"image/x-icon";case"pdf":return"application/pdf";default:return"text/plain"}},Sw=t=>{if(t.type&&t.type.trim().length>0)return t.type;const r=(t.name||"").toLowerCase(),s=r.includes(".")&&r.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying"]).has(r))return"text/plain";switch(s){case"md":case"markdown":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"yaml":case"yml":return"application/x-yaml";case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"sh":case"bash":case"zsh":return"text/plain";default:return"application/octet-stream"}},Nw=t=>{const r=t.replace(/\s+/g,"");if(!r)return 0;const s=r.endsWith("==")?2:r.endsWith("=")?1:0;return Math.floor(r.length*3/4)-s},kw=t=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let s="";for(let n=0;n<t.length;n+=3){const o=t[n]??0,a=t[n+1],c=t[n+2],l=o<<16|(a??0)<<8|(c??0);s+=r[l>>18&63],s+=r[l>>12&63],s+=typeof a=="number"?r[l>>6&63]:"=",s+=typeof c=="number"?r[l&63]:"="}return s},pr=ns()(fs(qs((t,r)=>({attachedFiles:[],addAttachedFile:async s=>{const{attachedFiles:n}=r();if(n.some(g=>g.filename===s.name&&g.size===s.size)){console.log(`File "${s.name}" is already attached`);return}const a=Ed;if(s.size>a)throw new Error(`File "${s.name}" is too large. Maximum size is 50MB.`);const c=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],l=Sw(s);!c.some(g=>l.startsWith(g)||l===g||l==="")&&l!==""&&console.warn(`File type "${l}" might not be supported`);const u=new FileReader,m=await new Promise((g,x)=>{u.onload=()=>g(u.result),u.onerror=x,u.readAsDataURL(s)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${l}`):m,p=g=>{const x=g.replace(/\\/g,"/").split("/");return x[x.length-1]||g},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:s,dataUrl:f,mimeType:l,filename:p(s.name),size:s.size,source:"local"};t(g=>({attachedFiles:[...g.attachedFiles,h]}))},addServerFile:async(s,n,o)=>{const{attachedFiles:a}=r();if(a.some(y=>y.serverPath===s&&y.source==="server")){console.log(`Server file "${n}" is already attached`);return}let l=o,d,u;if(!l)try{const y=Oe.getApiClient(),v=s.lastIndexOf("/"),S=v>0?s.substring(0,v):"/",C=v>0?s.substring(v+1):s,N=await y.file.read({path:C,directory:S});N.data&&"content"in N.data?(l=N.data.content,d=N.data.encoding??void 0,u=N.data.mimeType??void 0):l=""}catch(y){console.error("Failed to read server file:",y),l=`[File: ${n}]`}const m=u||jw(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return l||"";const v=new TextEncoder().encode(l||"");return kw(v)})(),h=d==="base64"?Nw(p):new TextEncoder().encode(l||"").length;if(h>Ed)throw new Error(`File "${n}" is too large. Maximum size is 50MB.`);const g=new File([],n,{type:f}),x=`data:${f};base64,${p}`,b={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:g,dataUrl:x,mimeType:f,filename:n,size:h,source:"server",serverPath:s};t(y=>({attachedFiles:[...y.attachedFiles,b]}))},removeAttachedFile:s=>{t(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==s)}))},clearAttachedFiles:()=>{t({attachedFiles:[]})}}),{name:"file-store",storage:Ks(()=>js()),partialize:t=>({attachedFiles:t.attachedFiles})}),{name:"file-store"})),Cw=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Mw=t=>t?Cw.has(t.toLowerCase()):!1,Dw=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Aw=t=>{if(t)try{const r=Dw();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===t)}catch{}},Ew=(t,r)=>{if(!t||t.length===0)return"ask";for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.permission===r&&n.pattern==="*")return n.action}for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.permission==="*"&&n.pattern==="*")return n.action}return"ask"},Ra=t=>{const r=Aw(t);return r?Ew(r.permission,"edit"):"ask"},Id=t=>{if(!t||typeof t!="object")return 0;const r=t.input??0,s=t.output??0,n=t.reasoning??0,o=t.cache&&typeof t.cache=="object"?t.cache.read??0:0,a=t.cache&&typeof t.cache=="object"?t.cache.write??0:0;return r+s+n+o+a},Ui=t=>{const r=t.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return Id(r);const s=t.parts.find(n=>typeof n.tokens<"u");return!s||typeof s.tokens>"u"?0:typeof s.tokens=="number"?s.tokens:Id(s.tokens)},Vi=(t,r,s)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(s)&&s>0,a=o?Math.max(s,0):0,c=Math.min(o?a:32e3,32e3),l=Math.min(c,n),d=n>0?Math.max(n-l,1):0,u=d>0?t/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:l}},vo=["ask","allow","full"],Pd="__global__",Ye=ns()(fs(qs((t,r)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(s,n,o)=>{t(a=>{const c=new Map(a.sessionModelSelections);return c.set(s,{providerId:n,modelId:o}),{sessionModelSelections:c}})},getSessionModelSelection:s=>{const{sessionModelSelections:n}=r();return n.get(s)||null},saveSessionAgentSelection:(s,n)=>{t(o=>{const a=new Map(o.sessionAgentSelections);a.set(s,n);const c=new Map(o.currentAgentContext);return c.set(s,n),{sessionAgentSelections:a,currentAgentContext:c}})},getSessionAgentSelection:s=>{const{sessionAgentSelections:n}=r();return n.get(s)||null},saveAgentModelForSession:(s,n,o,a)=>{t(c=>{const l=new Map(c.sessionAgentModelSelections);let d=l.get(s);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),l.set(s,d),{sessionAgentModelSelections:l}})},getAgentModelForSession:(s,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(s);return a&&a.get(n)||null},saveAgentModelVariantForSession:(s,n,o,a,c)=>{t(l=>{const d=new Map(l.sessionAgentModelVariantSelections);let u=d.get(s);u?u=new Map(u):u=new Map;let m=u.get(n);m?m=new Map(m):m=new Map;const f=`${o}/${a}`;return c===void 0?(m.delete(f),m.size===0?(u.delete(n),u.size===0?d.delete(s):d.set(s,u)):(u.set(n,m),d.set(s,u))):(m.set(f,c),u.set(n,m),d.set(s,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(s,n,o,a)=>{const{sessionAgentModelVariantSelections:c}=r(),l=c.get(s);if(!l)return;const d=l.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(s,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:c}=r(),l=new Map,d=(g,x)=>{if("mode"in g&&g.mode&&typeof g.mode=="string"&&n.find(S=>S.name===g.mode))return g.mode;if("agent"in g&&g.agent&&typeof g.agent=="string"&&n.find(S=>S.name===g.agent))return g.agent;if(g.providerID&&g.modelID){const v=n.find(S=>S.model?.providerID===g.providerID&&S.model?.modelID===g.modelID);if(v)return v.name}const{currentAgentContext:b}=r(),y=b.get(s);if(y&&n.find(v=>v.name===y))return y;if(x>0&&g.providerID&&g.modelID){const S=(o.get(s)||[]).filter(C=>C.info.role==="assistant").sort((C,N)=>C.info.time.created-N.info.time.created);for(let C=x-1;C>=0;C--){const j=S[C].info;if(j.providerID===g.providerID&&j.modelID===g.modelID){if(j.mode&&typeof j.mode=="string"&&n.find(M=>M.name===j.mode))return j.mode;const D=n.find(k=>k.model?.providerID===j.providerID&&k.model?.modelID===j.modelID);if(D)return D.name}}}return g.providerID&&g.modelID&&n.find(S=>S.name==="build")?"build":null},u=o.get(s)||[],m=u.filter(g=>g.info.role==="assistant"||g.info.role==="user").sort((g,x)=>g.info.time.created-x.info.time.created),f=u.filter(g=>g.info.role==="assistant").sort((g,x)=>g.info.time.created-x.info.time.created);let p,h;for(let g=0;g<m.length;g++){const x=m[g],{info:b}=x,y=b;if(y.role==="user"){const v=typeof y.mode=="string"&&y.mode.trim().length>0?y.mode:typeof y.agent=="string"&&y.agent.trim().length>0?y.agent:void 0,S=typeof y.model?.providerID=="string"&&y.model.providerID.trim().length>0?y.model.providerID:typeof y.providerID=="string"&&y.providerID.trim().length>0?y.providerID:void 0,C=typeof y.model?.modelID=="string"&&y.model.modelID.trim().length>0?y.model.modelID:typeof y.modelID=="string"&&y.modelID.trim().length>0?y.modelID:void 0;if(v&&S&&C&&n.find(N=>N.name===v)){const N={providerId:S,modelId:C,timestamp:b.time.created},j=l.get(v);(!j||N.timestamp>j.timestamp)&&l.set(v,N),typeof y.variant=="string"&&y.variant.trim().length>0&&c(s,v,S,C,y.variant)}p=typeof y.variant=="string"&&y.variant.trim().length>0?y.variant:void 0,h=y.model?.providerID&&y.model?.modelID?{providerID:y.model.providerID,modelID:y.model.modelID}:void 0;continue}if(y.providerID&&y.modelID){const v=d(y,f.indexOf(x));if(v&&n.find(S=>S.name===v)){p&&h&&h.providerID===y.providerID&&h.modelID===y.modelID&&c(s,v,y.providerID,y.modelID,p);const S={providerId:y.providerID,modelId:y.modelID,timestamp:b.time.created},C=l.get(v);(!C||S.timestamp>C.timestamp)&&l.set(v,S)}}p=void 0,h=void 0}for(const[g,x]of l)a(s,g,x.providerId,x.modelId);return l},getContextUsage:(s,n,o,a)=>{if(!s)return null;const c=Vi(0,n,o),l=c.contextLimit,d=c.normalizedOutput??0,u=c.thresholdLimit;if(l===0||u===0)return null;const f=(a.get(s)||[]).filter(S=>S.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],h=p.info.id,g=S=>{const C=()=>{t(N=>{const j=N.sessionContextUsage.get(s);if(j&&j.totalTokens===S.totalTokens&&j.percentage===S.percentage&&j.contextLimit===S.contextLimit&&(j.outputLimit??0)===(S.outputLimit??0)&&(j.normalizedOutput??0)===(S.normalizedOutput??0)&&j.thresholdLimit===S.thresholdLimit&&j.lastMessageId===S.lastMessageId)return N;const D=new Map(N.sessionContextUsage);return D.set(s,S),{sessionContextUsage:D}})};typeof queueMicrotask=="function"?queueMicrotask(C):typeof window<"u"?window.setTimeout(C,0):setTimeout(C,0)},x=r().sessionContextUsage.get(s);if(x&&x.lastMessageId===h){const S=x.normalizedOutput??x.outputLimit??0,C=x.contextLimit!==l||S!==d||x.thresholdLimit!==u;if(C&&x.totalTokens>0){const N=x.totalTokens/u*100,j={totalTokens:x.totalTokens,percentage:Math.min(N,100),contextLimit:l,outputLimit:c.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return g(j),j}if(!C&&x.totalTokens>0)return x}const b=Ui(p);if(b===0)return x||null;const y=Vi(b,n,o),v={totalTokens:b,percentage:y.percentage,contextLimit:y.contextLimit,outputLimit:y.outputLimit,normalizedOutput:y.normalizedOutput,thresholdLimit:y.thresholdLimit,lastMessageId:h};return g(v),v},updateSessionContextUsage:(s,n,o,a)=>{const l=(a.get(s)||[]).filter(f=>f.info.role==="assistant");if(l.length===0)return;const d=l[l.length-1],u=Ui(d);if(u===0)return;const m=Vi(u,n,o);t(f=>{const p=new Map(f.sessionContextUsage);return p.set(s,{totalTokens:u,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit,normalizedOutput:m.normalizedOutput,thresholdLimit:m.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(s,n,o,a)=>{const l=r().sessionContextUsage.get(s);(!l||l.totalTokens===0)&&r().updateSessionContextUsage(s,n,o,a)},pollForTokenUpdates:(s,n,o,a=10)=>{let c=0;const l=()=>{c++;const u=(o.get(s)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&Ui(u)>0){r().updateSessionContextUsage(s,0,0,o);return}c<a&&setTimeout(l,1e3)};setTimeout(l,2e3)},getCurrentAgent:s=>{const{currentAgentContext:n}=r();return n.get(s)},getSessionAgentEditMode:(s,n,o=Ra(n))=>{if(!s||!n)return o;const c=r().sessionAgentEditModes.get(s)?.get(n);if(c!==void 0)return c;if(s!==Pd){const d=r().sessionAgentEditModes.get(Pd)?.get(n);if(d!==void 0)return d}return o},setSessionAgentEditMode:(s,n,o,a=Ra(n))=>{if(!s||!n)return;const c=a??"ask";c==="deny"||o==="deny"||vo.includes(o)&&t(l=>{const d=new Map(l.sessionAgentEditModes),u=new Map(d.get(s)??new Map);return o===c?(u.delete(n),u.size===0?d.delete(s):d.set(s,u)):(u.set(n,o),d.set(s,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(s,n,o=Ra(n))=>{if(!s||!n)return;const a=o??"ask";if(a==="deny")return;const c=r().getSessionAgentEditMode(s,n,a),l=vo.indexOf(c),d=vo.indexOf(a),m=((l>=0?l:d>=0?d:0)+1)%vo.length,f=vo[m];r().setSessionAgentEditMode(s,n,f,a)}}),{name:"context-store",storage:Ks(()=>js()),partialize:t=>({sessionModelSelections:Array.from(t.sessionModelSelections.entries()),sessionAgentSelections:Array.from(t.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(t.sessionAgentModelSelections.entries()).map(([r,s])=>[r,Array.from(s.entries())]),sessionAgentModelVariantSelections:Array.from(t.sessionAgentModelVariantSelections.entries()).map(([r,s])=>[r,Array.from(s.entries()).map(([n,o])=>[n,Array.from(o.entries())])]),currentAgentContext:Array.from(t.currentAgentContext.entries()),sessionContextUsage:Array.from(t.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(t.sessionAgentEditModes.entries()).map(([r,s])=>[r,Array.from(s.entries())])}),merge:(t,r)=>{const s=new Map;t?.sessionAgentModelSelections&&t.sessionAgentModelSelections.forEach(([a,c])=>{s.set(a,new Map(c))});const n=new Map;t?.sessionAgentModelVariantSelections&&t.sessionAgentModelVariantSelections.forEach(([a,c])=>{const l=new Map;c.forEach(([d,u])=>{l.set(d,new Map(u))}),n.set(a,l)});const o=new Map;return t?.sessionAgentEditModes&&t.sessionAgentEditModes.forEach(([a,c])=>{o.set(a,new Map(c))}),{...r,...t,sessionModelSelections:new Map(t?.sessionModelSelections||[]),sessionAgentSelections:new Map(t?.sessionAgentSelections||[]),sessionAgentModelSelections:s,sessionAgentModelVariantSelections:n,currentAgentContext:new Map(t?.currentAgentContext||[]),sessionContextUsage:new Map(t?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),Td=(t,r)=>{const s=new Map(t);return s.delete(r),s};let Gi=[],qi=null;const Iw=50,Pw=3e4,dn=new Map,ia=new Map,On=new Map,Tw=10,Za=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.indexOf("_"),n=s>=0?r.slice(s+1):r;return!n||n.length<Tw?null:n},ca=(t,r)=>{const s=Za(t),n=Za(r);return!s||!n||s.length!==n.length?!0:s>n},Fw=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},qn=t=>!Array.isArray(t)||t.length===0?0:t.reduce((r,s)=>{if(!s||s.type!=="text")return r;const n=s.text??s.content;return typeof n=="string"?r+n.length:r},0),ei=t=>t?.finish==="stop",Fd=t=>{if(t){if(typeof t.id=="string"&&t.id.length>0)return t.id;if(t.type){const r=t.reason,s=t.callID;return`${t.type}-${r??""}-${s??""}`}}},Rd=new Set,ti=(t=[],r=[])=>{if(!r.length)return[...t];const s=[...t],n=new Set(t.map(Fd).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=Fd(o);a&&n.has(a)||(s.push(o),a&&n.add(a))}),s},Rw=(t,r)=>{const s=Array.isArray(t.parts)?t.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=qn(s),a=qn(n),c=ei(t.info),l=ei(r.info);let d=n;return c&&o>=a?d=ti(s,n):l&&a>=o?d=ti(n,s):o>=a&&(d=s),{...r,info:{...t.info,...r.info},parts:d}},la=t=>{const r=[],s=new Map;for(const n of t){const o=typeof n?.info?.id=="string"?n.info.id:null;if(!o){r.push(n);continue}const a=s.get(o);if(a===void 0){s.set(o,r.length),r.push(n);continue}r[a]=Rw(r[a],n)}return r},Lw=(t,r)=>{let s=r,n=r?Za(r):null;for(const o of t){const a=o?.info?.id,c=Za(a);!a||!c||(!n||c>n)&&(n=c,s=a)}return s},xr=(t,r,s)=>{if(t.get(r)===s)return t;const o=new Map(t);return s?o.set(r,s):o.delete(r),o},_n=(t,r,s)=>{if(t.get(r)===s)return t;const o=new Map(t);return o.set(r,s),o},da=(t,r)=>{const s=new Map(t);let n=!1;for(const o of r)s.delete(o)&&(n=!0);return n?s:t},Ow=(t,r)=>{const s=new Set,n=t.streamingMessageIds.get(r);return n&&s.add(n),t.messageStreamStates.forEach((o,a)=>{t.messageSessionIndex.get(a)===r&&s.add(a)}),s},Ld=(t,r,s)=>t.streamingMessageIds.get(r)===s?!0:t.messageSessionIndex.get(s)===r&&t.messageStreamStates.has(s),_w=async t=>{if(t)try{return gt.getState().getDirectoryForSession(t)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},Od=t=>{if(!t)return null;try{return gt.getState().sessions.find(n=>n.id===t)?.revert?.messageID??null}catch{return null}},_d=(t,r)=>{if(!r)return t;const s=t.findIndex(n=>n.info.id===r);return s===-1?t:t.slice(0,s)},Ki=async(t,r)=>{const s=await _w(t);return s?Oe.withDirectory(s,r):r()},Nt=ns()(fs(qs((t,r)=>({messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,messageSessionIndex:new Map,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,pendingAssistantParts:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,pendingAssistantHeaderSessions:new Set,pendingUserMessageMetaBySession:new Map,loadMessages:async(s,n)=>{const o=Ta(),a=n===1/0,c=a?1/0:n??o.HISTORICAL_MESSAGES,l=r().sessionMemoryState.get(s)?.isStreaming,d=l?o.VIEWPORT_MESSAGES:c,u=l||a?void 0:d+o.FETCH_BUFFER,m=await Ki(s,()=>Oe.getSessionMessages(s,u)),f=Od(s),p=_d(m,f),h=p.length>d,g=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,b=(g?p.filter(y=>{const v=y?.info?.id;return v?ca(v,g):!0}):p).slice(-d);t(y=>{const v=new Map(y.messages),S=y.messages.get(s)||[],C=new Map(S.filter(F=>typeof F.info?.id=="string").map(F=>[F.info.id,F])),N=b.map(F=>{const z={...F.info,clientRole:F.info?.clientRole??F.info.role,userMessageMarker:F.info.role==="user"?!0:F.info?.userMessageMarker},G=(Array.isArray(F.parts)?F.parts:[]).map(O=>{if(O?.type==="text"){const q=O.text??O.content??"";if(Hi(q))return{...O,synthetic:!0}}return O}),oe=z?.id?C.get(z.id):void 0;if(oe&&oe.info.role==="assistant"){const O=Array.isArray(oe.parts)?oe.parts:[],q=qn(O),Y=qn(G);if(ei(oe.info)&&q>Y){const B=ti(O,G);return{...F,info:z,parts:B}}}return{...F,info:z,parts:G}}),j=la(N),D=new Set(S.map(F=>F.info.id)),k=new Set(j.map(F=>F.info.id)),M=[];D.forEach(F=>{k.has(F)||M.push(F)}),v.set(s,j);const w=new Map(y.sessionMemoryState),T=y.sessionMemoryState.get(s);w.set(s,{...T,viewportAnchor:j.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:T?.totalAvailableMessages,hasMoreAbove:h,trimmedHeadMaxId:T?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const E={messages:v,sessionMemoryState:w};ln(M);const I=bo(y.messageStreamStates,M);if(I!==y.messageStreamStates&&(E.messageStreamStates=I),M.length>0){const F=y.streamingMessageIds.get(s);F&&M.includes(F)&&(E.streamingMessageIds=xr(E.streamingMessageIds??y.streamingMessageIds,s,null))}if(M.length>0){const F=da(E.messageSessionIndex??y.messageSessionIndex,M);F!==(E.messageSessionIndex??y.messageSessionIndex)&&(E.messageSessionIndex=F)}if(M.length>0){const F=new Map(y.pendingAssistantParts);let z=!1;M.forEach(G=>{F.delete(G)&&(z=!0)}),z&&(E.pendingAssistantParts=F)}const A=E.messageSessionIndex??y.messageSessionIndex;let P=A;return j.forEach(F=>{const z=F?.info?.id;typeof z=="string"&&z.length>0&&(P=_n(P,z,s))}),P!==A&&(E.messageSessionIndex=P),E})},sendMessage:async(s,n,o,a,c,l,d,u,m)=>{if(!c)throw new Error("No session selected");const f=c;r().sessionAbortFlags.has(f)&&t(p=>{const h=new Map(p.sessionAbortFlags);return h.delete(f),{sessionAbortFlags:h}}),await Ki(f,async()=>{try{let p=s;if(s.startsWith("/")){const g=s.indexOf(" "),x=g===-1?s.substring(1):s.substring(1,g),b=g===-1?"":s.substring(g+1).trim(),y=Oe.getApiClient(),v=Oe.getDirectory();if(x==="init"){const S=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await y.session.init({sessionID:f,...v?{directory:v}:{},messageID:S,providerID:n,modelID:o});return}if(x==="summarize"){await y.session.summarize({sessionID:f,...v?{directory:v}:{},providerID:n,modelID:o});return}try{const S=await Oe.getCommandDetails(x);S?.template?p=S.template.replace(/\$ARGUMENTS/g,b):p=s}catch(S){console.error("Command template resolution failed:",S),p=s}}t({lastUsedProvider:{providerID:n,modelID:o}}),t(g=>{const x=g.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},b=On.get(f);b&&(clearTimeout(b),On.delete(f));const y=new Map(g.sessionMemoryState);return y.set(f,{...x,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:y}});try{const g=new AbortController;t(y=>{const v=new Map(y.abortControllers);return v.set(f,g),{abortControllers:v}});const x=(l??[]).map(y=>({type:"file",mime:y.mimeType,filename:y.filename,url:y.dataUrl}));t(y=>{const v=new Set(y.pendingAssistantHeaderSessions);v.add(f);const S=new Map(y.pendingUserMessageMetaBySession);return S.set(f,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o,variant:typeof m=="string"&&m.trim().length>0?m:void 0}),{pendingAssistantHeaderSessions:v,pendingUserMessageMetaBySession:S}});const b=u?.map(y=>({text:y.text,synthetic:y.synthetic,files:y.attachments?.map(v=>({type:"file",mime:v.mimeType,filename:v.filename,url:v.dataUrl}))}));if(await Oe.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:x.length>0?x:void 0,additionalParts:b&&b.length>0?b:void 0,agentMentions:d?[{name:d}]:void 0}),x.length>0)try{pr.getState().clearAttachedFiles()}catch(y){console.error("Failed to clear attached files after send",y)}t(y=>{const v=new Map(y.abortControllers);return v.delete(f),{abortControllers:v}})}catch(g){let x="Network error while sending message. The message may still be processing.";if(g.name==="AbortError")x="Request timed out. The message may still be processing.";else if(g.message?.includes("504")||g.message?.includes("Gateway")){x="Gateway timeout - your message is being processed. Please wait for response.",t(b=>{const y=new Map(b.abortControllers);return y.delete(f),{abortControllers:y}});return}else g.message&&(x=g.message);throw t(b=>{const y=new Map(b.abortControllers);y.delete(f);const v=new Set(b.pendingAssistantHeaderSessions);v.delete(f);const S=new Map(b.pendingUserMessageMetaBySession);return S.delete(f),{abortControllers:y,pendingAssistantHeaderSessions:v,pendingUserMessageMetaBySession:S}}),new Error(x)}}catch(p){let h="Network error while sending message. The message may still be processing.";throw p.name==="AbortError"?h="Request timed out. The message may still be processing.":p.response?.status===401?h="Session not found or unauthorized. Please refresh the page.":p.response?.status===502?h="OpenCode is restarting. Please wait a moment and try again.":p.message?.includes("504")||p.message?.includes("Gateway")?h="Gateway timeout - your message is being processed. Please wait for response.":p.message&&(h=p.message),t(g=>{const x=new Map(g.abortControllers);x.delete(f);const b=new Set(g.pendingAssistantHeaderSessions);b.delete(f);const y=new Map(g.pendingUserMessageMetaBySession);return y.delete(f),{abortControllers:x,pendingAssistantHeaderSessions:b,pendingUserMessageMetaBySession:y}}),new Error(h)}})},abortCurrentOperation:async s=>{if(!s)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(s)?.abort();const l=Ow(n,s);if(l.size===0){const u=s?a.get(s)??[]:[];let m=null;for(let f=u.length-1;f>=0;f-=1){const p=u[f];if(!p||p.info.role!=="assistant")continue;if(m||(m=p.info.id),(p.parts??[]).some(g=>g.type==="reasoning"||g.type==="tool"||g.type==="step-start")){l.add(p.info.id);break}}l.size===0&&m&&l.add(m)}for(const u of l){const m=dn.get(u);m&&(clearTimeout(m),dn.delete(u),ia.delete(u))}l.size>0&&ln(l);const d=Date.now();t(u=>{const m=bo(u.messageStreamStates,l),f=u.messages.get(s)??[];let p=!1,h=u.messages;if(f.length>0&&l.size>0){const y=f.map(v=>{if(!l.has(v.info.id)&&l.size>0)return v;const S=(v.parts??[]).map(C=>{if(C.type==="reasoning"){const N=C,j={...N.time??{}};return typeof j.end!="number"&&(j.end=d),{...N,time:j}}if(C.type==="tool"){const N=C,j={...N.state??{}};return(j.status==="running"||j.status==="pending")&&(j.status="aborted"),{...N,state:j}}return C.type==="step-start"?{...C,type:"step-finish",aborted:!0}:C});return p=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:S}});p&&(h=new Map(u.messages),h.set(s,y))}const g=u.sessionMemoryState.get(s);let x=u.sessionMemoryState;if(g){const y=new Map(u.sessionMemoryState);y.set(s,{...g,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),x=y}const b=new Map(u.sessionAbortFlags);return b.set(s,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:x,sessionAbortFlags:b,abortControllers:(()=>{const y=new Map(u.abortControllers);return y.delete(s),y})(),streamingMessageIds:xr(u.streamingMessageIds,s,null),...p?{messages:h}:{}}}),Oe.abortSession(s).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(s,n,o,a,c)=>{const l=r();if(Rd.has(n))return;const d=l.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!ca(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=l.messages.get(s)||[],m=u.find(h=>h.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",p=r().sessionMemoryState.get(s);if(p?.streamStartTime&&Date.now()-p.streamStartTime>Tr.ZOMBIE_TIMEOUT){p.isZombie||t(g=>{const x=new Map(g.sessionMemoryState);return x.set(s,{...p,isZombie:!0}),{sessionMemoryState:x}}),setTimeout(()=>{r().completeStreamingMessage(s,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}t(h=>{const x=[...h.messages.get(s)||[]],b={},y=_n(h.messageSessionIndex,n,s);y!==h.messageSessionIndex&&(b.messageSessionIndex=y);const v=M=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(s)))return M;const T=new Map(h.sessionAbortFlags);return T.delete(s),{...M,sessionAbortFlags:T}},S=M=>{const w=M||"",T=ia.get(n);if(w&&T===w){const A=r();if(Ld(A,s,n)){const P=dn.get(n);P&&(clearTimeout(P),dn.delete(n)),setTimeout(()=>{const F=r();typeof F.forceCompleteMessage=="function"&&F.forceCompleteMessage(s,n,"timeout"),F.completeStreamingMessage(s,n)},100)}}ia.set(n,w);const E=dn.get(n);E&&clearTimeout(E);const I=setTimeout(()=>{const A=r();typeof A.forceCompleteMessage=="function"&&A.forceCompleteMessage(s,n,"timeout"),Ld(A,s,n)&&A.completeStreamingMessage(s,n),dn.delete(n),ia.delete(n)},8e3);dn.set(n,I)},C=s!==c,N=h.sessionMemoryState.get(s);if(C&&N?.isStreaming){x.length>=Tr.BACKGROUND_STREAMING_BUFFER&&x.shift();const M=new Map(h.sessionMemoryState);M.set(s,{...N,backgroundMessageCount:(N.backgroundMessageCount||0)+1}),h.sessionMemoryState=M}if(f==="assistant"){const M=h.sessionMemoryState.get(s);if(M){const w=Date.now(),T=new Map(h.sessionMemoryState);T.set(s,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??w,lastAccessedAt:w,isZombie:!1}),h.sessionMemoryState=T}}const j=Wn(o);if(Hi(j)&&(o.synthetic=!0),Fw()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:j.length,snapshotParts:u.length})}catch{}const D=b.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const M=xr(D,s,n);M!==D&&(b.streamingMessageIds=M,window.__messageTracker?.(n,"streamingId_set_latest"))}const k=x.findIndex(M=>M.info.id===n);if(k!==-1&&f==="user"){const M=x[k],w=M.parts.findIndex(P=>P.id===o.id);if(o.synthetic===!0){const P=Wn(o).trim();if(!(P.startsWith("User has requested to enter plan mode")||P.startsWith("The plan at ")))return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h}const T=wo(o,w!==-1?M.parts[w]:void 0);window.__messageTracker?.(n,`user_part_type:${T.type||"unknown"}`);const E={...M};w!==-1?E.parts=E.parts.map((P,F)=>F===w?T:P):E.parts=[...E.parts,T];const I=[...x];I[k]=E;const A=new Map(h.messages);return A.set(s,I),v({messages:A})}if(f==="assistant"&&k!==-1){const M=x[k],w=M.parts.findIndex(F=>F.id===o.id),T=wo(o,w!==-1?M.parts[w]:void 0);window.__messageTracker?.(n,`part_type:${T.type||"unknown"}`);const E={...M};w!==-1?E.parts=E.parts.map((F,z)=>z===w?T:F):E.parts=[...E.parts,T];const I=[...x];I[k]=E;const A=new Map(h.messages);A.set(s,I),b.messageStreamStates=Wi(h.messageStreamStates,n);const P=xr(b.streamingMessageIds??h.streamingMessageIds,s,n);return P!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=P,window.__messageTracker?.(n,"streamingId_set")),T.type==="text"?S(T.text||""):S(""),v({messages:A,...b})}if(k===-1){if(f==="user"){if(o.synthetic===!0){const we=Wn(o).trim();if(!(we.startsWith("User has requested to enter plan mode")||we.startsWith("The plan at ")))return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h}const te=wo(o);window.__messageTracker?.(n,`new_user_part_type:${te.type||"unknown"}`);const ye=h.pendingUserMessageMetaBySession.get(s),me=Ye.getState(),K=ye?.mode??me.getSessionAgentSelection(s)??me.getCurrentAgent(s),L=typeof K=="string"&&K.trim().length>0?K.trim():void 0,Q=ye?.providerID??(h.lastUsedProvider?.providerID||void 0),ce=ye?.modelID??(h.lastUsedProvider?.modelID||void 0);ye&&(b.pendingUserMessageMetaBySession=Td(h.pendingUserMessageMetaBySession,s));const he={info:{id:n,sessionID:s,role:"user",clientRole:"user",userMessageMarker:!0,...L?{mode:L}:{},...Q?{providerID:Q}:{},...ce?{modelID:ce}:{},time:{created:Date.now()}},parts:[te]},Ne=[...x,he];Ne.sort((we,ee)=>{const ue=we.info?.time?.created||0,ge=ee.info?.time?.created||0;return ue-ge});const H=new Map(h.messages);return H.set(s,Ne),v({messages:H})}if(o?.type==="text"){const te=Wn(o).trim();if(te.length>0){const ye=[...x].reverse().find(me=>me.info.role==="user");if(ye){const me=ye.parts.map(K=>Wn(K)).join("").trim();if(me.length>0&&me===te)return Rd.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const M=wo(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?S(M.text||""):S("");const w=h.pendingAssistantParts.get(n),T=w?[...w.parts]:[],E=T.findIndex(te=>te.id===M.id);E!==-1?T[E]=M:T.push(M);const I=new Map(h.pendingAssistantParts);I.set(n,{sessionId:s,parts:T});const A=h.lastUsedProvider?.providerID||"",P=h.lastUsedProvider?.modelID||"",F=Date.now(),z=Oe.getDirectory()??"/",G=Ye.getState(),oe=G.getSessionAgentSelection(s)??G.getCurrentAgent(s),O=typeof oe=="string"&&oe.trim().length>0?oe.trim():void 0,q=h.pendingAssistantHeaderSessions.has(s);if(q){const te=new Set(h.pendingAssistantHeaderSessions);te.delete(s),b.pendingAssistantHeaderSessions=te}const Z={info:f==="user"?{id:n,sessionID:s,role:"user",time:{created:F},agent:O||"default",model:{providerID:A,modelID:P},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:s,role:"assistant",time:{created:F},parentID:n,modelID:P,providerID:A,mode:O||"default",...q?{openchamberHeaderAnchor:!0}:{},path:{cwd:z,root:z},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:T},B=[...x,Z],W=new Map(h.messages);if(W.set(s,B),f==="assistant"){b.messageStreamStates=Wi(h.messageStreamStates,n);const te=xr(b.streamingMessageIds??h.streamingMessageIds,s,n);te!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=te,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:W,pendingAssistantParts:I,...b})}else{const M=x[k],w=M.parts.findIndex(P=>P.id===o.id),T=wo(o,w!==-1?M.parts[w]:void 0);window.__messageTracker?.(n,`part_type:${T.type||"unknown"}`);const E={...M};w!==-1?E.parts=E.parts.map((P,F)=>F===w?T:P):E.parts=[...E.parts,T];const I=[...x];I[k]=E;const A=new Map(h.messages);if(A.set(s,I),E.info.role==="assistant"){b.messageStreamStates=Wi(h.messageStreamStates,n);const P=xr(b.streamingMessageIds??h.streamingMessageIds,s,n);P!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=P,window.__messageTracker?.(n,"streamingId_set"))}return T.type==="text"?S(T.text||""):S(""),v({messages:A,...b})}})},addStreamingPart:(s,n,o,a,c)=>{if(a!=="user"){r()._addStreamingPartImmediate(s,n,o,a,c);return}Gi.push({sessionId:s,messageId:n,part:o,role:a,currentSessionId:c}),qi||(qi=setTimeout(()=>{const l=[...Gi];Gi=[],qi=null;const d=r();for(const u of l)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Iw))},forceCompleteMessage:(s,n,o="timeout")=>{const a=c=>{if(s)return s;for(const[l,d]of c.messages.entries())if(d.some(u=>u.info.id===n))return l;return null};t(c=>{const l=a(c);if(!l)return c;const d=c.messages.get(l)??[],u=d.findIndex(N=>N.info.id===n);if(u===-1)return c;const m=d[u];if(!m)return c;const f=Date.now(),p=m.info,h=typeof p?.time?.completed=="number"&&p.time.completed>0;let g=!1;const x={...p};h||(x.time={...p.time??{},completed:f},g=!0),x.status!=="completed"&&(x.status="completed",g=!0),x.streaming&&(x.streaming=!1,g=!0);let b=!1;const y=m.parts.map(N=>{if(!N)return N;if(N.type==="tool"){const j=N.state;if(!j)return N;const D=j.status,k=D==="running"||D==="pending"||D==="started",M=!j.time||typeof j.time?.end!="number";if(k||M){const w={...j};return k&&(w.status="completed"),M&&(w.time={...j.time??{},end:f}),b=!0,{...N,state:w}}return N}if(N.type==="reasoning"){const j=N.time;return!j||typeof j.end!="number"?(b=!0,{...N,time:{...j??{},end:f}}):N}if(N.type==="text"){const j=N.time;return j&&typeof j.end!="number"?(b=!0,{...N,time:{...j,end:f}}):N}return N});if(!g&&!b)return c;window.__messageTracker?.(n,`force_complete:${o}`);const v={...m,info:x,parts:b?y:m.parts},S=[...d];S[u]=v;const C=new Map(c.messages);return C.set(l,S),{messages:C}})},markMessageStreamSettled:s=>{t(n=>{Kf(s);const o=new Map(n.messageStreamStates);o.delete(s);let a=n.messages,c=!1;return n.messages.forEach((d,u)=>{if(c)return;const m=d.findIndex(x=>x.info.id===s);if(m===-1)return;const f=d[m];if(f.info?.animationSettled)return;const p={...f,info:{...f.info,animationSettled:!0}},h=[...d];h[m]=p;const g=new Map(n.messages);g.set(u,h),a=g,c=!0}),{messageStreamStates:o,...c?{messages:a}:{}}}),ln([s])},updateMessageInfo:(s,n,o)=>{t(l=>{const d=l.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!ca(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),l;const m=[...l.messages.get(s)??[]],f=m.findIndex(k=>k.info.id===n),p=l.pendingAssistantParts.get(n),h=(k=[],M=[])=>{if(!M.length)return k;const w=[...k];return M.forEach(T=>{const E=w.findIndex(I=>I.id===T.id);E===-1?w.push(T):w[E]=T}),w},g=k=>{if(!k)return k;const M=k.clientRole??k.role,w=M==="user"?!0:k.userMessageMarker;return{...k,clientRole:M,...w?{userMessageMarker:!0}:{}}};if(f===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:s,messageId:n,messageInfo:o,existingCount:m.length}),m.length>0){const z=m[0]?.info,G=typeof z?.time?.created=="number"?z.time.created:null,oe=typeof z?.id=="string"?z.id:null,O=o,q=typeof O?.time?.created=="number"?O.time.created:null,Y=typeof O?.id=="string"?O.id:n;let Z=!1;if(q!==null&&G!==null&&(Z=q<G),!Z&&Y&&oe&&(Z=Y.localeCompare(oe)<0),Z)return window.__messageTracker?.(n,"skipped_evicted_message_update"),l}const k=g(o);if(k&&k.role==="user"){const F=p?.parts??[],z=l.pendingUserMessageMetaBySession.get(s),G={info:{...k,userMessageMarker:!0,clientRole:"user",...z?.mode?{mode:z.mode}:{},...z?.providerID?{providerID:z.providerID}:{},...z?.modelID?{modelID:z.modelID}:{}},parts:F.length>0?[...F]:[]},oe=new Map(l.messages),O=[...m,G];O.sort((Z,B)=>{const W=Z.info?.time?.created||0,te=B.info?.time?.created||0;return W-te}),oe.set(s,O);const q={messages:oe,...z?{pendingUserMessageMetaBySession:Td(l.pendingUserMessageMetaBySession,s)}:{}},Y=_n(q.messageSessionIndex??l.messageSessionIndex,n,s);if(Y!==(q.messageSessionIndex??l.messageSessionIndex)&&(q.messageSessionIndex=Y),p){const Z=new Map(l.pendingAssistantParts);Z.delete(n),q.pendingAssistantParts=Z}return q}if(!k||k.role!=="assistant")return l;const M=p?.parts??[],w=l.pendingAssistantHeaderSessions.has(s),T={info:{...k,animationSettled:k?.animationSettled??!1,...w?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},E=new Map(l.messages),I=[...m,T];E.set(s,I);const A={messages:E,...w?{pendingAssistantHeaderSessions:(()=>{const F=new Set(l.pendingAssistantHeaderSessions);return F.delete(s),F})()}:{}},P=_n(A.messageSessionIndex??l.messageSessionIndex,n,s);if(P!==(A.messageSessionIndex??l.messageSessionIndex)&&(A.messageSessionIndex=P),p){const F=new Map(l.pendingAssistantParts);F.delete(n),A.pendingAssistantParts=F}return A}const x=m[f],b=x.info;if(b.userMessageMarker===!0||b.clientRole==="user"||b.role==="user"){const k={...x.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:b.providerID||void 0,modelID:b.modelID||void 0},M=l.pendingUserMessageMetaBySession.get(s);M&&!k.mode&&M.mode&&(k.mode=M.mode);const w={...x,info:k},T=new Map(l.messages),E=[...m];if(E[f]=w,T.set(s,E),M){const I=new Map(l.pendingUserMessageMetaBySession);return I.delete(s),{messages:T,pendingUserMessageMetaBySession:I}}return{messages:T}}const v={...x.info,...o};o.role&&o.role!==x.info.role&&(v.role=x.info.role),v.clientRole=v.clientRole??x.info.clientRole??x.info.role,v.clientRole==="user"&&(v.userMessageMarker=!0);const S=p?.parts?h(x.parts,p.parts):x.parts,C={...x,info:v,parts:S},N=new Map(l.messages),j=[...m];j[f]=C,N.set(s,j);const D={messages:N};if(p){const k=new Map(l.pendingAssistantParts);k.delete(n),D.pendingAssistantParts=k}return D});const a=o?.finish,c=o?.role;typeof a=="string"&&c!=="user"&&setTimeout(()=>{r().completeStreamingMessage(s,n)},0)},completeStreamingMessage:(s,n)=>{const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(s)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(s,n,"cooldown");const a=o.streamingMessageIds.get(s)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const c={};if(a&&(c.streamingMessageIds=xr(o.streamingMessageIds,s,null),c.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(s),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),c.messageStreamStates=d}Object.keys(c).length>0&&t(c),o.pendingAssistantParts.has(n)&&t(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),ln([n]);let l=!1;if(t(d=>{const u=d.sessionMemoryState.get(s);if(!u||!u.isStreaming)return d;const m=new Map(d.sessionMemoryState),f=Date.now(),p={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:f,streamingCooldownUntil:f+2e3};return m.set(s,p),l=!0,{sessionMemoryState:m}}),l){const d=On.get(s);d&&(clearTimeout(d),On.delete(s));const u=setTimeout(()=>{t(m=>{const f=m.sessionMemoryState.get(s);if(!f||f.isStreaming)return m;const p=new Map(m.sessionMemoryState),{streamingCooldownUntil:h,...g}=f;return p.set(s,g),{sessionMemoryState:p}}),On.delete(s)},2e3);On.set(s,u)}},syncMessages:(s,n)=>{const o=Od(s),a=_d(n,o),c=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,l=c?a.filter(d=>{const u=d?.info?.id;return u?ca(u,c):!0}):a;t(d=>{const u=new Map(d.messages),m=d.messages.get(s)||[],f=new Map(m.filter(N=>typeof N.info?.id=="string").map(N=>[N.info.id,N])),p=l.map(N=>{const j={...N.info,clientRole:N.info?.clientRole??N.info.role,userMessageMarker:N.info.role==="user"?!0:N.info?.userMessageMarker,animationSettled:N.info.role==="assistant"?N.info?.animationSettled??!0:N.info?.animationSettled},D=(Array.isArray(N.parts)?N.parts:[]).map(w=>{if(w?.type==="text"){const T=w.text??w.content??"";if(Hi(T))return{...w,synthetic:!0}}return w}),k=typeof j?.id=="string"?j.id:void 0,M=k?f.get(k):void 0;if(M&&M.info.role==="assistant"){const w=Array.isArray(M.parts)?M.parts:[],T=qn(w),E=qn(D);if(ei(M.info)&&T>E){const A=ti(w,D);return{...N,info:j,parts:A}}}return{...N,info:j,parts:D}}),h=la(p),g=new Set(m.map(N=>N.info.id)),x=new Set(h.map(N=>N.info.id)),b=[];g.forEach(N=>{x.has(N)||b.push(N)}),u.set(s,h);const y={messages:u,isSyncing:!0};ln(b);const v=bo(d.messageStreamStates,b);if(v!==d.messageStreamStates&&(y.messageStreamStates=v),b.length>0){const N=d.streamingMessageIds.get(s);N&&b.includes(N)&&(y.streamingMessageIds=xr(y.streamingMessageIds??d.streamingMessageIds,s,null))}if(b.length>0){const N=da(y.messageSessionIndex??d.messageSessionIndex,b);N!==(y.messageSessionIndex??d.messageSessionIndex)&&(y.messageSessionIndex=N)}if(b.length>0){const N=new Map(d.pendingAssistantParts);let j=!1;b.forEach(D=>{N.delete(D)&&(j=!0)}),j&&(y.pendingAssistantParts=N)}const S=y.messageSessionIndex??d.messageSessionIndex;let C=S;return h.forEach(N=>{const j=N?.info?.id;typeof j=="string"&&j.length>0&&(C=_n(C,j,s))}),C!==S&&(y.messageSessionIndex=C),y}),setTimeout(()=>{t({isSyncing:!1})},100)},updateSessionCompaction:(s,n)=>{t(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(s)?(a.delete(s),{sessionCompactionUntil:a}):o;const c=n+Pw;return a.get(s)===c?o:(a.set(s,c),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:s=>{s&&t(n=>{const o=n.sessionAbortFlags.get(s);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(s,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(s,n)=>{t(o=>{const a=o.sessionMemoryState.get(s)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},c=new Map(o.sessionMemoryState);return c.set(s,{...a,viewportAnchor:n}),{sessionMemoryState:c}})},trimToViewportWindow:(s,n,o)=>{const a=n??Ta().VIEWPORT_MESSAGES,c=r(),l=c.messages.get(s);if(!l||l.length<=a)return;const d=c.sessionMemoryState.get(s)||{viewportAnchor:l.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(d.isStreaming&&s===o)return;const u=d.viewportAnchor||l.length-1;let m=Math.max(0,u-Math.floor(a/2));const f=Math.min(l.length,m+a);f===l.length&&f-m<a&&(m=Math.max(0,f-a));const p=l.slice(m,f),h=l.slice(0,m),g=new Set(p.map(b=>b.info.id)),x=l.filter(b=>!g.has(b.info.id)).map(b=>b.info.id);t(b=>{const y=new Map(b.messages);y.set(s,p);const v=new Map(b.sessionMemoryState),S={...d,viewportAnchor:u-m,hasMoreAbove:!!d.hasMoreAbove||m>0,trimmedHeadMaxId:Lw(h,d.trimmedHeadMaxId)};v.set(s,S);const C={messages:y,sessionMemoryState:v};ln(x);const N=bo(b.messageStreamStates,x);if(N!==b.messageStreamStates&&(C.messageStreamStates=N),x.length>0){const k=b.streamingMessageIds.get(s);k&&x.includes(k)&&(C.streamingMessageIds=xr(C.streamingMessageIds??b.streamingMessageIds,s,null))}if(x.length>0){const k=da(C.messageSessionIndex??b.messageSessionIndex,x);k!==(C.messageSessionIndex??b.messageSessionIndex)&&(C.messageSessionIndex=k)}const j=C.messageSessionIndex??b.messageSessionIndex;let D=j;return p.forEach(k=>{const M=k?.info?.id;typeof M=="string"&&M.length>0&&(D=_n(D,M,s))}),D!==j&&(C.messageSessionIndex=D),C})},evictLeastRecentlyUsed:s=>{const n=r();if(n.messages.size<=Tr.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const m=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,m])});const c=a.filter(([d,u])=>d!==s&&!u.isStreaming);if(c.length===0)return;c.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const l=c[0][0];t(d=>{const m=(d.messages.get(l)||[]).map(C=>C.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(l);const h={messages:f,sessionMemoryState:p},g=new Map(d.pendingAssistantParts);let x=!1;g.forEach((C,N)=>{C.sessionId===l&&(g.delete(N),x=!0)}),x&&(h.pendingAssistantParts=g);const b=new Map(d.sessionCompactionUntil);b.delete(l)&&(h.sessionCompactionUntil=b),ln(m);const y=bo(d.messageStreamStates,m);y!==d.messageStreamStates&&(h.messageStreamStates=y);const v=da(h.messageSessionIndex??d.messageSessionIndex,m);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const S=xr(d.streamingMessageIds,l,null);if(S!==d.streamingMessageIds&&(h.streamingMessageIds=S),d.abortControllers.has(l)){const C=new Map(d.abortControllers);C.delete(l),h.abortControllers=C}return h})},loadMoreMessages:async(s,n="up")=>{const o=r(),a=o.messages.get(s),c=o.sessionMemoryState.get(s);if(!a||!c)return;const l=Ta(),d=Math.max(a.length+l.VIEWPORT_MESSAGES+l.FETCH_BUFFER,l.HISTORICAL_MESSAGES+l.FETCH_BUFFER),u=await Ki(s,()=>Oe.getSessionMessages(s,d));if(n==="up"&&a.length>0){const m=la(u),f=a[0],p=m.findIndex(h=>h.info.id===f.info.id);if(p>0){const h=Math.min(Tr.VIEWPORT_MESSAGES,p),g=m.slice(p-h,p);t(x=>{const b=[...g,...a],y=la(b),v=Math.max(0,y.length-a.length),S=new Map(x.messages);S.set(s,y);const C=new Map(x.sessionMemoryState);return C.set(s,{...c,viewportAnchor:c.viewportAnchor+v,hasMoreAbove:p-h>0,totalAvailableMessages:Math.max(c.totalAvailableMessages??0,m.length)}),{messages:S,sessionMemoryState:C}})}else p===0&&t(h=>{const g=new Map(h.sessionMemoryState);return g.set(s,{...c,hasMoreAbove:!1,totalAvailableMessages:Math.max(c.totalAvailableMessages??0,m.length)}),{sessionMemoryState:g}})}},getLastMessageModel:s=>{const{messages:n}=r(),o=n.get(s);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const c=o[a];if(c.info.role==="assistant"&&"providerID"in c.info&&"modelID"in c.info)return{providerID:c.info.providerID,modelID:c.info.modelID}}return null}}),{name:"message-store",storage:Ks(()=>js()),partialize:t=>({lastUsedProvider:t.lastUsedProvider,sessionMemoryState:Array.from(t.sessionMemoryState.entries()).map(([r,s])=>[r,{viewportAnchor:s.viewportAnchor,isStreaming:s.isStreaming,lastAccessedAt:s.lastAccessedAt,backgroundMessageCount:s.backgroundMessageCount,totalAvailableMessages:s.totalAvailableMessages,hasMoreAbove:s.hasMoreAbove,trimmedHeadMaxId:s.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(t.sessionAbortFlags.entries()).map(([r,s])=>[r,{timestamp:s.timestamp,acknowledged:s.acknowledged}])}),merge:(t,r)=>{if(!t)return r;let s=r.sessionMemoryState;Array.isArray(t.sessionMemoryState)&&(s=new Map(t.sessionMemoryState.map(o=>o)));let n=r.sessionAbortFlags;return Array.isArray(t.sessionAbortFlags)&&(n=new Map(t.sessionAbortFlags)),{...r,lastUsedProvider:t.lastUsedProvider??r.lastUsedProvider,sessionMemoryState:s,sessionAbortFlags:n}}}),{name:"message-store"})),$w=t=>typeof t=="object"&&t!==null,Bw=t=>{if(!Array.isArray(t))return[];const r=[];return t.forEach(s=>{if(!Array.isArray(s)||s.length!==2)return;const[n,o]=s;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},zw=async(t,r)=>{try{const n=gt.getState().getDirectoryForSession(t);if(n)return Oe.withDirectory(n,r)}catch(s){console.warn("Failed to resolve session directory for permission handling:",s)}return r()},zo=ns()(fs(qs((t,r)=>({permissions:new Map,addPermission:(s,n)=>{const o=s.sessionID;if(!o||r().permissions.get(o)?.some(f=>f.id===s.id))return;const c=s.permission?.toLowerCase?.()??null;let l=n?.currentAgentContext?.get(o);if(l||(l=n?.sessionAgentSelections?.get(o)??void 0),!l&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(l=f.getState().currentAgentName??void 0)}const d=Ra(l),u=n?.getSessionAgentEditMode?.(o,l)??d;if((u==="allow"||u==="full")&&Mw(c)){r().respondToPermission(o,s.id,"once").catch(()=>{});return}t(f=>{const p=f.permissions.get(o)||[],h=new Map(f.permissions);return h.set(o,[...p,s]),{permissions:h}})},respondToPermission:async(s,n,o)=>{await zw(s,()=>Oe.replyToPermission(n,o)),o==="reject"&&await Nt.getState().abortCurrentOperation(s),t(a=>{const l=(a.permissions.get(s)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(s,l),{permissions:d}})}}),{name:"permission-store",storage:Ks(()=>js()),partialize:t=>({permissions:Array.from(t.permissions.entries())}),merge:(t,r)=>{if(!$w(t))return r;const s=Bw(t.permissions);return{...r,permissions:new Map(s)}}}),{name:"permission-store"})),Hw=t=>typeof t=="object"&&t!==null,Ww=t=>{if(!Array.isArray(t))return[];const r=[];return t.forEach(s=>{if(!Array.isArray(s)||s.length!==2)return;const[n,o]=s;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},$d=async(t,r)=>{try{const n=gt.getState().getDirectoryForSession(t);if(n)return Oe.withDirectory(n,r)}catch(s){console.warn("Failed to resolve session directory for question handling:",s)}return r()},Kn=ns()(fs(qs((t,r)=>({questions:new Map,addQuestion:s=>{const n=s.sessionID;!n||r().questions.get(n)?.some(a=>a.id===s.id)||t(a=>{const c=a.questions.get(n)||[],l=new Map(a.questions);return l.set(n,[...c,s]),{questions:l}})},dismissQuestion:(s,n)=>{!s||!n||t(o=>{const c=(o.questions.get(s)||[]).filter(d=>d.id!==n),l=new Map(o.questions);return l.set(s,c),{questions:l}})},respondToQuestion:async(s,n,o)=>{await $d(s,()=>Oe.replyToQuestion(n,o)),r().dismissQuestion(s,n)},rejectQuestion:async(s,n)=>{await $d(s,()=>Oe.rejectQuestion(n)),r().dismissQuestion(s,n)}}),{name:"question-store",storage:Ks(()=>js()),partialize:t=>({questions:Array.from(t.questions.entries())}),merge:(t,r)=>{if(!Hw(t))return r;const s=Ww(t.questions);return{...r,questions:new Map(s)}}}),{name:"question-store"})),Sl=t=>t.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
9
+ `).replace(/\n\s*\n+/g,`
10
+ `),Eo=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},Bd=(t,r,s)=>{if(!r)return null;const n=s(r)?.path;if(typeof n=="string"&&n.trim().length>0)return Eo(n);const o=t.find(a=>a.id===r);return o?Eo(o.directory??null):null},ve=ns()(fs((t,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions:new Map,questions:new Map,attachedFiles:[],isLoading:!1,error:null,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,abortPromptSessionId:null,abortPromptExpiresAt:null,sessionActivityPhase:new Map,userSummaryTitles:new Map,pendingInputText:null,newSessionDraft:{open:!0,directoryOverride:null,parentID:null},getSessionAgentEditMode:(s,n,o)=>Ye.getState().getSessionAgentEditMode(s,n,o),toggleSessionAgentEditMode:(s,n,o)=>Ye.getState().toggleSessionAgentEditMode(s,n,o),setSessionAgentEditMode:(s,n,o,a)=>Ye.getState().setSessionAgentEditMode(s,n,o,a),loadSessions:()=>gt.getState().loadSessions(),openNewSessionDraft:s=>{let n=null;s?.directoryOverride!==void 0?n=s.directoryOverride:n=Lt.getState().getActiveProject()?.path??null,t({newSessionDraft:{open:!0,directoryOverride:n,parentID:s?.parentID??null,title:s?.title},currentSessionId:null,error:null});try{const o=Je.getState(),a=o.getVisibleAgents();let c;if(o.settingsDefaultAgent){const l=a.find(d=>d.name===o.settingsDefaultAgent);l&&(c=l.name)}c||(c=a.find(l=>l.name==="build")?.name||a[0]?.name),c&&o.setAgent(c)}catch{}},closeNewSessionDraft:()=>{const s=gt.getState().currentSessionId;t({newSessionDraft:{open:!1,directoryOverride:null,parentID:null,title:void 0},currentSessionId:s})},createSession:async(s,n,o)=>{r().closeNewSessionDraft();const a=await gt.getState().createSession(s,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async s=>{if(!s)return;const n=Nt.getState(),{messages:o,lastUsedProvider:a}=n;let c,l;if(o.forEach((y,v)=>{const S=y.find(C=>C.info?.id===s);S&&!c&&(c=S,l=v)}),!c||c.info.role!=="assistant")return;const d=Sl(c.parts);if(!d.trim())return;const u=gt.getState(),m=Bd(u.sessions,l??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:g}=Je.getState(),x=p||a?.providerID,b=h||a?.modelID;!x||!b||await Oe.sendMessage({id:f.id,providerID:x,modelID:b,text:d,prefaceText:qf,agent:g??void 0})},deleteSession:(s,n)=>gt.getState().deleteSession(s,n),deleteSessions:(s,n)=>gt.getState().deleteSessions(s,n),updateSessionTitle:(s,n)=>gt.getState().updateSessionTitle(s,n),shareSession:s=>gt.getState().shareSession(s),unshareSession:s=>gt.getState().unshareSession(s),setCurrentSession:async s=>{s&&r().closeNewSessionDraft();const n=gt.getState().currentSessionId,o=Bd(gt.getState().sessions,s,gt.getState().getWorktreeMetadata),a=Oe.getDirectory()??vt.getState().currentDirectory??null,c=o??a;try{Oe.setDirectory(c??void 0)}catch(l){console.warn("Failed to set OpenCode directory for session switch:",l)}if(n&&n!==s&&!r().sessionMemoryState.get(n)?.isStreaming){const d=r().messages.get(n)||[];d.length>0&&r().updateViewportAnchor(n,d.length-1),r().trimToViewportWindow(n,Ta().VIEWPORT_MESSAGES)}if(gt.getState().setCurrentSession(s),s){r().messages.get(s)||await r().loadMessages(s),r().trimToViewportWindow(s,Gr());const d=r().messages.get(s);if(d&&d.length>0){const u=Je.getState().agents;if(u.length>0)try{await Ye.getState().analyzeAndSaveExternalSessionChoices(s,u,r().messages)}catch(m){console.warn("Failed to analyze session choices:",m)}}}r().evictLeastRecentlyUsed()},loadMessages:(s,n)=>Nt.getState().loadMessages(s,n),sendMessage:async(s,n,o,a,c,l,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=v=>{t(S=>{const C=new Map(S.sessionActivityPhase??new Map);return C.set(v,"busy"),{sessionActivityPhase:C}})},h=v=>{t(S=>{const C=new Map(S.sessionActivityPhase??new Map);return C.set(v,"idle"),{sessionActivityPhase:C}})};if(m?.open){const v=await gt.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!v?.id)throw new Error("Failed to create session");const S=Je.getState(),C=S.currentAgentName,N=f??C,j=S.currentProviderId,D=S.currentModelId;if(j&&D)try{Ye.getState().saveSessionModelSelection(v.id,j,D)}catch{}if(N){try{Ye.getState().saveSessionAgentSelection(v.id,N)}catch{}if(j&&D){try{Ye.getState().saveAgentModelForSession(v.id,N,j,D)}catch{}if(u!==void 0)try{Ye.getState().saveAgentModelVariantForSession(v.id,N,j,D,u)}catch{}}}try{gt.getState().initializeNewOpenChamberSession(v.id,S.agents)}catch{}r().closeNewSessionDraft(),p(v.id);try{return await Nt.getState().sendMessage(s,n,o,N,v.id,c,l,d,u)}catch(k){throw h(v.id),k}}const g=gt.getState().currentSessionId,x=g?Ye.getState().getSessionAgentSelection(g):null,b=Je.getState().currentAgentName,y=f||x||b||void 0;if(g&&y){try{Ye.getState().saveSessionAgentSelection(g,y)}catch{}if(u!==void 0)try{Ye.getState().saveAgentModelVariantForSession(g,y,n,o,u)}catch{}}g&&p(g);try{return await Nt.getState().sendMessage(s,n,o,y,g||void 0,c,l,d,u)}catch(v){throw g&&h(g),v}},abortCurrentOperation:()=>{const s=gt.getState().currentSessionId;return Nt.getState().abortCurrentOperation(s||void 0)},armAbortPrompt:(s=3e3)=>{const n=gt.getState().currentSessionId;if(!n)return null;const o=Date.now()+s;return t({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{t({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:s=>{s&&Nt.getState().acknowledgeSessionAbort(s)},addStreamingPart:(s,n,o,a)=>{const l=gt.getState().currentSessionId||s;return Nt.getState().addStreamingPart(s,n,o,a,l)},completeStreamingMessage:(s,n)=>Nt.getState().completeStreamingMessage(s,n),markMessageStreamSettled:s=>Nt.getState().markMessageStreamSettled(s),updateMessageInfo:(s,n,o)=>Nt.getState().updateMessageInfo(s,n,o),updateSessionCompaction:(s,n)=>Nt.getState().updateSessionCompaction(s,n??null),addPermission:s=>{const n={currentAgentContext:Ye.getState().currentAgentContext,sessionAgentSelections:Ye.getState().sessionAgentSelections,getSessionAgentEditMode:Ye.getState().getSessionAgentEditMode};return zo.getState().addPermission(s,n)},respondToPermission:(s,n,o)=>zo.getState().respondToPermission(s,n,o),addQuestion:s=>Kn.getState().addQuestion(s),dismissQuestion:(s,n)=>Kn.getState().dismissQuestion(s,n),respondToQuestion:(s,n,o)=>Kn.getState().respondToQuestion(s,n,o),rejectQuestion:(s,n)=>Kn.getState().rejectQuestion(s,n),clearError:()=>gt.getState().clearError(),getSessionsByDirectory:s=>gt.getState().getSessionsByDirectory(s),getDirectoryForSession:s=>gt.getState().getDirectoryForSession(s),getLastMessageModel:s=>Nt.getState().getLastMessageModel(s),getCurrentAgent:s=>Ye.getState().getCurrentAgent(s),syncMessages:(s,n)=>Nt.getState().syncMessages(s,n),applySessionMetadata:(s,n)=>gt.getState().applySessionMetadata(s,n),addAttachedFile:s=>pr.getState().addAttachedFile(s),addServerFile:(s,n,o)=>pr.getState().addServerFile(s,n,o),removeAttachedFile:s=>pr.getState().removeAttachedFile(s),clearAttachedFiles:()=>pr.getState().clearAttachedFiles(),updateViewportAnchor:(s,n)=>Nt.getState().updateViewportAnchor(s,n),trimToViewportWindow:(s,n)=>{const o=gt.getState().currentSessionId,a=r().sessionActivityPhase?.get(s);if(!(a==="busy"||a==="cooldown"))return Nt.getState().trimToViewportWindow(s,n,o||void 0)},evictLeastRecentlyUsed:()=>{const s=gt.getState().currentSessionId;return Nt.getState().evictLeastRecentlyUsed(s||void 0)},loadMoreMessages:(s,n)=>Nt.getState().loadMoreMessages(s,n),saveSessionModelSelection:(s,n,o)=>Ye.getState().saveSessionModelSelection(s,n,o),getSessionModelSelection:s=>Ye.getState().getSessionModelSelection(s),saveSessionAgentSelection:(s,n)=>Ye.getState().saveSessionAgentSelection(s,n),getSessionAgentSelection:s=>Ye.getState().getSessionAgentSelection(s),saveAgentModelForSession:(s,n,o,a)=>Ye.getState().saveAgentModelForSession(s,n,o,a),getAgentModelForSession:(s,n)=>Ye.getState().getAgentModelForSession(s,n),saveAgentModelVariantForSession:(s,n,o,a,c)=>Ye.getState().saveAgentModelVariantForSession(s,n,o,a,c),getAgentModelVariantForSession:(s,n,o,a)=>Ye.getState().getAgentModelVariantForSession(s,n,o,a),analyzeAndSaveExternalSessionChoices:(s,n)=>{const o=Nt.getState().messages;return Ye.getState().analyzeAndSaveExternalSessionChoices(s,n,o)},isOpenChamberCreatedSession:s=>gt.getState().isOpenChamberCreatedSession(s),markSessionAsOpenChamberCreated:s=>gt.getState().markSessionAsOpenChamberCreated(s),initializeNewOpenChamberSession:(s,n)=>gt.getState().initializeNewOpenChamberSession(s,n),setWorktreeMetadata:(s,n)=>gt.getState().setWorktreeMetadata(s,n),setSessionDirectory:(s,n)=>gt.getState().setSessionDirectory(s,n),getWorktreeMetadata:s=>gt.getState().getWorktreeMetadata(s),getContextUsage:(s,n)=>{if(r().newSessionDraft?.open)return null;const o=gt.getState().currentSessionId;if(!o)return null;const a=Nt.getState().messages;return Ye.getState().getContextUsage(o,s,n,a)},updateSessionContextUsage:(s,n,o)=>{const a=Nt.getState().messages;return Ye.getState().updateSessionContextUsage(s,n,o,a)},initializeSessionContextUsage:(s,n,o)=>{const a=Nt.getState().messages;return Ye.getState().initializeSessionContextUsage(s,n,o,a)},debugSessionMessages:async s=>{const n=Nt.getState().messages.get(s)||[],o=gt.getState().sessions.find(a=>a.id===s);console.log(`Debug session ${s}:`,{session:o,messageCount:n.length,messages:n.map(a=>({id:a.info.id,role:a.info.role,parts:a.parts.length,tokens:a.info.tokens}))})},pollForTokenUpdates:(s,n,o)=>{const a=Nt.getState().messages;return Ye.getState().pollForTokenUpdates(s,n,a,o)},updateSession:s=>gt.getState().updateSession(s),removeSessionFromStore:s=>gt.getState().removeSessionFromStore(s),revertToMessage:async(s,n)=>{const a=(Nt.getState().messages.get(s)||[]).find(m=>m.info.id===n);let c="";a&&a.info.role==="user"&&(c=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
11
+ `).trim());const l=await Oe.revertSession(s,n);gt.getState().updateSession(l);const d=Nt.getState().messages.get(s)||[],u=l.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);Nt.getState().syncMessages(s,f)}}c&&t({pendingInputText:c})},handleSlashUndo:async s=>{const o=(r().messages.get(s)||[]).filter(p=>p.info.role==="user"),c=r().sessions.find(p=>p.id===s);if(o.length===0)return;const l=c?.revert?.messageID;let d;if(l){const p=o.findIndex(h=>h.info.id===l);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(s,d.info.id);const{toast:f}=await vs(async()=>{const{toast:p}=await import("./vendor-.bun-Bui932eM.js").then(h=>h.dj);return{toast:p}},__vite__mapDeps([0,1]));f.success(`Undid to: ${m}`)},handleSlashRedo:async s=>{const a=r().sessions.find(m=>m.id===s)?.revert?.messageID;if(!a)return;const l=(r().messages.get(s)||[]).filter(m=>m.info.role==="user"),d=l.findIndex(m=>m.info.id===a),u=l[d-1];if(u){const m=u.parts.find(h=>h.type==="text"),f=typeof m=="object"&&m&&"text"in m?String(m.text).slice(0,50)+(String(m.text).length>50?"...":""):"[No text]";await r().revertToMessage(s,u.info.id);const{toast:p}=await vs(async()=>{const{toast:h}=await import("./vendor-.bun-Bui932eM.js").then(g=>g.dj);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await Oe.unrevertSession(s);await gt.getState().updateSession(m),await r().loadMessages(s);const{toast:f}=await vs(async()=>{const{toast:p}=await import("./vendor-.bun-Bui932eM.js").then(h=>h.dj);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(s,n)=>{const a=r().sessions.find(c=>c.id===s);if(a)try{const c=await Oe.forkSession(s,n);if(!c||!c.id){const{toast:f}=await vs(async()=>{const{toast:p}=await import("./vendor-.bun-Bui932eM.js").then(h=>h.dj);return{toast:p}},__vite__mapDeps([0,1]));f.error("Failed to fork session");return}const d=(r().messages.get(s)||[]).find(f=>f.info.id===n);if(!d){const{toast:f}=await vs(async()=>{const{toast:p}=await import("./vendor-.bun-Bui932eM.js").then(h=>h.dj);return{toast:p}},__vite__mapDeps([0,1]));f.error("Message not found");return}let u="";for(const f of d.parts)f.type==="text"&&!f.synthetic&&!f.ignored&&(u+=f.text||"");r().setCurrentSession(c.id),u&&t({pendingInputText:u}),await r().loadMessages(c.id);const{toast:m}=await vs(async()=>{const{toast:f}=await import("./vendor-.bun-Bui932eM.js").then(p=>p.dj);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(c){console.error("Failed to fork session:",c);const{toast:l}=await vs(async()=>{const{toast:d}=await import("./vendor-.bun-Bui932eM.js").then(u=>u.dj);return{toast:d}},__vite__mapDeps([0,1]));l.error("Failed to fork session")}},setPendingInputText:s=>{t({pendingInputText:s})},consumePendingInputText:()=>{const s=r().pendingInputText;return s!==null&&t({pendingInputText:null}),s}}),{name:"composed-session-store"}));gt.subscribe((t,r)=>{if(t.sessions===r.sessions&&t.sessionsByDirectory===r.sessionsByDirectory&&t.currentSessionId===r.currentSessionId&&t.lastLoadedDirectory===r.lastLoadedDirectory&&t.isLoading===r.isLoading&&t.error===r.error&&t.webUICreatedSessions===r.webUICreatedSessions&&t.worktreeMetadata===r.worktreeMetadata&&t.availableWorktrees===r.availableWorktrees&&t.availableWorktreesByProject===r.availableWorktreesByProject)return;const s=ve.getState().newSessionDraft?.open;ve.setState({sessions:t.sessions,sessionsByDirectory:t.sessionsByDirectory,currentSessionId:s?null:t.currentSessionId,lastLoadedDirectory:t.lastLoadedDirectory,isLoading:t.isLoading,error:t.error,webUICreatedSessions:t.webUICreatedSessions,worktreeMetadata:t.worktreeMetadata,availableWorktrees:t.availableWorktrees,availableWorktreesByProject:t.availableWorktreesByProject})});Nt.subscribe((t,r)=>{if(t.messages===r.messages&&t.sessionMemoryState===r.sessionMemoryState&&t.messageStreamStates===r.messageStreamStates&&t.sessionCompactionUntil===r.sessionCompactionUntil&&t.sessionAbortFlags===r.sessionAbortFlags&&t.streamingMessageIds===r.streamingMessageIds&&t.abortControllers===r.abortControllers&&t.lastUsedProvider===r.lastUsedProvider&&t.isSyncing===r.isSyncing)return;const s=new Map;t.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const c=n[a];if(!c||!c.info)continue;const l=c.info;if(l.role==="user"){const d=l.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=l.time&&typeof l.time.created=="number"?l.time.created:null;s.set(o,{title:u,createdAt:m});break}}}}}),ve.setState({messages:t.messages,sessionMemoryState:t.sessionMemoryState,messageStreamStates:t.messageStreamStates,sessionCompactionUntil:t.sessionCompactionUntil,sessionAbortFlags:t.sessionAbortFlags,streamingMessageIds:t.streamingMessageIds,abortControllers:t.abortControllers,lastUsedProvider:t.lastUsedProvider,isSyncing:t.isSyncing,userSummaryTitles:s})});pr.subscribe((t,r)=>{t.attachedFiles!==r.attachedFiles&&ve.setState({attachedFiles:t.attachedFiles})});Ye.subscribe((t,r)=>{t.sessionModelSelections===r.sessionModelSelections&&t.sessionAgentSelections===r.sessionAgentSelections&&t.sessionAgentModelSelections===r.sessionAgentModelSelections&&t.currentAgentContext===r.currentAgentContext&&t.sessionContextUsage===r.sessionContextUsage&&t.sessionAgentEditModes===r.sessionAgentEditModes||ve.setState({sessionModelSelections:t.sessionModelSelections,sessionAgentSelections:t.sessionAgentSelections,sessionAgentModelSelections:t.sessionAgentModelSelections,currentAgentContext:t.currentAgentContext,sessionContextUsage:t.sessionContextUsage,sessionAgentEditModes:t.sessionAgentEditModes})});zo.subscribe((t,r)=>{t.permissions!==r.permissions&&ve.setState({permissions:t.permissions})});Kn.subscribe((t,r)=>{t.questions!==r.questions&&ve.setState({questions:t.questions})});vt.subscribe((t,r)=>{const s=Eo(t.currentDirectory??null),n=Eo(r.currentDirectory??null);if(s===n)return;const o=ve.getState().newSessionDraft;if(!o?.open)return;const a=Eo(o.directoryOverride);a&&a!==n||ve.setState(c=>({newSessionDraft:{...c.newSessionDraft,directoryOverride:s,parentID:null}}))});const Uw=ve.getState().newSessionDraft?.open;ve.setState({sessions:gt.getState().sessions,currentSessionId:Uw?null:gt.getState().currentSessionId,lastLoadedDirectory:gt.getState().lastLoadedDirectory,isLoading:gt.getState().isLoading,error:gt.getState().error,webUICreatedSessions:gt.getState().webUICreatedSessions,worktreeMetadata:gt.getState().worktreeMetadata,availableWorktrees:gt.getState().availableWorktrees,availableWorktreesByProject:gt.getState().availableWorktreesByProject,messages:Nt.getState().messages,sessionMemoryState:Nt.getState().sessionMemoryState,messageStreamStates:Nt.getState().messageStreamStates,sessionCompactionUntil:Nt.getState().sessionCompactionUntil,sessionAbortFlags:Nt.getState().sessionAbortFlags,streamingMessageIds:Nt.getState().streamingMessageIds,abortControllers:Nt.getState().abortControllers,lastUsedProvider:Nt.getState().lastUsedProvider,isSyncing:Nt.getState().isSyncing,permissions:zo.getState().permissions,questions:Kn.getState().questions,attachedFiles:pr.getState().attachedFiles,sessionModelSelections:Ye.getState().sessionModelSelections,sessionAgentSelections:Ye.getState().sessionAgentSelections,sessionAgentModelSelections:Ye.getState().sessionAgentModelSelections,currentAgentContext:Ye.getState().currentAgentContext,sessionContextUsage:Ye.getState().sessionContextUsage,sessionAgentEditModes:Ye.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=ve);const Vw=async t=>{if(t)return await t.authStatus();const r=await fetch("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),s=await r.json().catch(()=>null);if(!r.ok||!s)throw new Error(s?.error||r.statusText||"Failed to load GitHub status");return s},Bs=ns((t,r)=>({status:null,isLoading:!1,hasChecked:!1,setStatus:s=>t({status:s,hasChecked:!0}),refreshStatus:async(s,n)=>{const{hasChecked:o,status:a}=r();if(o&&!n?.force)return a;t({isLoading:!0});try{const c=await Vw(s);return t({status:c,isLoading:!1,hasChecked:!0}),c}catch(c){const l=c instanceof Error?c.message:String(c);return t({status:{connected:!1,error:l},isLoading:!1,hasChecked:!0}),null}}})),Nl=i.createContext(null),Hs=()=>{const t=i.useContext(Nl);if(!t)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return t},Jf=t=>{const r=Hs();return t(r)},Gw=()=>Jf(t=>t.runtime.isDesktop),Qf=()=>Jf(t=>t.runtime.isVSCode),kl=({containerRef:t,minThumbSize:r=32,hideDelayMs:s=1e3,className:n,disableHorizontal:o=!1})=>{const[a,c]=i.useState(!1),[l,d]=i.useState({length:0,offset:0}),[u,m]=i.useState({length:0,offset:0}),f=i.useRef(null),p=i.useRef(null),h=i.useRef(!1),g=i.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),x=i.useRef(null),b=i.useCallback(()=>{const M=t.current;if(!M)return;const{scrollHeight:w,clientHeight:T,scrollTop:E,scrollWidth:I,clientWidth:A,scrollLeft:P}=M,F=8;if(w>T){const z=Math.max(T-F*2,0),G=T/w*z,oe=Math.max(r,Math.min(z,G)),O=Math.max(z-oe,0),q=Math.max(w-T,1),Y=E/q*O;d({length:oe,offset:Y})}else d({length:0,offset:0});if(!o&&I>A){const z=Math.max(A-F*2,0),G=A/I*z,oe=Math.max(r,Math.min(z,G)),O=Math.max(z-oe,0),q=Math.max(I-A,1),Y=P/q*O;m({length:oe,offset:Y})}else m({length:0,offset:0})},[t,r,o]),y=i.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>c(!1),s)},[s]),v=i.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{b(),c(!0),y()})},[y,b]);i.useEffect(()=>{const M=t.current;if(!M)return;b(),c(!0),y(),M.addEventListener("scroll",v,{passive:!0});const w=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null;w?.observe(M);const T=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return T?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",v),w?.disconnect(),T?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[t,v,y,b]);const S=(M,w)=>{const T=t.current;T&&(h.current=!0,g.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:T.scrollTop,scrollLeft:T.scrollLeft},x.current=w,c(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},C=M=>{if(!h.current)return;const w=t.current;if(!w)return;const T=x.current;if(T==="vertical"){const{pointerY:E,scrollTop:I}=g.current,A=M.clientY-E,P=w.clientHeight,F=Math.max(P-l.length,1),z=Math.max(w.scrollHeight-w.clientHeight,1),G=A/F*z;w.scrollTop=I+G}else if(T==="horizontal"){const{pointerX:E,scrollLeft:I}=g.current,A=M.clientX-E,P=w.clientWidth,F=Math.max(P-u.length,1),z=Math.max(w.scrollWidth-w.clientWidth,1),G=A/F*z;w.scrollLeft=I+G}},N=M=>{h.current&&(h.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),y())},j=l.length>0,D=u.length>0;if(!j&&!D)return null;const k=8;return e.jsxs("div",{className:R("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[j&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${l.length}px`,top:`${k+l.offset}px`,right:`${k/2}px`},onPointerDown:M=>S(M,"vertical"),onPointerMove:C,onPointerUp:N,onPointerCancel:N}),D&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${k+u.offset}px`,bottom:`${k/2}px`},onPointerDown:M=>S(M,"horizontal"),onPointerMove:C,onPointerUp:N,onPointerCancel:N})]})},xt=i.forwardRef(({className:t,outerClassName:r,children:s,style:n,minThumbSize:o,hideDelayMs:a,as:c="div",scrollbarClassName:l,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const h=i.useRef(null);return i.useImperativeHandle(p,()=>h.current,[]),e.jsxs("div",{className:R("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-auto",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(c,{ref:h,className:R("overlay-scrollbar-target overlay-scrollbar-container overscroll-auto",u?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",t),style:n,...f,children:s}),e.jsx(kl,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:l,disableHorizontal:d})]})});xt.displayName="ScrollableOverlay";const zd="mobile-overlay-root",qw=()=>{if(typeof document>"u")return null;let t=document.getElementById(zd);return t||(t=document.createElement("div"),t.id=zd,document.body.appendChild(t)),t},Ws=({open:t,title:r,onClose:s,children:n,footer:o,className:a,contentMaxHeightClassName:c,renderHeader:l})=>{const d=i.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=qw()),i.useEffect(()=>{if(!t)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const p=h=>{h.key==="Escape"&&s()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",p)}},[t,s]),!t||!d.current)return null;const u=c??"max-h-[min(70vh,520px)]",m=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:s,children:e.jsxs("div",{className:R("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),"data-keyboard-avoid":"true",onClick:f=>f.stopPropagation(),children:[(()=>{const f=e.jsx("button",{type:"button",onClick:s,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(es,{className:"h-4 w-4"})});return l?l(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(xt,{outerClassName:u,className:"px-2 py-2 pwa-overlay-scroll",children:n}),o?e.jsx("div",{className:"border-t border-border/40 px-3 py-2",children:o}):null]})});return Lm.createPortal(m,d.current)},zc=({totalTokens:t,percentage:r,contextLimit:s,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[c,l]=i.useState(!1),d=i.useRef(void 0),u=b=>b>=1e6?`${(b/1e6).toFixed(1)}M`:b>=1e3?`${(b/1e3).toFixed(1)}K`:b.toFixed(1).replace(/\.0$/,""),m=b=>b>=90?"text-status-error":b>=75?"text-status-warning":"text-status-success",f=typeof n=="number"?Math.max(n,0):0,p=[`Used tokens: ${u(t)}`,`Context limit: ${u(s)}`,`Output limit: ${u(f)}`],h=i.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{l(!0)},500)},[]),g=i.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);i.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const x=e.jsxs("div",{className:R("app-region-no-drag flex items-center gap-1.5 text-muted-foreground/60 select-none",o==="compact"?"typography-micro":"typography-meta"),"aria-label":"Context usage",onTouchStart:a?h:void 0,onTouchEnd:a?g:void 0,children:[!a&&e.jsx(Jh,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:R(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[x,e.jsx(Ws,{open:c,onClose:()=>l(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(s)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(f)})]}),e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:R("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:x}),e.jsx(lt,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(b=>e.jsx("p",{className:"typography-micro leading-tight",children:b},b))})})]})},jo={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Yf=(t,r,s)=>{if(typeof window>"u")return;const n=document.documentElement,o=r==="mobile",a=r==="tablet";n.classList.remove("device-mobile","device-tablet","device-desktop"),n.classList.add(r==="mobile"?"device-mobile":r==="tablet"?"device-tablet":"device-desktop"),t?(n.classList.add("desktop-runtime"),n.style.setProperty("--is-mobile","0"),n.style.setProperty("--device-type","desktop"),n.style.setProperty("--font-scale","1"),n.style.setProperty("--has-coarse-pointer","0"),n.style.setProperty("--has-touch-input","0"),n.classList.remove("mobile-pointer")):(n.classList.remove("desktop-runtime"),n.style.setProperty("--is-mobile",o?"1":"0"),n.style.setProperty("--device-type",r),n.style.setProperty("--font-scale",o?"0.9":a?"0.95":"1"),n.style.setProperty("--has-coarse-pointer",s?"1":"0"),n.style.setProperty("--has-touch-input",s?"1":"0"),s?n.classList.add("mobile-pointer"):n.classList.remove("mobile-pointer"))};function Ji(){const t=window.innerWidth,r=typeof window.matchMedia=="function",s=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=s?.matches??!1,a=n?.matches??!1,c=typeof navigator<"u"?navigator.maxTouchPoints??0:0,l=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||c>0,u=t>jo.md&&t<=jo.lg,m=t<=jo.md;let f=d&&m,p=d&&!f&&u,h=!d||t>jo.lg,g="desktop";l?(f=!1,p=!1,h=!0,g="desktop"):f?g="mobile":p?g="tablet":(h=!0,g="desktop"),Yf(l,g,d);let x="xs";for(const[b,y]of Object.entries(jo))t>=y&&(x=b);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:g,screenWidth:t,breakpoint:x,hasTouchInput:d}}function Gt(){const[t,r]=i.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Ji());return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(Ji())};return window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[]),i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const s=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(Ji())},a=[],c=l=>{l&&(typeof l.addEventListener=="function"?(l.addEventListener("change",o),a.push(()=>l.removeEventListener("change",o))):typeof l.addListener=="function"&&(l.addListener(o),a.push(()=>l.removeListener(o))))};return c(s),c(n),()=>{a.forEach(l=>l())}},[]),i.useEffect(()=>{if(typeof window>"u")return;const s=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,c=o?.matches??!1,l=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=c||l||d>0;Yf(s,t.deviceType,u)},[t.deviceType,t.hasTouchInput]),t}const Yo=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s,newSessionDraft:n}=ve(),{currentDirectory:o}=vt();if(t){const a=s.get(t);if(a?.path)return a.path;const l=r.find(d=>d.id===t)?.directory;if(l)return l}return n?.open&&n.directoryOverride?n.directoryOverride:o??void 0},ua=5e3,Kw=1e4,Jw=5e3,Qw=1e4,Yw=25,Xw=4,Hd=15e3,Zw=30,ev=20*1024*1024,yr=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),Wd=(t,r=Zw,s=ev)=>{let n=0;for(const l of t.values())n+=(l.original?.length??0)+(l.modified?.length??0);if(t.size<=r&&n<=s)return t;const o=Array.from(t.entries()).sort((l,d)=>l[1].fetchedAt-d[1].fetchedAt),a=new Map;let c=0;for(let l=o.length-1;l>=0;l--){const[d,u]=o[l],m=(u.original?.length??0)+(u.modified?.length??0);if(a.size>=r)break;c+m>s&&a.size>0||(a.set(d,u),c+=m)}return a},tv=(t,r)=>{if(!t&&!r)return!1;if(!t||!r)return!0;const s=new Set([...Object.keys(t),...Object.keys(r)]);for(const n of s){const o=t[n],a=r[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},sv=(t,r)=>{if(!t&&!r)return!1;if(!t||!r)return!0;const s=t.files??[],n=r.files??[];if(s.length!==n.length||t.ahead!==r.ahead||t.behind!==r.behind||t.current!==r.current||t.tracking!==r.tracking||t.isClean!==r.isClean)return!0;const o=new Set(s.map(a=>`${a.path}:${a.index}:${a.working_dir}`));for(const a of n)if(!o.has(`${a.path}:${a.index}:${a.working_dir}`))return!0;return!!tv(t.diffStats,r.diffStats)},rv=(t,r)=>{const s=new Set;if(!r)return s;const n=t?.files??[],o=r.files??[],a=new Map(n.map(f=>[f.path,f])),c=new Map(o.map(f=>[f.path,f])),l=new Set([...a.keys(),...c.keys()]);for(const f of l){const p=a.get(f),h=c.get(f);if(!p||!h){s.add(f);continue}if(p.index!==h.index||p.working_dir!==h.working_dir){s.add(f);continue}}const d=t?.diffStats??{},u=r.diffStats??{},m=new Set([...Object.keys(d),...Object.keys(u)]);for(const f of m){const p=d[f],h=u[f];if(!p||!h){s.add(f);continue}(p.insertions!==h.insertions||p.deletions!==h.deletions)&&s.add(f)}return s},is=ns()(fs((t,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:ua,setActiveDirectory:s=>{const{activeDirectory:n,directories:o}=r();if(n!==s)if(s&&!o.has(s)){const a=new Map(o);a.set(s,yr()),t({activeDirectory:s,directories:a})}else t({activeDirectory:s})},getDirectoryState:s=>r().directories.get(s)??null,fetchStatus:async(s,n,o={})=>{const{silent:a=!1}=o,{directories:c}=r();let l=c.get(s);l||(l=yr()),a||t({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(s)){const f=new Map(c);return f.set(s,{...l,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),t({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(s);if(sv(l.status,m)){d=!0;const f=new Map(r().directories),p=f.get(s)??yr(),h=rv(p.status,m),g=new Set((p.status?.files??[]).map(v=>v.path)),x=new Set((m.files??[]).map(v=>v.path)),b=new Map(p.diffCache);for(const v of g)x.has(v)||b.delete(v);for(const v of h)b.delete(v);const y=h.size>0;f.set(s,{...p,isGitRepo:!0,status:m,diffCache:b,lastStatusFetch:Date.now(),lastStatusChange:y?Date.now():p.lastStatusChange}),t({directories:f})}else{const f=new Map(r().directories),p=f.get(s)??yr();f.set(s,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),t({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||t({isLoadingStatus:!1})}return d},fetchBranches:async(s,n)=>{t({isLoadingBranches:!0});try{const o=await n.getGitBranches(s),a=new Map(r().directories),c=a.get(s)??yr();a.set(s,{...c,branches:o}),t({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{t({isLoadingBranches:!1})}},fetchLog:async(s,n,o)=>{const{directories:a}=r(),c=a.get(s),l=o??c?.logMaxCount??25;t({isLoadingLog:!0});try{const d=await n.getGitLog(s,{maxCount:l}),u=new Map(r().directories),m=u.get(s)??yr();u.set(s,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:l}),t({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{t({isLoadingLog:!1})}},fetchIdentity:async(s,n)=>{t({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(s),a=new Map(r().directories),c=a.get(s)??yr();a.set(s,{...c,identity:o}),t({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{t({isLoadingIdentity:!1})}},fetchAll:async(s,n,o={})=>{const{directories:a}=r();let c=a.get(s);if(!c){c=yr();const f=new Map(a);f.set(s,c),t({directories:f})}const{force:l=!1}=o,d=Date.now();await r().fetchStatus(s,n);const u=r().directories.get(s);if(!u?.isGitRepo)return;await r().fetchBranches(s,n);const m=d-(u.lastLogFetch||0);(l||m>Qw||!u.log)&&await r().fetchLog(s,n),await r().fetchIdentity(s,n),r().fetchAllDiffs(s,n)},getDiff:(s,n)=>r().directories.get(s)?.diffCache.get(n)??null,setDiff:(s,n,o)=>{const a=new Map(r().directories),c=a.get(s)??yr(),l=new Map(c.diffCache);l.set(n,{...o,fetchedAt:Date.now()});const d=Wd(l);a.set(s,{...c,diffCache:d}),t({directories:a})},clearDiffCache:s=>{const n=new Map(r().directories),o=n.get(s);o&&(n.set(s,{...o,diffCache:new Map}),t({directories:n}))},fetchAllDiffs:async(s,n)=>{const o=r().directories.get(s);if(!o?.status?.files||o.status.files.length===0)return;const l=o.status.files.filter(S=>!o.diffCache.has(S.path)).slice(0,Yw);if(l.length===0)return;let d=0;const u=[],m=()=>{const S=d;return d+=1,S<l.length?l[S]:null},f=async S=>{const C=n.getGitFileDiff(s,{path:S}),N=new Promise((D,k)=>{setTimeout(()=>k(new Error(`Timed out after ${Hd}ms`)),Hd)}),j=await Promise.race([C,N]);return{path:S,diff:{original:j.original??"",modified:j.modified??""}}},p=async()=>{for(;;){const S=m();if(!S)return;try{u.push(await f(S.path))}catch{}}},h=Math.min(Xw,l.length);await Promise.allSettled(Array.from({length:h},()=>p()));const g=new Map(r().directories),x=g.get(s);if(!x)return;const b=new Map(x.diffCache),y=Date.now();u.forEach(S=>{b.set(S.path,{...S.diff,fetchedAt:y})});const v=Wd(b);g.set(s,{...x,diffCache:v}),t({directories:g})},setLogMaxCount:(s,n)=>{const o=new Map(r().directories),a=o.get(s)??yr();o.set(s,{...a,logMaxCount:n}),t({directories:o})},startPolling:s=>{const{pollIntervalId:n}=r();if(n)return;const o=()=>{const{currentPollInterval:a}=r();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){t({pollIntervalId:o()});return}const{activeDirectory:l}=r();if(!l){t({pollIntervalId:o()});return}if(await r().fetchStatus(l,s,{silent:!0}))await r().fetchLog(l,s),r().fetchAllDiffs(l,s),t({currentPollInterval:ua});else{const m=Math.min(a+Jw,Kw);t({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&t({pollIntervalId:o()})},a)};t({pollIntervalId:o(),currentPollInterval:ua})},stopPolling:()=>{const{pollIntervalId:s}=r();s&&(clearTimeout(s),t({pollIntervalId:null,currentPollInterval:ua}))},refresh:async(s,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,s,n)}}),{name:"git-store"})),Xf=t=>is(r=>t?r.directories.get(t)?.status??null:null),Zf=t=>is(r=>t?r.directories.get(t)?.branches??null:null),nv=t=>is(r=>t?r.directories.get(t)?.log??null:null),ov=t=>is(r=>t?r.directories.get(t)?.identity??null:null),ep=t=>is(r=>t?r.directories.get(t)?.isGitRepo??null:null),av=t=>is(r=>t?r.directories.get(t)?.status?.files?.length??0:0),iv=Qh("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg typography-ui-label font-medium transition-[background-color,border-color,color,box-shadow,opacity] duration-150 ease-in-out disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-none hover:bg-primary/90",destructive:"bg-destructive text-white shadow-none hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-none hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-none hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-lg gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-lg px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function Se({className:t,variant:r,size:s,asChild:n=!1,...o}){const a=n?Om:"button";return e.jsx(a,{"data-slot":"button",className:R(iv({variant:r,size:s,className:t})),...o})}const Pn=Yh,xo=({className:t,...r})=>e.jsx(Xh,{className:R("flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left text-foreground hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",t),...r}),Tn=({className:t,...r})=>e.jsx(Zh,{className:R("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",t),...r}),cv={read:{displayName:"Read File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"offset",label:"Start Line",type:"text"},{key:"limit",label:"Lines to Read",type:"text"}]},write:{displayName:"Write File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"content",label:"Content",type:"code"}]},edit:{displayName:"Edit File",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"oldString",label:"Find",type:"code"},{key:"newString",label:"Replace",type:"code"},{key:"replaceAll",label:"Replace All",type:"text"}]},multiedit:{displayName:"Multi-Edit",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"edits",label:"Edits",type:"code",language:"json"}]},apply_patch:{displayName:"Apply Patch",category:"file",outputLanguage:"diff",inputFields:[{key:"patchText",label:"Patch",type:"code",language:"diff"}]},bash:{displayName:"Shell Command",category:"system",outputLanguage:"text",inputFields:[{key:"command",label:"Command",type:"command",language:"bash"},{key:"description",label:"Description",type:"text"},{key:"timeout",label:"Timeout (ms)",type:"text"}]},grep:{displayName:"Search Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"},{key:"include",label:"Include Pattern",type:"pattern"}]},glob:{displayName:"Find Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"}]},list:{displayName:"List Directory",category:"file",outputLanguage:"text",inputFields:[{key:"path",label:"Directory",type:"file"},{key:"ignore",label:"Ignore Patterns",type:"pattern"}]},task:{displayName:"Agent Task",category:"ai",outputLanguage:"markdown",inputFields:[{key:"description",label:"Task",type:"text"},{key:"prompt",label:"Instructions",type:"text"},{key:"subagent_type",label:"Agent Type",type:"text"}]},webfetch:{displayName:"Fetch URL",category:"web",outputLanguage:"auto",inputFields:[{key:"url",label:"URL",type:"text"},{key:"format",label:"Format",type:"text"},{key:"timeout",label:"Timeout",type:"text"}]},websearch:{displayName:"Web Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"numResults",label:"Results Count",type:"text"},{key:"type",label:"Search Type",type:"text"}]},codesearch:{displayName:"Code Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"tokensNum",label:"Tokens",type:"text"}]},todowrite:{displayName:"Update Todo List",category:"system",outputLanguage:"json",inputFields:[{key:"todos",label:"Todo Items",type:"code",language:"json"}]},todoread:{displayName:"Read Todo List",category:"system",outputLanguage:"json",inputFields:[]},skill:{displayName:"Load Skill",category:"ai",outputLanguage:"markdown",inputFields:[{key:"name",label:"Skill Name",type:"text"}]},question:{displayName:"Question",category:"ai",outputLanguage:"text",inputFields:[{key:"questions",label:"Questions",type:"code",language:"json"}]},plan_enter:{displayName:"Plan Mode",category:"ai",outputLanguage:"text",inputFields:[]},plan_exit:{displayName:"Build Mode",category:"ai",outputLanguage:"text",inputFields:[]}};function Cl(t){return cv[t]||{displayName:t.charAt(0).toUpperCase()+t.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function lv(t,r,s){const n=Cl(t);if(n.outputLanguage==="auto"){if(s?.filePath||s?.file_path||s?.sourcePath){const o=s.filePath||s.file_path||s.sourcePath,a=Er(o);if(a)return a}if(t==="webfetch"){if(r.trim().startsWith("{")||r.trim().startsWith("["))try{return JSON.parse(r),"json"}catch{}if(r.trim().startsWith("<"))return"html";if(r.includes("```"))return"markdown"}return"text"}return n.outputLanguage||"text"}function Er(t){const r=t.split(".").pop()?.toLowerCase(),s=t.split("/").pop()?.toLowerCase()||"",n={dockerfile:"dockerfile",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake",gemfile:"ruby",rakefile:"ruby",podfile:"ruby",vagrantfile:"ruby",guardfile:"ruby",brewfile:"ruby",fastfile:"ruby",appfile:"ruby",matchfile:"ruby",pluginfile:"ruby",scanfile:"ruby",snapfile:"ruby",".gitignore":"text",".gitattributes":"text",".gitmodules":"ini",".editorconfig":"ini",".npmrc":"ini",".yarnrc":"yaml",".prettierrc":"json",".eslintrc":"json",".babelrc":"json",".browserslistrc":"text","tsconfig.json":"jsonc","jsconfig.json":"jsonc",".env":"bash",".env.local":"bash",".env.development":"bash",".env.production":"bash",".env.test":"bash",procfile:"yaml",codeowners:"text","package-lock.json":"json","composer.lock":"json","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","cargo.lock":"toml","poetry.lock":"toml","gemfile.lock":"ruby","pubspec.lock":"yaml","packages.lock.json":"json","bun.lockb":"text","bun.lock":"json"};return n[s]?n[s]:{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",mts:"typescript",cts:"typescript",html:"html",htm:"html",xhtml:"html",vue:"html",svelte:"html",astro:"html",ejs:"html",hbs:"handlebars",handlebars:"handlebars",mustache:"handlebars",njk:"twig",nunjucks:"twig",twig:"twig",liquid:"liquid",css:"css",scss:"scss",sass:"sass",less:"less",styl:"stylus",stylus:"stylus",pcss:"css",postcss:"css",json:"json",jsonc:"json",json5:"json",jsonl:"json",ndjson:"json",geojson:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",xsl:"xml",xslt:"xml",xsd:"xml",dtd:"xml",plist:"xml",svg:"xml",rss:"xml",atom:"xml",xaml:"xml",csproj:"xml",vbproj:"xml",fsproj:"xml",props:"xml",targets:"xml",nuspec:"xml",resx:"xml",ini:"ini",cfg:"ini",conf:"ini",config:"ini",properties:"properties",env:"bash",csv:"text",tsv:"text",py:"python",pyw:"python",pyx:"python",pxd:"python",pxi:"python",pyi:"python",gyp:"python",gypi:"python",bzl:"python",rb:"ruby",erb:"erb",rake:"ruby",gemspec:"ruby",ru:"ruby",podspec:"ruby",thor:"ruby",jbuilder:"ruby",rabl:"ruby",builder:"ruby",php:"php",phtml:"php",php3:"php",php4:"php",php5:"php",php7:"php",phps:"php",inc:"php","blade.php":"php",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",sc:"scala",groovy:"groovy",gradle:"groovy",gvy:"groovy",gy:"groovy",gsh:"groovy",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hxx:"cpp",hh:"cpp","h++":"cpp",ino:"cpp",m:"objectivec",mm:"objectivec",cs:"csharp",csx:"csharp",cake:"csharp",fs:"fsharp",fsx:"fsharp",fsi:"fsharp",vb:"vbnet",go:"go",mod:"go",sum:"text",rs:"rust",swift:"swift",dart:"dart",lua:"lua",pl:"perl",pm:"perl",pod:"perl",t:"perl",r:"r",R:"r",rmd:"markdown",rnw:"r",jl:"julia",hs:"haskell",lhs:"haskell",ex:"elixir",exs:"elixir",eex:"elixir",heex:"elixir",leex:"elixir",erl:"erlang",hrl:"erlang",clj:"clojure",cljs:"clojure",cljc:"clojure",edn:"clojure",lisp:"lisp",cl:"lisp",el:"lisp",scm:"scheme",ss:"scheme",rkt:"scheme",ml:"ocaml",mli:"ocaml",re:"reason",rei:"reason",nim:"nim",nims:"nim",nimble:"nim",zig:"zig",v:"v",vsh:"v",cr:"crystal",d:"d",di:"d",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ksh:"bash",csh:"bash",tcsh:"bash",ps1:"powershell",psm1:"powershell",psd1:"powershell",bat:"batch",cmd:"batch",sql:"sql",psql:"sql",plsql:"sql",mysql:"sql",pgsql:"sql",sqlite:"sql",graphql:"graphql",gql:"graphql",sol:"solidity",asm:"nasm",s:"nasm",S:"nasm",nix:"nix",tf:"hcl",tfvars:"hcl",hcl:"hcl",dockerignore:"text",pp:"puppet",tex:"latex",latex:"latex",sty:"latex",cls:"latex",bib:"bibtex",bst:"bibtex",md:"markdown",mdx:"markdown",markdown:"markdown",mdown:"markdown",mkd:"markdown",rst:"text",adoc:"asciidoc",asciidoc:"asciidoc",org:"text",txt:"text",text:"text",rtf:"text",vim:"vim",vimrc:"vim",mk:"makefile",cmake:"cmake",diff:"diff",patch:"diff",prisma:"prisma",proto:"protobuf",thrift:"thrift",wat:"wasm",wast:"wasm",glsl:"glsl",vert:"glsl",frag:"glsl",geom:"glsl",comp:"glsl",hlsl:"hlsl",fx:"hlsl",cg:"cg",shader:"glsl",htaccess:"apacheconf",nginx:"nginx",kubeconfig:"yaml",ansible:"yaml"}[r||""]||null}const dv=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function Ho(t){const r=t.split(".").pop()?.toLowerCase();return dv.includes(r||"")}function Hc(t){const r=t.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif"}[r||""]||"image/png"}function uv(t,r){if(!t)return"";const s=n=>{const o=t[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(r==="bash"){const n=s("command");if(n)return n}if(r==="task"){const n=s("prompt");if(n)return n;const o=s("description");if(o)return o}if(r==="apply_patch"&&typeof t=="object"){const n=s("patchText")||s("patch_text")||s("patch");if(n)return n}if((r==="edit"||r==="multiedit")&&typeof t=="object"){const n=s("filePath")||s("file_path")||s("path");if(n)return`File path: ${n}`}if(r==="write"&&typeof t=="object"){const n=s("content");if(n)return n}return typeof t=="object"?Object.entries(t).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const c=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let l=a;return typeof a=="object"?l=JSON.stringify(a,null,2):typeof a=="boolean"&&(l=a?"Yes":"No"),`${c}: ${l}`}).join(`
12
+ `):String(t)}const tp=({mode:t,onModeChange:r,className:s})=>{const n=i.useCallback(o=>{o.stopPropagation(),r(t==="side-by-side"?"unified":"side-by-side")},[t,r]);return e.jsx(Se,{size:"sm",variant:"ghost",className:R("h-5 w-5 p-0 opacity-60 hover:opacity-100",s),onClick:n,title:t==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:t==="side-by-side"?e.jsx(eg,{className:"h-3 w-3"}):e.jsx(tg,{className:"h-3 w-3"})})},Ml=Ae.createContext(void 0);function Wr(){const t=Ae.useContext(Ml);if(!t)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return t}function Ci(){return Ae.useContext(Ml)}const mv="Flexoki",fv="dark",pv={"editor.background":"#100F0F","editor.foreground":"#CECDC3","editor.hoverHighlightBackground":"#343331","editor.lineHighlightBackground":"#1C1B1A","editor.selectionBackground":"#CECDC333","editor.selectionHighlightBackground":"#CECDC333","editor.findMatchBackground":"#AD8301","editor.findMatchHighlightBackground":"#AD8301cc","editor.findRangeHighlightBackground":"#1C1B1A","editor.inactiveSelectionBackground":"#282726","editor.lineHighlightBorder":"#282726","editor.rangeHighlightBackground":"#403E3C","notifications.background":"#282726","editorInlayHint.typeBackground":"#343331","editorInlayHint.typeForeground":"#CECDC3","editorWhitespace.foreground":"#403E3C","editorIndentGuide.background1":"#343331","editorHoverWidget.background":"#282726","editorLineNumber.activeForeground":"#CECDC3","editorLineNumber.foreground":"#403E3C","editorGutter.background":"#100F0F","editorGutter.modifiedBackground":"#3AA99F","editorGutter.addedBackground":"#879A39","editorGutter.deletedBackground":"#D14D41","editorBracketMatch.background":"#282726","editorBracketMatch.border":"#343331","editorError.foreground":"#D14D41","editorWarning.foreground":"#DA702C","editorInfo.foreground":"#4385BE","diffEditor.insertedTextBackground":"#66800B99","diffEditor.removedTextBackground":"#AF302999","editorGroupHeader.tabsBackground":"#100F0F","editorGroup.border":"#343331","tab.activeBackground":"#100F0F","tab.inactiveBackground":"#1C1B1A","tab.inactiveForeground":"#878580","tab.activeForeground":"#CECDC3","tab.hoverBackground":"#343331","tab.unfocusedHoverBackground":"#343331","tab.border":"#343331","tab.activeModifiedBorder":"#D0A215","tab.inactiveModifiedBorder":"#4385BE","tab.unfocusedActiveModifiedBorder":"#AD8301","tab.unfocusedInactiveModifiedBorder":"#205EA6","editorWidget.background":"#1C1B1A","editorWidget.border":"#343331","editorSuggestWidget.background":"#100F0F","editorSuggestWidget.border":"#343331","editorSuggestWidget.foreground":"#CECDC3","editorSuggestWidget.highlightForeground":"#878580","editorSuggestWidget.selectedBackground":"#343331","peekView.border":"#343331","peekViewEditor.background":"#100F0F","peekViewEditor.matchHighlightBackground":"#403E3C","peekViewResult.background":"#1C1B1A","peekViewResult.fileForeground":"#CECDC3","peekViewResult.lineForeground":"#878580","peekViewResult.matchHighlightBackground":"#403E3C","peekViewResult.selectionBackground":"#282726","peekViewResult.selectionForeground":"#575653","peekViewTitle.background":"#343331","peekViewTitleDescription.foreground":"#878580","peekViewTitleLabel.foreground":"#CECDC3","merge.currentHeaderBackground":"#879A39","merge.currentContentBackground":"#66800B","merge.incomingHeaderBackground":"#3AA99F","merge.incomingContentBackground":"#24837B","merge.border":"#343331","merge.commonContentBackground":"#403E3C","merge.commonHeaderBackground":"#343331","panel.background":"#100F0F","panel.border":"#343331","panelTitle.activeBorder":"#403E3C","panelTitle.activeForeground":"#CECDC3","panelTitle.inactiveForeground":"#878580","statusBar.background":"#100F0F","statusBar.foreground":"#CECDC3","statusBar.border":"#343331","statusBar.debuggingBackground":"#D14D41","statusBar.debuggingForeground":"#CECDC3","statusBar.noFolderBackground":"#403E3C","statusBar.noFolderForeground":"#575653","titleBar.activeBackground":"#100F0F","titleBar.activeForeground":"#CECDC3","titleBar.inactiveBackground":"#1C1B1A","titleBar.inactiveForeground":"#878580","titleBar.border":"#343331","menu.foreground":"#CECDC3","menu.background":"#100F0F","menu.selectionForeground":"#CECDC3","menu.selectionBackground":"#343331","menu.border":"#343331","editorInlayHint.foreground":"#878580","editorInlayHint.background":"#343331","terminal.foreground":"#CECDC3","terminal.background":"#100F0F","terminalCursor.foreground":"#CECDC3","terminalCursor.background":"#100F0F","terminal.ansiRed":"#D14D41","terminal.ansiGreen":"#879A39","terminal.ansiYellow":"#D0A215","terminal.ansiBlue":"#4385BE","terminal.ansiMagenta":"#3AA99F","terminal.ansiCyan":"#3AA99F","activityBar.background":"#100F0F","activityBar.foreground":"#CECDC3","activityBar.inactiveForeground":"#878580","activityBar.activeBorder":"#CECDC3","activityBar.border":"#343331","sideBar.background":"#100F0F","sideBar.foreground":"#CECDC3","sideBar.border":"#343331","sideBarTitle.foreground":"#CECDC3","sideBarSectionHeader.background":"#1C1B1A","sideBarSectionHeader.foreground":"#CECDC3","sideBarSectionHeader.border":"#343331","sideBar.activeBackground":"#403E3C","sideBar.activeForeground":"#CECDC3","sideBar.hoverBackground":"#343331","sideBar.hoverForeground":"#878580","sideBar.folderIcon.foreground":"#879A39","sideBar.fileIcon.foreground":"#4385BE","list.warningForeground":"#DA702C","list.errorForeground":"#D14D41","list.inactiveSelectionBackground":"#343331","list.activeSelectionBackground":"#403E3C","list.inactiveSelectionForeground":"#CECDC3","list.activeSelectionForeground":"#CECDC3","list.hoverForeground":"#CECDC3","list.hoverBackground":"#343331","input.background":"#1C1B1A","input.foreground":"#CECDC3","input.border":"#343331","input.placeholderForeground":"#878580","inputOption.activeBorder":"#343331","inputOption.activeBackground":"#282726","inputOption.activeForeground":"#CECDC3","inputValidation.infoBackground":"#3AA99F","inputValidation.infoBorder":"#24837B","inputValidation.warningBackground":"#DA702C","inputValidation.warningBorder":"#BC5215","inputValidation.errorBackground":"#D14D41","inputValidation.errorBorder":"#AF3029","dropdown.background":"#1C1B1A","dropdown.foreground":"#CECDC3","dropdown.border":"#343331","dropdown.listBackground":"#100F0F","badge.background":"#3AA99F","activityBarBadge.background":"#3AA99F","button.background":"#3AA99F","button.foreground":"#100F0F","badge.foreground":"#100F0F","activityBarBadge.foreground":"#100F0F"},hv=[{name:"plain",scope:["source","support.type.property-name.css"],settings:{foreground:"#CECDC3"}},{name:"classes",scope:["entity.name.type.class"],settings:{foreground:"#DA702C"}},{name:"interfaces",scope:["entity.name.type.interface","entity.name.type"],settings:{foreground:"#D0A215"}},{name:"structs",scope:["entity.name.type.struct"],settings:{foreground:"#DA702C"}},{name:"enums",scope:["entity.name.type.enum"],settings:{foreground:"#DA702C"}},{name:"keys",scope:["meta.object-literal.key","support.type.property-name"],settings:{foreground:"#DA702C"}},{name:"methods",scope:["entity.name.function.method","meta.function.method"],settings:{foreground:"#879A39"}},{name:"functions",scope:["entity.name.function","support.function","meta.function-call.generic"],settings:{foreground:"#DA702C",fontStyle:"bold"}},{name:"variables",scope:["variable","meta.variable","variable.other.object.property"],settings:{foreground:"#CECDC3"}},{name:"variablesOther",scope:["variable.other.object","variable.other.readwrite.alias"],settings:{foreground:"#879A39"}},{name:"globalVariables",scope:["variable.other.global","variable.language.this"],settings:{foreground:"#CE5D97"}},{name:"localVariables",scope:["variable.other.local"],settings:{foreground:"#282726"}},{name:"parameters",scope:["variable.parameter","meta.parameter"],settings:{foreground:"#CECDC3"}},{name:"properties",scope:["variable.other.property","meta.property"],settings:{foreground:"#4385BE"}},{name:"strings",scope:["string","string.other.link","markup.inline.raw.string.markdown"],settings:{foreground:"#3AA99F"}},{name:"stringEscapeSequences",scope:["constant.character.escape","constant.other.placeholder"],settings:{foreground:"#CECDC3"}},{name:"keywords",scope:["keyword"],settings:{foreground:"#879A39"}},{name:"keywordsControl",scope:["keyword.control.import","keyword.control.from","keyword.import"],settings:{foreground:"#D14D41"}},{name:"storageModifiers",scope:["storage.modifier","keyword.modifier","storage.type"],settings:{foreground:"#4385BE"}},{name:"comments",scope:["comment","punctuation.definition.comment"],settings:{foreground:"#878580"}},{name:"docComments",scope:["comment.documentation","comment.line.documentation"],settings:{foreground:"#575653"}},{name:"numbers",scope:["constant.numeric"],settings:{foreground:"#8B7EC8"}},{name:"booleans",scope:["constant.language.boolean","constant.language.json"],settings:{foreground:"#D0A215"}},{name:"operators",scope:["keyword.operator"],settings:{foreground:"#D14D41"}},{name:"macros",scope:["entity.name.function.preprocessor","meta.preprocessor"],settings:{foreground:"#4385BE"}},{name:"preprocessor",scope:["meta.preprocessor"],settings:{foreground:"#CE5D97"}},{name:"urls",scope:["markup.underline.link"],settings:{foreground:"#4385BE"}},{name:"tags",scope:["entity.name.tag"],settings:{foreground:"#4385BE"}},{name:"jsxTags",scope:["support.class.component"],settings:{foreground:"#CE5D97"}},{name:"attributes",scope:["entity.other.attribute-name","meta.attribute"],settings:{foreground:"#D0A215"}},{name:"types",scope:["support.type"],settings:{foreground:"#D0A215"}},{name:"constants",scope:["variable.other.constant","variable.readonly"],settings:{foreground:"#CECDC3"}},{name:"labels",scope:["entity.name.label","punctuation.definition.label"],settings:{foreground:"#CE5D97"}},{name:"namespaces",scope:["entity.name.namespace","storage.modifier.namespace","markup.bold.markdown"],settings:{foreground:"#D0A215"}},{name:"modules",scope:["entity.name.module","storage.modifier.module"],settings:{foreground:"#D14D41"}},{name:"typeParameters",scope:["variable.type.parameter","variable.parameter.type"],settings:{foreground:"#DA702C"}},{name:"exceptions",scope:["keyword.control.exception","keyword.control.trycatch"],settings:{foreground:"#CE5D97"}},{name:"decorators",scope:["meta.decorator","punctuation.decorator","entity.name.function.decorator"],settings:{foreground:"#D0A215"}},{name:"calls",scope:["variable.function"],settings:{foreground:"#CECDC3"}},{name:"punctuation",scope:["punctuation","punctuation.terminator","punctuation.definition.tag","punctuation.separator","punctuation.definition.string","punctuation.section.block"],settings:{foreground:"#878580"}},{name:"yellow",scope:["storage.type.numeric.go","storage.type.byte.go","storage.type.boolean.go","storage.type.string.go","storage.type.uintptr.go","storage.type.error.go","storage.type.rune.go","constant.language.go","support.class.dart","keyword.other.documentation","storage.modifier.import.java","punctuation.definition.list.begin.markdown","punctuation.definition.quote.begin.markdown","meta.separator.markdown","entity.name.section.markdown"],settings:{foreground:"#D0A215"}},{name:"green",scope:[],settings:{foreground:"#879A39"}},{name:"cyan",scope:["markup.italic.markdown","support.type.python","variable.legacy.builtin.python","support.constant.property-value.css","storage.modifier.attribute.swift"],settings:{foreground:"#3AA99F"}},{name:"blue",scope:[],settings:{foreground:"#4385BE"}},{name:"purple",scope:["keyword.channel.go","keyword.other.platform.os.swift"],settings:{foreground:"#8B7EC8"}},{name:"magenta",scope:["punctuation.definition.heading.markdown"],settings:{foreground:"#CE5D97"}},{name:"red",scope:[],settings:{foreground:"#D14D41"}},{name:"orange",scope:[],settings:{foreground:"#DA702C"}}],gv={name:mv,type:fv,colors:pv,tokenColors:hv},xv="Flexoki",yv="light",bv={"editor.background":"#FFFCF0","editor.foreground":"#100F0F","editor.hoverHighlightBackground":"#DAD8CE","editor.lineHighlightBackground":"#F2F0E5","editor.selectionBackground":"#100F0F44","editor.selectionHighlightBackground":"#100F0F44","editor.findMatchBackground":"#D0A215","editor.findMatchHighlightBackground":"#D0A215cc","editor.findRangeHighlightBackground":"#F2F0E5","editor.inactiveSelectionBackground":"#E6E4D9","editor.lineHighlightBorder":"#E6E4D9","editor.rangeHighlightBackground":"#CECDC3","notifications.background":"#E6E4D9","editorInlayHint.typeBackground":"#DAD8CE","editorInlayHint.typeForeground":"#100F0F","editorWhitespace.foreground":"#CECDC3","editorIndentGuide.background1":"#DAD8CE","editorHoverWidget.background":"#E6E4D9","editorLineNumber.activeForeground":"#100F0F","editorLineNumber.foreground":"#CECDC3","editorGutter.background":"#FFFCF0","editorGutter.modifiedBackground":"#24837B","editorGutter.addedBackground":"#66800B","editorGutter.deletedBackground":"#AF3029","editorBracketMatch.background":"#E6E4D9","editorBracketMatch.border":"#DAD8CE","editorError.foreground":"#AF3029","editorWarning.foreground":"#BC5215","editorInfo.foreground":"#205EA6","diffEditor.insertedTextBackground":"#879A3999","diffEditor.removedTextBackground":"#D14D4199","editorGroupHeader.tabsBackground":"#FFFCF0","editorGroup.border":"#DAD8CE","tab.activeBackground":"#FFFCF0","tab.inactiveBackground":"#F2F0E5","tab.inactiveForeground":"#6F6E69","tab.activeForeground":"#100F0F","tab.hoverBackground":"#DAD8CE","tab.unfocusedHoverBackground":"#DAD8CE","tab.border":"#DAD8CE","tab.activeModifiedBorder":"#AD8301","tab.inactiveModifiedBorder":"#205EA6","tab.unfocusedActiveModifiedBorder":"#D0A215","tab.unfocusedInactiveModifiedBorder":"#4385BE","editorWidget.background":"#F2F0E5","editorWidget.border":"#DAD8CE","editorSuggestWidget.background":"#FFFCF0","editorSuggestWidget.border":"#DAD8CE","editorSuggestWidget.foreground":"#100F0F","editorSuggestWidget.highlightForeground":"#6F6E69","editorSuggestWidget.selectedBackground":"#DAD8CE","peekView.border":"#DAD8CE","peekViewEditor.background":"#FFFCF0","peekViewEditor.matchHighlightBackground":"#CECDC3","peekViewResult.background":"#F2F0E5","peekViewResult.fileForeground":"#100F0F","peekViewResult.lineForeground":"#6F6E69","peekViewResult.matchHighlightBackground":"#CECDC3","peekViewResult.selectionBackground":"#E6E4D9","peekViewResult.selectionForeground":"#B7B5AC","peekViewTitle.background":"#DAD8CE","peekViewTitleDescription.foreground":"#6F6E69","peekViewTitleLabel.foreground":"#100F0F","merge.currentHeaderBackground":"#66800B","merge.currentContentBackground":"#879A39","merge.incomingHeaderBackground":"#24837B","merge.incomingContentBackground":"#3AA99F","merge.border":"#DAD8CE","merge.commonContentBackground":"#CECDC3","merge.commonHeaderBackground":"#DAD8CE","panel.background":"#FFFCF0","panel.border":"#DAD8CE","panelTitle.activeBorder":"#CECDC3","panelTitle.activeForeground":"#100F0F","panelTitle.inactiveForeground":"#6F6E69","statusBar.background":"#FFFCF0","statusBar.foreground":"#100F0F","statusBar.border":"#DAD8CE","statusBar.debuggingBackground":"#AF3029","statusBar.debuggingForeground":"#100F0F","statusBar.noFolderBackground":"#CECDC3","statusBar.noFolderForeground":"#B7B5AC","titleBar.activeBackground":"#FFFCF0","titleBar.activeForeground":"#100F0F","titleBar.inactiveBackground":"#F2F0E5","titleBar.inactiveForeground":"#6F6E69","titleBar.border":"#DAD8CE","menu.foreground":"#100F0F","menu.background":"#FFFCF0","menu.selectionForeground":"#100F0F","menu.selectionBackground":"#DAD8CE","menu.border":"#DAD8CE","editorInlayHint.foreground":"#6F6E69","editorInlayHint.background":"#DAD8CE","terminal.foreground":"#100F0F","terminal.background":"#FFFCF0","terminalCursor.foreground":"#100F0F","terminalCursor.background":"#FFFCF0","terminal.ansiRed":"#AF3029","terminal.ansiGreen":"#66800B","terminal.ansiYellow":"#AD8301","terminal.ansiBlue":"#205EA6","terminal.ansiMagenta":"#24837B","terminal.ansiCyan":"#24837B","activityBar.background":"#FFFCF0","activityBar.foreground":"#100F0F","activityBar.inactiveForeground":"#6F6E69","activityBar.activeBorder":"#100F0F","activityBar.border":"#DAD8CE","sideBar.background":"#FFFCF0","sideBar.foreground":"#100F0F","sideBar.border":"#DAD8CE","sideBarTitle.foreground":"#100F0F","sideBarSectionHeader.background":"#F2F0E5","sideBarSectionHeader.foreground":"#100F0F","sideBarSectionHeader.border":"#DAD8CE","sideBar.activeBackground":"#CECDC3","sideBar.activeForeground":"#100F0F","sideBar.hoverBackground":"#DAD8CE","sideBar.hoverForeground":"#6F6E69","sideBar.folderIcon.foreground":"#66800B","sideBar.fileIcon.foreground":"#205EA6","list.warningForeground":"#BC5215","list.errorForeground":"#AF3029","list.inactiveSelectionBackground":"#DAD8CE","list.activeSelectionBackground":"#CECDC3","list.inactiveSelectionForeground":"#100F0F","list.activeSelectionForeground":"#100F0F","list.hoverForeground":"#100F0F","list.hoverBackground":"#DAD8CE","input.background":"#F2F0E5","input.foreground":"#100F0F","input.border":"#DAD8CE","input.placeholderForeground":"#6F6E69","inputOption.activeBorder":"#DAD8CE","inputOption.activeBackground":"#E6E4D9","inputOption.activeForeground":"#100F0F","inputValidation.infoBackground":"#24837B","inputValidation.infoBorder":"#3AA99F","inputValidation.warningBackground":"#BC5215","inputValidation.warningBorder":"#DA702C","inputValidation.errorBackground":"#AF3029","inputValidation.errorBorder":"#D14D41","dropdown.background":"#F2F0E5","dropdown.foreground":"#100F0F","dropdown.border":"#DAD8CE","dropdown.listBackground":"#FFFCF0","badge.background":"#24837B","activityBarBadge.background":"#24837B","button.background":"#24837B","button.foreground":"#FFFCF0","badge.foreground":"#FFFCF0","activityBarBadge.foreground":"#FFFCF0"},wv=[{name:"plain",scope:["source","support.type.property-name.css"],settings:{foreground:"#100F0F"}},{name:"classes",scope:["entity.name.type.class"],settings:{foreground:"#BC5215"}},{name:"interfaces",scope:["entity.name.type.interface","entity.name.type"],settings:{foreground:"#AD8301"}},{name:"structs",scope:["entity.name.type.struct"],settings:{foreground:"#BC5215"}},{name:"enums",scope:["entity.name.type.enum"],settings:{foreground:"#BC5215"}},{name:"keys",scope:["meta.object-literal.key","support.type.property-name"],settings:{foreground:"#BC5215"}},{name:"methods",scope:["entity.name.function.method","meta.function.method"],settings:{foreground:"#66800B"}},{name:"functions",scope:["entity.name.function","support.function","meta.function-call.generic"],settings:{foreground:"#BC5215",fontStyle:"bold"}},{name:"variables",scope:["variable","meta.variable","variable.other.object.property"],settings:{foreground:"#100F0F"}},{name:"variablesOther",scope:["variable.other.object","variable.other.readwrite.alias"],settings:{foreground:"#66800B"}},{name:"globalVariables",scope:["variable.other.global","variable.language.this"],settings:{foreground:"#A02F6F"}},{name:"localVariables",scope:["variable.other.local"],settings:{foreground:"#E6E4D9"}},{name:"parameters",scope:["variable.parameter","meta.parameter"],settings:{foreground:"#100F0F"}},{name:"properties",scope:["variable.other.property","meta.property"],settings:{foreground:"#205EA6"}},{name:"strings",scope:["string","string.other.link","markup.inline.raw.string.markdown"],settings:{foreground:"#24837B"}},{name:"stringEscapeSequences",scope:["constant.character.escape","constant.other.placeholder"],settings:{foreground:"#100F0F"}},{name:"keywords",scope:["keyword"],settings:{foreground:"#66800B"}},{name:"keywordsControl",scope:["keyword.control.import","keyword.control.from","keyword.import"],settings:{foreground:"#AF3029"}},{name:"storageModifiers",scope:["storage.modifier","keyword.modifier","storage.type"],settings:{foreground:"#205EA6"}},{name:"comments",scope:["comment","punctuation.definition.comment"],settings:{foreground:"#6F6E69"}},{name:"docComments",scope:["comment.documentation","comment.line.documentation"],settings:{foreground:"#B7B5AC"}},{name:"numbers",scope:["constant.numeric"],settings:{foreground:"#5E409D"}},{name:"booleans",scope:["constant.language.boolean","constant.language.json"],settings:{foreground:"#AD8301"}},{name:"operators",scope:["keyword.operator"],settings:{foreground:"#AF3029"}},{name:"macros",scope:["entity.name.function.preprocessor","meta.preprocessor"],settings:{foreground:"#205EA6"}},{name:"preprocessor",scope:["meta.preprocessor"],settings:{foreground:"#A02F6F"}},{name:"urls",scope:["markup.underline.link"],settings:{foreground:"#205EA6"}},{name:"tags",scope:["entity.name.tag"],settings:{foreground:"#205EA6"}},{name:"jsxTags",scope:["support.class.component"],settings:{foreground:"#A02F6F"}},{name:"attributes",scope:["entity.other.attribute-name","meta.attribute"],settings:{foreground:"#AD8301"}},{name:"types",scope:["support.type"],settings:{foreground:"#AD8301"}},{name:"constants",scope:["variable.other.constant","variable.readonly"],settings:{foreground:"#100F0F"}},{name:"labels",scope:["entity.name.label","punctuation.definition.label"],settings:{foreground:"#A02F6F"}},{name:"namespaces",scope:["entity.name.namespace","storage.modifier.namespace","markup.bold.markdown"],settings:{foreground:"#AD8301"}},{name:"modules",scope:["entity.name.module","storage.modifier.module"],settings:{foreground:"#AF3029"}},{name:"typeParameters",scope:["variable.type.parameter","variable.parameter.type"],settings:{foreground:"#BC5215"}},{name:"exceptions",scope:["keyword.control.exception","keyword.control.trycatch"],settings:{foreground:"#A02F6F"}},{name:"decorators",scope:["meta.decorator","punctuation.decorator","entity.name.function.decorator"],settings:{foreground:"#AD8301"}},{name:"calls",scope:["variable.function"],settings:{foreground:"#100F0F"}},{name:"punctuation",scope:["punctuation","punctuation.terminator","punctuation.definition.tag","punctuation.separator","punctuation.definition.string","punctuation.section.block"],settings:{foreground:"#6F6E69"}},{name:"yellow",scope:["storage.type.numeric.go","storage.type.byte.go","storage.type.boolean.go","storage.type.string.go","storage.type.uintptr.go","storage.type.error.go","storage.type.rune.go","constant.language.go","support.class.dart","keyword.other.documentation","storage.modifier.import.java","punctuation.definition.list.begin.markdown","punctuation.definition.quote.begin.markdown","meta.separator.markdown","entity.name.section.markdown"],settings:{foreground:"#AD8301"}},{name:"green",scope:[],settings:{foreground:"#66800B"}},{name:"cyan",scope:["markup.italic.markdown","support.type.python","variable.legacy.builtin.python","support.constant.property-value.css","storage.modifier.attribute.swift"],settings:{foreground:"#24837B"}},{name:"blue",scope:[],settings:{foreground:"#205EA6"}},{name:"purple",scope:["keyword.channel.go","keyword.other.platform.os.swift"],settings:{foreground:"#5E409D"}},{name:"magenta",scope:["punctuation.definition.heading.markdown"],settings:{foreground:"#A02F6F"}},{name:"red",scope:[],settings:{foreground:"#AF3029"}},{name:"orange",scope:[],settings:{foreground:"#BC5215"}}],vv={name:xv,type:yv,colors:bv,tokenColors:wv},Dl="flexoki-dark",Al="flexoki-light",jv=gv,Sv=vv;function sp(t,r){return Object.defineProperty(t,"toString",{value:()=>r,enumerable:!1,configurable:!0}),Object.defineProperty(t,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0}),t}function rp(t,r,s){const n=t.colors?.["editor.background"],o=t.colors?.["editor.foreground"];if(!n||!o)throw new Error(`Flexoki Shiki theme "${r}" is missing editor.background/editor.foreground`);const a=t.tokenColors??[];return{...t,name:r,type:s,fg:o,bg:n,settings:a}}const El=rp(jv,Dl,"dark"),Il=rp(Sv,Al,"light");sp(El,Dl);sp(Il,Al);const ao={dark:Dl,light:Al},Ud=[Il,El];let Vd=!1;function np(){Vd||(ql(ao.dark,async()=>El),ql(ao.light,async()=>Il),Vd=!0)}const Qi=({...t})=>{const{theme:r="system"}=sg();return e.jsx(rg,{theme:r,className:"toaster group",closeButton:!1,style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--error-bg":"var(--popover)","--error-text":"var(--popover-foreground)","--error-border":"var(--border)","--success-bg":"var(--popover)","--success-text":"var(--popover-foreground)","--success-border":"var(--border)","--warning-bg":"var(--popover)","--warning-text":"var(--popover-foreground)","--warning-border":"var(--border)","--info-bg":"var(--popover)","--info-text":"var(--popover-foreground)","--info-border":"var(--border)"},...t})},Gd=async t=>{try{await navigator.clipboard.writeText(t)}catch(r){console.error("Failed to copy to clipboard:",r)}},V={...Ys,success:(t,r)=>Ys.success(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),info:(t,r)=>Ys.info(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),error:(t,r)=>Ys.error(t,{...r,action:r?.action||{label:"Copy",onClick:()=>Gd(String(t))}}),warning:(t,r)=>Ys.warning(t,{...r,action:r?.action||{label:"Copy",onClick:()=>Gd(String(t))}})},Fs=Ae.forwardRef(({className:t,...r},s)=>e.jsx(xt,{as:"textarea",ref:s,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:R("text-foreground border-input placeholder:text-muted-foreground appearance-none hover:border-input focus:border-ring focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-3 py-2 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...r}));Fs.displayName="Textarea";const Nv=`
13
+ :host {
14
+ font-family: var(--font-mono);
15
+ font-size: var(--text-code);
16
+ }
17
+
18
+ :host, pre, [data-diffs], [data-code] {
19
+ transform: translateZ(0);
20
+ -webkit-transform: translateZ(0);
21
+ -webkit-backface-visibility: hidden;
22
+ backface-visibility: hidden;
23
+ }
24
+
25
+ pre, [data-code] {
26
+ font-family: var(--font-mono);
27
+ font-size: var(--text-code);
28
+ }
29
+
30
+ [data-code] {
31
+ -webkit-overflow-scrolling: touch;
32
+ }
33
+
34
+ /* Mobile touch selection support */
35
+ [data-line-number] {
36
+ touch-action: manipulation;
37
+ -webkit-tap-highlight-color: transparent;
38
+ cursor: pointer;
39
+ }
40
+
41
+ /* Ensure interactive line numbers work on touch */
42
+ pre[data-interactive-line-numbers] [data-line-number] {
43
+ touch-action: manipulation;
44
+ }
45
+ /* Reduce hunk separator height */
46
+ [data-separator-content] {
47
+ height: 24px !important;
48
+ }
49
+ [data-expand-button] {
50
+ height: 24px !important;
51
+ width: 24px !important;
52
+ }
53
+ [data-separator-multi-button] {
54
+ row-gap: 0 !important;
55
+ }
56
+ [data-expand-up] {
57
+ height: 12px !important;
58
+ min-height: 12px !important;
59
+ max-height: 12px !important;
60
+ margin: 0 !important;
61
+ margin-top: 3px !important;
62
+ padding: 0 !important;
63
+ border-radius: 4px 4px 0 0 !important;
64
+ }
65
+ [data-expand-down] {
66
+ height: 12px !important;
67
+ min-height: 12px !important;
68
+ max-height: 12px !important;
69
+ margin: 0 !important;
70
+ margin-top: -3px !important;
71
+ padding: 0 !important;
72
+ border-radius: 0 0 4px 4px !important;
73
+ }
74
+ `;function kv(t,r,s){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s;return`${t}:${r.length}:${s.length}:${n.length}:${o.length}`}const Cv=(t,r,s)=>{const a=(s.side==="deletions"?t:r).split(`
75
+ `),c=Math.max(1,s.start),l=Math.min(a.length,s.end);return c>l?"":a.slice(c-1,l).join(`
76
+ `)},op=({original:t,modified:r,language:s,fileName:n="file",renderSideBySide:o,wrapLines:a=!1,layout:c="fill"})=>{const{isMobile:l}=Gt(),{inputBarOffset:d,isKeyboardOpen:u}=Me(),f=Ci()?.currentTheme?.metadata?.variant==="dark",p=Me(q=>q.setActiveMainTab),[h,g]=Ae.useState(null),[x,b]=Ae.useState(""),y=Ae.useRef(null),v=Ae.useCallback(()=>{if(l)return"50%";const q=document.querySelector("main.flex-1");if(q){const Y=q.getBoundingClientRect();return`${Y.left+Y.width/2}px`}return"50%"},[l]),[S,C]=Ae.useState(v),N=ve(q=>q.sendMessage),j=ve(q=>q.currentSessionId),{currentProviderId:D,currentModelId:k,currentAgentName:M,currentVariant:w}=Je(),T=Ye(q=>q.getSessionAgentSelection),E=Ye(q=>q.getAgentModelForSession),I=Ye(q=>q.getAgentModelVariantForSession);Ae.useEffect(()=>{if(l)return;const q=()=>{C(v())};return window.addEventListener("resize",q),()=>window.removeEventListener("resize",q)},[l,v]);const A=Ae.useCallback(q=>{if(l&&q&&h&&q.start===q.end){const Y=q.start,Z=h.start,B=h.end,W=Math.min(Z,B,Y),te=Math.max(Z,B,Y);if(Y<Z||Y>B){g({...q,start:W,end:te});return}}g(q),q||b("")},[l,h]);Ae.useEffect(()=>{if(!h)return;const q=Z=>{const B=Z.target;if(y.current?.contains(B)||B.closest("[data-sonner-toast]")||B.closest("[data-sonner-toaster]"))return;Z.composedPath().some(ye=>ye instanceof HTMLElement?ye.hasAttribute("data-line-number")||ye.closest?.("[data-line-number]"):!1)||(g(null),b(""))},Y=setTimeout(()=>{document.addEventListener("click",q)},100);return()=>{clearTimeout(Y),document.removeEventListener("click",q)}},[h]);const P=Ae.useCallback(async()=>{if(!h||!x.trim())return;if(!j){V.error("Select a session to send comment");return}const q=T(j)||M,Y=q?E(j,q):null,Z=Y?.providerId||D,B=Y?.modelId||k;if(!Z||!B){V.error("Select a model to send comment");return}const W=q&&Z&&B?I(j,q,Z,B)??w:w,te=Cv(t,r,h),ye=h.start,me=h.end,K=h.side==="deletions"?"original":"modified",L=`Comment on \`${n}\` lines ${ye}-${me} (${K}):
77
+ \`\`\`${s}
78
+ ${te}
79
+ \`\`\`
80
+
81
+ ${x}`;b(""),g(null),p("chat"),N(L,Z,B,q,void 0,void 0,void 0,W).catch(Q=>{console.error("Failed to send comment",Q)})},[h,x,t,r,n,s,N,j,D,k,M,w,p,T,E,I]);np();const F=Ae.useRef(null),z=Ae.useMemo(()=>{const q=kv(n,t,r);if(F.current?.key===q)return F.current.fileDiff;const Y={name:n,contents:t,cacheKey:`old-${q}`},Z={name:n,contents:r,cacheKey:`new-${q}`},B=kc(Y,Z);return F.current={key:q,fileDiff:B},B},[n,t,r,s]),G=Ae.useMemo(()=>({theme:{dark:ao.dark,light:ao.light},themeType:f?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!0,enableHoverUtility:!1,onLineSelected:A,unsafeCSS:Nv}),[f,o,a,A]);if(typeof window>"u")return null;const O=h?e.jsx("div",{className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-sidebar flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Fs,{value:x,onChange:q=>{b(q.target.value);const Y=q.target;Y.style.height="auto";const B=20*5+8;Y.style.height=`${Math.min(Y.scrollHeight,B)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!l,rows:1,onKeyDown:q=>{q.key==="Enter"&&(q.metaKey||q.ctrlKey)&&(q.preventDefault(),P()),q.key==="Escape"&&(q.preventDefault(),g(null),b(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.split("/").pop(),":",h.start,"-",h.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!l&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Yt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:q=>{x.trim()&&(q.preventDefault(),P())},onClick:()=>{l||P()},disabled:!x.trim(),className:R("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",x.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Vo,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return c==="fill"?e.jsxs("div",{className:R("flex flex-col relative","size-full"),style:{paddingBottom:l?"var(--oc-keyboard-inset, 0px)":void 0},children:[e.jsx("div",{className:"flex-1 relative min-h-0",children:e.jsx(xt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,children:e.jsx(Kl,{fileDiff:z,options:G,selectedLines:h})})}),h&&e.jsx("div",{className:R("pointer-events-auto relative pb-2 transition-none z-50 flex justify-center",l&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:l&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:O})]}):e.jsxs("div",{className:R("relative","w-full"),children:[e.jsx("div",{className:"pierre-diff-wrapper w-full overflow-x-auto overflow-y-visible",children:e.jsx(Kl,{fileDiff:z,options:G,selectedLines:h})}),h&&Lm.createPortal(e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col justify-end items-start pointer-events-none transition-none transform-gpu",style:{paddingBottom:l?"var(--oc-keyboard-inset, 0px)":"0px",isolation:"isolate"},children:e.jsx("div",{className:R("pointer-events-auto relative pb-2 transition-none",l&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginLeft:S,transform:"translateX(-50%)",marginBottom:l&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:O})}),document.body)]})},Mv=1100,ap=15e3,Dv=10,ip={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},Av=ip.M,La=[{value:"single",label:"Single file",description:"Show one file at a time"},{value:"stacked",label:"All files",description:"Stack all modified files together"}],Ev=t=>{const r=t.index?.trim(),s=t.working_dir?.trim();return r&&r!=="?"?r.charAt(0):s?s.charAt(0):r?.charAt(0)||s?.charAt(0)||"M"},cp=t=>{const r=Ev(t);return ip[r]??Av},Iv=t=>{const{index:r,working_dir:s}=t;return r==="A"||s==="A"||r==="?"||s==="?"},si=(t,r)=>{const s=t??0,n=r??0;return!s&&!n?null:e.jsxs("span",{className:"typography-meta flex flex-shrink-0 items-center gap-1 text-xs whitespace-nowrap",children:[s?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",s]}):null,n?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",n]}):null]})},Pv=i.memo(({changedFiles:t,selectedFile:r,selectedFileEntry:s,onSelectFile:n,isMobile:o,showModeSelector:a=!1,mode:c,onModeChange:l})=>{const d=i.useCallback(u=>{if(!o)return u;const m=u.lastIndexOf("/");return m>=0?u.slice(m+1):u},[o]);return t.length===0?null:e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[s?e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:d(s.path)}),si(s.insertions,s.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Wt,{className:"size-4 opacity-50"})]})}),e.jsxs(rs,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:[a&&c&&l?e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"typography-meta text-muted-foreground",children:"View mode"}),e.jsx(qa,{value:c,onValueChange:u=>l(u),children:La.map(u=>e.jsx(Ka,{value:u.value,className:"items-center",children:e.jsx("span",{className:"typography-meta text-foreground",children:u.label})},u.value))}),e.jsx(Ds,{})]}):null,e.jsx(qa,{value:r??"",onValueChange:n,children:t.map(u=>e.jsx(Ka,{value:u.path,children:e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:d(u.path)}),e.jsx("span",{className:"ml-auto",children:si(u.insertions,u.deletions)})]})},u.path))})]})]})}),Tv=i.memo(({mode:t,onModeChange:r})=>{const s=La.find(n=>n.value===t)??La[0];return e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("span",{className:"min-w-0 truncate typography-meta",children:s.label}),e.jsx(Wt,{className:"size-4 opacity-50"})]})}),e.jsx(rs,{className:"min-w-[220px]",children:e.jsx(qa,{value:t,onValueChange:n=>r(n),children:La.map(n=>e.jsx(Ka,{value:n.value,children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-meta text-foreground",children:n.label}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:n.description})]})},n.value))})})]})}),Fv=i.memo(({changedFiles:t,selectedFile:r,onSelectFile:s})=>t.length===0?null:e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:e.jsx("ul",{className:"flex flex-col gap-1",children:t.map(n=>{const o=cp(n),a=r===n.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(n.path),className:R("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",a?"bg-accent/70 text-foreground":"text-muted-foreground hover:bg-accent/40 hover:text-foreground"),children:[e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:o.color},title:o.description,"aria-label":o.description,children:o.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:n.path,children:n.path}),si(n.insertions,n.deletions)]})},n.path)})})})),Rv=i.memo(({filePath:t,diff:r,isVisible:s,renderSideBySide:n})=>{const o=r.original.length>0,a=r.modified.length>0;if(!s)return e.jsx("div",{className:"absolute inset-0 hidden"});const c=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",l=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:c,children:[o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${t}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${t}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Lv=i.memo(({filePath:t,diff:r,renderSideBySide:s})=>{const n=r.original.length>0,o=r.modified.length>0,a=s?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",c=s?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return e.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:e.jsxs("div",{className:a,children:[n&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${t}`,className:s?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),o&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:n?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${t}`,className:s?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Ov=i.memo(({filePath:t,diff:r,renderSideBySide:s,wrapLines:n})=>{const o=i.useMemo(()=>Er(t)||"text",[t]);return Ho(t)?e.jsx(Lv,{filePath:t,diff:r,renderSideBySide:s}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(op,{original:r.original,modified:r.modified,language:o,fileName:t,renderSideBySide:s,wrapLines:n,layout:"inline"})})}),_v=i.memo(({filePath:t,diff:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=i.useMemo(()=>Er(t)||"text",[t]);return s?Ho(t)?e.jsx(Rv,{filePath:t,diff:r,isVisible:s,renderSideBySide:n}):e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(op,{original:r.original,modified:r.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})}):null}),$v=i.memo(({directory:t,filePath:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=is(i.useCallback(l=>l.directories.get(t)?.diffCache.get(r)??null,[t,r])),c=i.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return c?e.jsx(_v,{filePath:r,diff:c,isVisible:s,renderSideBySide:n,wrapLines:o}):null}),Bv=i.memo(({directory:t,file:r,layout:s,wrapLines:n,scrollRootRef:o,isSelected:a,onSelect:c,registerSectionRef:l,defaultCollapsed:d=!1})=>{const{git:u}=Hs(),m=is(i.useCallback(P=>P.directories.get(t)?.diffCache.get(r.path)??null,[t,r.path])),f=is(P=>P.setDiff),p=Me(P=>P.setDiffFileLayout),[h,g]=i.useState(!d),[x,b]=i.useState(!1),[y,v]=i.useState(0),[S,C]=i.useState(null),[N,j]=i.useState(!1),D=i.useRef(null),k=i.useRef(null),M=i.useMemo(()=>cp(r),[r]),w=s==="side-by-side",T=i.useMemo(()=>m?{original:m.original,modified:m.modified}:null,[m]),E=i.useCallback(P=>{k.current=P,l(r.path,P)},[r.path,l]),I=i.useCallback(P=>{g(P),P&&b(!0)},[]),A=i.useCallback(()=>{c(r.path)},[r.path,c]);return i.useEffect(()=>{if(!h||x)return;const P=k.current;if(!P)return;if(!o.current||typeof IntersectionObserver>"u"){b(!0);return}const F=new IntersectionObserver(z=>{z.some(G=>G.isIntersecting)&&(b(!0),F.disconnect())},{root:o.current,rootMargin:"200px 0px",threshold:.1});return F.observe(P),()=>F.disconnect()},[x,h,o]),i.useEffect(()=>{if(!h||!x)return;if(!t||T){D.current=null,j(!1);return}const P=`${t}::${r.path}::${y}`;if(D.current===P)return;D.current=P,C(null),j(!0);let F=!1;return(async()=>{try{const z=u.getGitFileDiff(t,{path:r.path}),G=ap,oe=new Promise((q,Y)=>{setTimeout(()=>Y(new Error(`Timed out after ${G}ms`)),G)}),O=await Promise.race([z,oe]);if(F)return;f(t,r.path,{original:O.original??"",modified:O.modified??""}),j(!1)}catch(z){if(F)return;const G=z instanceof Error?z.message:String(z);C(G),j(!1)}})(),()=>{F=!0,D.current===P&&(D.current=null)}},[t,T,y,r.path,u,x,h,f]),e.jsx("div",{ref:E,className:"scroll-mt-4",children:e.jsxs(Pn,{open:h,onOpenChange:I,className:"group/collapsible",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background",children:e.jsxs(xo,{onClick:A,className:R("relative flex w-full items-center gap-2 px-3 py-1.5 transition-colors rounded-t-xl border border-border/60 overflow-hidden","bg-background hover:bg-background",h?"rounded-b-none":"rounded-b-xl",a?"text-primary":"text-muted-foreground hover:text-foreground"),children:[e.jsx("div",{className:R("absolute inset-0 pointer-events-none transition-colors",a?"bg-primary/10":"group-hover:bg-accent/40")}),e.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[e.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover:opacity-100 transition-opacity",children:h?e.jsx(Wt,{className:"size-4"}):e.jsx(tr,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:M.color},title:M.description,"aria-label":M.description,children:M.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",style:{direction:"rtl",textAlign:"left"},title:r.path,children:r.path})]}),e.jsxs("div",{className:"relative flex items-center gap-2",children:[si(r.insertions,r.deletions),e.jsx(tp,{mode:w?"side-by-side":"unified",onModeChange:P=>{const F=P==="side-by-side"?"side-by-side":"inline";p(r.path,F)},className:"opacity-70"})]})]})}),e.jsx(Tn,{children:e.jsxs("div",{className:"relative border border-t-0 border-border/60 bg-background rounded-b-xl overflow-hidden",children:[S?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:S}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>v(P=>P+1),children:"Retry"})]}):null,N&&!T&&!S?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(Mt,{size:16,className:"animate-spin"}),"Loading diff…"]}):null,T?e.jsx(Ov,{filePath:r.path,diff:T,renderSideBySide:w,wrapLines:n}):null]})})]})})}),zv=()=>{const{git:t}=Hs(),r=Yo(),{screenWidth:s,isMobile:n}=Gt(),o=ep(r??null),a=Xf(r??null),c=is(H=>H.isLoadingStatus),{setActiveDirectory:l,fetchStatus:d,setDiff:u}=is(),[m,f]=i.useState(null),[p,h]=i.useState(0),[g,x]=i.useState(null),b=i.useRef(null),y=Me(H=>H.pendingDiffFile),v=Me(H=>H.setPendingDiffFile),S=Me(H=>H.diffLayoutPreference),C=Me(H=>H.diffFileLayout),N=Me(H=>H.setDiffFileLayout),j=Me(H=>H.diffWrapLines),D=Me(H=>H.setDiffWrapLines),k=Me(H=>H.diffViewMode),M=Me(H=>H.setDiffViewMode),w=n||j,T=k==="stacked",E=n||s<=768,I=!E&&s>=1024,A=i.useRef(null),P=i.useRef(new Map),F=i.useRef(null),z=i.useMemo(()=>{if(!a?.files)return[];const H=a.diffStats??{};return a.files.map(we=>({...we,insertions:H[we.path]?.insertions??0,deletions:H[we.path]?.deletions??0,isNew:Iv(we)})).sort((we,ee)=>we.path.localeCompare(ee.path))},[a]),G=i.useMemo(()=>m?z.find(H=>H.path===m)??null:null,[z,m]),oe=i.useCallback(H=>{const we=C[H.path];if(we)return we;if(S==="inline")return"inline";if(S==="side-by-side")return"side-by-side";const ee=s<Mv;return H.isNew||ee?"inline":"side-by-side"},[C,S,s]),O=i.useMemo(()=>G?oe(G):null,[oe,G]);i.useEffect(()=>{r&&(l(r),is.getState().directories.get(r)?.status||d(r,t))},[r,l,d,t]),i.useEffect(()=>{y&&(f(y),v(null),T&&(F.current=y))},[T,y,v]),i.useEffect(()=>{!m&&!y&&z.length>0&&f(z[0].path)},[z,m,y]),i.useEffect(()=>{if(!T){F.current=null;return}const H=F.current;if(!H)return;const we=P.current.get(H);we&&(we.scrollIntoView({behavior:"smooth",block:"start"}),F.current=null)},[z,T]),i.useEffect(()=>{m&&z.length>0&&(z.some(we=>we.path===m)||f(z[0]?.path??null))},[z,m]);const q=i.useCallback((H,we)=>{const ee=P.current;we?ee.set(H,we):ee.delete(H)},[]),Y=i.useCallback((H,we="smooth")=>{const ee=P.current.get(H);return ee?(ee.scrollIntoView({behavior:we,block:"start"}),!0):!1},[]),Z=i.useCallback(H=>{f(H)},[]),B=i.useCallback(H=>{f(H),T&&!Y(H)&&(F.current=H)},[T,Y]),W=i.useCallback(H=>{M(H),H==="stacked"&&m&&!Y(m,"auto")&&(F.current=m)},[Y,m,M]),te=i.useCallback(H=>{const we=H==="side-by-side"?"side-by-side":"inline";if(T){z.forEach(ee=>{N(ee.path,we)});return}G&&N(G.path,we)},[z,T,G,N]),ye=(O??"side-by-side")==="side-by-side",me=!T||!I,K=is(i.useCallback(H=>!r||!m?null:H.directories.get(r)?.diffCache.get(m)??null,[r,m])),L=!!K,Q=!T&&!!m&&!L;i.useEffect(()=>{if(T)return;if(x(null),!r||!m){b.current=null;return}if(K){b.current=null;return}const H=`${r}::${m}::${p}`;if(b.current===H)return;b.current=H;let we=!1;return(async()=>{try{const ee=t.getGitFileDiff(r,{path:m}),ue=ap,ge=new Promise((de,ae)=>{setTimeout(()=>ae(new Error(`Timed out after ${ue}ms`)),ue)}),X=await Promise.race([ee,ge]);if(we)return;u(r,m,{original:X.original??"",modified:X.modified??""})}catch(ee){if(we)return;const ue=ee instanceof Error?ee.message:String(ee);x(ue)}})(),()=>{we=!0,b.current===H&&(b.current=null)}},[r,T,m,K,t,u,p]);const ce=()=>!r||!m?null:e.jsx($v,{directory:r,filePath:m,isVisible:!0,renderSideBySide:ye,wrapLines:w},m),he=()=>r?e.jsxs("div",{className:"flex flex-1 min-h-0 h-full gap-3 px-3 pb-3 pt-2",children:[I&&e.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:z.length})]}),e.jsx(Fv,{changedFiles:z,selectedFile:m,onSelectFile:B})]}),e.jsx(xt,{ref:A,outerClassName:"flex-1 min-h-0 h-full",className:"pr-2",disableHorizontal:!0,children:e.jsx("div",{className:"flex flex-col gap-3",children:z.map((H,we)=>e.jsx(Bv,{directory:r,file:H,layout:oe(H),wrapLines:w,scrollRootRef:A,isSelected:H.path===m,onSelect:Z,registerSectionRef:q,defaultCollapsed:we>=Dv},H.path))})})]}):null,Ne=()=>r?c&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Mt,{size:16,className:"animate-spin"}),"Loading repository status…"]}):o===!1?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Not a git repository. Use the Git tab to initialize or change directories."}):z.length===0?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Working tree clean — no changes to display"}):T?he():e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[ce(),Q&&!L&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:g?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:g}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{x(null),h(H=>H+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Mt,{size:16,className:"animate-spin"}),"Loading diff…"]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 bg-background",children:[!n&&e.jsxs("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:[e.jsx(ol,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:c&&!a?"Loading changes…":`${z.length} ${z.length===1?"file":"files"} changed`})]}),!E&&e.jsx(Tv,{mode:k,onModeChange:W}),me&&e.jsx(Pv,{changedFiles:z,selectedFile:m,selectedFileEntry:G,onSelectFile:B,isMobile:E,showModeSelector:E,mode:k,onModeChange:W}),e.jsx("div",{className:"flex-1"}),G&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>D(!j),className:R("h-5 w-5 p-0 transition-opacity",w?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:w?"Disable line wrap":"Enable line wrap",children:e.jsx(Cc,{className:"size-4"})}),G&&O&&e.jsx(tp,{mode:O==="side-by-side"?"side-by-side":"unified",onModeChange:te})]}),Ne()]})},Hv=()=>{const{git:t}=Hs(),r=Yo(),{setActiveDirectory:s,fetchStatus:n}=is(),o=av(r??null);return i.useEffect(()=>{r&&(s(r),is.getState().directories.get(r)?.status||n(r,t))},[r,s,n,t]),o},bn=Ae.forwardRef(({className:t,...r},s)=>e.jsx(_m,{className:R("peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none 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 data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted-foreground/30",t),style:{width:"36px",height:"20px",minWidth:"36px",minHeight:"20px"},...r,ref:s,children:e.jsx(ng,{className:R("pointer-events-none block rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"),style:{width:"16px",height:"16px",minWidth:"16px",minHeight:"16px"}})}));bn.displayName=_m.displayName;const Wv={},Oa=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s.length>1?s.replace(/\/+$/,""):s},qd=t=>Oa(t)??"__global__",Uv=t=>{const r=Object.entries(t??{}),s=r.filter(([,c])=>c?.status==="connected").length,n=r.length,o=r.some(([,c])=>c?.status==="failed"),a=r.some(([,c])=>c?.status==="needs_auth"||c?.status==="needs_client_registration");return{connected:s,total:n,hasFailed:o,hasAuthRequired:a}},Co=ns()(fs((t,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:s=>{const n=qd(s??vt.getState().currentDirectory);return r().byDirectory[n]??Wv},refresh:async s=>{const n=Oa(s?.directory??vt.getState().currentDirectory),o=qd(n);s?.silent||t(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const l=(await Oe.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};t(d=>({byDirectory:{...d.byDirectory,[o]:l},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const c=a instanceof Error?a.message:"Failed to load MCP status";t(l=>({loadingKeys:{...l.loadingKeys,[o]:!1},lastErrorKeys:{...l.lastErrorKeys,[o]:c}}))}},connect:async(s,n)=>{const o=Oa(n??vt.getState().currentDirectory);await Oe.getApiClient().mcp.connect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(s,n)=>{const o=Oa(n??vt.getState().currentDirectory);await Oe.getApiClient().mcp.disconnect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function Vv(t){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",stroke:"currentColor",strokeWidth:"0.5",fillRule:"evenodd",viewBox:"-0.5 -0.5 25 25",...t,children:[e.jsx("path",{d:"M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"}),e.jsx("path",{d:"M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"})]})}const Gv=t=>{if(!t)return"Unknown";switch(t.status){case"connected":return"Connected";case"failed":return`Failed: ${t.error||"Unknown error"}`;case"needs_auth":return"Needs authentication";case"needs_client_registration":return`Needs registration: ${t.error||""}`;default:return t.status}},qv=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},Wc=({headerIconButtonClass:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(!1),{isMobile:c}=Gt(),d=vt(k=>k.currentDirectory)??null,u=Co(k=>k.getStatusForDirectory(d)),m=Co(k=>k.refresh),f=Co(k=>k.connect),p=Co(k=>k.disconnect),h=i.useCallback(k=>{k||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),s(k)},[]),g=i.useCallback(k=>{a.current||o(k)},[]),[x,b]=i.useState(!1),[y,v]=i.useState(null);i.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),i.useEffect(()=>{r&&m({directory:d,silent:!0})},[r,m,d]);const S=i.useMemo(()=>Uv(u),[u]),C=i.useMemo(()=>Object.keys(u).sort((k,M)=>k.localeCompare(M)),[u]),N=i.useCallback(k=>{if(k?.preventDefault(),x)return;b(!0);const M=new Promise(w=>setTimeout(w,500));Promise.all([m({directory:d}),M]).finally(()=>{b(!1)})},[x,m,d]),j=()=>e.jsxs(e.Fragment,{children:[C.map(k=>{const M=u[k],w=qv(M),T=M?.status==="connected",E=y===k,I=Gv(M);return e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-muted/50",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[c?e.jsx("span",{className:R("h-2 w-2 rounded-full flex-shrink-0",w==="success"&&"bg-status-success",w==="error"&&"bg-status-error",w==="warning"&&"bg-status-warning",w==="default"&&"bg-muted-foreground/40"),"aria-label":I}):e.jsxs(dt,{delayDuration:300,children:[e.jsx(ut,{asChild:!0,children:e.jsx("span",{className:R("h-2 w-2 rounded-full flex-shrink-0",w==="success"&&"bg-status-success",w==="error"&&"bg-status-error",w==="warning"&&"bg-status-warning",w==="default"&&"bg-muted-foreground/40"),"aria-label":I})}),e.jsx(lt,{side:"left",children:e.jsx("p",{children:I})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:k})]})}),e.jsx(bn,{checked:T,disabled:E,className:"data-[state=checked]:bg-status-info",onCheckedChange:async A=>{v(k);try{A?await f(k,d):await p(k,d)}finally{v(null)}}})]},k)}),C.length===0&&e.jsx("div",{className:"px-2 py-3 typography-ui-label text-muted-foreground text-center",children:"Configure MCP servers in Opencode config."})]}),D=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:R(t,"relative"),onClick:c?()=>s(!0):void 0,children:[e.jsx(Vv,{className:"h-[1.0625rem] w-[1.0625rem]"}),S.total>0&&e.jsx("span",{className:R("absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full",S.hasFailed?"bg-status-error":S.hasAuthRequired?"bg-status-warning":S.connected>0?"bg-status-success":"bg-muted-foreground/40"),"aria-label":"MCP status"})]});return c?e.jsxs(e.Fragment,{children:[D,e.jsxs(Ws,{open:r,title:"MCP Servers",onClose:()=>s(!1),renderHeader:k=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"MCP Servers"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{type:"button",className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",disabled:x,onClick:N,"aria-label":"Refresh",children:e.jsx(en,{className:R("h-4 w-4",x&&"animate-spin")})}),k]})]}),children:[e.jsx("div",{className:"py-1",children:j()}),d&&e.jsx("div",{className:"px-2 py-1 border-t border-border/40 mt-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]}):e.jsxs(ts,{open:r,onOpenChange:h,children:[e.jsxs(dt,{delayDuration:1e3,open:r?!1:n,onOpenChange:g,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:D})}),e.jsx(lt,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsxs(rs,{align:"end",className:"w-72",children:[e.jsxs("div",{className:"flex items-center justify-between px-2 py-1",children:[e.jsx("span",{className:"typography-ui-label font-semibold",children:"MCP Servers"}),e.jsx("button",{type:"button",className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",disabled:x,onClick:N,"aria-label":"Refresh",children:e.jsx(en,{className:R("h-4 w-4",x&&"animate-spin")})})]}),e.jsx(Ds,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:j()}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),e.jsx("div",{className:"px-2 py-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]})]})},lp=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Kd=(t,r)=>{const s=lp(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},Kv=t=>Kd(Kd(t,".opencode"),"plans"),Jv=()=>"~/.opencode/plans",Qv=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},Jd=()=>{const t=Me(ee=>ee.setSessionSwitcherOpen),r=Me(ee=>ee.toggleSidebar),s=Me(ee=>ee.setSettingsDialogOpen),n=Me(ee=>ee.toggleCommandPalette),o=Me(ee=>ee.toggleHelpDialog),a=Me(ee=>ee.activeMainTab),c=Me(ee=>ee.setActiveMainTab),{getCurrentModel:l}=Je(),d=Hs(),u=ve(ee=>ee.getContextUsage),m=ve(ee=>ee.currentSessionId),f=ve(ee=>ee.sessions),p=vt(ee=>ee.homeDirectory),{isMobile:h}=Gt(),g=Hv(),x=xi(ee=>ee.available),b=Bs(ee=>ee.status),y=Bs(ee=>ee.setStatus),v=i.useRef(null),[S,C]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),N=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Ae.useEffect(()=>{if(typeof window>"u")return;const ee=typeof window.opencodeDesktop<"u";C(ee)},[]);const j=l(),D=j&&typeof j.limit=="object"&&j.limit!==null?j.limit:null,k=D&&typeof D.context=="number"?D.context:0,M=D&&typeof D.output=="number"?D.output:0,w=u(k,M),T=Me(ee=>ee.isSessionSwitcherOpen),E=b?.connected?b.user?.avatarUrl:null,I=b?.connected?b.user?.login:null,A=b?.accounts??[],[P,F]=i.useState(!1),z=i.useMemo(()=>m?f.find(ee=>ee.id===m)??null:null,[m,f]),G=i.useMemo(()=>{const ee=typeof z?.directory=="string"?z.directory:"";return lp(ee||"")},[z?.directory]),[oe,O]=i.useState(!1),q=oe,Y=i.useRef(""),Z=i.useCallback(async ee=>{if(!(!ee||P)){F(!0);try{const ue=d.github?await d.github.authActivate(ee):await(async()=>{const ge=await fetch("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:ee})}),X=await ge.json().catch(()=>null);if(!ge.ok||!X)throw new Error(X?.error||ge.statusText);return X})();y(ue)}catch(ue){console.error("Failed to switch GitHub account:",ue)}finally{F(!1)}}},[P,d.github,y]);i.useEffect(()=>{let ee=!1;const ue=async(ae,fe)=>{if(!ae||!fe||!d.files?.listDirectory)return!1;try{const ie=await d.files.listDirectory(ae);return(Array.isArray(ie?.entries)?ie.entries:[]).some(re=>re?.name===fe&&!re?.isDirectory)}catch{return!1}},ge=async()=>{if(ee)return;if(!z?.slug||!z?.time?.created||!G){O(!1),Me.getState().activeMainTab==="plan"&&Me.getState().setActiveMainTab("chat");return}const ae=`${z.time.created}-${z.slug}.md`,fe=Kv(G),ie=Qv(Jv(),p||null),[se,re]=await Promise.all([ue(fe,ae),ue(ie,ae)]);if(ee)return;const ne=se||re;O(ne),!ne&&Me.getState().activeMainTab==="plan"&&Me.getState().setActiveMainTab("chat")},X=`${m||"none"}:${G||"none"}:${z?.time?.created||0}:${z?.slug||"none"}`;Y.current!==X&&(Y.current=X,O(!1)),ge();const de=window.setInterval(()=>{ge()},3e3);return()=>{ee=!0,window.clearInterval(de)}},[G,z?.slug,z?.time?.created,m,p,d.files]);const B=i.useCallback(()=>{if(typeof document>"u")return;const ee=document.activeElement;if(!ee)return;const ue=ee.tagName;(ue==="INPUT"||ue==="TEXTAREA"||ue==="SELECT"||ee.isContentEditable)&&ee.blur()},[]),W=i.useCallback(()=>{if(h){B(),t(!T);return}r()},[B,h,T,t,r]),te=i.useCallback(()=>{h&&B(),t(!1),s(!0)},[B,h,t,s]),ye="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-secondary/50 transition-colors",me=i.useMemo(()=>S&&N?"pl-[5.75rem]":"pl-3",[S,N]),K=i.useCallback(()=>{if(typeof document>"u")return;const ee=v.current?.getBoundingClientRect().height;ee&&document.documentElement.style.setProperty("--oc-header-height",`${ee}px`)},[]);Ae.useEffect(()=>{if(typeof window>"u")return;K();const ee=v.current;if(!ee||typeof ResizeObserver>"u")return()=>{};const ue=new ResizeObserver(()=>{K()});return ue.observe(ee),window.addEventListener("resize",K),window.addEventListener("orientationchange",K),()=>{ue.disconnect(),window.removeEventListener("resize",K),window.removeEventListener("orientationchange",K)}},[K]),Ae.useEffect(()=>{K()},[K,h]);const L=i.useCallback(async ee=>{if(!ee.target.closest("button, a, input, select, textarea")&&ee.button===0&&S)try{const{getCurrentWindow:ue}=await vs(async()=>{const{getCurrentWindow:X}=await import("./vendor-.bun-Bui932eM.js").then(de=>de.dl);return{getCurrentWindow:X}},__vite__mapDeps([0,1]));await ue().startDragging()}catch(ue){console.error("Failed to start window dragging:",ue)}},[S]),Q=i.useCallback(async ee=>{if(ee.button===0&&S)try{const{getCurrentWindow:ue}=await vs(async()=>{const{getCurrentWindow:X}=await import("./vendor-.bun-Bui932eM.js").then(de=>de.dl);return{getCurrentWindow:X}},__vite__mapDeps([0,1]));await ue().startDragging()}catch(ue){console.error("Failed to start window dragging:",ue)}},[S]),ce=i.useMemo(()=>{const ee=[{id:"chat",label:"Chat",icon:og}];return q&&ee.push({id:"plan",label:"Plan",icon:Zn}),ee.push({id:"diff",label:"Diff",icon:sr,badge:!h&&g>0?g:void 0},{id:"files",label:"Files",icon:lr},{id:"terminal",label:"Terminal",icon:rn},{id:"git",label:"Git",icon:Ut,showDot:h&&g>0}),ee},[g,h,q]);Ae.useEffect(()=>{const ee=ue=>{if($s(ue)&&!ue.shiftKey&&!ue.altKey){const ge=parseInt(ue.key,10);ge>=1&&ge<=ce.length&&(ue.preventDefault(),c(ce[ge-1].id))}};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[ce,c]);const he=ee=>{const ue=a===ee.id,ge=ee.icon,X=ee.id==="chat";return e.jsxs("button",{type:"button",onClick:()=>c(ee.id),onMouseDown:ue?Q:void 0,className:R("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",ue?"app-region-drag bg-secondary text-foreground shadow-sm":"app-region-no-drag text-muted-foreground hover:bg-secondary/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",X&&!h&&"min-w-[100px] justify-center"),"aria-label":ee.label,"aria-selected":ue,role:"tab",children:[h?e.jsx(ge,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),e.jsx("span",{className:"header-tab-label",children:ee.label})]}),X&&!h&&w&&w.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(zc,{totalTokens:w.totalTokens,percentage:w.percentage,contextLimit:w.contextLimit,outputLimit:w.outputLimit??0,size:"compact"})}),ee.badge!==void 0&&ee.badge>0&&e.jsx("span",{className:"ml-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary/10 px-1 text-[10px] font-bold text-primary",children:ee.badge})]},ee.id)},Ne=()=>e.jsxs("div",{onMouseDown:L,className:R("app-region-drag relative flex h-12 select-none items-center",me),role:"tablist","aria-label":"Main navigation",children:[e.jsx("button",{type:"button",onClick:W,"aria-label":"Open sessions",className:`${ye} mr-2`,children:e.jsx(il,{className:"h-5 w-5"})}),e.jsx("div",{className:"flex items-center gap-1 p-1 bg-background/50 rounded-lg",children:ce.map(ee=>he(ee))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:ye,children:e.jsx(En,{className:"h-5 w-5"})})}),e.jsx(lt,{children:e.jsxs("p",{children:["Command Palette (",Yt(),"+K)"]})})]}),e.jsx(Wc,{headerIconButtonClass:ye}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:ye,children:e.jsx(jn,{className:"h-5 w-5"})})}),e.jsx(lt,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Yt(),"+.)"]})})]}),b?.connected&&!h?A.length>1?e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx("button",{type:"button",className:R(ye,"h-8 w-8 p-0 overflow-hidden rounded-full border border-border/60 bg-muted/80"),title:I?`GitHub: ${I}`:"GitHub connected",disabled:P,children:E?e.jsx("img",{src:E,alt:I?`${I} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs(rs,{align:"end",className:"w-64",children:[e.jsx(Lr,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),e.jsx(Ds,{}),A.map(ee=>{const ue=ee.user,ge=!!ee.current;return e.jsxs(kt,{className:"gap-2",disabled:ge||P,onSelect:()=>{ge||Z(ee.id)},children:[ue?.avatarUrl?e.jsx("img",{src:ue.avatarUrl,alt:ue.login?`${ue.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:e.jsx(Qr,{className:"h-3 w-3 text-muted-foreground"})}),e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:ue?.name?.trim()||ue?.login||"GitHub"}),ue?.login?e.jsx("span",{className:"typography-micro text-muted-foreground truncate font-mono",children:ue.login}):null]}),ge?e.jsx(Tt,{className:"h-4 w-4 text-primary"}):null]},ee.id)})]})]}):e.jsx("div",{className:"app-region-no-drag flex h-8 w-8 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:I?`GitHub: ${I}`:"GitHub connected",children:E?e.jsx("img",{src:E,alt:I?`${I} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"})}):null]})]}),H=()=>e.jsxs("div",{className:"app-region-drag relative flex items-center justify-between gap-2 px-3 py-2 select-none",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T?e.jsx("button",{onClick:()=>t(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-secondary","aria-label":"Back",children:e.jsx(al,{className:"h-5 w-5"})}):e.jsx("button",{onClick:W,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-secondary","aria-label":"Open sessions",children:e.jsx(ag,{className:"h-5 w-5"})}),!T&&w&&w.totalTokens>0&&a==="chat"&&e.jsx(zc,{totalTokens:w.totalTokens,percentage:w.percentage,contextLimit:w.contextLimit,outputLimit:w.outputLimit??0,size:"compact",isMobile:!0}),T&&e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),!T&&e.jsxs("div",{className:"app-region-no-drag flex items-center gap-1",children:[e.jsx("div",{className:"flex items-center gap-0.5",role:"tablist","aria-label":"Main navigation",children:ce.map(ee=>{const ue=a===ee.id,ge=ee.icon;return e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{h&&B(),c(ee.id)},"aria-label":ee.label,"aria-selected":ue,role:"tab",className:R(ye,"relative",ue&&"text-foreground bg-secondary"),children:[e.jsx(ge,{className:"h-5 w-5"}),ee.badge!==void 0&&ee.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:ee.badge}),ee.showDot&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),e.jsx(lt,{children:e.jsx("p",{children:ee.label})})]},ee.id)})}),e.jsx(Wc,{headerIconButtonClass:ye}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:te,"aria-label":"Open settings",className:R(ye,"relative"),children:[e.jsx(vn,{className:"h-5 w-5"}),x&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Update available"})]})}),e.jsx(lt,{children:e.jsx("p",{children:x?"Settings (Update available)":"Settings"})})]})]})]}),we=R("header-safe-area border-b border-border/50 relative z-10",S?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:v,className:we,style:{"--padding-scale":"1"},children:h?H():Ne()})};function Pl({className:t,...r}){return e.jsx("div",{"data-slot":"card",className:R("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",t),...r})}function dp({className:t,...r}){return e.jsx("div",{"data-slot":"card-header",className:R("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...r})}function up({className:t,...r}){return e.jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",t),...r})}function mp({className:t,...r}){return e.jsx("div",{"data-slot":"card-content",className:R("px-6",t),...r})}class os extends i.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,s){this.setState({error:r,errorInfo:s})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:e.jsxs(Pl,{className:"w-full max-w-md",children:[e.jsx(dp,{className:"text-center",children:e.jsxs(up,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Mc,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(mp,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The application encountered an unexpected error. This has been logged for debugging."}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(Se,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ls,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let ma=0;function us({...t}){return e.jsx(ig,{"data-slot":"dialog",...t})}function Yv({...t}){return e.jsx(dg,{"data-slot":"dialog-portal",...t})}const fp=Ae.forwardRef(({className:t,...r},s)=>(Ae.useEffect(()=>(ma+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{ma=Math.max(0,ma-1),ma===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx($m,{ref:s,"data-slot":"dialog-overlay",className:R("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",t),...r})));fp.displayName=$m.displayName;function ms({className:t,children:r,showCloseButton:s=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Yv,{"data-slot":"dialog-portal",children:[e.jsx(fp,{className:"rounded-none"}),e.jsxs(cg,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:R("bg-background text-foreground fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border p-6 shadow-none overflow-hidden pwa-dialog-content",t),...o,children:[r,s&&e.jsxs(lg,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(es,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function xs({className:t,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:R("flex flex-col gap-2 text-center sm:text-left",t),...r})}function Gs({className:t,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:R("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",t),...r})}function ys({className:t,...r}){return e.jsx(ug,{"data-slot":"dialog-title",className:R("typography-markdown leading-none font-semibold text-foreground",t),...r})}function Ss({className:t,...r}){return e.jsx(mg,{"data-slot":"dialog-description",className:R("text-muted-foreground typography-ui-label",t),...r})}const Qd="https://github.com/btriapitsyn/openchamber/releases";async function Xv(){try{const t=await fetch("/api/openchamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return t.ok?{success:!0}:{success:!1,error:(await t.json().catch(()=>({}))).error||`Server error: ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Failed to install update"}}}async function Zv(t=30,r=2e3){for(let s=0;s<t;s++){try{if((await fetch("/health",{method:"GET"})).ok)return!0}catch{}await new Promise(n=>setTimeout(n,r))}return!1}const Uc=({open:t,onOpenChange:r,info:s,downloading:n,downloaded:o,progress:a,error:c,onDownload:l,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Ae.useState(!1),[p,h]=Ae.useState("idle"),[g,x]=Ae.useState(null),b=s?.version?`${Qd}/tag/v${s.version}`:Qd,y=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",S=s?.updateCommand||"openchamber update";Ae.useEffect(()=>{t||(h("idle"),x(null))},[t]);const C=async()=>{try{await navigator.clipboard.writeText(S),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},N=Ae.useCallback(async()=>{h("updating"),x(null);const D=await Xv();if(!D.success){h("error"),x(D.error||"Update failed");return}h("restarting"),await new Promise(M=>setTimeout(M,2e3)),h("reconnecting"),await Zv()?window.location.reload():(h("error"),x("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),j=p!=="idle"&&p!=="error";return e.jsx(us,{open:t,onOpenChange:j?void 0:r,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(xs,{children:e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(fg,{className:"h-5 w-5 text-primary"}),p==="restarting"||p==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(s?.currentVersion||s?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s?.currentVersion&&e.jsx("span",{className:"font-mono",children:s.currentVersion}),s?.currentVersion&&s?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),s?.version&&e.jsx("span",{className:"font-mono text-primary",children:s.version})]}),v&&j&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ka,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"text-sm",children:[p==="updating"&&"Installing update...",p==="restarting"&&"Server restarting...",p==="reconnecting"&&"Waiting for server..."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),s?.body&&!j&&e.jsx(xt,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:s.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((D,k)=>/^\d+\.\d+\.\d+$/.test(D.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",D.trim(),`
82
+ `]},k):D.replace(/^- /gm,"• ").trim()+`
83
+
84
+ `)})}),v&&p==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(pg,{className:"h-4 w-4"}),e.jsx("span",{children:"Or update via terminal:"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 px-3 py-2 bg-muted rounded-md font-mono text-sm text-foreground overflow-x-auto",children:S}),e.jsx("button",{onClick:C,className:R("flex items-center justify-center p-2 rounded-md","text-muted-foreground hover:text-foreground hover:bg-accent","transition-colors",m&&"text-primary"),title:m?"Copied!":"Copy command",children:m?e.jsx(Tt,{className:"h-4 w-4"}):e.jsx(Wa,{className:"h-4 w-4"})})]})]}),!v&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[y,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${y}%`}})})]}),(c||g)&&e.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-sm text-destructive",children:c||g})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:b,target:"_blank",rel:"noopener noreferrer",className:R("flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md","text-sm text-muted-foreground","hover:text-foreground hover:bg-accent","transition-colors"),children:[e.jsx(Zs,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!n&&e.jsxs("button",{onClick:l,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(tn,{className:"h-4 w-4"}),"Download Update"]}),!v&&n&&e.jsxs("button",{disabled:!0,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(ka,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&o&&e.jsxs("button",{onClick:d,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Ls,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!j&&e.jsxs("button",{onClick:N,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(tn,{className:"h-4 w-4"}),"Update Now"]}),v&&j&&e.jsxs("button",{disabled:!0,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(ka,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Yd=264,Xd=200,Zd=500,eu="openchamber:check-for-updates",ej=({isOpen:t,isMobile:r,children:s})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:c}=Me(),[l,d]=i.useState(!1),u=i.useRef(0),m=i.useRef(n||Yd),[f,p]=i.useState(!1),h=xi(),g=i.useRef(!1),x=h.checkForUpdates,{available:b,downloaded:y,checking:v}=h,[S,C]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");if(i.useEffect(()=>{if(typeof window>"u")return;const D=typeof window.opencodeDesktop<"u";C(D)},[]),i.useEffect(()=>{if(typeof window>"u")return;const D=()=>{typeof window.opencodeDesktop<"u"&&(g.current=!0,x())};return window.addEventListener(eu,D),()=>{window.removeEventListener(eu,D)}},[x]),i.useEffect(()=>{g.current&&(v||(b||y?p(!0):V.success("No updates available",{description:"You are running the latest version."}),g.current=!1))},[b,y,v]),i.useEffect(()=>{if(r||!l)return;const D=M=>{const w=M.clientX-u.current,T=Math.min(Zd,Math.max(Xd,m.current+w));o(T)},k=()=>{d(!1)};return window.addEventListener("pointermove",D),window.addEventListener("pointerup",k,{once:!0}),()=>{window.removeEventListener("pointermove",D),window.removeEventListener("pointerup",k)}},[r,l,o]),i.useEffect(()=>{r&&l&&d(!1)},[r,l]),r)return null;const N=t?Math.min(Zd,Math.max(Xd,n||Yd)):0,j=D=>{t&&(d(!0),u.current=D.clientX,m.current=N,D.preventDefault())};return e.jsxs("aside",{className:R("relative flex h-full overflow-hidden border-r border-border",S?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",l?"transition-none":"transition-[width] duration-300 ease-in-out",!t&&"border-r-0"),style:{width:`${N}px`,minWidth:`${N}px`,maxWidth:`${N}px`,overflowX:"clip"},"aria-hidden":!t||N===0,children:[t&&e.jsx("div",{className:R("absolute right-0 top-0 z-20 h-full w-[4px] cursor-col-resize hover:bg-primary/50 transition-colors",l&&"bg-primary"),onPointerDown:j,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:R("relative z-10 flex h-full flex-col transition-opacity duration-300 ease-in-out",!t&&"pointer-events-none select-none opacity-0"),style:{width:`${N}px`,overflowX:"hidden"},"aria-hidden":!t,children:[e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:s})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border h-12 px-2 bg-sidebar-accent/10",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:R("flex h-8 items-center gap-2 rounded-md px-2","text-sm font-semibold text-sidebar-foreground/90","hover:text-sidebar-foreground hover:bg-sidebar-accent","transition-all duration-200"),children:[e.jsx(vn,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),b||y?e.jsxs("button",{onClick:()=>p(!0),className:R("flex items-center gap-1.5 rounded-md px-2 py-1","text-xs font-semibold","bg-primary/10 text-primary","hover:bg-primary/20","transition-colors"),children:[e.jsx(tn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!S&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{onClick:()=>c(!0),className:R("flex h-8 w-8 items-center justify-center rounded-md","text-sidebar-foreground/70","hover:text-sidebar-foreground hover:bg-sidebar-accent","transition-all duration-200"),children:e.jsx(ks,{className:"h-4 w-4"})})}),e.jsx(lt,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Uc,{open:f,onOpenChange:p,info:h.info,downloading:h.downloading,downloaded:h.downloaded,progress:h.progress,error:h.error,onDownload:h.downloadUpdate,onRestart:h.restartToUpdate,runtimeType:h.runtimeType})]})]})};function Mi({className:t,...r}){return e.jsx(In,{"data-slot":"command",className:R("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",t),...r})}function tj({title:t="Command Palette",description:r="Search for a command to run...",children:s,className:n,showCloseButton:o=!0,...a}){return e.jsxs(us,{...a,children:[e.jsxs(xs,{className:"sr-only",children:[e.jsx(ys,{children:t}),e.jsx(Ss,{children:r})]}),e.jsx(ms,{className:R("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Mi,{className:"[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-input]]:h-8 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-item]]:typography-meta",children:s})})]})}function Di({className:t,...r}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(Vs,{className:"size-4 shrink-0 opacity-50"}),e.jsx(In.Input,{"data-slot":"command-input",className:R("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",t),...r})]})}function Ai({className:t,children:r,scrollbarClassName:s,disableHorizontal:n,...o}){return e.jsx(xt,{as:In.List,"data-slot":"command-list",outerClassName:"max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0",className:R("scroll-py-1 overflow-x-hidden h-full min-h-0",t),scrollbarClassName:s??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:n??!0,...o,children:r})}function Ei({...t}){return e.jsx(In.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...t})}function Xr({className:t,...r}){return e.jsx(In.Group,{"data-slot":"command-group",className:R("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium",t),...r})}function ri({className:t,...r}){return e.jsx(In.Separator,{"data-slot":"command-separator",className:R("bg-border -mx-1 h-px",t),...r})}function ws({className:t,...r}){return e.jsx(In.Item,{"data-slot":"command-item",className:R("data-[selected=true]:bg-muted hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r})}function Pr({className:t,...r}){const s=a=>{const c=a.trim().toLowerCase();return c==="ctrl"||c==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):c==="cmd"||c==="⌘"||c==="command"||c==="meta"?e.jsx(En,{className:"size-3.5"}):c==="shift"||c==="⇧"?e.jsx(eo,{className:"size-3.5"}):e.jsx("span",{className:"text-xs font-medium",children:a})},n=typeof r.children=="string"?r.children:"",o=n?n.split("+").map(a=>a.trim()).filter(Boolean):[];return e.jsx("span",{"data-slot":"command-shortcut",className:R("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",t),...r,children:o.length>0?o.map((a,c)=>e.jsxs(Ae.Fragment,{children:[c>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),s(a)]},`${a}-${c}`)):r.children})}const tu=["artful","bionic","cosmic","disco","focal","groovy","jammy","kinetic","lunar","noble","bold","brave","calm","eager","gentle","happy","keen","lively","merry","swift","warm","wise","bright","clever","daring","agile","crisp","fresh","lucid","quick","sharp","vivid","zealous"],su=["aardvark","beaver","chipmunk","dolphin","falcon","gopher","hedgehog","jackal","koala","lemur","mongoose","narwhal","otter","pangolin","quokka","raccoon","salamander","toucan","walrus","yak","zebra","badger","condor","dingo","egret","ferret","gecko","heron","iguana"];function pp(){const t=tu[Math.floor(Math.random()*tu.length)],r=su[Math.floor(Math.random()*su.length)];return`${t}-${r}`}function sj(t){return pp()}const ru=t=>t.replace(/\\/g,"/").replace(/\/+$/,"")||t,hp=t=>{const r=ru(t),n=Lt.getState().projects.find(o=>ru(o.path)===r);return n?{id:n.id,path:n.path}:null};let Br=!1;async function Ii(){if(Br)return null;const t=Lt.getState().getActiveProject();if(!t?.path)return V.error("No active project",{description:"Please select a project first."}),null;const r=t.path;let s=!1;try{s=await Hr(r)}catch{}if(!s)return V.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Br=!0,Us("Creating new worktree session...");try{const o=t.worktreeDefaults?.baseBranch,a={id:t.id,path:r},c=sj(),l=o&&o!=="HEAD"?o:void 0,d=await go(a),u=await ki(a,{preferredName:c,setupCommands:d,startPoint:l}),m={...u,createdFromBranch:l??"HEAD"},f=await Jo(u.path).catch(()=>{}),p=f?{...m,status:f}:m,h=ve.getState(),g=await h.createSession(void 0,u.path);if(!g)return await Qo(a,u).catch(()=>{}),V.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const x=Je.getState(),b=x.agents;h.initializeNewOpenChamberSession(g.id,b),h.setSessionDirectory(g.id,u.path),h.setWorktreeMetadata(g.id,p);try{const y=x.getVisibleAgents();let v;if(x.settingsDefaultAgent){const S=y.find(C=>C.name===x.settingsDefaultAgent);S&&(v=S.name)}if(v||(v=y.find(S=>S.name==="build")?.name||y[0]?.name),v){x.setAgent(v),Ye.getState().saveSessionAgentSelection(g.id,v);const S=x.settingsDefaultModel;if(S){const C=S.split("/");if(C.length===2){const[N,j]=C;if(x.getModelMetadata(N,j)){Ye.getState().saveSessionModelSelection(g.id,N,j),Ye.getState().saveAgentModelForSession(g.id,v,N,j);const k=x.settingsDefaultVariant;if(k){const T=x.providers.find(E=>E.id===N)?.models.find(E=>E.id===j)?.variants;T&&Object.prototype.hasOwnProperty.call(T,k)&&(x.setCurrentVariant(k),Ye.getState().saveAgentModelVariantForSession(g.id,v,N,j,k))}}}}}}catch{}vt.getState().setDirectory(u.path,{showOverlay:!1});try{await h.loadSessions()}catch{}return V.success("Worktree created",{description:u.branch?`Branch: ${u.branch}`:"Ready"}),g}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return V.error("Failed to create worktree",{description:o}),null}finally{_s(),Br=!1}}async function rj(t,r){if(Br)return null;let s=!1;try{s=await Hr(t)}catch{}if(!s)return V.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Br=!0,Us("Creating worktree session...");try{const n=hp(t);if(!n)throw new Error("Project is not registered in OpenChamber");const o=await go(n),a=await ki(n,{preferredName:r,setupCommands:o,startPoint:r}),c={...a,createdFromBranch:r},l=await Jo(a.path).catch(()=>{}),d=l?{...c,status:l}:c,u=ve.getState(),m=await u.createSession(void 0,a.path);if(!m)return await Qo(n,a).catch(()=>{}),V.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const f=Je.getState(),p=f.agents;u.initializeNewOpenChamberSession(m.id,p),u.setSessionDirectory(m.id,a.path),u.setWorktreeMetadata(m.id,d);try{const h=f.getVisibleAgents();let g;if(f.settingsDefaultAgent){const x=h.find(b=>b.name===f.settingsDefaultAgent);x&&(g=x.name)}if(g||(g=h.find(x=>x.name==="build")?.name||h[0]?.name),g){f.setAgent(g),Ye.getState().saveSessionAgentSelection(m.id,g);const x=f.settingsDefaultModel;if(x){const b=x.split("/");if(b.length===2){const[y,v]=b;if(f.getModelMetadata(y,v)){Ye.getState().saveSessionModelSelection(m.id,y,v),Ye.getState().saveAgentModelForSession(m.id,g,y,v);const C=f.settingsDefaultVariant;if(C){const D=f.providers.find(k=>k.id===y)?.models.find(k=>k.id===v)?.variants;D&&Object.prototype.hasOwnProperty.call(D,C)&&(f.setCurrentVariant(C),Ye.getState().saveAgentModelVariantForSession(m.id,g,y,v,C))}}}}}}catch{}vt.getState().setDirectory(a.path,{showOverlay:!1});try{await u.loadSessions()}catch{}return V.success("Worktree created",{description:a.branch?`Branch: ${a.branch}`:"Ready"}),m}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return V.error("Failed to create worktree",{description:o}),null}finally{_s(),Br=!1}}async function gp(t,r,s,n){if(Br)return null;let o=!1;try{o=await Hr(t)}catch{}if(!o)return V.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Br=!0,Us("Creating worktree session...");try{const a=s?.trim()||"HEAD",c=r?.trim();if(!c)throw new Error("Branch name is required");const l=n?.allowSuffix!==!1,d=hp(t);if(!d)throw new Error("Project is not registered in OpenChamber");const u=await go(d);try{const m=await ki(d,{preferredName:c,setupCommands:u,startPoint:a,allowSuffix:l}),f={...m,createdFromBranch:a},p=await Jo(m.path).catch(()=>{}),h=p?{...f,status:p}:f,g=ve.getState(),x=await g.createSession(void 0,m.path);if(!x)throw await Qo(d,m).catch(()=>{}),new Error("Could not create a session for the worktree.");const b=Je.getState();g.initializeNewOpenChamberSession(x.id,b.agents),g.setSessionDirectory(x.id,m.path),g.setWorktreeMetadata(x.id,h);try{const y=b.getVisibleAgents();let v;if(b.settingsDefaultAgent){const S=y.find(C=>C.name===b.settingsDefaultAgent);S&&(v=S.name)}if(v||(v=y.find(S=>S.name==="build")?.name||y[0]?.name),v){b.setAgent(v),Ye.getState().saveSessionAgentSelection(x.id,v);const S=b.settingsDefaultModel;if(S){const C=S.split("/");if(C.length===2){const[N,j]=C;if(b.getModelMetadata(N,j)){Ye.getState().saveSessionModelSelection(x.id,N,j),Ye.getState().saveAgentModelForSession(x.id,v,N,j);const k=b.settingsDefaultVariant;if(k){const T=b.providers.find(E=>E.id===N)?.models.find(E=>E.id===j)?.variants;T&&Object.prototype.hasOwnProperty.call(T,k)&&(b.setCurrentVariant(k),Ye.getState().saveAgentModelVariantForSession(x.id,v,N,j,k))}}}}}}catch{}vt.getState().setDirectory(m.path,{showOverlay:!1});try{await g.loadSessions()}catch{}return V.success("Worktree created",{description:m.branch?`Branch: ${m.branch}`:"Ready"}),{id:x.id,branch:m.branch||c}}catch(m){const f=m instanceof Error?m.message:"Failed to create worktree session";return V.error("Failed to create worktree",{description:f}),null}}finally{_s(),Br=!1}}async function nj(t,r,s){return gp(t,r,s,{allowSuffix:!1})}const oj=()=>{const{isCommandPaletteOpen:t,setCommandPaletteOpen:r,setHelpDialogOpen:s,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:c,toggleSidebar:l}=Me(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=ve(),f=Je(P=>P.settingsAutoCreateWorktree),{currentDirectory:p}=vt(),{themeMode:h,setThemeMode:g}=Wr(),x=()=>{r(!1)},b=async()=>{n("chat"),a(!1),d(),x()},y=P=>{u(P),x()},v=P=>{g(P),x()},S=()=>{s(!0),x()},C=()=>{x(),Ii()},{isMobile:N}=Gt(),j=()=>{if(N){const{isSessionSwitcherOpen:P}=Me.getState();a(!P)}else l();x()},D=()=>{n("diff"),x()},k=()=>{n("git"),x()},M=()=>{n("terminal"),x()},w=()=>{o(!0),x()},T=()=>{Ao(),x()},E=()=>{c(!0),x()},I=m(p??""),A=i.useMemo(()=>I.slice(0,5),[I]);return e.jsxs(tj,{open:t,onOpenChange:r,children:[e.jsx(Di,{placeholder:"Type a command or search..."}),e.jsxs(Ai,{children:[e.jsx(Ei,{children:"No results found."}),e.jsxs(Xr,{heading:"Actions",children:[e.jsxs(ws,{onSelect:j,children:[e.jsx(il,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(Pr,{children:[Yt()," + L"]})]}),e.jsxs(ws,{onSelect:b,children:[e.jsx(ls,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Pr,{children:f?`Shift + ${Yt()} + N`:`${Yt()} + N`})]}),e.jsxs(ws,{onSelect:C,children:[e.jsx(Ut,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Pr,{children:f?`${Yt()} + N`:`Shift + ${Yt()} + N`})]}),e.jsxs(ws,{onSelect:S,children:[e.jsx(jn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(Pr,{children:[Yt()," + ."]})]}),e.jsxs(ws,{onSelect:D,children:[e.jsx(sr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(Pr,{children:[Yt()," + 2"]})]}),e.jsxs(ws,{onSelect:M,children:[e.jsx(rn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(Pr,{children:[Yt()," + 3"]})]}),e.jsxs(ws,{onSelect:k,children:[e.jsx(Ut,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(Pr,{children:[Yt()," + 4"]})]}),e.jsxs(ws,{onSelect:E,children:[e.jsx(Cr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(Pr,{children:[Yt()," + T"]})]}),e.jsxs(ws,{onSelect:w,children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(Pr,{children:[Yt()," + ,"]})]}),e.jsxs(ws,{onSelect:T,children:[e.jsx(Ls,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(ri,{}),e.jsxs(Xr,{heading:"Theme",children:[e.jsxs(ws,{onSelect:()=>v("light"),children:[e.jsx(hg,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx(Tt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(ws,{onSelect:()=>v("dark"),children:[e.jsx(gg,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx(Tt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(ws,{onSelect:()=>v("system"),children:[e.jsx(Bm,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx(Tt,{className:"ml-auto h-4 w-4"})]})]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ri,{}),e.jsx(Xr,{heading:"Recent Sessions",children:A.map(P=>e.jsxs(ws,{onSelect:()=>y(P.id),children:[e.jsx(cl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:P.title||"Untitled Session"})]},P.id))})]})]})]})},aj=(t,r)=>{const s=t.trim().toLowerCase();return s==="ctrl"||s==="control"?e.jsx(mi,{className:"h-3.5 w-3.5"},`ctrl-${r}`):s==="⌘"||s==="cmd"||s==="command"||s==="meta"?e.jsx(En,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:t.trim()},`key-${r}`)},ij=t=>{const r=t.split("+").map(s=>s.trim()).filter(Boolean);return r.length===0?t.trim():r.map((s,n)=>e.jsxs(i.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),aj(s,n)]},`${s}-${n}`))},cj=()=>{const{isHelpDialogOpen:t,setHelpDialogOpen:r}=Me(),s=Je(a=>a.settingsAutoCreateWorktree),n=Yt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:En},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:jn},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:il},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:Sn},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:ll},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:Mr}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:s?"Create New Session in Worktree":"Create New Session",icon:s?Ut:ls},{keys:[`Shift + ${n} + N`],description:s?"Create New Session":"Create New Session in Worktree",icon:s?ls:Ut},{keys:[`${n} + I`],description:"Focus Chat Input",icon:zm},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:to}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:xg},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:sr},{keys:[`${n} + 3`],description:"Open Files",icon:lr},{keys:[`${n} + 4`],description:"Open Terminal",icon:rn},{keys:[`${n} + 5`],description:"Open Git Panel",icon:Ut},{keys:[`${n} + T`],description:"Open Timeline",icon:Cr},{keys:[`${n} + ,`],description:"Open Settings",icon:vn}]}];return e.jsx(us,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(xs,{children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Ss,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:[e.jsx("div",{className:"space-y-4",children:o.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:a.category}),e.jsx("div",{className:"space-y-1",children:a.items.map((c,l)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c.icon&&e.jsx(c.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:c.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(c.keys)?c.keys:c.keys.split(" / ")).map((d,u)=>e.jsxs(i.Fragment,{children:[u>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:ij(d)})]},`${d}-${u}`))})]},l))})]},a.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(jn,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("p",{className:"font-medium mb-1",children:"Pro Tips:"}),e.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[e.jsxs("li",{children:["• Use Command Palette (",n," + K) to quickly access all actions"]}),e.jsx("li",{children:"• The 5 most recent sessions appear in the Command Palette"}),e.jsx("li",{children:"• Theme cycling remembers your preference across sessions"})]})]})]})})]})]})})},lj={xs:{container:"gap-[1px]",dot:"h-[3px] w-[3px]"},sm:{container:"gap-0.5",dot:"h-1 w-1"},md:{container:"gap-1",dot:"h-1.5 w-1.5"},lg:{container:"gap-1.5",dot:"h-2 w-2"}},xp=({className:t,size:r="md"})=>{const s=lj[r];return e.jsx("div",{className:R("grid grid-cols-3",s.container,t),"aria-label":"Loading",children:Array.from({length:9},(n,o)=>e.jsx("div",{className:R("rounded-full bg-current animate-grid-pulse",s.dot),style:{animationDelay:`${(o%3+Math.floor(o/3))*150}ms`}},o))})},Yi=new Set,Xi=new Set,Zi=new Set,io={onDeleteRequest(t){return Yi.add(t),()=>{Yi.delete(t)}},requestDelete(t){!t.sessions.length&&t.mode!=="worktree"||Yi.forEach(r=>r(t))},onCreateRequest(t){return Xi.add(t),()=>{Xi.delete(t)}},requestCreate(t){const r=t??{};Xi.forEach(s=>s(r))},onDirectoryRequest(t){return Zi.add(t),()=>{Zi.delete(t)}},requestDirectoryDialog(){Zi.forEach(t=>t())}};function yp(t){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...t,children:e.jsx("path",{d:"M232.49,192.49l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,0,1,17-17L180,187V141L128,89,76,141V187l11.51-11.52a12,12,0,0,1,17,17l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,1,1,17-17L52,187V136a12,12,0,0,1,3.51-8.49L116,67V24a12,12,0,0,1,24,0V67l60.49,60.48A12,12,0,0,1,204,136v51l11.51-11.52a12,12,0,0,1,17,17Z",transform:"rotate(180 128 128)"})})}function St({className:t,type:r,...s}){return e.jsx("input",{type:r,"data-slot":"input",className:R("text-foreground border-input file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none hover:border-input focus:border-ring flex h-9 w-full min-w-0 rounded-lg border bg-transparent px-3 py-1 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...s})}const dj=t=>t.label||t.normalizedPath.split("/").pop()||t.normalizedPath;function uj({open:t,onOpenChange:r,project:s}){const[n,o]=Ae.useState(""),[a,c]=Ae.useState(null),[l,d]=Ae.useState([]),[u,m]=Ae.useState(!1),[f,p]=Ae.useState(null),[h,g]=Ae.useState(null),[x,b]=Ae.useState(null),[y,v]=Ae.useState(null),[S,C]=Ae.useState(null),[N,j]=Ae.useState(null),[D,k]=Ae.useState(""),[M,w]=Ae.useState(null),T=Ae.useCallback(async()=>{if(s){m(!0),p(null);try{const[Z,B]=await Promise.all([wl(s.path),Pf(s.path)]);c(Z),d(B)}catch(Z){p(Z instanceof Error?Z.message:"Failed to load"),c(null),d([])}finally{m(!1)}}},[s]);Ae.useEffect(()=>{if(!t){o(""),v(null),C(null),j(null),k(""),w(null);return}T()},[t,T]);const E=(Z,B)=>{if(!B.trim())return Z;const W=B.toLowerCase();return Z.filter(te=>te.toLowerCase().includes(W))},I=async Z=>{if(s){g(Z);try{await rj(s.path,Z),r(!1)}catch(B){V.error("Failed to create worktree",{description:B instanceof Error?B.message:"Create failed"})}finally{g(null)}}},A=Ae.useCallback(Z=>{j(Z),k(Z)},[]),P=Ae.useCallback(()=>{j(null),k(""),w(null)},[]),F=Ae.useCallback(()=>{v(null),C(null)},[]),z=Ae.useCallback(async Z=>{if(!s)return;const B=D.trim();if(!B||B===Z){P();return}w(Z);try{if(!(await Bb(s.path,Z,B))?.success)throw new Error("Rename rejected");await T(),P(),V.success("Branch renamed",{description:`${Z} -> ${B}`})}catch(W){V.error("Failed to rename branch",{description:W instanceof Error?W.message:"Rename failed"}),w(null)}},[s,D,T,P]),G=Ae.useCallback(async Z=>{if(s){b(Z);try{const B=S===Z;if(!(await Bc(s.path,{branch:Z,force:B}))?.success)throw new Error("Delete rejected");await T(),V.success("Branch deleted",{description:Z}),v(null),C(null)}catch(B){const W=B instanceof Error?B.message:"Delete failed";/not fully merged/i.test(W)&&S!==Z?(C(Z),V.error("Branch not merged",{description:"Confirm again to force delete"})):V.error("Failed to delete branch",{description:W})}finally{b(null)}}},[s,T,S]),oe=new Set(l.map(Z=>Z.branch).filter(Boolean)),O=a?.all||[],Y=E(O,n).filter(Z=>!Z.startsWith("remotes/"));return e.jsx(us,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl max-h-[70vh] flex flex-col overflow-hidden gap-3",children:[e.jsxs(xs,{className:"flex-shrink-0",children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(Ut,{className:"h-5 w-5"}),"Manage Branches"]}),e.jsx(Ss,{children:s?`Local branches for ${dj(s)}`:"Select a project"})]}),e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(St,{placeholder:"Search branches...",value:n,onChange:Z=>o(Z.target.value),className:"pl-9"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"space-y-1",children:s?u?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading branches..."}):f?e.jsx("div",{className:"px-2 py-2 text-destructive text-sm",children:f}):Y.length===0?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:n?"No matching branches":"No branches found"}):Y.map(Z=>{const B=a?.branches[Z],W=!!B?.current,te=h===Z,ye=x===Z,me=M===Z,K=oe.has(Z),L=N===Z,Q=y===Z,ce=S===Z,he=!!(W||K||ye||me||L),Ne=!!(K||ye||me||L);return e.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5 hover:bg-muted/30 rounded-md overflow-hidden",children:[e.jsx(Ut,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[L?e.jsx("form",{className:"flex w-full items-center min-w-0",onSubmit:H=>{H.preventDefault(),z(Z)},children:e.jsx("input",{value:D,onChange:H=>k(H.target.value),className:"flex-1 min-w-0 h-5 bg-transparent text-sm leading-none outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename branch",onKeyDown:H=>{H.key==="Escape"&&(H.preventDefault(),P()),H.key==="Enter"&&(H.preventDefault(),z(Z))}})}):e.jsx("span",{className:R("text-sm truncate",W&&"font-medium text-primary"),children:Z}),W&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded flex-shrink-0 whitespace-nowrap",children:"current"}),K&&!L&&e.jsx("span",{className:"text-xs bg-muted/40 text-muted-foreground px-1.5 py-0.5 rounded flex-shrink-0 whitespace-nowrap",children:"worktree"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[B?.commit?e.jsx("span",{className:"font-mono",children:B.commit.slice(0,7)}):null,typeof B?.ahead=="number"&&B.ahead>0?e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["↑",B.ahead]}):null,typeof B?.behind=="number"&&B.behind>0?e.jsxs("span",{className:"text-[color:var(--status-warning)]",children:["↓",B.behind]}):null]})]}),!L&&!Q?e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>I(Z),disabled:te,className:"inline-flex h-7 w-7 items-center justify-center rounded-md bg-primary/10 hover:bg-primary/20 text-primary transition-colors disabled:opacity-50","aria-label":"Create worktree from",children:te?e.jsx(Mt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ut,{className:"h-4 w-4"})})}),e.jsx(lt,{side:"left",children:"Create worktree from"})]}),e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>A(Z),disabled:Ne,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-muted/40 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50","aria-label":"Rename",children:e.jsx(Hm,{className:"h-4 w-4"})})}),e.jsx(lt,{side:"left",children:K?"Rename (remove worktree first)":"Rename"})]}),e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>v(Z),disabled:he,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50","aria-label":"Delete",children:ye?e.jsx(Mt,{className:"h-4 w-4 animate-spin"}):e.jsx(zs,{className:"h-4 w-4"})})}),e.jsx(lt,{side:"left",children:W?"Delete (current branch)":K?"Delete (remove worktree first)":"Delete"})]})]}):null,L?e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("button",{type:"button",onClick:()=>{z(Z)},disabled:me,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-muted/40 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50","aria-label":"Confirm rename",children:me?e.jsx(Mt,{className:"h-4 w-4 animate-spin"}):e.jsx(Tt,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:P,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-muted/40 text-muted-foreground hover:text-foreground transition-colors","aria-label":"Cancel rename",children:e.jsx(es,{className:"h-4 w-4"})})]}):null,!L&&Q?e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("span",{className:R("text-xs mr-1",ce?"text-destructive":"text-muted-foreground"),children:ce?"Force delete?":"Delete?"}),e.jsx("button",{type:"button",onClick:()=>{G(Z)},disabled:ye,className:R("inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors disabled:opacity-50",ce?"bg-destructive/10 text-destructive hover:bg-destructive/15":"hover:bg-destructive/10 text-muted-foreground hover:text-destructive"),"aria-label":"Confirm delete",children:ye?e.jsx(Mt,{className:"h-4 w-4 animate-spin"}):e.jsx(Tt,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:F,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-muted/40 text-muted-foreground hover:text-foreground transition-colors","aria-label":"Cancel delete",children:e.jsx(es,{className:"h-4 w-4"})})]}):null]},Z)}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No project selected"})})})]})})}const mj=t=>{const r=t.trim();if(!r)return null;const s=r.match(/\/issues\/(\d+)(?:\b|\/|$)/i);if(s){const o=Number(s[1]);return Number.isFinite(o)&&o>0?o:null}const n=r.match(/^#?(\d+)$/);if(n){const o=Number(n[1]);return Number.isFinite(o)&&o>0?o:null}return null},fj=t=>{const r={repo:t.repo??null,issue:t.issue,comments:t.comments};return`GitHub issue context (JSON)
85
+ ${JSON.stringify(r,null,2)}`};function pj({open:t,onOpenChange:r}){const{github:s}=Hs(),n=Bs(W=>W.status),o=Bs(W=>W.hasChecked),a=Me(W=>W.setSettingsDialogOpen),c=Me(W=>W.setSidebarSection),l=Lt(W=>W.getActiveProject()),d=l?.path??null,u=l?.worktreeDefaults?.baseBranch||"main",[m,f]=i.useState(""),[p,h]=i.useState(!1),[g,x]=i.useState(null),[b,y]=i.useState([]),[v,S]=i.useState(1),[C,N]=i.useState(!1),[j,D]=i.useState(null),[k,M]=i.useState(!1),[w,T]=i.useState(!1),[E,I]=i.useState(null),A=i.useCallback(async()=>{if(!d){x(null),I("No active project");return}if(o&&n?.connected===!1){x({connected:!1}),y([]),N(!1),S(1),I(null);return}if(!s?.issuesList){x(null),I("GitHub runtime API unavailable");return}M(!0),I(null);try{const W=await s.issuesList(d,{page:1});x(W),y(W.issues??[]),S(W.page??1),N(!!W.hasMore),W.connected===!1&&I(null)}catch(W){I(W instanceof Error?W.message:String(W))}finally{M(!1)}},[s,o,n,d]),P=i.useCallback(async()=>{if(d&&s?.issuesList&&!(w||k)&&C){T(!0);try{const W=v+1,te=await s.issuesList(d,{page:W});x(te),y(ye=>[...ye,...te.issues??[]]),S(te.page??W),N(!!te.hasMore)}catch(W){const te=W instanceof Error?W.message:String(W);V.error("Failed to load more issues",{description:te})}finally{T(!1)}}},[s,C,k,w,v,d]);i.useEffect(()=>{if(!t){f(""),h(!1),D(null),I(null),x(null),y([]),S(1),N(!1),M(!1);return}A()},[t,A]),i.useEffect(()=>{t&&o&&n?.connected===!1&&(x({connected:!1}),y([]),N(!1),S(1),I(null))},[o,n,t]);const F=o?g?.connected!==!1:!0,z=g?.repo?.url??null,G=i.useCallback(()=>{c("settings"),a(!0)},[a,c]),oe=i.useMemo(()=>{const W=m.trim().toLowerCase();return W?b.filter(te=>String(te.number)===W.replace(/^#/,"")?!0:te.title.toLowerCase().includes(W)):b},[b,m]),O=i.useMemo(()=>mj(m),[m]),q=i.useCallback(()=>{const W=Je.getState(),te=W.getVisibleAgents();if(W.settingsDefaultAgent){const ye=te.find(me=>me.name===W.settingsDefaultAgent);if(ye)return ye.name}return te.find(ye=>ye.name==="build")?.name||te[0]?.name},[]),Y=i.useCallback(()=>{const W=Je.getState(),te=W.settingsDefaultModel;if(!te)return null;const ye=te.split("/");if(ye.length!==2)return null;const[me,K]=ye;return!me||!K||!W.getModelMetadata(me,K)?null:{providerID:me,modelID:K}},[]),Z=i.useCallback((W,te)=>{const ye=Je.getState(),me=ye.settingsDefaultVariant;if(!me)return;const Q=ye.providers.find(ce=>ce.id===W)?.models.find(ce=>ce.id===te)?.variants;if(Q&&Object.prototype.hasOwnProperty.call(Q,me))return me},[]),B=i.useCallback(async W=>{if(!d){V.error("No active project");return}if(!s?.issueGet||!s?.issueComments){V.error("GitHub runtime API unavailable");return}if(!j){D(W);try{const te=await s.issueGet(d,W);if(te.connected===!1){V.error("GitHub not connected");return}if(!te.repo){V.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}const ye=te.issue;if(!ye){V.error("Issue not found");return}const me=await s.issueComments(d,W);if(me.connected===!1){V.error("GitHub not connected");return}const K=me.comments??[],L=`#${ye.number} ${ye.title}`.trim(),Q=await(async()=>{if(p){const fe=`issue-${ye.number}-${pp()}`,ie=await gp(d,fe,u||"main");if(!ie?.id)throw new Error("Failed to create worktree session");return ie.id}const ae=await ve.getState().createSession(L,d,null);if(!ae?.id)throw new Error("Failed to create session");return ae.id})();ve.getState().updateSessionTitle(Q,L).catch(()=>{});try{ve.getState().initializeNewOpenChamberSession(Q,Je.getState().agents)}catch{}r(!1);const ce=Je.getState(),he=Nt.getState().lastUsedProvider,Ne=Y(),H=Ne?.providerID||ce.currentProviderId||he?.providerID,we=Ne?.modelID||ce.currentModelId||he?.modelID,ee=q()||ce.currentAgentName||void 0;if(!H||!we){V.error("No model selected");return}const ue=Z(H,we);try{Ye.getState().saveSessionModelSelection(Q,H,we)}catch{}if(ee){try{ce.setAgent(ee)}catch{}try{Ye.getState().saveSessionAgentSelection(Q,ee)}catch{}try{Ye.getState().saveAgentModelForSession(Q,ee,H,we)}catch{}if(ue!==void 0){try{ce.setCurrentVariant(ue)}catch{}try{Ye.getState().saveAgentModelVariantForSession(Q,ee,H,we,ue)}catch{}}}const ge="Review this issue using the provided issue context: title, body, labels, assignees, comments, metadata.",X=`Review this issue using the provided issue context.
86
+
87
+ Process:
88
+ - First classify the issue type (bug / feature request / question/support / refactor / ops) and state it as: Type: <one label>.
89
+ - Gather any needed repository context (code, config, docs) to validate assumptions.
90
+ - After gathering, if anything is still unclear or cannot be verified, do not speculate—state what’s missing and ask targeted questions.
91
+
92
+ Output rules:
93
+ - Compact output; pick ONE template below and omit the others.
94
+ - No emojis. No code snippets. No fenced blocks.
95
+ - Short inline code identifiers allowed.
96
+ - Reference evidence with file paths and line ranges when applicable; if exact lines aren’t available, cite the file and say “approx” + why.
97
+ - Keep the entire response under ~300 words.
98
+
99
+ Templates (choose one):
100
+ Bug:
101
+ - Summary (1-2 sentences)
102
+ - Likely cause (max 2)
103
+ - Repro/diagnostics needed (max 3)
104
+ - Fix approach (max 4 steps)
105
+ - Verification (max 3)
106
+
107
+ Feature:
108
+ - Summary (1-2 sentences)
109
+ - Requirements (max 4)
110
+ - Unknowns/questions (max 4)
111
+ - Proposed plan (max 5 steps)
112
+ - Verification (max 3)
113
+
114
+ Question/Support:
115
+ - Summary (1-2 sentences)
116
+ - Answer/guidance (max 6 lines)
117
+ - Missing info (max 4)
118
+
119
+ Do not implement changes until I confirm; end with: “Next actions: <1 sentence>”.`,de=fj({repo:te.repo,issue:ye,comments:K});Oe.sendMessage({id:Q,providerID:H,modelID:we,agent:ee,variant:ue,text:ge,additionalParts:[{text:X,synthetic:!0},{text:de,synthetic:!0}]}).catch(ae=>{const fe=ae instanceof Error?ae.message:String(ae);V.error("Failed to send issue context",{description:fe})}),V.success("Session created from issue")}catch(te){const ye=te instanceof Error?te.message:String(te);V.error("Failed to start session",{description:ye})}finally{D(null)}}},[p,s,r,d,u,q,Y,Z,j]);return e.jsx(us,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(xs,{className:"flex-shrink-0",children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(Wm,{className:"h-5 w-5"}),"New Session From GitHub Issue"]}),e.jsx(Ss,{children:"Seeds a new session with hidden issue context (title/body/labels/comments)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(St,{placeholder:"Search by title or #123, or paste issue URL",value:m,onChange:W=>f(W.target.value),className:"pl-9 w-full"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[d?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No active project selected."}),s?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"GitHub runtime API unavailable."}),k?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Mt,{className:"h-4 w-4 animate-spin"}),"Loading issues..."]}):null,F===!1?e.jsxs("div",{className:"text-center text-muted-foreground py-8 space-y-3",children:[e.jsx("div",{children:"GitHub not connected. Connect your GitHub account in settings."}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Se,{variant:"outline",size:"sm",onClick:G,children:"Open settings"})})]}):null,E?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:E}):null,O&&d&&s&&F?e.jsxs("div",{className:R("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",j===O&&"bg-muted/30"),onClick:()=>{B(O)},children:[e.jsx("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:"#"}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:["Use issue #",O]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:j===O?e.jsx(Mt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,oe.length===0&&!k&&F&&s&&d?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:m?"No issues found":"No open issues found"}):null,oe.map(W=>e.jsxs("div",{className:R("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",j===W.number&&"bg-muted/30"),onClick:()=>{B(W.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0",children:["#",W.number]}),e.jsx("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:W.title}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:j===W.number?e.jsx(Mt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:W.url,target:"_blank",rel:"noopener noreferrer",className:"hidden group-hover:flex h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:te=>te.stopPropagation(),"aria-label":"Open in GitHub",children:e.jsx(Zs,{className:"h-4 w-4"})})})]},W.number)),C&&F&&d&&s?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{P()},disabled:w||!!j,className:R("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(w||!!j)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:w?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Mt,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):"Load more"})}):null]}),e.jsxs("div",{className:"mt-4 p-3 bg-muted/30 rounded-lg",children:[e.jsx("p",{className:"typography-meta text-muted-foreground font-medium mb-2",children:"Actions"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":p,onClick:()=>h(W=>!W),onKeyDown:W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),h(te=>!te))},children:[e.jsx("button",{type:"button",onClick:W=>{W.preventDefault(),W.stopPropagation(),h(te=>!te)},"aria-label":"Toggle worktree",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:p?e.jsx(Nn,{className:"h-4 w-4 text-primary"}):e.jsx(kn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Create in worktree"}),e.jsx("span",{className:"typography-meta text-muted-foreground/70",children:"(issue-<number>-<slug>)"})]}),e.jsx("div",{className:"flex-1"}),z?e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:z,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Zs,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(Se,{variant:"outline",size:"sm",onClick:A,disabled:k||!!j,children:"Refresh"})]})]})]})})}const ec="/api",hj=()=>(ec.startsWith("/"),ec);function gj(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}async function _a(t,r){const s=gj();if(s?.execCommands)return s.execCommands(t,r);const n=await fetch(`${hj()}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:t,cwd:r,background:!1})});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Command exec failed")}const o=await n.json().catch(()=>null);return{success:!!o?.success,results:Array.isArray(o?.results)?o.results:[]}}async function Ht(t,r){const s=await _a([t],r),n=s.results[0];return n||{command:t,success:s.success}}const xj=t=>{const r=t.trim();if(!r)return null;const s=r.match(/\/pull\/(\d+)(?:\b|\/|$)/i);if(s){const o=Number(s[1]);return Number.isFinite(o)&&o>0?o:null}const n=r.match(/^#?(\d+)$/);if(n){const o=Number(n[1]);return Number.isFinite(o)&&o>0?o:null}return null},yj=t=>`GitHub pull request context (JSON)
120
+ ${JSON.stringify(t,null,2)}`,bj=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64);function wj({open:t,onOpenChange:r}){const{github:s}=Hs(),n=Bs(Q=>Q.status),o=Bs(Q=>Q.hasChecked),a=Me(Q=>Q.setSettingsDialogOpen),c=Me(Q=>Q.setSidebarSection),d=Lt(Q=>Q.getActiveProject())?.path??null,[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,g]=i.useState(!1),[x,b]=i.useState(null),[y,v]=i.useState([]),[S,C]=i.useState(1),[N,j]=i.useState(!1),[D,k]=i.useState(null),[M,w]=i.useState(!1),[T,E]=i.useState(!1),[I,A]=i.useState(new Map),[P,F]=i.useState(null),z=i.useCallback(async()=>{if(!d){b(null),F("No active project");return}if(o&&n?.connected===!1){b({connected:!1}),v([]),j(!1),C(1),F(null);return}if(!s?.prsList){b(null),F("GitHub runtime API unavailable");return}w(!0),F(null);try{const Q=await s.prsList(d,{page:1});b(Q),v(Q.prs??[]),C(Q.page??1),j(!!Q.hasMore),Q.connected===!1&&F(null)}catch(Q){F(Q instanceof Error?Q.message:String(Q))}finally{w(!1)}},[s,o,n,d]),G=i.useCallback(async()=>{if(d&&s?.prsList&&!(T||M)&&N){E(!0);try{const Q=S+1,ce=await s.prsList(d,{page:Q});b(ce),v(he=>[...he,...ce.prs??[]]),C(ce.page??Q),j(!!ce.hasMore)}catch(Q){const ce=Q instanceof Error?Q.message:String(Q);V.error("Failed to load more PRs",{description:ce})}finally{E(!1)}}},[s,N,M,T,S,d]);i.useEffect(()=>{if(!t){m(""),p(!1),g(!1),b(null),v([]),C(1),j(!1),k(null),w(!1),F(null),A(new Map);return}z()},[t,z]);const oe=i.useCallback(async Q=>{if(!d)return;const ce=Array.from(new Set(Q.map(Ne=>(Ne||"").trim()).filter(Boolean)));if(ce.length===0)return;const he=ce.filter(Ne=>!I.has(Ne));if(he.length!==0){const Ne=he.map(we=>`git show-ref --verify --quiet ${JSON.stringify(`refs/heads/${we}`)}`),H=await _a(Ne,d);A(we=>{const ee=new Map(we);for(let ue=0;ue<he.length;ue+=1){const ge=he[ue];ee.set(ge,!!H.results[ue]?.success)}return ee})}},[d,I]);i.useEffect(()=>{t&&d&&f&&oe(y.map(Q=>Q.head))},[t,d,f,y,oe]),i.useEffect(()=>{t&&o&&n?.connected===!1&&(b({connected:!1}),v([]),j(!1),C(1),F(null))},[o,n,t]);const O=o?x?.connected!==!1:!0,q=x?.repo?.url??null,Y=i.useCallback(()=>{c("settings"),a(!0)},[a,c]),Z=i.useMemo(()=>{const Q=u.trim().toLowerCase();return Q?y.filter(ce=>String(ce.number)===Q.replace(/^#/,"")?!0:ce.title.toLowerCase().includes(Q)):y},[y,u]),B=i.useCallback(Q=>{if(!f)return!1;const ce=Q.head?.trim();return ce?I.get(ce)===!0:!0},[f,I]),W=i.useMemo(()=>xj(u),[u]),te=i.useCallback(()=>{const Q=Je.getState(),ce=Q.getVisibleAgents();if(Q.settingsDefaultAgent){const he=ce.find(Ne=>Ne.name===Q.settingsDefaultAgent);if(he)return he.name}return ce.find(he=>he.name==="build")?.name||ce[0]?.name},[]),ye=i.useCallback(()=>{const Q=Je.getState(),ce=Q.settingsDefaultModel;if(!ce)return null;const he=ce.split("/");if(he.length!==2)return null;const[Ne,H]=he;return!Ne||!H||!Q.getModelMetadata(Ne,H)?null:{providerID:Ne,modelID:H}},[]),me=i.useCallback((Q,ce)=>{const he=Je.getState(),Ne=he.settingsDefaultVariant;if(!Ne)return;const ee=he.providers.find(ue=>ue.id===Q)?.models.find(ue=>ue.id===ce)?.variants;if(ee&&Object.prototype.hasOwnProperty.call(ee,Ne))return Ne},[]),K=i.useCallback(async(Q,ce)=>{if(!d)return null;const he=ce.head,Ne=ce.headRepo;if(!he)throw new Error("PR head ref missing");const H=!!(Ne?.owner&&Ne?.repo&&Q?.owner&&Q?.repo&&(Ne.owner!==Q.owner||Ne.repo!==Q.repo)),we=H?Ne?.cloneUrl||Ne?.url||"":"origin";if(!we)throw new Error("PR head remote URL missing");const ee=`refs/heads/${he}`;if(!(await $b(d,{remote:we,branch:ee}))?.success)throw new Error("Failed to fetch PR head");const ge=ce.headSha?.trim()||(await Ht("git rev-parse FETCH_HEAD",d)).stdout?.trim()||"";if(!ge)throw new Error("PR head commit not resolvable");const X=ce.head;if(I.get(X)===!0)throw new Error(`Local branch already exists: ${X}`);const de=await nj(d,X,ge);if(!de?.id)throw new Error("Failed to create PR worktree session");const ae=ve.getState().worktreeMetadata.get(de.id),fe=ae?.path;if(!fe)throw new Error("Worktree directory not found");const ie=(ae?.branch||de.branch||"").replace(/^refs\/heads\//,"").trim(),se=[`git -C ${JSON.stringify(fe)} switch -c ${JSON.stringify(X)} ${JSON.stringify(ge)}`];ie&&ie.startsWith("opencode/")&&se.push(`git -C ${JSON.stringify(d)} branch -D ${JSON.stringify(ie)}`);const re=await _a(se,d);if(!re.success){const ne=re.results.find(xe=>!xe.success);throw new Error(ne?.stderr||ne?.stdout||"Failed to switch worktree to PR branch")}try{const ne=H?bj(`pr-${Ne?.owner||"fork"}-${Ne?.repo||""}`):"origin",xe=H&&(Ne?.cloneUrl||Ne?.url)||"",Ue=`+refs/heads/${X}:refs/remotes/${ne}/${X}`,ze=[];H&&xe&&ze.push(`git -C ${JSON.stringify(d)} remote add ${JSON.stringify(ne)} ${JSON.stringify(xe)} 2>/dev/null || git -C ${JSON.stringify(d)} remote set-url ${JSON.stringify(ne)} ${JSON.stringify(xe)}`),ze.push(`git -C ${JSON.stringify(d)} fetch ${JSON.stringify(ne)} ${JSON.stringify(Ue)}`),ze.push(`git -C ${JSON.stringify(fe)} branch --set-upstream-to=${JSON.stringify(`${ne}/${X}`)} ${JSON.stringify(X)}`);const Ke=await _a(ze,d);if(!Ke.success){const rt=Ke.results.find(jt=>!jt.success);V.message("PR upstream not set",{description:rt?.stderr||rt?.stdout||"Configure remote manually if needed."})}}catch{V.message("PR upstream not set",{description:"Configure remote manually if needed."})}return ve.getState().setWorktreeMetadata(de.id,{...ae||{path:fe,projectDirectory:d,branch:X,label:X},path:fe,projectDirectory:d,branch:X,label:X,createdFromBranch:ce.base}),{id:de.id}},[d,I]),L=i.useCallback(async Q=>{if(!d){V.error("No active project");return}if(!s?.prContext){V.error("GitHub runtime API unavailable");return}if(!D){k(Q);try{const ce=await s.prContext(d,Q,{includeDiff:h,includeCheckDetails:!1});if(ce.connected===!1){V.error("GitHub not connected");return}if(!ce.repo){V.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}if(!ce.pr){V.error("PR not found");return}const he=ce.pr,Ne=`#${he.number} ${he.title}`.trim(),H=await(async()=>{if(f)try{return(await K(ce.repo,he))?.id||null}catch(ne){const xe=ne instanceof Error?ne.message:String(ne);V.error("PR worktree failed",{description:xe})}return(await ve.getState().createSession(Ne,d,null))?.id||null})();if(!H)throw new Error("Failed to create session");ve.getState().updateSessionTitle(H,Ne).catch(()=>{});try{ve.getState().initializeNewOpenChamberSession(H,Je.getState().agents)}catch{}r(!1);const we=Je.getState(),ee=Nt.getState().lastUsedProvider,ue=ye(),ge=ue?.providerID||we.currentProviderId||ee?.providerID,X=ue?.modelID||we.currentModelId||ee?.modelID,de=te()||we.currentAgentName||void 0;if(!ge||!X){V.error("No model selected");return}const ae=me(ge,X);try{Ye.getState().saveSessionModelSelection(H,ge,X)}catch{}if(de){try{we.setAgent(de)}catch{}try{Ye.getState().saveSessionAgentSelection(H,de)}catch{}try{Ye.getState().saveAgentModelForSession(H,de,ge,X)}catch{}if(ae!==void 0){try{we.setCurrentVariant(ae)}catch{}try{Ye.getState().saveAgentModelVariantForSession(H,de,ge,X,ae)}catch{}}}const fe="Review this pull request using the provided PR context: description, comments, files, diff, checks.",ie=`Before reporting issues:
121
+ - First identify the PR intent (what it’s trying to achieve) from title/body/diff, then evaluate whether the implementation matches that intent; call out missing pieces, incorrect behavior vs intent, and scope creep.
122
+ - Gather any needed repository context (code, config, docs) to validate assumptions.
123
+ - No speculation: if something is unclear or cannot be verified, say what’s missing and ask for it instead of guessing.
124
+
125
+ Output rules:
126
+ - Start with a 1-2 sentence summary.
127
+ - Provide a single concise PR review comment.
128
+ - No emojis. No code snippets. No fenced blocks.
129
+ - Short inline code identifiers allowed, but no snippets or fenced blocks.
130
+ - Reference evidence with file paths and line ranges (e.g., path/to/file.ts:120-138). If exact lines aren’t available, cite the file and say “approx” + why.
131
+ - Keep the entire comment under ~300 words.
132
+
133
+ Report:
134
+ - Must-fix issues (blocking) — brief why and a one-line action each.
135
+ - Nice-to-have improvements (optional) — brief why and a one-line action each.
136
+
137
+ Quality & safety (general):
138
+ - Call out correctness risks, edge cases, performance regressions, security/privacy concerns, and backwards-compatibility risks.
139
+ - Call out missing tests/verification steps and suggest the minimal validation needed.
140
+ - Note readability/maintainability issues when they materially affect future changes.
141
+
142
+ Applicability (only if relevant):
143
+ - If changes affect multiple components/targets/environments (e.g., client/server, OSs, deployments), state what is affected vs not, and why.
144
+
145
+ Architecture:
146
+ - Call out breakages, missing implementations across modules/targets, boundary violations, and cross-cutting concerns (errors, logging/observability, accessibility).
147
+
148
+ Precedence:
149
+ - If local precedent conflicts with best practices, state it and suggest a follow-up task.
150
+
151
+ Do not implement changes until I confirm; end with a short “Next actions” sentence describing the recommended plan.
152
+
153
+ Format exactly:
154
+ Must-fix:
155
+ - <issue> — <brief why> — <file:line-range> — Action: <one-line action>
156
+ Nice-to-have:
157
+ - <issue> — <brief why> — <file:line-range> — Action: <one-line action>
158
+ If no issues, write:
159
+ Must-fix:
160
+ - None
161
+ Nice-to-have:
162
+ - None`,se=yj(ce);Oe.sendMessage({id:H,providerID:ge,modelID:X,agent:de,variant:ae,text:fe,additionalParts:[{text:ie,synthetic:!0},{text:se,synthetic:!0}]}).catch(re=>{const ne=re instanceof Error?re.message:String(re);V.error("Failed to send PR context",{description:ne})}),V.success("Session created from PR")}catch(ce){const he=ce instanceof Error?ce.message:String(ce);V.error("Failed to start session",{description:he})}finally{k(null)}}},[f,K,s,h,r,d,te,ye,me,D]);return e.jsx(us,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(xs,{className:"flex-shrink-0",children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-5 w-5"}),"New Session From GitHub PR"]}),e.jsx(Ss,{children:"Seeds a new session with hidden PR context (title/body/comments/files/checks)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(St,{placeholder:"Search by title or #123, or paste PR URL",value:u,onChange:Q=>m(Q.target.value),className:"pl-9 w-full"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[d?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No active project selected."}),s?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"GitHub runtime API unavailable."}),M?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Mt,{className:"h-4 w-4 animate-spin"}),"Loading pull requests..."]}):null,O===!1?e.jsxs("div",{className:"text-center text-muted-foreground py-8 space-y-3",children:[e.jsx("div",{children:"GitHub not connected. Connect your GitHub account in settings."}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Se,{variant:"outline",size:"sm",onClick:Y,children:"Open settings"})})]}):null,P?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:P}):null,W&&d&&s&&O?e.jsxs("div",{className:R("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",D===W&&"bg-muted/30"),onClick:()=>{L(W)},children:[e.jsx("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:"#"}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:["Use PR #",W]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:D===W?e.jsx(Mt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,Z.length===0&&!M&&O&&s&&d?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:u?"No PRs found":"No open PRs found"}):null,Z.map(Q=>{const ce=B(Q);return e.jsxs("div",{className:R("group flex items-start gap-2 py-1.5 rounded transition-colors",D===Q.number&&"bg-muted/30",ce?"opacity-50 cursor-not-allowed":"hover:bg-muted/30 cursor-pointer"),onClick:()=>{ce||L(Q.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0 pt-0.5",children:["#",Q.number]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"typography-small text-foreground truncate ml-0.5",children:Q.title}),f&&ce?e.jsxs("p",{className:"typography-micro text-muted-foreground mt-0.5 ml-0.5",children:["PR worktree disabled: local branch exists (",Q.head,")"]}):null]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2 pt-0.5",children:D===Q.number?e.jsx(Mt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:Q.url,target:"_blank",rel:"noopener noreferrer",className:R("hidden group-hover:flex h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors",ce&&"pointer-events-none"),onClick:he=>he.stopPropagation(),"aria-label":"Open in GitHub",children:e.jsx(Zs,{className:"h-4 w-4"})})})]},Q.number)}),N&&O&&d&&s?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{G()},disabled:T||!!D,className:R("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(T||!!D)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:T?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Mt,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):"Load more"})}):null]}),e.jsxs("div",{className:"mt-4 p-3 bg-muted/30 rounded-lg",children:[e.jsx("p",{className:"typography-meta text-muted-foreground font-medium mb-2",children:"Actions"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":f,onClick:()=>p(Q=>!Q),onKeyDown:Q=>{(Q.key===" "||Q.key==="Enter")&&(Q.preventDefault(),p(ce=>!ce))},children:[e.jsx("button",{type:"button",onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),p(ce=>!ce)},"aria-label":"Toggle worktree",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:f?e.jsx(Nn,{className:"h-4 w-4 text-primary"}):e.jsx(kn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Create session in PR worktree"})]}),e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":h,onClick:()=>g(Q=>!Q),onKeyDown:Q=>{(Q.key===" "||Q.key==="Enter")&&(Q.preventDefault(),g(ce=>!ce))},children:[e.jsx("button",{type:"button",onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),g(ce=>!ce)},"aria-label":"Toggle diff",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:h?e.jsx(Nn,{className:"h-4 w-4 text-primary"}):e.jsx(kn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Include full diff"})]}),e.jsx("div",{className:"flex-1"}),q?e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:q,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Zs,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(Se,{variant:"outline",size:"sm",onClick:z,disabled:M||!!D,children:"Refresh"})]})]})]})})}const nu="oc.sessions.projectCollapse",ou="oc.sessions.expandedParents",au=t=>{const r=new Date(t),s=new Date,n=(c,l)=>c.getFullYear()===l.getFullYear()&&c.getMonth()===l.getMonth()&&c.getDate()===l.getDate(),o=new Date(s);return o.setDate(s.getDate()-1),n(r,s)?"Today":n(r,o)?"Yesterday":r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},br=t=>{if(!t)return null;const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},iu=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),vj=({id:t,projectLabel:r,projectDescription:s,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:c,isDesktopRuntime:l,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:h,onNewWorktreeSession:g,onOpenBranchPicker:x,onNewSessionFromGitHubIssue:b,onNewSessionFromGitHubPR:y,onOpenMultiRunLauncher:v,onClose:S,sentinelRef:C,children:N,settingsAutoCreateWorktree:j})=>{const{attributes:D,listeners:k,setNodeRef:M,isDragging:w}=Ag({id:t}),[T,E]=i.useState(!1);return e.jsxs("div",{ref:M,className:R("relative",w&&"opacity-40"),children:[l&&e.jsx("div",{ref:C,"data-project-id":t,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("div",{className:R("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b select-none",!l&&"bg-sidebar"),style:{backgroundColor:l?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:c?"var(--color-border)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onContextMenu:I=>{I.preventDefault(),E(!0)},children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...D,children:[e.jsxs(dt,{delayDuration:1500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...k,className:"flex-1 min-w-0 flex items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-sm cursor-grab active:cursor-grabbing",children:e.jsx("span",{className:R("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(lt,{side:"right",sideOffset:8,children:s})]}),e.jsxs(ts,{open:T,onOpenChange:E,children:[e.jsx(ss,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",m?"opacity-70":"opacity-0 group-hover/project:opacity-100"),"aria-label":"Project menu",onClick:I=>I.stopPropagation(),children:e.jsx(nn,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"min-w-[180px]",children:[a&&!u&&j&&h&&e.jsxs(kt,{onClick:h,children:[e.jsx(ls,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),a&&!u&&!j&&g&&e.jsxs(kt,{onClick:g,children:[e.jsx(Ut,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),a&&!u&&b&&e.jsxs(kt,{onClick:b,children:[e.jsx(Wm,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub issue"]}),a&&!u&&y&&e.jsxs(kt,{onClick:y,children:[e.jsx(Ua,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub PR"]}),a&&!u&&e.jsxs(kt,{onClick:v,children:[e.jsx(yp,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),a&&!u&&x&&e.jsxs(kt,{onClick:x,children:[e.jsx(Um,{className:"mr-1.5 h-4 w-4"}),"Manage Branches"]}),e.jsxs(kt,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),a&&!u&&g&&j&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),g()},className:R("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground flex-shrink-0",m?"opacity-70":"opacity-100"),"aria-label":"New session in worktree",children:e.jsx(Ut,{className:"h-4 w-4"})})}),e.jsx(lt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session in worktree"})})]}),(!j||!a)&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),h()},className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground flex-shrink-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"New session",children:e.jsx(ls,{className:"h-4 w-4"})})}),e.jsx(lt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session"})})]})]})}),N]})},jj=({projectLabel:t,isActiveProject:r})=>e.jsx("div",{className:"bg-sidebar border border-border rounded-md shadow-lg px-2 py-1.5",style:{width:"max-content",maxWidth:"280px"},children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:R("typography-ui font-semibold truncate",r?"text-primary":"text-foreground"),children:t})})}),ni=({mobileVariant:t=!1,onSessionSelected:r,allowReselect:s=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,c]=i.useState(null),[l,d]=i.useState(""),[u,m]=i.useState(null),f=i.useRef(null),[p,h]=i.useState(new Set),[g,x]=i.useState(()=>new Map),b=i.useRef(new Set),y=i.useMemo(()=>js(),[]),[v,S]=i.useState(new Set),[C,N]=i.useState(new Map),[j,D]=i.useState(new Set),[k,M]=i.useState(null),[w,T]=i.useState(!1),[E,I]=i.useState(null),[A,P]=i.useState(!1),[F,z]=i.useState(!1),[G,oe]=i.useState(null),[O,q]=i.useState(new Set),[Y,Z]=i.useState(null),B=i.useRef(new Map),W=i.useRef(0),te=vt($=>$.homeDirectory),ye=vt($=>$.currentDirectory),me=vt($=>$.setDirectory),K=Lt($=>$.projects),L=Lt($=>$.activeProjectId),Q=Lt($=>$.addProject),ce=Lt($=>$.removeProject),he=Lt($=>$.setActiveProject),Ne=Lt($=>$.setActiveProjectIdOnly),H=Lt($=>$.reorderProjects),we=Me($=>$.setActiveMainTab),ee=Me($=>$.setSessionSwitcherOpen),ue=Me($=>$.openMultiRunLauncher),ge=Je($=>$.settingsAutoCreateWorktree),X=ve($=>$.sessions),de=ve($=>$.sessionsByDirectory),ae=ve($=>$.currentSessionId),fe=ve($=>$.setCurrentSession),ie=ve($=>$.updateSessionTitle),se=ve($=>$.shareSession),re=ve($=>$.unshareSession),ne=ve($=>$.sessionMemoryState),xe=ve($=>$.sessionActivityPhase),Ue=ve($=>$.permissions),ze=ve($=>$.worktreeMetadata),Ke=ve($=>$.availableWorktreesByProject),rt=ve($=>$.getSessionsByDirectory),jt=ve($=>$.openNewSessionDraft),[Xe,Ct]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),st=i.useMemo(()=>zt(),[]);i.useEffect(()=>{try{const $=y.getItem(ou);if($){const J=JSON.parse($);Array.isArray(J)&&h(new Set(J.filter(pe=>typeof pe=="string")))}const U=y.getItem(nu);if(U){const J=JSON.parse(U);Array.isArray(J)&&S(new Set(J.filter(pe=>typeof pe=="string")))}}catch{}},[y]),i.useEffect(()=>{typeof window>"u"||Ct(typeof window.opencodeDesktop<"u")},[]);const mt=i.useMemo(()=>[...X].sort(($,U)=>(U.time?.updated||0)-($.time?.updated||0)),[X]);i.useEffect(()=>{let $=!1;const U=K.map(J=>({id:J.id,path:br(J.path)})).filter(J=>!!J.path);return N(new Map),U.length===0?()=>{$=!0}:(U.forEach(J=>{Hr(J.path).then(pe=>{$||N(Ee=>{const He=new Map(Ee);return He.set(J.id,pe),He})}).catch(()=>{$||N(pe=>{const Ee=new Map(pe);return Ee.set(J.id,null),Ee})})}),()=>{$=!0})},[K]);const Pt=i.useMemo(()=>{const $=new Map;return mt.forEach(U=>{const J=U.parentID;J&&$.set(U.id,J)}),$},[mt]),Ot=i.useMemo(()=>{const $=new Map;return mt.forEach(U=>{const J=U.parentID;if(!J)return;const pe=$.get(J)??[];pe.push(U),$.set(J,pe)}),$.forEach(U=>U.sort((J,pe)=>(pe.time?.updated||0)-(J.time?.updated||0))),$},[mt]);i.useEffect(()=>{ae&&h($=>{const U=new Set($);let J=Pt.get(ae)||null,pe=!1;for(;J;)U.has(J)||(U.add(J),pe=!0),J=Pt.get(J)||null;return pe?U:$})},[ae,Pt]),i.useEffect(()=>{const $=new Set;mt.forEach(U=>{const J=br(U.directory??null);J&&$.add(J)}),K.forEach(U=>{const J=br(U.path);J&&$.add(J)}),$.forEach(U=>{const J=g.get(U);J&&J!=="unknown"||b.current.has(U)||(b.current.add(U),Oe.listLocalDirectory(U).then(()=>{x(pe=>{const Ee=new Map(pe);return Ee.get(U)==="exists"?pe:(Ee.set(U,"exists"),Ee)})}).catch(async()=>{if((U.includes("/opencode/worktree/")||U.includes("/.opencode/data/worktree/")||U.includes("/.local/share/opencode/worktree/"))&&await Oe.probeDirectory(U).catch(()=>!1)){x(He=>{const ft=new Map(He);return ft.get(U)==="exists"?He:(ft.set(U,"exists"),ft)});return}x(Ee=>{const He=new Map(Ee);return He.get(U)==="missing"?Ee:(He.set(U,"missing"),He)})}).finally(()=>{b.current.delete(U)}))})},[mt,K,g]),i.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const $e=e.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-ui-label font-semibold",children:"No sessions yet"}),e.jsx("p",{className:"typography-meta mt-1",children:"Create your first session to start coding."})]}),be=i.useCallback(($,U,J,pe)=>{if(!J){if(pe&&pe!==L&&Ne(pe),U&&U!==ye&&me(U,{showOverlay:!1}),t&&(we("chat"),ee(!1)),!s&&$===ae){r?.($);return}fe($),r?.($)}},[L,s,ye,ae,t,r,we,Ne,fe,me,ee]),tt=i.useCallback(async()=>{a&&l.trim()&&(await ie(a,l.trim()),c(null),d(""))},[a,l,ie]),Ce=i.useCallback(()=>{c(null),d("")},[]),Ie=i.useCallback(async $=>{const U=await se($.id);U&&U.share?.url?V.success("Session shared",{description:"You can copy the link from the menu."}):V.error("Unable to share session")},[se]),Qe=i.useCallback(($,U)=>{navigator.clipboard.writeText($).then(()=>{m(U),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{V.error("Failed to copy URL")})},[]),Te=i.useCallback(async $=>{await re($)?V.success("Session unshared"):V.error("Unable to unshare session")},[re]),Pe=i.useCallback($=>{const U=[],J=pe=>{(Ot.get(pe)??[]).forEach(He=>{U.push(He),J(He.id)})};return J($),U},[Ot]),Fe=ve($=>$.deleteSession),Ve=ve($=>$.deleteSessions),et=i.useCallback(async $=>{const U=Pe($.id),J=ze.get($.id);if(J){const pe=J.path,Ee=[],He=new Set;X.forEach(ft=>{const pt=ze.get(ft.id);pt&&pt.path===pe&&!He.has(ft.id)&&(Ee.push(ft),He.add(ft.id),Pe(ft.id).forEach(at=>{He.has(at.id)||(Ee.push(at),He.add(at.id))}))}),io.requestDelete({sessions:Ee,mode:"worktree",worktree:J});return}if(U.length===0)await Fe($.id)?V.success("Session deleted",{action:{label:"OK",onClick:()=>{}}}):V.error("Failed to delete session");else{const pe=[$.id,...U.map(ft=>ft.id)],{deletedIds:Ee,failedIds:He}=await Ve(pe);Ee.length>0&&V.success(`Deleted ${Ee.length} session${Ee.length===1?"":"s"}`,{action:{label:"OK",onClick:()=>{}}}),He.length>0&&V.error(`Failed to delete ${He.length} session${He.length===1?"":"s"}`)}},[Pe,Fe,Ve,ze,X]),ot=i.useCallback(()=>{Xe&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then($=>{$.success&&$.path?Q($.path,{id:$.projectId})||V.error("Failed to add project",{description:"Please select a valid directory."}):$.error&&$.error!=="Directory selection cancelled"&&V.error("Failed to select directory",{description:$.error})}).catch($=>{console.error("Desktop: Error selecting directory:",$),V.error("Failed to select directory")}):io.requestDirectoryDialog()},[Q,Xe]),yt=i.useCallback($=>{h(U=>{const J=new Set(U);J.has($)?J.delete($):J.add($);try{y.setItem(ou,JSON.stringify(Array.from(J)))}catch{}return J})},[y]),Dt=i.useCallback($=>{const U=Ot.get($.id)??[];return{session:$,children:U.map(J=>Dt(J)),worktree:ze.get($.id)??null}},[Ot,ze]),bt=i.useCallback(($,U,J)=>{const pe=br(U??null),Ee=[...$].sort((ht,Et)=>(Et.time?.updated||0)-(ht.time?.updated||0)),He=new Map(Ee.map(ht=>[ht.id,ht])),ft=new Map;Ee.forEach(ht=>{const Et=ht.parentID;if(!Et)return;const Jt=ft.get(Et)??[];Jt.push(ht),ft.set(Et,Jt)}),ft.forEach(ht=>ht.sort((Et,Jt)=>(Jt.time?.updated||0)-(Et.time?.updated||0)));const pt=new Map;J.forEach(ht=>{if(ht.path){const Et=br(ht.path)??ht.path;pt.set(Et,ht)}});const wt=ht=>{const Et=br(ht.directory??null),Jt=ze.get(ht.id)??null;if(Jt)return Jt;if(Et){const Js=pt.get(Et)??null;if(Js&&Et!==pe)return Js}return null},at=ht=>{const Et=ft.get(ht.id)??[];return{session:ht,children:Et.map(Jt=>at(Jt)),worktree:wt(ht)}},qt=Ee.filter(ht=>{const Et=ht.parentID;return Et?!He.has(Et):!0}).map(ht=>at(ht));return[{id:"all",label:"All sessions",description:pe?Yr(pe,te):null,isMain:!0,worktree:null,directory:pe,sessions:qt}]},[te,ze]),Qt=i.useCallback($=>{D(U=>{const J=new Set(U);return J.has($)?J.delete($):J.add($),J})},[]),Vt=i.useCallback($=>{W.current=Date.now()+150,S(U=>{const J=new Set(U);J.has($)?J.delete($):J.add($);try{y.setItem(nu,JSON.stringify(Array.from(J)))}catch{}return J})},[y]),Ft=i.useMemo(()=>K.map($=>({...$,normalizedPath:br($.path)})).filter($=>!!$.normalizedPath),[K]),Kt=i.useCallback($=>{const U=st?[]:Ke.get($.normalizedPath)??[],J=[$.normalizedPath,...U.map(He=>br(He.path)??He.path).filter(He=>!!He)],pe=new Set,Ee=[];return J.forEach(He=>{(de.get(He)??rt(He)).forEach(pt=>{pe.has(pt.id)||(pe.add(pt.id),Ee.push(pt))})}),Ee},[Ke,rt,de,st]),Rt=i.useMemo(()=>Ft.map($=>{const U=Kt($),J=Ke.get($.normalizedPath)??[],pe=bt(U,$.normalizedPath,J);return{project:$,groups:pe}}),[Ft,Kt,bt,Ke]);i.useEffect(()=>{if(!Xe)return;const $=new IntersectionObserver(U=>{U.forEach(J=>{const pe=J.target.dataset.projectId;pe&&q(Ee=>{const He=new Set(Ee);return J.isIntersecting?He.delete(pe):He.add(pe),He})})},{threshold:0});return B.current.forEach(U=>{U&&$.observe(U)}),()=>$.disconnect()},[Xe,Rt]);const cs=i.useCallback(($,U=0,J,pe)=>{const Ee=$.session,He=br(Ee.directory??null)??br(J??null),pt=(He?g.get(He):null)==="missing",wt=ne.get(Ee.id),at=ae===Ee.id,_t=Ee.title||"Untitled Session",qt=$.children.length>0,ht=p.has(Ee.id),Et=Ee.summary?.additions,Jt=Ee.summary?.deletions,Js=typeof Et=="number"||typeof Jt=="number";if(a===Ee.id)return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",U>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[e.jsxs("form",{className:"flex w-full items-center gap-2","data-keyboard-avoid":"true",onSubmit:nt=>{nt.preventDefault(),tt()},children:[e.jsx("input",{value:l,onChange:nt=>d(nt.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename session",onKeyDown:nt=>{nt.key==="Escape"&&Ce()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Tt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:Ce,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(es,{className:"size-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[qt?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:ht?e.jsx(Wt,{className:"h-3 w-3"}):e.jsx(tr,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:au(Ee.time?.created||Date.now())}),Ee.share?e.jsx(Ri,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Js&&((Et??0)!==0||(Jt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,Et??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Jt??0)]})]}):null,qt?e.jsxs("span",{className:"truncate",children:[$.children.length," ",$.children.length===1?"task":"tasks"]}):null]})]})},Ee.id);const De=xe?.get(Ee.id)??"idle",Be=De==="busy"||De==="cooldown",Le=Ue.get(Ee.id)?.length??0,Ze=wt&&wt.isZombie?e.jsx(Mc,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(i.Fragment,{children:[e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1",at?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",pt?"opacity-75":"",U>0&&"pl-[20px]"),onContextMenu:nt=>{nt.preventDefault(),Z(Ee.id)},children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:pt,onClick:()=>be(Ee.id,He,pt,pe),className:R("flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[Be?e.jsx(xp,{size:"xs",className:"text-primary flex-shrink-0"}):null,e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:_t}),Le>0?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:"Permission required","aria-label":"Permission required",children:[e.jsx(yg,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:Le})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[qt?e.jsx("span",{role:"button",tabIndex:0,onClick:nt=>{nt.stopPropagation(),yt(Ee.id)},onKeyDown:nt=>{(nt.key==="Enter"||nt.key===" ")&&(nt.preventDefault(),nt.stopPropagation(),yt(Ee.id))},className:"inline-flex items-center justify-center text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 flex-shrink-0 rounded-sm","aria-label":ht?"Collapse subsessions":"Expand subsessions",children:ht?e.jsx(Wt,{className:"h-3 w-3"}):e.jsx(tr,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:au(Ee.time?.created||Date.now())}),Ee.share?e.jsx(Ri,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,$.worktree?e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(Ut,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(lt,{side:"top",className:"text-xs",children:$.worktree.branch||$.worktree.label||"Worktree"})]}):null,Js&&((Et??0)!==0||(Jt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,Et??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Jt??0)]})]}):null,qt?e.jsxs("span",{className:"truncate",children:[$.children.length," ",$.children.length===1?"task":"tasks"]}):null,pt?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(Mc,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Ze,e.jsxs(ts,{open:Y===Ee.id,onOpenChange:nt=>Z(nt?Ee.id:null),children:[e.jsx(ss,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:nt=>nt.stopPropagation(),onKeyDown:nt=>nt.stopPropagation(),children:e.jsx(nn,{className:t?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"min-w-[180px]",children:[e.jsxs(kt,{onClick:()=>{c(Ee.id),d(_t)},className:"[&>svg]:mr-1",children:[e.jsx(Fr,{className:"mr-1 h-4 w-4"}),"Rename"]}),Ee.share?e.jsxs(e.Fragment,{children:[e.jsx(kt,{onClick:()=>{Ee.share?.url&&Qe(Ee.share.url,Ee.id)},className:"[&>svg]:mr-1",children:u===Ee.id?e.jsxs(e.Fragment,{children:[e.jsx(Tt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(nr,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(kt,{onClick:()=>Te(Ee.id),className:"[&>svg]:mr-1",children:[e.jsx(bg,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(kt,{onClick:()=>Ie(Ee),className:"[&>svg]:mr-1",children:[e.jsx(Ri,{className:"mr-1 h-4 w-4"}),"Share"]}),$.worktree?e.jsxs(kt,{onClick:()=>{pe&&pe!==L&&he(pe),we("chat"),t&&ee(!1),jt({directoryOverride:$.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(Ut,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(kt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>et(Ee),children:[e.jsx(zs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),qt&&ht?$.children.map(nt=>cs(nt,U+1,He??J,pe)):null]},Ee.id)},[g,ne,xe,Ue,ae,p,a,l,tt,Ce,yt,be,Ie,Qe,Te,et,u,t,L,he,we,ee,jt,Y]),Ns=i.useCallback(($,U,J)=>{const pe=j.has(U),Ee=n?10:5,He=$.sessions.length,ft=pe?$.sessions:$.sessions.slice(0,Ee),pt=He-ft.length;return e.jsxs(e.Fragment,{children:[ft.map(wt=>cs(wt,0,$.directory,J)),He===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,pt>0&&!pe?e.jsxs("button",{type:"button",onClick:()=>Qt(U),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:["Show ",pt," more ",pt===1?"session":"sessions"]}):null,pe&&He>Ee?e.jsx("button",{type:"button",onClick:()=>Qt(U),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})},[j,n,cs,Qt]),bs=wg(Jl(Dg,{activationConstraint:{distance:8}}),Jl(Mg,{coordinateGetter:Cg})),Cs=i.useCallback($=>{oe($.active.id)},[]),Ms=i.useCallback($=>{const{active:U,over:J}=$;if(oe(null),!J||U.id===J.id)return;const pe=Ft.findIndex(He=>He.id===U.id),Ee=Ft.findIndex(He=>He.id===J.id);pe!==-1&&Ee!==-1&&H(pe,Ee)},[Ft,H]),ps=i.useCallback(()=>{oe(null)},[]),Xt=i.useMemo(()=>{if(!G)return null;const $=Rt.find(J=>J.project.id===G);if(!$)return null;const U=$.project;return{id:U.id,label:iu(U.label?.trim()||sd(U.normalizedPath,te)||U.normalizedPath),isActive:U.id===L}},[G,Rt,te,L]);return e.jsxs("div",{className:R("flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-8 select-none pl-3.5 pr-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("p",{className:"typography-ui-label font-medium text-muted-foreground",children:"Projects"}),e.jsx("span",{className:"typography-micro text-muted-foreground/50",children:K.length})]}),e.jsx("button",{type:"button",onClick:ot,className:R("inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!Xe&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(Dc,{className:"h-4.5 w-4.5"})})]})}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:R("space-y-1 pb-1 pl-2.5 pr-1",""),children:Rt.length===0?$e:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const $=Rt.find(pe=>pe.project.id===L)??Rt[0];if(!$)return $e;const U=$.groups.find(pe=>pe.isMain&&pe.sessions.length>0)??$.groups.find(pe=>pe.sessions.length>0)??$.groups.find(pe=>pe.isMain)??$.groups[0];if(!U)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const J=`${$.project.id}:${U.id}`;return Ns(U,J,$.project.id)})()}):e.jsxs(vg,{sensors:bs,collisionDetection:jg,onDragStart:Cs,onDragEnd:Ms,onDragCancel:ps,children:[e.jsx(Sg,{items:Ft.map($=>$.id),strategy:Ng,children:Rt.map($=>{const U=$.project,J=U.id,pe=iu(U.label?.trim()||sd(U.normalizedPath,te)||U.normalizedPath),Ee=Yr(U.normalizedPath,te),He=v.has(J),ft=J===L,pt=C.get(J),wt=k===J;return e.jsx(vj,{id:J,projectLabel:pe,projectDescription:Ee,isCollapsed:He,isActiveProject:ft,isRepo:!!pt,isHovered:wt,isDesktopRuntime:Xe,isStuck:O.has(J),hideDirectoryControls:n,mobileVariant:t,onToggle:()=>Vt(J),onHoverChange:at=>M(at?J:null),onNewSession:()=>{J!==L&&he(J),we("chat"),t&&ee(!1),jt({directoryOverride:U.normalizedPath})},onNewWorktreeSession:()=>{J!==L&&he(J),we("chat"),t&&ee(!1),Ii()},onOpenBranchPicker:()=>{I(J),T(!0)},onNewSessionFromGitHubIssue:()=>{J!==L&&he(J),we("chat"),t&&ee(!1),P(!0)},onNewSessionFromGitHubPR:()=>{J!==L&&he(J),we("chat"),t&&ee(!1),z(!0)},onOpenMultiRunLauncher:()=>{J!==L&&he(J),ue()},onClose:()=>ce(J),sentinelRef:at=>{B.current.set(J,at)},settingsAutoCreateWorktree:ge,children:He?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:$.groups[0]?Ns($.groups[0],`${J}:all`,J):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},J)})}),e.jsx(kg,{children:Xt?e.jsx(jj,{projectLabel:Xt.label,isActiveProject:Xt.isActive}):null})]})}),e.jsx(uj,{open:w,onOpenChange:T,project:E?Ft.find($=>$.id===E)??null:null}),e.jsx(pj,{open:A,onOpenChange:P}),e.jsx(wj,{open:F,onOpenChange:z})]})},Pi=()=>{const[t,r]=Ae.useState(!1);Ae.useEffect(()=>{r(ds())},[]);const s=Ae.useCallback(async a=>t?await vy(a):{success:!0,path:a},[t]),n=Ae.useCallback(async a=>t?await jy(a):{success:!0},[t]),o=Ae.useCallback(async a=>t?await Sy(a):{success:!0},[t]);return{isDesktop:t,requestAccess:s,startAccessing:n,stopAccessing:o}},cu=({currentPath:t,onSelectPath:r,triggerClassName:s,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:c,showHidden:l=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=i.useMemo(()=>ds(),[]),{isMobile:p}=Gt(),[h,g]=i.useState([]),[x,b]=i.useState(new Set),[y,v]=i.useState(!0),[S,C]=i.useState(!1),[N,j]=i.useState(""),[D,k]=i.useState(new Set),[M,w]=i.useState(null),[T,E]=i.useState(""),[I,A]=i.useState(!0),P=i.useRef(null),{requestAccess:F,startAccessing:z,isDesktop:G}=Pi(),oe=i.useRef(l),O=i.useCallback(X=>{if(!X)return X;if(X==="/"||X.length===0)return"/";let de=X;for(;de.length>1&&de.endsWith("/");)de=de.slice(0,-1);return de.length===0?"/":de},[]),q=i.useMemo(()=>{if(!N)return null;const X=N.replace(/\\/g,"/");return O(X)},[N,O]),Y=i.useMemo(()=>{if(typeof d=="string"&&d.length>0){const X=d.replace(/\\/g,"/"),de=O(X);if(de&&de!=="/")return de}return q&&q!=="/"?q:null},[d,q,O]),Z=i.useMemo(()=>typeof u=="boolean"?!!(u&&Y):!!Y,[u,Y]);i.useEffect(()=>{Z||(v(!0),g([]))},[Z]);const B=i.useCallback(X=>{if(!X||!Z||!Y)return!1;const de=X.replace(/\\/g,"/"),ae=O(de)??de;if(ae===Y)return!0;const fe=`${Y}/`;return ae.startsWith(fe)},[Z,Y,O]),W=async X=>{if(Z){if(a==="deferred"){r(X);return}if(G){const de=await F(X);de.success&&de.path?(await z(de.path),r(de.path)):(console.error("Failed to get directory access:",de.error),r(X))}else r(X)}};i.useEffect(()=>{let X=!1;const de=ie=>{if(!ie)return!1;const se=O(ie.replace(/\\/g,"/"));return!se||se==="/"?!1:(j(typeof se=="string"?se:ie.replace(/\\/g,"/")),!0)};return d&&de(d)||(async()=>{try{const ie=await Oe.getFilesystemHome();if(!X&&de(ie))return}catch(ie){console.warn("Failed to resolve filesystem home directory:",ie)}try{const ie=await Oe.getSystemInfo();if(!X&&de(ie?.homeDirectory))return}catch(ie){console.warn("Failed to resolve home directory from system info:",ie)}})(),()=>{X=!0}},[d,O]),i.useEffect(()=>{let X=!1;const de=se=>{if(X)return;const re=se.filter(ne=>typeof ne=="string"&&ne.length>0).map(ne=>{const xe=ne.replace(/\\/g,"/");return O(xe)??xe});k(new Set(re))},ae=()=>{try{const se=localStorage.getItem("pinnedDirectories");if(!se)return;const re=JSON.parse(se);Array.isArray(re)&&de(re)}catch(se){console.warn("Failed to load pinned directories from local storage:",se)}},fe=async()=>{try{let se=[];if(f){const re=await zr();se=Array.isArray(re?.pinnedDirectories)?re.pinnedDirectories:[]}else{const re=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(re.ok){const ne=await re.json();se=Array.isArray(ne?.pinnedDirectories)?ne.pinnedDirectories:[]}}if(X)return;de(se)}catch(se){console.warn("Failed to load pinned directories:",se)}};ae();const ie=se=>{const re=se.detail;re&&Array.isArray(re.pinnedDirectories)&&de(re.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",ie),fe(),()=>{X=!0,window.removeEventListener("openchamber:settings-synced",ie)}},[f,O]);const te=i.useRef(!0);i.useEffect(()=>{if(te.current){te.current=!1;return}const X={pinnedDirectories:Array.from(D)};as(X)},[D]),i.useEffect(()=>{Y&&k(X=>{const de=Array.from(X).map(ae=>O(ae.replace(/\\/g,"/"))??ae).filter(ae=>B(ae));return new Set(de)})},[Y,B,O]),i.useEffect(()=>{oe.current!==l&&(oe.current=l)},[l]);const ye=X=>{k(de=>{if(!B(X))return de;const ae=O(X.replace(/\\/g,"/"))??X.replace(/\\/g,"/"),fe=new Set(de);return fe.has(ae)?fe.delete(ae):fe.add(ae),fe})},me=i.useMemo(()=>Array.from(D).map(X=>O(X.replace(/\\/g,"/"))??X).filter(X=>B(X)).map(X=>({path:X,name:X.split("/").pop()||X})).sort((X,de)=>X.name.localeCompare(de.name)),[D,B,O]),K=i.useCallback(async X=>{const de=re=>l||!re.startsWith("."),ae=Y;if(!Z||!ae)return[];const fe=X&&X.length>0?X:ae,ie=fe?fe.replace(/\\/g,"/"):null,se=ie?O(ie)??ie:null;if(se){const re=`${ae}/`;if(!(se===ae||se.startsWith(re)))return[]}try{return(await Oe.listLocalDirectory(X)).filter(ne=>{if(!ne.isDirectory||!de(ne.name))return!1;const xe=ne.path.replace(/\\/g,"/"),Ue=O(xe)??xe,ze=Ue===ae?ae:`${ae}/`;return Ue===ae||Ue.startsWith(ze)}).map(ne=>({name:ne.name,path:ne.path.replace(/\\/g,"/"),isDirectory:!0})).sort((ne,xe)=>ne.name.localeCompare(xe.name))}catch{try{const ne=await Oe.getApiClient().file.list({path:".",directory:X});return ne.data?ne.data.filter(xe=>{if(xe.type!=="directory"||!xe.name||!de(xe.name))return!1;const Ue=String(xe.absolute||xe.path||xe.name).replace(/\\/g,"/"),ze=O(Ue)??Ue,Ke=ze===ae?ae:`${ae}/`;return ze===ae||ze.startsWith(Ke)}).map(xe=>({name:xe.name||"",path:String(xe.absolute||xe.path||xe.name).replace(/\\/g,"/"),isDirectory:!0})).filter(xe=>xe.name!=="").sort((xe,Ue)=>xe.name.localeCompare(Ue.name)):[]}catch{return[]}}},[l,Y,O,Z]),L=i.useRef(!1),Q=i.useCallback(async()=>{if(!Z||!Y){v(!0),g([]);return}L.current||v(!0);try{const X=await K(Y);g(X),L.current=!0}catch{}finally{v(!1)}},[Z,Y,K]);i.useEffect(()=>{Z&&(n==="inline"||S)&&Q()},[n,S,Z,Q]);const ce=async X=>{if(!Z)return;const de=x.has(X.path),ae=new Set(x);if(de){ae.delete(X.path),b(ae);return}ae.add(X.path),b(ae);const fe=await K(X.path),ie=se=>se.map(re=>re.path===X.path?{...re,children:fe}:re.children?{...re,children:ie(re.children)}:re);g(se=>ie(se))};i.useEffect(()=>{M&&P.current&&(P.current.focus(),P.current.select())},[M]);const he=(X,de=[])=>{const ae="new_directory",fe=de.map(ne=>ne.name);if(!fe.includes(ae))return ae;let ie=1;const se=new RegExp(`^${ae}(\\d+)$`);for(const ne of fe){const xe=ne.match(se);if(xe){const Ue=parseInt(xe[1],10);Ue>ie&&(ie=Ue)}}let re=2;for(;fe.includes(`${ae}${re}`);)re++;return`${ae}${Math.max(re,ie+1)}`},Ne=async X=>{if(Z){if(x.has(X.path)){const de=he(X.path,X.children);E(de)}else{const de=new Set(x);if(de.add(X.path),b(de),X.children){const ae=he(X.path,X.children);E(ae)}else{const ae=await K(X.path),fe=se=>se.map(re=>re.path===X.path?{...re,children:ae}:re.children?{...re,children:fe(re.children)}:re);g(se=>fe(se));const ie=he(X.path,ae);E(ie)}}w(X.path)}},H=async()=>{if(!M||!Z)return;const X=T.trim()||"new_directory",de=`${M}/${X}`;try{await Oe.createDirectory(de);const ae=await K(M),fe=ie=>ie.map(se=>se.path===M?{...se,children:ae}:se.children?{...se,children:fe(se.children)}:se);g(ie=>fe(ie)),w(null),E("")}catch(ae){console.error("Failed to create directory:",ae)}},we=()=>{w(null),E("")},ee=(X,de=0)=>{const ae=x.has(X.path),fe=X.isDirectory,ie=D.has(X.path),se=t===X.path,re=n==="inline",ne=e.jsxs(e.Fragment,{children:[fe&&e.jsx("button",{onClick:xe=>{xe.stopPropagation(),ce(X)},className:R("hover:bg-accent rounded","p-0.5"),children:ae?e.jsx(Wt,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(tr,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!fe&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:xe=>{xe.stopPropagation(),W(X.path),n==="dropdown"&&a==="immediate"&&C(!1)},onDoubleClick:xe=>{xe.stopPropagation(),c&&c(X.path)},className:R("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",re&&se?"text-primary":"text-foreground"),children:[e.jsx(lr,{className:R("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",re&&se&&"text-primary")}),e.jsx("span",{className:R("font-medium truncate","typography-ui-label",re&&se?"text-primary":"text-foreground"),children:X.name})]}),e.jsx("button",{onClick:xe=>{xe.stopPropagation(),Ne(X)},className:R("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(ls,{className:R("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:xe=>{xe.stopPropagation(),ye(X.path)},className:R("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:ie?"Unpin directory":"Pin directory",children:ie?e.jsx(Li,{className:R("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(Eg,{className:R("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:R("group flex items-center gap-1 rounded-lg mx-1 text-left transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",se?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${de*(p?12:14)+(p?4:6)}px`},children:ne}),ae&&e.jsxs(e.Fragment,{children:[M===X.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(de+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(lr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{ref:P,value:T,onChange:xe=>E(xe.target.value),onKeyDown:xe=>{xe.key==="Enter"?(xe.preventDefault(),xe.stopPropagation(),H()):xe.key==="Escape"&&(xe.preventDefault(),xe.stopPropagation(),we())},onBlur:H,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),H()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Tt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),we()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(es,{className:"h-3 w-3 text-muted-foreground"})})]}),X.children&&X.children.map(xe=>ee(xe,de+1))]})]},X.path):e.jsxs("div",{children:[e.jsxs(kt,{className:R("flex items-center gap-1 cursor-pointer group",t===X.path&&"bg-accent"),style:{paddingLeft:`${de*12+8}px`},onSelect:xe=>{xe.preventDefault()},children:[fe&&e.jsx("button",{onClick:xe=>{xe.stopPropagation(),ce(X)},className:"p-0.5 hover:bg-accent rounded",children:ae?e.jsx(Wt,{className:"h-3 w-3"}):e.jsx(tr,{className:"h-3 w-3"})}),!fe&&e.jsx("div",{className:"w-4"}),ne]}),ae&&e.jsxs("div",{children:[M===X.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(de+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(lr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{ref:P,value:T,onChange:xe=>E(xe.target.value),onKeyDown:xe=>{xe.key==="Enter"?(xe.preventDefault(),xe.stopPropagation(),H()):xe.key==="Escape"&&(xe.preventDefault(),xe.stopPropagation(),we())},onBlur:H,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),H()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Tt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),we()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(es,{className:"h-3 w-3 text-muted-foreground"})})]}),X.children&&X.children.map(xe=>ee(xe,de+1))]})]},X.path)},ue=(X,de)=>{if(n==="inline"){const ae=t===de;return e.jsxs("div",{className:R("group flex items-center gap-2 mx-1 rounded-lg transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",ae?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>W(de),onDoubleClick:fe=>{fe.stopPropagation(),c&&c(de)},className:R("flex flex-1 items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded min-w-0",ae?"text-primary":"text-foreground"),children:[e.jsx(lr,{className:R("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",ae?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:R("typography-ui-label font-medium truncate flex-shrink-0",ae?"text-primary":"text-foreground"),children:X}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:Yr(de,N)})]}),e.jsx("button",{onClick:()=>ye(de),className:R("hover:bg-accent rounded-md transition-opacity",p?"p-1.5 opacity-60":"p-1 opacity-0 group-hover:opacity-100"),title:"Unpin directory",children:e.jsx(Li,{className:R("text-primary","h-3.5 w-3.5")})})]},de)}return e.jsxs(kt,{onSelect:ae=>{ae.preventDefault(),W(de),a==="immediate"&&C(!1)},className:R("flex items-start gap-2 cursor-pointer group py-2",t===de&&"bg-accent"),children:[e.jsx(lr,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium",children:X}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Yr(de,N)})]}),e.jsx("button",{onClick:ae=>{ae.stopPropagation(),ae.preventDefault(),ye(de)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Li,{className:"h-3 w-3 text-primary"})})]},de)},ge=e.jsx(e.Fragment,{children:Z?e.jsxs(e.Fragment,{children:[me.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>A(X=>!X),className:R("flex w-full items-center gap-1.5 typography-meta font-medium text-muted-foreground/80 hover:bg-accent/30 rounded transition-colors uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:[I?e.jsx(Wt,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(tr,{className:p?"h-3.5 w-3.5":"h-3 w-3"}),e.jsx("span",{children:"Pinned"}),e.jsx("span",{className:"ml-auto typography-micro text-muted-foreground/60 normal-case tracking-normal",children:me.length})]}),I&&me.map(({name:X,path:de})=>ue(X,de)),n==="dropdown"&&e.jsx(Ds,{}),n==="inline"&&I&&e.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),e.jsx("div",{className:R("typography-meta font-medium text-muted-foreground/80 flex items-center gap-1.5 uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:"Browse"}),y?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):h.map(X=>ee(X)),!y&&h.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No directories found"})]}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Locating home directory..."})});return n==="inline"?e.jsx("div",{className:R("overflow-hidden flex flex-col",o),children:e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:ge})}):e.jsxs(ts,{open:S,onOpenChange:C,children:[e.jsx(ss,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",className:R("w-full h-8 px-2.5 justify-between items-center rounded-lg border border-transparent bg-sidebar-accent/40 text-foreground/90 hover:bg-sidebar-accent/60 typography-meta",s),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(lr,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:t,children:Yr(t,N)})]}),e.jsx(Wt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(rs,{align:"start",className:"w-[350px]",children:e.jsx(xt,{outerClassName:"h-full",className:"w-full",children:ge})})]})},Ti=(t,r=200)=>{const[s,n]=Ae.useState(t);return Ae.useEffect(()=>{const o=window.setTimeout(()=>{n(t)},r);return()=>{window.clearTimeout(o)}},[t,r]),s},bp=i.forwardRef(({inputValue:t,homeDirectory:r,onSelectSuggestion:s,visible:n,onClose:o,showHidden:a},c)=>{const[l,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(0),h=i.useRef(null),g=i.useRef([]),x=i.useCallback((N,j)=>{const D=N.trim().toLowerCase();if(!D)return 0;const k=j.toLowerCase();let M=0,w=-1,T=0;for(let E=0;E<D.length;E+=1){const I=D[E];if(!I||I===" ")continue;const A=k.indexOf(I,w+1);if(A===-1)return null;const P=A-w-1;if(P===0?T+=1:T=0,M+=10,M+=Math.max(0,18-A),M-=Math.max(0,P),A===0)M+=12;else{const F=k[A-1];(F==="/"||F==="_"||F==="-"||F==="."||F===" ")&&(M+=10)}M+=T>0?12:0,w=A}return M+=Math.max(0,24-Math.round(k.length/3)),M},[]),b=i.useCallback(N=>N.startsWith("~")&&r?N.replace(/^~/,r):N,[r]),y=i.useCallback(N=>{const j=b(N);if(j.endsWith("/"))return j;const D=j.lastIndexOf("/");return D===-1?"":D===0?"/":j.substring(0,D+1)},[b]),v=i.useCallback(N=>{const j=b(N);if(j.endsWith("/"))return"";const D=j.lastIndexOf("/");return D===-1?j:j.substring(D+1)},[b]),S=Ti(t,150);i.useEffect(()=>{if(!n||!S){d([]);return}const N=y(S),j=v(S).toLowerCase();if(!N){d([]);return}let D=!1;return m(!0),Oe.listLocalDirectory(N).then(k=>{if(D)return;const M=k.filter(T=>!(!T.isDirectory||!a&&T.name.startsWith("."))),w=j?M.map(T=>{const E=x(j,T.name);return E!==null?{entry:T,score:E}:null}).filter(T=>T!==null).sort((T,E)=>E.score-T.score||T.entry.name.localeCompare(E.entry.name)).map(T=>T.entry):M.sort((T,E)=>T.name.localeCompare(E.name));d(w.slice(0,10)),p(0)}).catch(()=>{D||d([])}).finally(()=>{D||m(!1)}),()=>{D=!0}},[n,S,y,v,a,x]),i.useEffect(()=>{g.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),i.useEffect(()=>{if(!n)return;const N=j=>{const D=j.target;!D||!h.current||h.current.contains(D)||o()};return document.addEventListener("pointerdown",N,!0),()=>{document.removeEventListener("pointerdown",N,!0)}},[n,o]);const C=i.useCallback(N=>{const j=N.path.endsWith("/")?N.path:N.path+"/";s(j)},[s]);return i.useImperativeHandle(c,()=>({handleKeyDown:N=>{if(!n||l.length===0)return!1;const j=l.length;if(N.key==="Tab"){if(N.preventDefault(),N.shiftKey)p(D=>(D-1+j)%j);else if(j===1){const D=l[0];D&&C(D)}else p(D=>(D+1)%j);return!0}if(N.key==="ArrowDown")return N.preventDefault(),p(D=>(D+1)%j),!0;if(N.key==="ArrowUp")return N.preventDefault(),p(D=>(D-1+j)%j),!0;if(N.key==="Enter"){N.preventDefault();const D=(f%j+j)%j,k=l[D];return k&&C(k),o(),!0}return N.key==="Escape"?(N.preventDefault(),o(),!0):!1}}),[n,l,f,C,o]),!n||l.length===0&&!u?null:e.jsxs("div",{ref:h,className:"absolute z-[100] w-full max-h-48 bg-background border border-border rounded-lg shadow-lg top-full mt-1 left-0 flex flex-col overflow-hidden",children:[u?e.jsx("div",{className:"flex items-center justify-center py-3",children:e.jsx(en,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:l.map((N,j)=>{const D=f===j;return e.jsxs("div",{ref:k=>{g.current[j]=k},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",D&&"bg-muted"),onClick:()=>{C(N),o()},onMouseEnter:()=>p(j),children:[e.jsx(Dr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:N.name})]},N.path)})}),e.jsx("div",{className:"px-3 py-1.5 border-t typography-meta text-muted-foreground bg-sidebar/50",children:"Tab cycle • ↑↓ navigate • Enter select"})]})});bp.displayName="DirectoryAutocomplete";const Sj=({open:t,onOpenChange:r})=>{const{currentDirectory:s,homeDirectory:n,isHomeReady:o}=vt(),{addProject:a,getActiveProject:c}=Lt(),[l,d]=i.useState(null),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,g]=i.useState(!1),x=Go(),{isDesktop:b,requestAccess:y,startAccessing:v}=Pi(),{isMobile:S}=Gt(),[C,N]=i.useState(!1),j=i.useRef(null),D=i.useCallback(W=>W?Yr(W,n):"",[n]);i.useEffect(()=>{if(t){p(!1),g(!1),N(!1);const te=c()?.path||s||n||"";d(te),m(D(te))}},[t,s,n,D,c]),i.useEffect(()=>{!t||f||l||n&&o&&(d(n),p(!0),m("~"))},[t,f,l,n,o]);const k=i.useCallback(()=>{r(!1)},[r]),M=i.useCallback(async W=>{if(!(!W||h)){g(!0);try{let te=W,ye;if(b){const K=await y(W);if(!K.success){V.error("Unable to access directory",{description:K.error||"Desktop denied directory access."});return}te=K.path??W,ye=K.projectId;const L=await v(te);if(!L.success){V.error("Failed to open directory",{description:L.error||"Desktop could not grant file access."});return}}if(!a(te,{id:ye})){V.error("Failed to add project",{description:"Please select a valid directory path."});return}k()}catch(te){V.error("Failed to select directory",{description:te instanceof Error?te.message:"Unknown error occurred."})}finally{g(!1)}}},[a,k,b,y,v,h]),w=i.useCallback(async()=>{const W=u.trim()||l;W&&await M(W)},[M,u,l]),T=i.useCallback(W=>{d(W),p(!0),m(D(W))},[D]),E=i.useCallback(async W=>{d(W),p(!0),m(D(W)),await M(W)},[M,D]),I=i.useCallback(W=>{const te=W.target.value;if(m(te),p(!0),N(te.startsWith("/")||te.startsWith("~")),te.startsWith("/")||te.startsWith("~")){const ye=te.startsWith("~")&&n?te.replace(/^~/,n):te;d(ye)}},[n]),A=i.useCallback(W=>{j.current?.handleKeyDown(W)||W.key==="Enter"&&(W.preventDefault(),w())},[w]),P=i.useCallback(W=>{d(W),p(!0),m(D(W))},[D]),F=i.useCallback(()=>{N(!1)},[]),z=i.useCallback(()=>{gl(!x)},[x]),G=e.jsxs("button",{type:"button",onClick:z,className:"flex items-center gap-2 px-2 py-1 rounded-lg hover:bg-accent/40 transition-colors typography-meta text-muted-foreground flex-shrink-0",children:[x?e.jsx(Nn,{className:"h-4 w-4 text-primary"}):e.jsx(kn,{className:"h-4 w-4"}),"Show hidden"]}),oe=e.jsxs(xs,{className:"flex-shrink-0 px-4 pb-2 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)] sm:px-0 sm:pb-3 sm:pt-0",children:[e.jsx(ys,{children:"Add project directory"}),e.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[e.jsx(Ss,{className:"flex-1",children:"Choose a folder to add as a project."}),G]})]}),O=e.jsxs("div",{className:"relative",children:[e.jsx(St,{value:u,onChange:I,onKeyDown:A,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(bp,{ref:j,inputValue:u,homeDirectory:n,onSelectSuggestion:P,visible:C,onClose:F,showHidden:x})]}),q=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(cu,{variant:"inline",currentPath:l??s,onSelectPath:T,onDoubleClickPath:E,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:x,rootDirectory:o?n:null,isRootReady:o})}),Y=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:O}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:G}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(cu,{variant:"inline",currentPath:l??s,onSelectPath:T,onDoubleClickPath:E,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:x,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),Z=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[O,q]}),B=()=>e.jsxs(e.Fragment,{children:[e.jsx(Se,{variant:"ghost",onClick:k,disabled:h,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(Se,{onClick:w,disabled:h||!f||!l&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:h?"Adding...":"Add Project"})]});return S?e.jsx(Ws,{open:t,onClose:()=>r(!1),title:"Add project directory",className:"max-w-full",contentMaxHeightClassName:"max-h-[min(70vh,520px)] h-[min(70vh,520px)]",footer:e.jsx("div",{className:"flex flex-row gap-2",children:B()}),children:Y}):e.jsx(us,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:R("flex w-full max-w-[min(560px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-xl sm:p-6"),onOpenAutoFocus:W=>{W.preventDefault()},children:[oe,Z,e.jsx(Gs,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-row gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:justify-end sm:border-0 sm:bg-transparent sm:px-0 sm:pt-4 sm:pb-0",children:B()})]})})},fa=t=>t?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,Nj=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},kj=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),[o,a]=i.useState(null),[c,l]=i.useState([]),[d,u]=i.useState(!1),[m,f]=i.useState(!1),{deleteSession:p,deleteSessions:h,loadSessions:g,getWorktreeMetadata:x}=ve(),{currentDirectory:b,homeDirectory:y,isHomeReady:v}=vt(),{projects:S,addProject:C,activeProjectId:N}=Lt(),{requestAccess:j,startAccessing:D}=Pi(),{isMobile:k,isTablet:M,hasTouchInput:w}=Gt(),T=k||M||w,E=i.useMemo(()=>{const L=(N?S.find(Q=>Q.id===N)??null:null)?.path??b;return Nj(L)},[N,b,S]),I=i.useMemo(()=>(o?.worktree?.status?.isDirty??!1)||c.some(K=>K.metadata.status?.isDirty),[o?.worktree?.status?.isDirty,c]),A=i.useMemo(()=>{const K=o?.worktree;return K&&typeof K.branch=="string"&&K.branch.trim().length>0?!0:c.length>0&&c.every(({metadata:L})=>typeof L.branch=="string"&&L.branch.trim().length>0)},[o?.worktree,c]),P=o?.mode==="worktree",F=P,z=m||!P||!A;i.useEffect(()=>{g()},[g,b]);const G=i.useMemo(()=>S.map(K=>`${K.id}:${K.path}`).join("|"),[S]),oe=i.useRef(G);i.useEffect(()=>{G!==oe.current&&(oe.current=G,g())},[g,G]),i.useEffect(()=>{if(!(s||!v||S.length>0)){if(n(!0),ds()){j("").then(async K=>{if(!K.success||!K.path){K.error&&K.error!=="Directory selection cancelled"&&V.error("Failed to select directory",{description:K.error});return}const L=await D(K.path);if(!L.success){V.error("Failed to open directory",{description:L.error||"Desktop could not grant file access."});return}C(K.path,{id:K.projectId})||V.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(K=>{console.error("Desktop: Error selecting directory:",K),V.error("Failed to select directory")});return}r(!0)}},[C,s,v,S.length,j,D]);const O=i.useCallback(K=>{a({sessions:K.sessions,dateLabel:K.dateLabel,mode:K.mode??"session",worktree:K.worktree??null})},[]),q=i.useCallback(()=>{a(null),l([]),u(!1),f(!1)},[]);i.useEffect(()=>io.onDeleteRequest(K=>{O(K)}),[O]),i.useEffect(()=>io.onDirectoryRequest(()=>{r(!0)}),[]),i.useEffect(()=>{if(!o){l([]),u(!1);return}const K=o.sessions.map(Q=>{const ce=x(Q.id);return ce?{session:Q,metadata:ce}:null}).filter(Q=>!!Q);if(l(K),u(!1),K.length===0)return;let L=!1;return(async()=>{const Q=await Promise.all(K.map(async({metadata:ce})=>{if(ce.status&&typeof ce.status.isDirty=="boolean")return ce.status;try{return await Jo(ce.path)}catch{return ce.status}})).catch(ce=>(console.warn("Failed to inspect worktree status before deletion:",ce),K.map(({metadata:he})=>he.status)));L||!Array.isArray(Q)||l(ce=>ce.map((he,Ne)=>({session:he.session,metadata:{...he.metadata,status:Q[Ne]??he.metadata.status}})))})(),()=>{L=!0}},[o,x]),i.useEffect(()=>{A||u(!1)},[A]);const Y=i.useCallback(async()=>{if(o){f(!0);try{const K=F,L=K&&d;if(o.sessions.length===0&&P&&o.worktree){const Q=d&&A;await Qo({id:N||`path:${E}`,path:E},o.worktree,{deleteRemoteBranch:Q,force:!0});const ce=Q?"Worktree and remote branch removed.":"Worktree removed.";V.success("Worktree removed",{description:fa(ce)}),q(),g();return}if(o.sessions.length===1){const Q=o.sessions[0];if(!await p(Q.id,{archiveWorktree:K,deleteRemoteBranch:L})){V.error("Failed to delete session"),f(!1);return}const he=K?L?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;V.success("Session deleted",{description:fa(he),action:{label:"OK",onClick:()=>{}}})}else{const Q=o.sessions.map(Ne=>Ne.id),{deletedIds:ce,failedIds:he}=await h(Q,{archiveWorktree:K,deleteRemoteBranch:L});if(ce.length>0){const Ne=K?L?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,we=[he.length>0?`${he.length} session${he.length===1?"":"s"} could not be deleted.`:o.dateLabel?`Removed all sessions from ${o.dateLabel}.`:void 0,Ne].filter(Boolean).join(" ");V.success(`Deleted ${ce.length} session${ce.length===1?"":"s"}`,{description:fa(we||void 0),action:{label:"OK",onClick:()=>{}}})}if(he.length>0&&(V.error(`Failed to delete ${he.length} session${he.length===1?"":"s"}`,{description:fa("Please try again in a moment.")}),ce.length===0)){f(!1);return}}q()}finally{f(!1)}}},[o,d,p,h,q,F,P,A,E,N,g]),Z=o?.worktree??c[0]?.metadata??null,B=o?o.mode==="worktree"?o.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and ${o.sessions.length===1?"1 linked session":`${o.sessions.length} linked sessions`}.`:`This action permanently removes ${o.sessions.length===1?"1 session":`${o.sessions.length} sessions`}${o.dateLabel?` from ${o.dateLabel}`:""}.`:"",W=o?e.jsxs("div",{className:R(P?"space-y-3":"space-y-2"),children:[o.sessions.length>0&&e.jsxs("div",{className:R(P?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[P&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:o.sessions.length===1?"Linked session":"Linked sessions"}),e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:o.sessions.length})]}),e.jsxs("ul",{className:R(P?"mt-2 space-y-1":"space-y-0.5"),children:[o.sessions.slice(0,5).map(K=>e.jsxs("li",{className:R(P?"flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-muted-foreground":"typography-micro text-muted-foreground/80"),children:[e.jsx("span",{className:R(!P&&"hidden"),children:"•"}),e.jsx("span",{className:"truncate",children:K.title||"Untitled Session"})]},K.id)),o.sessions.length>5&&e.jsxs("li",{className:R(P?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",o.sessions.length-5," more"]})]})]}),P?e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),Z?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:Z.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:Z?Yr(Z.path,y):"Worktree path unavailable."}),I&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."})]}):e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,te=P?A?e.jsxs("button",{type:"button",onClick:()=>{z||u(K=>!K)},disabled:z,className:R("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",z?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[d?e.jsx(Nn,{className:"size-4 text-primary"}):e.jsx(kn,{className:"size-4"}),"Delete remote branch"]}):e.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,ye=P?e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-col items-start gap-1",children:te}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{variant:"ghost",onClick:q,disabled:m,children:"Cancel"}),e.jsx(Se,{variant:"destructive",onClick:Y,disabled:m,children:m?"Deleting…":"Delete worktree"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Se,{variant:"ghost",onClick:q,disabled:m,children:"Cancel"}),e.jsx(Se,{variant:"destructive",onClick:Y,disabled:m,children:m?"Deleting…":o?.sessions.length===1?"Delete session":"Delete sessions"})]}),me=P?"Delete worktree":o?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[T?e.jsx(Ws,{open:!!o,onClose:()=>{m||q()},title:me,footer:e.jsx("div",{className:"flex justify-end gap-2",children:ye}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[B&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:B}),W]})}):e.jsx(us,{open:!!o,onOpenChange:K=>{if(!K){if(m)return;q()}},children:e.jsxs(ms,{className:R(P?"max-w-xl max-h-[70vh] flex flex-col overflow-hidden gap-3":"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2"),children:[e.jsxs(xs,{children:[e.jsxs(ys,{className:R(P&&"flex items-center gap-2"),children:[P&&e.jsx(zs,{className:"h-5 w-5"}),me]}),B&&e.jsx(Ss,{children:B})]}),e.jsx("div",{className:R(P&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:W}),e.jsx(Gs,{className:"mt-2 gap-2 pt-1 pb-1",children:ye})]})}),e.jsx(Sj,{open:t,onOpenChange:r})]})};function Cj(){return new Worker(Ig,{type:"module"})}const Mj=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"],Dj=10;function Aj(t,r,s){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s;return`${t}:${r.length}:${s.length}:${n.length}:${o.length}`}function lu(t){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>t(void 0),0);return()=>window.clearTimeout(r)}const Ej=({children:t})=>{const r=Tg(),s=is(l=>l.activeDirectory),n=is(l=>s?l.directories.get(s)?.lastStatusChange??0:0),o=is(l=>s?l.directories.get(s)?.diffCache.size??0:0),a=Ae.useRef(!1),c=Ae.useRef(new Map);return Ae.useEffect(()=>{if(!r||a.current)return;a.current=!0;const l={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=kc(l,{...l,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Ae.useEffect(()=>{if(!r||!s||!n||o===0)return;const l=is.getState().directories.get(s);if(!l||l.diffCache.size===0||(c.current.get(s)??0)>=l.lastStatusChange)return;c.current.set(s,l.lastStatusChange);let u=!1,m=null;const p=Array.from(l.diffCache.entries()).slice(0,Dj);let h=0;const g=x=>{if(u)return;const b=Date.now();for(;h<p.length&&!(x&&x.timeRemaining()<8||!x&&Date.now()-b>8);){const[y,v]=p[h];h+=1,Er(y);const S=Aj(y,v.original,v.modified),C={name:y,contents:v.original,cacheKey:`old-${S}`},N={name:y,contents:v.modified,cacheKey:`new-${S}`},j=kc(C,N),D={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(D,j)}h<p.length&&(m=lu(g))};return g(void 0),h<p.length&&(m=lu(g)),()=>{u=!0,m?.()}},[r,s,n,o]),e.jsx(e.Fragment,{children:t})},Ij=({children:t})=>{const s=Ci()?.currentTheme?.metadata?.variant==="dark";np();const n=Ae.useMemo(()=>({theme:{dark:ao.dark,light:ao.light},themeType:s?"dark":"light",langs:Mj}),[s]);return e.jsx(Pg,{poolOptions:{workerFactory:Cj,poolSize:2,totalASTLRUCacheSize:50},highlighterOptions:n,children:e.jsx(Ej,{children:t})})},Vc=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),Pj=(t,r)=>{const s=Vc(t),n=Vc(r);return`${s}-${n}`.substring(0,60)},du=(t,r)=>`${t}/${r}`,Tj=()=>{const t=Lt.getState(),r=t.activeProjectId;if(!r)return null;const s=t.projects.find(o=>o.id===r);if(s?.path)return{id:s.id,path:s.path};const n=vt.getState().currentDirectory??null;if(n&&n.trim().length>0){const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n;return{id:`path:${o}`,path:o}}return null},Io=ns()(fs(t=>({isLoading:!1,error:null,createMultiRun:async r=>{const s=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:c,setupCommands:l}=r;if(!s)return t({error:"Group name is required"}),null;if(!n)return t({error:"Prompt is required"}),null;if(o.length<1)return t({error:"Select at least 1 model"}),null;if(o.length>5)return t({error:"Maximum 5 models allowed"}),null;t({isLoading:!0,error:null});try{const d=Tj();if(!d)return t({error:"Select a project",isLoading:!1}),null;const u=d.path;if(!await Hr(u))return t({error:"Not in a git repository",isLoading:!1}),null;const f=Vc(s),p=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",h=p!=="HEAD"?p:void 0,g=[],x=l?.filter(j=>j.trim().length>0)??[],b=new Map;for(const j of o){const D=`${j.providerID}:${j.modelID}`;b.set(D,(b.get(D)||0)+1)}const y=new Map;for(const j of o){const D=`${j.providerID}:${j.modelID}`,k=b.get(D)||1,M=(y.get(D)||0)+1;y.set(D,M);const w=Pj(j.providerID,j.modelID),T=k>1?du(f,`${w}/${M}`):du(f,w);try{const E=await ki(d,{preferredName:T,setupCommands:x,startPoint:h??null}),I={...E,createdFromBranch:h??"HEAD"},A=k>1?`${f}/${j.providerID}/${j.modelID}/${M}`:`${f}/${j.providerID}/${j.modelID}`,P=await Oe.withDirectory(E.path,()=>Oe.createSession({title:A}));gt.getState().setWorktreeMetadata(P.id,I),g.push({sessionId:P.id,worktreePath:E.path,providerID:j.providerID,modelID:j.modelID,variant:j.variant})}catch(E){console.warn("[MultiRun] Failed to create session:",E)}}const v=l?.filter(j=>j.trim().length>0)??[];v.length>0&&zf(d,v).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const S=g.map(j=>j.sessionId),C=g[0]?.sessionId??null;if(S.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const N=c?.map(j=>({type:"file",mime:j.mime,filename:j.filename,url:j.url}));try{await gt.getState().loadSessions()}catch{}return(async()=>{try{await Promise.allSettled(g.map(async j=>{try{await Oe.withDirectory(j.worktreePath,()=>Oe.sendMessage({id:j.sessionId,providerID:j.providerID,modelID:j.modelID,variant:j.variant,text:n,agent:a,files:N}))}catch(D){console.warn("[MultiRun] Failed to start run:",D)}}))}catch(j){console.warn("[MultiRun] Failed to start runs:",j)}})(),t({isLoading:!1}),{groupSlug:f,sessionIds:S,firstSessionId:C}}catch(d){return t({error:d instanceof Error?d.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{t({error:null})}}),{name:"multirun-store"}));function As({...t}){return e.jsx(Fg,{"data-slot":"select",...t})}function wn({...t}){return e.jsx(zg,{"data-slot":"select-group",...t})}function Cn({...t}){return e.jsx(Og,{"data-slot":"select-value",...t})}function Es({className:t,size:r="default",children:s,...n}){return e.jsxs(Rg,{"data-slot":"select-trigger","data-size":r,className:R("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-muted data-[state=open]:bg-muted focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 data-[size=lg]:h-8 data-[size=lg]:py-1.5 data-[size=chip]:h-7 data-[size=chip]:py-1 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...n,children:[s,e.jsx(Lg,{asChild:!0,children:e.jsx(Wt,{className:"size-4 opacity-50"})})]})}function Is({className:t,children:r,position:s="popper",fitContent:n=!1,...o}){return e.jsx(_g,{children:e.jsx($g,{"data-slot":"select-content",className:R("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden rounded-xl border shadow-none transform-gpu will-change-transform",s==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",n&&"w-max min-w-0",t),position:s,...o,children:e.jsx(xt,{as:Bg,outerClassName:R("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:R("p-1",s==="popper"&&(n?"h-[var(--radix-select-trigger-height)] w-max min-w-0 scroll-my-1":"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1")),children:r})})})}function Xn({className:t,...r}){return e.jsx(Hg,{"data-slot":"select-label",className:R("text-muted-foreground px-2 py-1.5 typography-meta",t),...r})}function Bt({className:t,children:r,...s}){return e.jsxs(Wg,{"data-slot":"select-item",className:R("hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...s,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(Ug,{children:e.jsx(Tt,{className:"size-4"})})}),e.jsx(Vg,{children:r})]})}function oi({className:t,...r}){return e.jsx(Gg,{"data-slot":"select-separator",className:R("bg-border pointer-events-none -mx-1 my-1 h-px",t),...r})}const Fj="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!--%20Uploaded%20to:%20SVG%20Repo,%20www.svgrepo.com,%20Generator:%20SVG%20Repo%20Mixer%20Tools%20--%3e%3csvg%20fill='%23000000'%20width='800px'%20height='800px'%20viewBox='0%200%2024%2024'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.702%202.29c-2.494-1.554-5.778-1.187-8.706.654C9.076%201.104%205.79.736%203.3%202.29c-3.941%202.463-4.42%208.806-1.07%2014.167%202.47%203.954%206.333%206.269%209.77%206.226%203.439.043%207.301-2.273%209.771-6.226%203.347-5.361%202.872-11.704-1.069-14.167zM4.042%2015.328a12.838%2012.838%200%200%201-1.546-3.541%2010.12%2010.12%200%200%201-.336-3.338c.15-1.98.956-3.524%202.27-4.345%201.315-.822%203.052-.87%204.903-.137.281.113.556.24.825.382A15.11%2015.11%200%200%200%207.5%207.54c-2.035%203.255-2.655%206.878-1.945%209.765a13.247%2013.247%200%200%201-1.514-1.98zm17.465-3.541a12.866%2012.866%200%200%201-1.547%203.54%2013.25%2013.25%200%200%201-1.513%201.984c.635-2.589.203-5.76-1.353-8.734a.39.39%200%200%200-.563-.153l-4.852%203.032a.397.397%200%200%200-.126.546l.712%201.139a.395.395%200%200%200%20.547.126l3.145-1.965c.101.306.203.606.28.916.296%201.086.41%202.214.335%203.337-.15%201.982-.956%203.525-2.27%204.347a4.437%204.437%200%200%201-2.25.65h-.101a4.432%204.432%200%200%201-2.25-.65c-1.314-.822-2.121-2.365-2.27-4.347a10.153%2010.153%200%200%201%20.335-3.337%2013.212%2013.212%200%200%201%204.05-6.482%2010.148%2010.148%200%200%201%202.849-1.765c1.845-.733%203.586-.685%204.9.137%201.316.822%202.122%202.365%202.271%204.345a10.146%2010.146%200%200%201-.33%203.334z'/%3e%3c/svg%3e",Rj=Object.assign({"../assets/provider-logos/gocode.svg":Fj}),Gc=new Map;for(const[t,r]of Object.entries(Rj)){const s=t.match(/provider-logos\/([^/]+)\.svg$/i);s?.[1]&&r&&Gc.set(s[1].toLowerCase(),r)}function wp(t){const r=t?.toLowerCase()??null,s=r?Gc.has(r):!1,n=r?Gc.get(r)??null:null,[o,a]=Ae.useState(s?"local":"remote");Ae.useEffect(()=>{a(s?"local":"remote")},[s,r]);const c=Ae.useCallback(()=>{a(l=>l==="local"&&s?"remote":"none")},[s]);return r?o==="local"&&n?{src:n,onError:c,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:c,hasLogo:!0}:{src:null,onError:c,hasLogo:!1}:{src:null,onError:c,hasLogo:!1}}const gs=({providerId:t,alt:r,className:s,onError:n})=>{const{src:o,onError:a,hasLogo:c}=wp(t),l=i.useCallback(()=>{a(),n?.()},[a,n]);return!c||!o?null:e.jsx("img",{src:o,alt:r||`${t} logo`,className:R("dark:invert",s),onError:l})},Tl=t=>t.nativeEvent.isComposing||t.nativeEvent.keyCode===229,Fl=()=>{const{providers:t}=Je(),{favoriteModels:r,recentModels:s}=Me(),n=i.useMemo(()=>r.map(({providerID:a,modelID:c})=>{const l=t.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===c);return u?{provider:l,model:u,providerID:a,modelID:c}:null}).filter(a=>a!==null),[r,t]),o=i.useMemo(()=>s.map(({providerID:a,modelID:c})=>{const l=t.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===c);return u?{provider:l,model:u,providerID:a,modelID:c}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:c})=>!r.some(l=>l.providerID===a&&l.modelID===c)),[s,t,r]);return{favoriteModelsList:n,recentModelsList:o}},vp="h-7",ai=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Lj=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Oj=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=Lj.format(t);return r.endsWith(".0")?r.slice(0,-2):r},_j=({model:t,instanceIndex:r,totalSameModel:s,onRemove:n})=>{const o=t.displayName||`${t.providerID}/${t.modelID}`,a=s>1?`${o} (${r})`:o;return e.jsxs("div",{className:R("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",vp),children:[e.jsx(gs,{providerId:t.providerID,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:a}),e.jsx("button",{type:"button",onClick:n,className:"text-muted-foreground hover:text-foreground ml-0.5",children:e.jsx(es,{className:"h-3.5 w-3.5"})})]})},jp=({selectedModels:t,onAdd:r,onRemove:s,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:c=!0,maxModels:l})=>{const{providers:d,modelsMetadata:u}=Je(),{favoriteModelsList:m,recentModelsList:f}=Fl(),[p,h]=i.useState(!1),[g,x]=i.useState(""),[b,y]=i.useState(0),[v,S]=i.useState(null),C=i.useRef(null),N=i.useRef(null),j=i.useRef(null),D=i.useRef([]),k=i.useMemo(()=>{const G=new Map;for(const oe of t){const O=`${oe.providerID}:${oe.modelID}`;G.set(O,(G.get(O)||0)+1)}return G},[t]),M=i.useCallback(G=>t.filter(O=>O.providerID===G.providerID&&O.modelID===G.modelID).findIndex(O=>O.instanceId===G.instanceId)+1,[t]),w=(G,oe)=>{const O=`${G}/${oe}`;return u.get(O)},T=G=>{const oe=G?.name||G?.id||"",O=String(oe);return O.length>40?O.substring(0,37)+"...":O},E=i.useCallback((G,oe)=>{if(!g.trim())return!0;const O=g.toLowerCase();return G.toLowerCase().includes(O)||oe.toLowerCase().includes(O)},[g]),I=i.useMemo(()=>m.filter(({model:G,providerID:oe})=>{const q=d.find(Z=>Z.id===oe)?.name||oe,Y=T(G);return E(Y,q)}),[m,d,E]),A=i.useMemo(()=>f.filter(({model:G,providerID:oe})=>{const q=d.find(Z=>Z.id===oe)?.name||oe,Y=T(G);return E(Y,q)}),[f,d,E]),P=i.useMemo(()=>d.map(G=>{const O=(Array.isArray(G.models)?G.models:[]).filter(q=>{const Y=T(q);return E(Y,G.name||G.id||"")});return{...G,models:O}}).filter(G=>G.models.length>0),[d,E]),F=I.length>0||A.length>0||P.length>0;i.useEffect(()=>{if(p&&j.current){const oe=j.current.getBoundingClientRect().top-100;S(Math.max(150,Math.min(400,oe)))}},[p]),i.useEffect(()=>{p&&C.current&&C.current.focus()},[p]),i.useEffect(()=>{if(!p)return;const G=oe=>{N.current&&!N.current.contains(oe.target)&&(h(!1),x(""),y(0))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[p]),i.useEffect(()=>{y(0)},[g]);const z=(G,oe,O,q,Y,Z)=>{const B=`${oe}:${O}`,W=k.get(B)||0,te=w(oe,O),ye=Oj(te?.limit?.context),me=q==="fav"||q==="recent";return e.jsxs("button",{ref:K=>{D.current[Y]=K},type:"button",onClick:()=>{r({providerID:oe,modelID:O,displayName:G.name||O,instanceId:ai()})},onMouseEnter:()=>y(Y),className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",Z?"bg-accent":"hover:bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[me&&e.jsx(gs,{providerId:oe,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:T(G)}),ye&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:ye})]}),W>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",W]})]},`${q}-${B}`)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsxs("div",{className:"relative",ref:N,children:[e.jsxs(Se,{ref:j,type:"button",variant:"outline",size:"sm",className:vp,onClick:()=>h(!p),children:[e.jsx(ls,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const G=[];I.forEach(({model:Y,providerID:Z,modelID:B})=>{G.push({model:Y,providerID:Z,modelID:B,section:"fav"})}),A.forEach(({model:Y,providerID:Z,modelID:B})=>{G.push({model:Y,providerID:Z,modelID:B,section:"recent"})}),P.forEach(Y=>{Y.models.forEach(Z=>{G.push({model:Z,providerID:Y.id,modelID:Z.id,section:"provider"})})});const oe=G.length,O=Y=>{if(!Tl(Y))if(Y.key==="ArrowDown"){Y.preventDefault(),Y.stopPropagation();const Z=(b+1)%Math.max(1,oe);y(Z),setTimeout(()=>{D.current[Z]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Y.key==="ArrowUp"){Y.preventDefault(),Y.stopPropagation();const Z=(b-1+Math.max(1,oe))%Math.max(1,oe);y(Z),setTimeout(()=>{D.current[Z]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Y.key==="Enter"){Y.preventDefault(),Y.stopPropagation();const Z=G[b];Z&&r({providerID:Z.providerID,modelID:Z.modelID,displayName:Z.model.name||Z.modelID,instanceId:ai()})}else Y.key==="Escape"&&(Y.preventDefault(),Y.stopPropagation(),h(!1),x(""),y(0))};let q=0;return e.jsxs("div",{className:"absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden bg-background shadow-lg w-[min(380px,calc(100vw-2rem))] flex flex-col",children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{ref:C,type:"text",placeholder:"Search models",value:g,onChange:Y=>x(Y.target.value),onKeyDown:O,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(xt,{outerClassName:"flex-1",style:{maxHeight:v?`${v}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!F&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),I.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Rr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),I.map(({model:Y,providerID:Z,modelID:B})=>{const W=q++;return z(Y,Z,B,"fav",W,b===W)})]}),A.length>0&&e.jsxs(e.Fragment,{children:[I.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Cr,{className:"h-4 w-4"}),"Recent"]}),A.map(({model:Y,providerID:Z,modelID:B})=>{const W=q++;return z(Y,Z,B,"recent",W,b===W)})]}),(I.length>0||A.length>0)&&P.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),P.map((Y,Z)=>e.jsxs(i.Fragment,{children:[Z>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(gs,{providerId:Y.id,className:"h-4 w-4 flex-shrink-0"}),Y.name]}),Y.models.map(B=>{const W=q++;return z(B,Y.id,B.id,"provider",W,b===W)})]},Y.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),c&&t.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:t.map((G,oe)=>{const O=`${G.providerID}:${G.modelID}`,q=k.get(O)||1,Y=M(G),B=d.find(K=>K.id===G.providerID)?.models.find(K=>K.id===G.modelID),W=B?.variants?Object.keys(B.variants):[],te=W.length>0,ye="__default__",me=G.variant??ye;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(_j,{model:G,instanceIndex:Y,totalSameModel:q,onRemove:()=>s(oe)}),te&&e.jsxs(As,{value:me,onValueChange:K=>{if(!n)return;n(oe,{...G,variant:K===ye?void 0:K})},children:[e.jsxs(Es,{size:"chip",className:"px-2 gap-1.5 rounded-md bg-accent/50 border-border/30 hover:bg-accent/60 typography-meta font-medium text-foreground",children:[e.jsx(Mr,{className:R("h-3.5 w-3.5 flex-shrink-0",me===ye?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(Cn,{placeholder:"Thinking"})]}),e.jsxs(Is,{fitContent:!0,children:[e.jsx(Bt,{value:ye,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),W.map(K=>e.jsx(Bt,{value:K,className:"pr-2 [&>span:first-child]:hidden",children:K},K))]})]})]},G.instanceId)})})]}),o!==void 0&&t.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",l!==void 0?`to ${l} models`:"","."]})]})};function Rl(t){const[r,s]=i.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=i.useState(!1),[a,c]=i.useState(null);return i.useEffect(()=>{let l=!1;if(!t){c(null),o(!1),s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),c(null),(async()=>{try{const d=await Hr(t);if(l)return;if(c(d),!d){s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await wl(t).catch(()=>null);if(l)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(g=>!g.startsWith("remotes/")).sort((g,x)=>g.localeCompare(x)).forEach(g=>{m.push({value:g,label:g,group:"local"})}),u.all.filter(g=>g.startsWith("remotes/")).map(g=>g.replace(/^remotes\//,"")).sort((g,x)=>g.localeCompare(x)).forEach(g=>{m.push({value:g,label:g,group:"remote"})})),s(m)}finally{l||o(!1)}})(),()=>{l=!0}},[t]),{branches:r,isLoading:n,isGitRepository:a}}const Sp=({directory:t,value:r,onChange:s,className:n,disabled:o,id:a})=>{const{branches:c,isLoading:l,isGitRepository:d}=Rl(t),u=i.useMemo(()=>c.find(f=>f.value===r)?.label??null,[c,r]);i.useEffect(()=>{!c.some(p=>p.value===r)&&c.length>0&&s("HEAD")},[c,r,s]);const m=o||!d||l;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(As,{value:r,onValueChange:s,disabled:m,children:[e.jsx(Es,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(Cn,{children:u}):e.jsx(Cn,{placeholder:l?"Loading branches…":"Select a branch"})}),e.jsxs(Is,{fitContent:!0,children:[e.jsxs(wn,{children:[e.jsx(Xn,{children:"Default"}),c.filter(f=>f.group==="special").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),c.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(oi,{}),e.jsxs(wn,{children:[e.jsx(Xn,{children:"Local branches"}),c.filter(f=>f.group==="local").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,c.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(oi,{}),e.jsxs(wn,{children:[e.jsx(Xn,{children:"Remote branches"}),c.filter(f=>f.group==="remote").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null]})]}),d===!1&&e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."})]})},Np=({value:t,onChange:r,className:s,disabled:n,id:o})=>{const a=Je(f=>f.getVisibleAgents),c=Je(f=>f.loadAgents),l=Je(f=>f.currentAgentName),d=a(),u=i.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(n)return;const f=t.trim();if(f.length>0&&u.some(g=>g.name===f))return;const p=typeof l=="string"&&l.trim().length>0?l.trim():null;if(p&&u.some(g=>g.name===p)){r(p);return}const h=u[0]?.name;h&&r(h)},[l,n,r,u,t]);const m=t.trim().length>0?t:void 0;return e.jsxs(As,{value:m,onValueChange:r,disabled:n,children:[e.jsx(Es,{id:o,size:"lg",className:s??"max-w-full typography-meta text-foreground",children:e.jsx(Cn,{placeholder:"Select an agent"})}),e.jsx(Is,{fitContent:!0,children:u.length>0&&e.jsx(wn,{children:u.map(f=>e.jsx(Bt,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},$j=10*1024*1024,uu=5,mu=({initialPrompt:t,onCreated:r,onCancel:s})=>{const[n,o]=i.useState(""),[a,c]=i.useState(()=>t??""),[l,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState([]),[h,g]=i.useState(!1),[x,b]=i.useState([]),[y,v]=i.useState(!1),[S,C]=i.useState(!1),N=i.useRef(null),j=vt(L=>L.currentDirectory??null),D=i.useMemo(()=>{if(typeof window>"u")return null;const L=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof L=="string"&&L.trim().length>0?L.trim():null},[]),k=Lt(L=>L.activeProjectId),M=Lt(L=>L.projects),w=i.useMemo(()=>{if(k){const Q=M.find(ce=>ce.id===k);if(Q?.path)return{id:Q.id,path:Q.path}}const L=j??D;return L?{id:`path:${L}`,path:L}:null},[k,M,j,D]),[T,E]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),I=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const L=typeof window.opencodeDesktop<"u";E(L)},[]);const A=i.useMemo(()=>T&&I?"pl-[5.75rem]":"pl-3",[T,I]),P=i.useCallback(async L=>{if(!L.target.closest("button, a, input, select, textarea")&&L.button===0&&T)try{const{getCurrentWindow:Q}=await vs(async()=>{const{getCurrentWindow:he}=await import("./vendor-.bun-Bui932eM.js").then(Ne=>Ne.dl);return{getCurrentWindow:he}},__vite__mapDeps([0,1]));await Q().startDragging()}catch{}},[T]),[F,z]=i.useState("HEAD"),{isLoading:G,isGitRepository:oe}=Rl(j),O=Io(L=>L.createMultiRun),q=Io(L=>L.error),Y=Io(L=>L.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&c(L=>L.trim().length>0?L:t)},[t]),i.useEffect(()=>{if(!w)return;let L=!1;return C(!0),(async()=>{try{const Q=await go(w);L||b(Q)}catch{}finally{L||C(!1)}})(),()=>{L=!0}},[w]);const Z=L=>{l.length>=uu||(d(Q=>[...Q,L]),Y())},B=L=>{d(Q=>Q.filter((ce,he)=>he!==L)),Y()},W=i.useCallback((L,Q)=>{d(ce=>ce.map((he,Ne)=>Ne===L?Q:he))},[]),te=async L=>{const Q=L.target.files;if(!Q)return;let ce=0;for(let he=0;he<Q.length;he++){const Ne=Q[he];if(Ne.size>$j){V.error(`File "${Ne.name}" is too large (max 10MB)`);continue}try{const H=await new Promise((ee,ue)=>{const ge=new FileReader;ge.onload=()=>ee(ge.result),ge.onerror=ue,ge.readAsDataURL(Ne)}),we={id:ai(),filename:Ne.name,mimeType:Ne.type||"application/octet-stream",size:Ne.size,dataUrl:H};p(ee=>[...ee,we]),ce++}catch(H){console.error("File attach failed",H),V.error(`Failed to attach "${Ne.name}"`)}}ce>0&&V.success(`Attached ${ce} file${ce>1?"s":""}`),N.current&&(N.current.value="")},ye=L=>{p(Q=>Q.filter(ce=>ce.id!==L))},me=async L=>{if(L.preventDefault(),!!a.trim()&&!(l.length<2)){g(!0),Y();try{const Q=l.map(({instanceId:we,...ee})=>ee),ce=f.map(we=>({mime:we.mimeType,filename:we.filename,url:we.dataUrl})),he=x.filter(we=>we.trim().length>0),Ne={name:n.trim(),prompt:a.trim(),models:Q,agent:u||void 0,worktreeBaseBranch:F,files:ce.length>0?ce:void 0,setupCommands:he.length>0?he:void 0},H=await O(Ne);H&&(H.firstSessionId&&ve.getState().setCurrentSession(H.firstSessionId),r?.())}finally{g(!1)}}},K=!!(n.trim()&&a.trim()&&l.length>=2&&oe&&!G);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{onMouseDown:P,className:R("flex h-12 items-center justify-between border-b app-region-drag select-none",A),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"})}),s&&e.jsx("div",{className:"flex items-center pr-3",children:e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close",className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:e.jsx(es,{className:"h-5 w-5"})})}),e.jsx(lt,{children:e.jsx("p",{children:"Close"})})]})})]}),e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"chat-column py-6",children:e.jsxs("form",{onSubmit:me,className:"space-y-6","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:["Group name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(St,{id:"group-name",value:n,onChange:L=>o(L.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body max-w-full sm:max-w-xs",required:!0}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch names"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Worktrees"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Create one worktree per model by creating a new branch from a base branch."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"multirun-worktree-base-branch",children:"Base branch"}),e.jsx(Sp,{directory:j,value:F,onChange:z,id:"multirun-worktree-base-branch"}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:F||"HEAD"}),"."]})]}),e.jsxs(Pn,{open:y,onOpenChange:v,children:[e.jsxs(xo,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",x.filter(L=>L.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",x.filter(L=>L.trim()).length," configured)"]})]}),e.jsx(Wt,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",y&&"rotate-180")})]}),e.jsx(Tn,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_PROJECT_PATH"})," for project root."]}),S?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[x.map((L,Q)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(St,{value:L,onChange:ce=>{const he=[...x];he[Q]=ce.target.value,b(he)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const ce=x.filter((he,Ne)=>Ne!==Q);b(ce)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(es,{className:"h-4 w-4"})})]},Q)),e.jsxs("button",{type:"button",onClick:()=>b([...x,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(ls,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",htmlFor:"multirun-agent",children:"Agent"}),e.jsx(Np,{value:u,onChange:m,id:"multirun-agent"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:["Prompt ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Fs,{id:"prompt",value:a,onChange:L=>c(L.target.value),placeholder:"Enter the prompt to send to all models...",className:"typography-body min-h-[120px] max-h-[400px] resize-none overflow-y-auto field-sizing-content",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Attachments"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"(optional, same files for all runs)"})]}),e.jsx("input",{ref:N,type:"file",multiple:!0,className:"hidden",onChange:te,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(Se,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>N.current?.click(),children:[e.jsx(Va,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(L=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[L.mimeType.startsWith("image/")?e.jsx(Ar,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(jr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:L.filename,children:L.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",L.size<1024?`${L.size}B`:L.size<1024*1024?`${(L.size/1024).toFixed(1)}KB`:`${(L.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>ye(L.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(es,{className:"h-3.5 w-3.5"})})]},L.id))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Models ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(jp,{selectedModels:l,onAdd:Z,onRemove:B,onUpdate:W,minModels:2,maxModels:uu})]}),q&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:q}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(Se,{type:"button",variant:"outline",onClick:s,children:"Cancel"}),e.jsx(Se,{type:"submit",disabled:!K||h,children:h?"Creating...":e.jsxs(e.Fragment,{children:["Start (",l.length," models)"]})})]})]})})})]})},Bj=(t={})=>{const{edgeThreshold:r=30,minSwipeDistance:s=50,maxSwipeTime:n=300,enabled:o=!0}=t,{isMobile:a,setSessionSwitcherOpen:c,isSessionSwitcherOpen:l}=Me(),d=Ae.useRef(null),u=Ae.useRef(null);return Ae.useEffect(()=>{if(!o||!a)return;const m=g=>{const x=g.touches[0];if(!x){d.current=null;return}x.clientX<=r?d.current={x:x.clientX,y:x.clientY,time:Date.now()}:d.current=null},f=g=>{if(!d.current)return;const x=g.touches[0];if(!x)return;x.clientX-d.current.x>10&&g.preventDefault()},p=g=>{if(!d.current)return;const x=g.changedTouches[0];if(!x){d.current=null,u.current=null;return}u.current={x:x.clientX,y:x.clientY,time:Date.now()};const{x:b,y,time:v}=d.current,{x:S,y:C,time:N}=u.current,j=S-b,D=C-y,k=N-v,M=Math.abs(D)<Math.abs(j),w=k<=n,T=Math.abs(D)<s;j>=s&&M&&w&&T&&!l&&c(!0),d.current=null,u.current=null},h=()=>{d.current=null,u.current=null};return document.addEventListener("touchstart",m,{passive:!0,capture:!0}),document.addEventListener("touchmove",f,{passive:!1,capture:!0}),document.addEventListener("touchend",p,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",m,{capture:!0}),document.removeEventListener("touchmove",f,{capture:!0}),document.removeEventListener("touchend",p,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0})}},[o,a,r,s,n,c,l]),null},kp=t=>t==="full"?{text:"var(--status-info)",border:"color-mix(in srgb, var(--status-info) 25%, transparent)",background:"color-mix(in srgb, var(--status-info) 4%, transparent)",borderWidth:1.5}:t==="allow"?{text:"var(--status-info)",border:"color-mix(in srgb, var(--status-info) 25%, transparent)",background:"color-mix(in srgb, var(--status-info) 4%, transparent)",borderWidth:1.5}:null;Ae.memo(()=>{const t=Ae.useRef(null),{addAttachedFile:r}=ve(),{isMobile:s}=Me(),n=Qf(),o=s?"h-9 w-9":"h-7 w-7",a=s?"h-5 w-5":"h-[18px] w-[18px]",c=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],h=ve.getState().attachedFiles.length;try{await r(p),ve.getState().attachedFiles.length>h&&m++}catch(g){console.error("File attach failed",g),V.error(g instanceof Error?g.message:"Failed to attach file")}}m>0&&V.success(`Attached ${m} file${m>1?"s":""}`)},l=async u=>{const m=u.target.files;m&&(await c(m),t.current&&(t.current.value=""))},d=async()=>{try{const m=await(await fetch("/api/vscode/pick-files")).json(),f=Array.isArray(m?.files)?m.files:[],p=Array.isArray(m?.skipped)?m.skipped:[];if(p.length>0){const g=p.map(x=>`${x?.name||"file"}: ${x?.reason||"skipped"}`).join(`
163
+ `);V.error(`Some files were skipped:
164
+ ${g}`)}const h=f.map(g=>{if(!g?.dataUrl)return null;try{const[x,b]=g.dataUrl.split(","),y=g.mimeType||x?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!b)return null;const v=atob(b),S=new Uint8Array(v.length);for(let N=0;N<v.length;N++)S[N]=v.charCodeAt(N);const C=new Blob([S],{type:y});return new File([C],g.name||"file",{type:y})}catch(x){return console.error("Failed to decode VS Code picked file",x),null}}).filter(Boolean);h.length>0&&await c(h)}catch(u){console.error("VS Code file pick failed",u),V.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:t,type:"file",multiple:!0,className:"hidden",onChange:l,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():t.current?.click()},className:R(o,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),title:"Attach files",children:e.jsx(Va,{className:R(a,"text-current")})})]})});const zj=Ae.memo(({file:t,onRemove:r})=>{const s=()=>t.mimeType.startsWith("image/")?e.jsx(Ar,{className:"h-3.5 w-3.5"}):t.mimeType.includes("text")||t.mimeType.includes("code")?e.jsx(jr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("json")||t.mimeType.includes("xml")?e.jsx(fi,{className:"h-3.5 w-3.5"}):e.jsx(jr,{className:"h-3.5 w-3.5"}),n=c=>c<1024?c+" B":c<1048576?(c/1024).toFixed(1)+" KB":(c/1048576).toFixed(1)+" MB",a=(c=>{const d=c.replace(/\\/g,"/").split("/");return d[d.length-1]||c})(t.filename);return e.jsxs("div",{className:"flex w-full sm:inline-flex sm:w-auto items-center gap-1.5 px-3 sm:px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta max-w-full min-w-0",children:[e.jsx("div",{title:t.source==="server"?"Server file":"Local file",children:t.source==="server"?e.jsx(qg,{className:"h-3 w-3 text-primary flex-shrink-0"}):e.jsx(Bm,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"})}),s(),e.jsx("div",{className:"overflow-hidden max-w-[120px] sm:max-w-[180px] flex-1 min-w-0",children:e.jsx("span",{className:"truncate block",title:t.serverPath||a,children:a})}),e.jsx("span",{className:"ml-auto text-muted-foreground flex-shrink-0 text-xs",children:n(t.size)}),e.jsx("button",{onClick:r,className:"hover:text-destructive min-h-6 min-w-6 sm:min-h-0 sm:min-w-0 sm:p-0.5 flex items-center justify-center flex-shrink-0 rounded focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",title:"Remove file",children:e.jsx(es,{className:"h-4 w-4 sm:h-3 sm:w-3"})})]})}),Hj=Ae.memo(()=>{const{attachedFiles:t,removeAttachedFile:r}=ve();return t.length===0?null:e.jsx("div",{className:"pb-2 overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium flex-shrink-0",children:"Attached:"}),t.map(s=>e.jsx(zj,{file:s,onRemove:()=>r(s.id)},s.id))]})})}),Cp=Ae.memo(({files:t,onShowPopup:r})=>{const s=t.filter(d=>d.type==="file"&&(d.mime||d.url)),n=d=>{if(!d)return"Unnamed file";const m=d.replace(/\\/g,"/").split("/");return m[m.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(Ar,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(jr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(fi,{className:"h-3.5 w-3.5"}):e.jsx(jr,{className:"h-3.5 w-3.5"}):e.jsx(jr,{className:"h-3.5 w-3.5"}),a=s.filter(d=>d.mime?.startsWith("image/")&&d.url),c=s.filter(d=>!d.mime?.startsWith("image/")),l=i.useCallback(d=>{if(!r||!d?.url)return;const u=n(d.filename)||"Image",m={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};r(m)},[r]);return s.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:c.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("div",{className:"overflow-hidden max-w-[200px]",children:e.jsx("span",{className:"truncate block",title:n(d.filename),children:n(d.filename)})})]},`file-${u}`))}),a.length>0&&e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-1 scrollbar-thin",children:e.jsx("div",{className:"flex gap-3 snap-x snap-mandatory",children:a.map((d,u)=>{const m=n(d.filename)||"Image";return e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>l(d),className:"relative flex-none w-16 sm:w-20 md:w-24 aspect-square rounded-xl border border-border/40 bg-muted/10 overflow-hidden snap-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[d.url?e.jsx("img",{src:d.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:f=>{const p=f.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(Ar,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(lt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Mp=Ae.memo(({message:t,sessionId:r,onEdit:s})=>{const n=vr(c=>c.removeFromQueue),o=i.useMemo(()=>{const c=t.content.split(`
165
+ `),l=c[0]||"",d=50;return l.length>d?l.substring(0,d)+"...":l+(c.length>1?"...":"")},[t.content]),a=t.attachments?.length??0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta group",children:[e.jsx(Kg,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>s(t),className:"flex items-center gap-1.5 hover:text-foreground transition-colors text-left",title:"Click to edit",children:[e.jsx("span",{className:"truncate max-w-[200px]",children:o||"(empty)"}),a>0&&e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["+",a," file",a>1?"s":""]})]}),e.jsx("button",{type:"button",onClick:()=>n(r,t.id),className:"ml-1 hover:text-destructive p-0.5 opacity-60 group-hover:opacity-100 transition-opacity",title:"Remove from queue",children:e.jsx(es,{className:"h-3 w-3"})})]})});Mp.displayName="QueuedMessageChip";const fu=[],Dp=Ae.memo(({onEditMessage:t})=>{const r=ve(a=>a.currentSessionId),s=vr(i.useCallback(a=>r?a.queuedMessages[r]??fu:fu,[r])),n=vr(a=>a.popToInput),o=i.useCallback(a=>{if(!r)return;const c=n(r,a.id);if(c){if(c.attachments&&c.attachments.length>0){const l=pr.getState().attachedFiles;pr.setState({attachedFiles:[...l,...c.attachments]})}t(c.content,c.attachments)}},[r,n,t]);return s.length===0||!r?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Queued:"}),s.map(a=>e.jsx(Mp,{message:a,sessionId:r,onEdit:o},a.id))]})})});Dp.displayName="QueuedMessageChips";const Wj=i.forwardRef(({searchQuery:t,onFileSelect:r,onClose:s},n)=>{const{currentDirectory:o}=vt(),{addServerFile:a}=ve(),c=wi(I=>I.searchFiles),l=Ti(t,180),d=Go(),u=bi(),[m,f]=i.useState([]),[p,h]=i.useState(!1),[g,x]=i.useState(0),[b,y]=i.useState(360),[v,S]=i.useState({}),[C,N]=i.useState({}),j=i.useRef([]),D=i.useRef([]),k=i.useRef([]),M=i.useRef(null),w=i.useCallback((I,A)=>{const P=I.trim().toLowerCase();if(!P)return 0;const F=A.toLowerCase();let z=0,G=-1,oe=0;for(let O=0;O<P.length;O+=1){const q=P[O];if(!q||q===" ")continue;const Y=F.indexOf(q,G+1);if(Y===-1)return null;const Z=Y-G-1;if(Z===0?oe+=1:oe=0,z+=10,z+=Math.max(0,18-Y),z-=Math.max(0,Z),Y===0)z+=12;else{const B=F[Y-1];(B==="/"||B==="_"||B==="-"||B==="."||B===" ")&&(z+=10)}z+=oe>0?12:0,G=Y}return z+=Math.max(0,24-Math.round(F.length/3)),z},[]);i.useEffect(()=>{const I=A=>{const P=A.target;!P||!M.current||M.current.contains(P)||s()};return document.addEventListener("pointerdown",I,!0),()=>{document.removeEventListener("pointerdown",I,!0)}},[s]),i.useEffect(()=>{if(!o){f([]);return}const A=(l??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();let P=!1;return h(!0),c(o,A,80,{includeHidden:d,respectGitignore:!u}).then(F=>{if(P)return;const z=A?F.map(G=>{const oe=G.relativePath||G.name||G.path,O=w(A,oe);return O===null?null:{file:G,score:O,labelLength:oe.length}}).filter(Boolean):F.map(G=>({file:G,score:0,labelLength:(G.relativePath||G.name||G.path).length}));z.sort((G,oe)=>oe.score-G.score||G.labelLength-oe.labelLength||G.file.path.localeCompare(oe.file.path)),f(z.slice(0,15).map(G=>G.file))}).catch(()=>{P||f([])}).finally(()=>{P||h(!1)}),()=>{P=!0}},[o,l,w,c,d,u]),i.useEffect(()=>{x(0),S({}),N({})},[m]),i.useEffect(()=>{j.current[g]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[g]),i.useEffect(()=>{let I=null;const A=()=>{I!==null&&cancelAnimationFrame(I),I=requestAnimationFrame(()=>{const P={},F={};D.current.forEach((z,G)=>{if(!z)return;const O=k.current[G]?.offsetWidth??z.scrollWidth,q=Math.max(0,O-z.clientWidth),Y=q>8;if(P[G]=Y,Y){const Z=Math.max(.6,q/110);F[G]=Z}}),S(P),N(F)})};return A(),window.addEventListener("resize",A),()=>{I!==null&&cancelAnimationFrame(I),window.removeEventListener("resize",A)}},[m]),i.useEffect(()=>{const I=D.current[g];if(!I)return;const A=()=>{const F=I.clientWidth;F>0&&y(F)};if(A(),typeof ResizeObserver>"u")return;const P=new ResizeObserver(A);return P.observe(I),()=>{P.disconnect()}},[g]);const T=i.useCallback(async I=>{await a(I.path,I.name),r(I)},[a,r]);i.useImperativeHandle(n,()=>({handleKeyDown:I=>{if(I==="Escape"){s();return}const A=m.length;if(A!==0){if(I==="ArrowDown"){x(P=>(P+1)%A);return}if(I==="ArrowUp"){x(P=>(P-1+A)%A);return}if(I==="Enter"||I==="Tab"){const P=(g%A+A)%A,F=m[P];F&&T(F)}}}}),[m,g,s,T]);const E=I=>{switch(I.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(sr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(sr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(jr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Ar,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(fi,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:M,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"px-0",children:p?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(en,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[m.map((I,A)=>{const P=I.relativePath||I.name,F=pf(P,{maxLength:45}),z=g===A,G=v[A]??!1,oe=C[A]??2.6,O=e.jsxs("div",{ref:q=>{j.current[A]=q},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",z&&"bg-muted"),onClick:()=>T(I),onMouseEnter:()=>x(A),children:[E(I),e.jsxs("span",{ref:q=>{D.current[A]=q},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:z?{"--file-mention-marquee-width":`${b}px`,"--file-mention-marquee-duration":`${oe}s`}:void 0,"aria-label":P,children:[e.jsx("span",{ref:q=>{k.current[A]=q},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:P}),G&&z?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:P}):e.jsx("span",{className:"block truncate",children:F})]})]});return e.jsx(i.Fragment,{children:O},I.path)}),m.length>0&&e.jsx("div",{className:"h-2"}),m.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No files found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})}),Ap=i.forwardRef(({searchQuery:t,onCommandSelect:r,onClose:s},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=ve(Un(v=>{const S=v.currentSessionId;return{hasMessagesInCurrentSession:(S?v.messages.get(S)?.length??0:0)>0,currentSessionId:S}})),c=!!a,[l,d]=i.useState([]),[u,m]=i.useState(!1),{commands:f,loadCommands:p}=an(),[h,g]=i.useState(0),x=i.useRef([]),b=i.useRef(null);i.useEffect(()=>{const v=S=>{const C=S.target;!C||!b.current||b.current.contains(C)||s()};return document.addEventListener("pointerdown",v,!0),()=>{document.removeEventListener("pointerdown",v,!0)}},[s]),i.useEffect(()=>{p()},[p]),i.useEffect(()=>{(async()=>{m(!0);try{const S=f.map(M=>({name:M.name,description:M.description,agent:M.agent??void 0,model:M.model??void 0,isBuiltIn:M.name==="init"||M.name==="review",scope:M.scope})),C=[...c&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...c?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],N=new Map;C.forEach(M=>N.set(M.name,M)),S.forEach(M=>N.set(M.name,M));const j=Array.from(N.values()),D=!o,k=(t?j.filter(M=>Xs(M.name,t)||M.description&&Xs(M.description,t)):j).filter(M=>D||M.name!=="init");k.sort((M,w)=>{const T=M.name.toLowerCase().startsWith(t.toLowerCase()),E=w.name.toLowerCase().startsWith(t.toLowerCase());return T&&!E?-1:!T&&E?1:M.name.localeCompare(w.name)}),d(k)}catch{const S=!o,C=[...c&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...c?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],N=(t?C.filter(j=>Xs(j.name,t)||j.description&&Xs(j.description,t)):C).filter(j=>S||j.name!=="init");d(N)}finally{m(!1)}})()},[t,o,c,f]),i.useEffect(()=>{g(0)},[l]),i.useEffect(()=>{x.current[h]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[h]),i.useImperativeHandle(n,()=>({handleKeyDown:v=>{const S=l.length;if(v==="Escape"){s();return}if(S!==0){if(v==="ArrowDown"){g(C=>(C+1)%S);return}if(v==="ArrowUp"){g(C=>(C-1+S)%S);return}if(v==="Enter"||v==="Tab"){const C=(h%S+S)%S,N=l[C];N&&r(N)}}}}),[l,h,s,r]);const y=v=>{switch(v.name){case"init":return e.jsx(jr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(so,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(Yg,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(Cr,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(Qg,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(rn,{className:"h-3.5 w-3.5 text-cyan-500"});default:return v.isBuiltIn?e.jsx(Jg,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(En,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:b,className:"absolute z-[100] min-w-0 w-full max-w-[450px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:u?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(en,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[l.map((v,S)=>{const C=v.isBuiltIn,N=v.scope==="project";return e.jsxs("div",{ref:j=>{x.current[S]=j},className:R("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",S===h&&"bg-muted"),onClick:()=>r(v),onMouseEnter:()=>g(S),children:[e.jsx("div",{className:"mt-0.5",children:y(v)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-medium",children:["/",v.name]}),C?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):v.scope?e.jsx("span",{className:R("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",N?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:v.scope}):null,v.agent&&e.jsx("span",{className:"text-[10px] leading-none font-bold tracking-tight bg-[var(--surface-subtle)] text-[var(--surface-foreground)] border-[var(--interactive-border)] px-1.5 py-1 rounded border flex-shrink-0",children:v.agent})]}),v.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:v.description})]})]},v.name)}),l.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Ap.displayName="CommandAutocomplete";const Uj=t=>t?t!=="primary":!1,Ep=i.forwardRef(({searchQuery:t,onAgentSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,c]=i.useState(0),[l,d]=i.useState([]),u=i.useRef([]),{getVisibleAgents:m}=Je(),{agents:f,loadAgents:p}=cn();i.useEffect(()=>{f.length===0&&p()},[p,f.length]),i.useEffect(()=>{const x=m().filter(v=>Uj(v.mode)).map(v=>{const S=f.find(C=>C.name===v.name);return{name:v.name,description:v.description,mode:v.mode??void 0,scope:S?.scope,isBuiltIn:S?hn(S):!1}}),b=t.trim(),y=b.length?x.filter(v=>Xs(v.name,b)):x;y.sort((v,S)=>v.name.localeCompare(S.name)),d(y),c(0)},[m,t,f]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const g=x=>{const b=x.target;!b||!o.current||o.current.contains(b)||s()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[s]),i.useImperativeHandle(n,()=>({handleKeyDown:g=>{if(g==="Escape"){s();return}if(l.length){if(g==="ArrowDown"){c(x=>(x+1)%l.length);return}if(g==="ArrowUp"){c(x=>(x-1+l.length)%l.length);return}if(g==="Enter"||g==="Tab"){const x=l[(a+l.length)%l.length];x&&r(x.name)}}}}),[l,r,s,a]);const h=(g,x)=>{const b=g.isBuiltIn,y=g.scope==="project";return e.jsx("div",{ref:v=>{u.current[x]=v},className:R("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",x===a&&"bg-muted"),onClick:()=>r(g.name),onMouseEnter:()=>c(x),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-semibold",children:["#",g.name]}),b?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):g.scope?e.jsx("span",{className:R("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",y?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:g.scope}):null]}),g.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:g.description})]})},g.name)};return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.map((g,x)=>h(g,x))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No agents found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Ep.displayName="AgentMentionAutocomplete";const Ip=i.forwardRef(({searchQuery:t,onSkillSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,c]=i.useState(0),[l,d]=i.useState([]),u=i.useRef([]),{skills:m,loadSkills:f}=fr();i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const h=t.trim(),x=[...h.length?m.filter(b=>Xs(b.name,h)):m].sort((b,y)=>b.scope==="project"&&y.scope!=="project"?-1:b.scope!=="project"&&y.scope==="project"?1:b.name.localeCompare(y.name));d(x),c(0)},[m,t]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const h=g=>{const x=g.target;!x||!o.current||o.current.contains(x)||s()};return document.addEventListener("pointerdown",h,!0),()=>{document.removeEventListener("pointerdown",h,!0)}},[s]),i.useImperativeHandle(n,()=>({handleKeyDown:h=>{if(h==="Escape"){s();return}if(l.length){if(h==="ArrowDown"){c(g=>(g+1)%l.length);return}if(h==="ArrowUp"){c(g=>(g-1+l.length)%l.length);return}if(h==="Enter"||h==="Tab"){const g=l[a];g&&r(g.name)}}}}),[l,r,s,a]);const p=(h,g)=>{const x=h.scope==="project";return e.jsx("div",{ref:b=>{u.current[g]=b},className:R("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",g===a&&"bg-muted"),onClick:()=>r(h.name),onMouseEnter:()=>c(g),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold truncate",children:h.name}),e.jsx("span",{className:R("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0 transition-colors",x?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:h.scope})]}),h.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:h.description})]})},`${h.name}-${h.scope}`)};return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.map((h,g)=>p(h,g))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No skills found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Ip.displayName="SkillAutocomplete";function Vj({className:t,children:r,...s}){return e.jsxs(Xg,{"data-slot":"scroll-area",className:R("relative",t),...s,children:[e.jsx(Zg,{"data-slot":"scroll-area-viewport",className:"focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:outline-none focus-visible:ring-[3px] will-change-scroll",children:r}),e.jsx(Gj,{}),e.jsx(ex,{})]})}function Gj({className:t,orientation:r="vertical",...s}){return e.jsx(tx,{"data-slot":"scroll-area-scrollbar",orientation:r,className:R("flex touch-none p-px select-none",r==="vertical"&&"h-full w-2.5 border-l border-l-transparent",r==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",t),...s,children:e.jsx(sx,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const qj=({onFilesSelected:t,multiSelect:r=!1,children:s,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:c}=Gt(),l=c,{currentDirectory:d}=vt(),u=wi(ie=>ie.searchFiles),m=Go(),f=bi(),[p,h]=i.useState(!1),[g,x]=i.useState(0),[b,y]=i.useState(!1),[v,S]=i.useState(""),C=Ti(v,200),[N,j]=i.useState(new Set),[D,k]=i.useState(new Set),[M,w]=i.useState({}),T=i.useRef(new Set),E=i.useRef(new Set),[I,A]=i.useState([]),[P,F]=i.useState(!1),[z,G]=i.useState(!1),[oe,O]=i.useState(!1),[q,Y]=i.useState(null),Z=n??p,B=o??h,W=i.useCallback(ie=>ie.slice().sort((se,re)=>se.type!==re.type?se.type==="directory"?-1:1:se.name.localeCompare(re.name)),[]),te=i.useCallback((ie,se)=>W(se.filter(re=>m||!re.name.startsWith(".")).map(re=>{const ne=re.name,xe=!re.isDirectory&&ne.includes(".")?ne.split(".").pop()?.toLowerCase():void 0;return{name:ne,path:re.path||`${ie}/${ne}`,type:re.isDirectory?"directory":"file",size:0,extension:xe}})),[W,m]),ye=i.useCallback(async ie=>{G(!0),Y(null);try{const se=await Oe.listLocalDirectory(ie,{respectGitignore:!f}),re=te(ie,se.map(ne=>({name:ne.name,path:ne.path,isDirectory:ne.isDirectory})));T.current=new Set([ie]),E.current=new Set,w({[ie]:re}),k(new Set)}catch{Y("Failed to load directory contents"),T.current=new Set([ie]),E.current=new Set,w({[ie]:[]}),k(new Set)}finally{G(!1)}},[te,f]),me=i.useCallback(async ie=>{const se=ie.trim();if(!se)return;const re=`${se}::${g}`;if(!T.current.has(re)&&!E.current.has(re)){E.current=new Set(E.current),E.current.add(re);try{const ne=await Oe.listLocalDirectory(se,{respectGitignore:!f}),xe=te(se,ne.map(Ue=>({name:Ue.name,path:Ue.path,isDirectory:Ue.isDirectory})));T.current=new Set(T.current),T.current.add(re),w(Ue=>({...Ue,[se]:xe}))}catch{w(ne=>ne[se]?ne:{...ne,[se]:[]})}finally{E.current=new Set(E.current),E.current.delete(re)}}},[te,f,g]);i.useEffect(()=>{(Z||b)&&d&&ye(d)},[Z,b,d,ye]),i.useEffect(()=>{x(ie=>ie+1)},[m,f]),i.useEffect(()=>{if(!(Z||b)||!d){A([]),F(!1);return}const ie=C.trim().replace(/^\.\//,"").replace(/^\/+/,"");if(!ie){A([]),F(!1);return}const se=ie.toLowerCase();let re=!1;return F(!0),u(d,se,150,{includeHidden:m,respectGitignore:!f}).then(ne=>{if(re)return;const xe=ne.map(Ue=>({name:Ue.name,path:Ue.path,type:"file",extension:Ue.extension,relativePath:Ue.relativePath,size:0}));A(xe)}).catch(()=>{re||A([])}).finally(()=>{re||F(!1)}),()=>{re=!0}},[Z,b,d,C,u,m,f]),i.useEffect(()=>{!Z&&!b&&(j(new Set),S(""),A([]),F(!1),T.current=new Set,E.current=new Set,w({}),k(new Set))},[Z,b]);const K=ie=>{if(ie.type==="directory")return D.has(ie.path)?e.jsx(lr,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(lr,{className:"h-3.5 w-3.5 text-primary/60"});switch(ie.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(sr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(sr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Zn,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Ar,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Zn,{className:"h-3.5 w-3.5 text-muted-foreground"})}},L=async ie=>{D.has(ie)?k(re=>{const ne=new Set(re);return ne.delete(ie),ne}):(k(re=>{const ne=new Set(re);return ne.add(ie),ne}),await me(ie))},Q=ie=>{j(r?se=>{const re=new Set(se);return re.has(ie)?re.delete(ie):re.add(ie),re}:new Set([ie]))},ce=async()=>{const ie=new Map;Object.values(M).forEach(ne=>{ne.forEach(xe=>{xe.type==="file"&&ie.set(xe.path,xe)})});const se=new Map(I.map(ne=>[ne.path,ne])),re=Array.from(N).map(ne=>ie.get(ne)??se.get(ne)).filter(ne=>!!ne);O(!0);try{await t(re),j(new Set),B(!1),y(!1)}finally{O(!1)}},he=i.useMemo(()=>d?M[d]??[]:[],[M,d]),Ne=v.trim().length>0,H=ie=>M[ie]??[],we=ie=>{if(d&&ie.startsWith(d)){const se=ie.substring(d.length);return se.startsWith("/")?se.substring(1):se}return ie.split("/").pop()||ie},ee=(ie,se)=>{const re=Ne?ie.relativePath||we(ie.path):ie.name,ne=Ne&&re.includes("/")&&re.length>45,xe=ne?pf(re,{maxLength:l?42:48}):re,Ue=e.jsxs("div",{className:R("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded hover:bg-muted cursor-pointer typography-ui-label text-foreground text-left",ie.type==="file"&&N.has(ie.path)&&"bg-primary/10"),style:{paddingLeft:`${se*12}px`},onClick:ze=>{ze.preventDefault(),ze.stopPropagation(),ie.type==="file"&&Q(ie.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:K(ie)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":re,children:xe})]}),ie.type==="file"&&N.has(ie.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return ne?e.jsxs(dt,{delayDuration:120,children:[e.jsx(ut,{asChild:!0,children:Ue}),e.jsx(lt,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:re})})]},ie.path):i.cloneElement(Ue,{key:ie.path})},ue=(ie,se)=>{const re=ie.type==="directory",ne=re?H(ie.path):[],xe=D.has(ie.path),Ue=re&&xe&&E.current.has(ie.path)&&ne.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!re&&N.has(ie.path)&&"bg-primary/10"),style:{paddingLeft:`${se*12}px`},onClick:ze=>{ze.preventDefault(),ze.stopPropagation(),re?L(ie.path):Q(ie.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:K(ie)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:ie.name}),!re&&N.has(ie.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),re&&xe&&ne.length>0&&e.jsx("div",{children:ne.map(ze=>ue(ze,se+1))}),re&&xe&&Ue&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(se+1)*12}px`},children:"Loading…"})]},ie.path)},ge=N.size>0?`${N.size} file${N.size!==1?"s":""} selected`:"No files selected",X=e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 shrink-0",children:[e.jsx("div",{className:"typography-meta text-muted-foreground",children:ge}),e.jsx(Se,{size:"sm",onClick:ce,disabled:N.size===0||oe,className:"h-6 typography-meta",children:oe?"Attaching...":"Attach Files"})]}),de=l?"flex-1 min-h-[240px]":"h-[300px]",ae=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsx("div",{className:"font-medium typography-ui-label text-foreground",children:"Select Project Files"})}),e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{value:v,onChange:ie=>S(ie.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:ie=>ie.stopPropagation()}),v&&e.jsx("button",{onClick:ie=>{ie.stopPropagation(),S("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(es,{className:"h-3 w-3"})})]})}),e.jsxs(Vj,{className:de,children:[z&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Loading files..."})}),q&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:q})}),!z&&!q&&e.jsxs("div",{className:"py-1 px-2",children:[Ne?P?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):I.map(ie=>ee(ie,0)):he.map(ie=>ue(ie,0)),!Ne&&he.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),Ne&&!P&&I.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),fe=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),y(!0)},children:s});return a==="modal"?e.jsxs(e.Fragment,{children:[s?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),B(!0)},children:s}):null,e.jsx(Ws,{open:Z,onClose:()=>B(!1),title:"Select Project Files",footer:X,children:e.jsx("div",{className:"flex flex-col gap-0",children:ae})})]}):l?e.jsxs(e.Fragment,{children:[fe,e.jsx(Ws,{open:b,onClose:()=>y(!1),title:"Select Project Files",footer:X,children:e.jsx("div",{className:"flex flex-col gap-0",children:ae})})]}):e.jsxs(ts,{open:Z,onOpenChange:B,children:[e.jsx(ss,{asChild:!0,children:s}),e.jsxs(rs,{className:R("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[ae,e.jsx(Ds,{}),X]})]})},pa=[{var:"--status-success",class:"agent-success"},{var:"--syntax-keyword",class:"agent-keyword"},{var:"--syntax-type",class:"agent-type"},{var:"--syntax-function",class:"agent-function"},{var:"--syntax-number",class:"agent-number"},{var:"--status-info",class:"agent-info"},{var:"--status-warning",class:"agent-warning"},{var:"--syntax-variable",class:"agent-variable"}];function Kr(t){if(!t||t==="build")return pa[0];let r=0;for(let n=0;n<t.length;n++){const o=t.charCodeAt(n);r=(r<<5)-r+o,r=r&r}const s=1+Math.abs(r)%(pa.length-1);return pa[s]}const Kj=typeof window<"u"?i.useLayoutEffect:i.useEffect,Jj=(t,r=[])=>{const[s,n]=i.useState(!1),o=i.useCallback(()=>{const a=t.current;if(!a)return;const c=a.scrollWidth>a.clientWidth+1;n(c)},[t]);return Kj(()=>{o()},[o,...r]),i.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>{o()});return c.observe(a),()=>c.disconnect()},[o,t]),i.useEffect(()=>{if(typeof window>"u")return;const a=()=>o();return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[o]),s},ha=t=>t==="primary"||t==="all"||t===void 0||t===null,qc=t=>{if(!Array.isArray(t))return null;const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},tc=(t,r)=>{const s=qc(t);if(!(!s||s.length===0)){for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},Qj=[{key:"tool_call",icon:pi,label:"Tool calling",isActive:t=>t?.tool_call===!0},{key:"reasoning",icon:Mr,label:"Reasoning",isActive:t=>t?.reasoning===!0}],Yj={text:{icon:zm,label:"Text"},image:{icon:Ar,label:"Image"},video:{icon:nx,label:"Video"},audio:{icon:rx,label:"Audio"},pdf:{icon:fi,label:"PDF"}},Xj=t=>t.trim().toLowerCase(),So=(t,r)=>{const s=r==="input"?t?.modalities?.input:t?.modalities?.output;return!Array.isArray(s)||s.length===0?[]:Array.from(new Set(s.map(o=>Xj(o)))).map(o=>{const a=Yj[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Zj=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),e0=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),ar=t=>{if(typeof t!="number"||Number.isNaN(t))return"—";if(t===0)return"0";const r=Zj.format(t);return r.endsWith(".0")?r.slice(0,-2):r},ga=t=>typeof t!="number"||!Number.isFinite(t)?"—":e0.format(t),sc=t=>Qj.filter(r=>r.isActive(t)).map(r=>({key:r.key,icon:r.icon,label:r.label})),pu=t=>{if(!t)return"—";const r=t.match(/^(\d{4})-(\d{2})$/);if(r){const s=Number.parseInt(r[1],10),n=Number.parseInt(r[2],10)-1,o=new Date(Date.UTC(s,n,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return t},hu=t=>{if(!t)return"—";const r=new Date(t);return Number.isNaN(r.getTime())?t:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(r)},gu=({className:t})=>{const{providers:r,currentProviderId:s,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:c,setProvider:l,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:h,getCurrentAgent:g,getVisibleAgents:x}=Je(),b=x(),{currentSessionId:y,messages:v,saveSessionAgentSelection:S,saveAgentModelForSession:C,getAgentModelForSession:N,saveAgentModelVariantForSession:j,getAgentModelVariantForSession:D,analyzeAndSaveExternalSessionChoices:k}=ve(),M=Ye(De=>De.hasHydrated),w=Ye(De=>y?De.sessionAgentSelections.get(y)??null:null),T=i.useRef(null);i.useEffect(()=>{if(!y){T.current=null;return}w&&(T.current=w)},[y,w]);const E=y?T.current:null,I=y&&(w||E)||a,A=y??"__global__",P=Ye(De=>{if(I)return De.getSessionAgentEditMode(A,I,"ask")}),F=Ye(De=>De.setSessionAgentEditMode),{toggleFavoriteModel:z,isFavoriteModel:G,addRecentModel:oe,isModelSelectorOpen:O,setModelSelectorOpen:q}=Me(),{favoriteModelsList:Y,recentModelsList:Z}=Fl(),{isMobile:B}=Gt(),W=Gw(),te=Qf(),ye=B,[me,K]=i.useState(null),[L,Q]=i.useState(null),[ce,he]=i.useState(""),Ne=i.useCallback(()=>K(null),[]),H=i.useCallback(()=>Q(null),[]),we=i.useRef(void 0),[ee,ue]=i.useState(()=>{const De=new Set;return s&&De.add(s),De}),ge=O,X=q,[de,ae]=i.useState(""),[fe,ie]=i.useState(0),se=i.useRef([]);i.useEffect(()=>{me==="model"&&ue(()=>{const De=new Set;return s&&De.add(s),De})},[me,s]),i.useEffect(()=>{me!=="model"&&he("")},[me]);const re=i.useRef(ge);i.useEffect(()=>{const De=re.current;re.current=ge,ge||(ae(""),ie(0),De&&!ye&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[ge,ye]),i.useEffect(()=>{ie(0)},[de]);const ne=i.useMemo(()=>I?b.find(De=>De.name===I):g?.(),[b,g,I]),xe=i.useMemo(()=>ne?tc(ne.permission,"edit")??"allow":"deny",[ne]),Ue=!!I,ze=xe==="ask",Ke=ze?P==="allow"||P==="full":xe==="allow",rt=!Ue||!ze,jt=B?"mobile":te?"vscode":"default",Xe=jt==="mobile"?"h-9":jt==="vscode"?"h-6":"h-8",Ct=jt==="mobile"?"h-5 w-5":"h-4 w-4",st=jt==="mobile"?"h-5 w-5":"h-4 w-4",mt=ye?"typography-micro":"typography-meta",Pt=jt==="mobile"||jt==="vscode"?"gap-x-1":"gap-x-3",Ot=i.useCallback((De,Be=Ct)=>{const Le=R(Be,"flex-shrink-0"),Ze=kp(De),ke={color:Ze?Ze.text:"var(--foreground)"};return De==="full"?e.jsx(Fr,{className:Le,style:ke}):De==="allow"?e.jsx(Ca,{className:Le,style:ke}):De==="deny"?e.jsx(to,{className:Le,style:ke}):e.jsx(jn,{className:Le,style:ke})},[Ct]),$e=i.useCallback(De=>{!Ue||!a||!ze||F(A,a,De?"allow":"ask","ask")},[ze,a,Ue,F,A]),be=p(),tt=Array.isArray(be?.models)?be.models:[],Ce=s&&n?h(s,n):void 0,Ie=sc(Ce),Qe=So(Ce,"input"),Te=So(Ce,"output"),Pe=i.useMemo(()=>`${s}/${n}`?m():[],[m,s,n]),Fe=Pe.length>0,Ve=[{label:"Input",value:ga(Ce?.cost?.input)},{label:"Output",value:ga(Ce?.cost?.output)},{label:"Cache read",value:ga(Ce?.cost?.cache_read)},{label:"Cache write",value:ga(Ce?.cost?.cache_write)}],et=[{label:"Context",value:ar(Ce?.limit?.context)},{label:"Output",value:ar(Ce?.limit?.output)}],ot=i.useRef(void 0),yt=y?v.get(y)?.length??-1:-1,Dt=i.useRef(null);i.useEffect(()=>{if(!y)return;const De=Dt.current;!De||De.sessionId!==y||w&&b.some(Be=>Be.name===w)&&(De.resolved=!0,De.inFlight=!1)},[b,y,w]);const bt=i.useCallback((De,Be,Le)=>{if(!De||!Be)return"model-missing";const Ze=r.find(_=>_.id===De);return Ze?(Array.isArray(Ze.models)?Ze.models:[]).find(_=>_.id===Be)?(l(De),d(Be),y&&Le&&C(y,Le,De,Be),"applied"):"model-missing":"provider-missing"},[r,l,d,y,C]);i.useEffect(()=>{if(!y){Dt.current=null;return}if(!M||r.length===0||b.length===0)return;(!Dt.current||Dt.current.sessionId!==y)&&(Dt.current={sessionId:y,resolved:!1,inFlight:!1});const De=Dt.current;if(!De||De.resolved||De.inFlight)return;let Be=!1;const Le=()=>{if(Be)return;const _=Dt.current;_&&_.sessionId===y&&(_.resolved=!0,_.inFlight=!1)},Ze=()=>{const _=y?Ye.getState().getSessionAgentSelection(y)||T.current:null;if(_){a!==_&&f(_);const je=N(y,_);if(je){const le=bt(je.providerId,je.modelId,_);if(le==="applied")return"resolved";if(le==="provider-missing")return"waiting"}else return"resolved"}for(const je of b){const le=N(y,je.name);if(!le)continue;a!==je.name&&f(je.name),Ye.getState().getSessionAgentSelection(y)||T.current||S(y,je.name);const _e=bt(le.providerId,le.modelId,je.name);if(_e==="applied")return"resolved";if(_e==="provider-missing")return"waiting"}return"continue"},nt=()=>{if(b.length===0)return;const _=y?Ye.getState().getSessionAgentSelection(y)||T.current:null,je=(y?Ye.getState().getSessionAgentSelection(y)||T.current:null)||a;if(je&&b.some(_e=>_e.name===je)){a!==je&&f(je);return}const le=b.filter(_e=>ha(_e.mode)),Re=b.find(_e=>_e.name==="build")||le[0]||b[0];Re&&(_||S(y,Re.name),a!==Re.name&&f(Re.name),Re.model?.providerID&&Re.model?.modelID&&bt(Re.model.providerID,Re.model.modelID,Re.name))};return(async()=>{try{const _=Ze();if(_==="resolved"){Le();return}if(_==="waiting"||yt===-1)return;if(yt>0){De.inFlight=!0;try{const je=await k(y,b);if(Be)return;if(je.size>0){let le=null,Re=-1/0;for(const[_e,We]of je)We.timestamp>Re&&(Re=We.timestamp,le=_e);if(le){const _e=Ye.getState().getSessionAgentSelection(y)||T.current;if(_e&&_e!==le){Le();return}_e||S(y,le),a!==le&&f(le);const We=je.get(le);if(We){const qe=bt(We.providerId,We.modelId,le);if(qe==="applied"){Le();return}if(qe==="provider-missing")return}else{Le();return}}}}catch(je){Be||console.error("[ModelControls] Error resolving session from messages:",je)}finally{const je=Dt.current;!Be&&je&&je.sessionId===y&&(je.inFlight=!1)}}if(Be)return;nt(),Le()}catch(_){Be||console.error("[ModelControls] Error in session switch:",_)}})(),()=>{Be=!0}},[y,yt,b,a,N,f,bt,k,S,M,r,w]),i.useEffect(()=>{if(!M||!y||r.length===0||b.length===0)return;const De=w||a;if(!De)return;const Be=N(y,De);if(!Be)return;const Le=r.find(_=>_.id===Be.providerId);if(!Le||!(Array.isArray(Le.models)?Le.models.some(_=>_.id===Be.modelId):!1))return;const nt=s===Be.providerId,ke=n===Be.modelId;nt&&ke||(De!==a&&f(De),bt(Be.providerId,Be.modelId,De))},[M,y,a,s,n,r,b,N,bt,f,w]),i.useEffect(()=>{if(!M)return;(async()=>{try{if(a!==ot.current&&(ot.current=a,a&&y)){await new Promise(Ze=>setTimeout(Ze,50));const Be=N(y,a);if(Be){const Ze=bt(Be.providerId,Be.modelId,a);if(Ze==="applied"||Ze==="provider-missing")return}const Le=b.find(Ze=>Ze.name===a);if(Le?.model?.providerID&&Le?.model?.modelID&&bt(Le.model.providerID,Le.model.modelID,a)==="provider-missing")return}}catch(Be){console.error("[ModelControls] Agent change error:",Be)}})()},[a,y,N,bt,b,M]),i.useEffect(()=>{if(!M||!a){u(void 0);return}if(!s||!n){u(void 0);return}if(Pe.length===0){u(void 0);return}if(o&&!Pe.includes(o)){u(void 0);return}if(!y){if(!o){const Le=c&&Pe.includes(c)?c:void 0;u(Le)}return}const De=D(y,a,s,n),Be=De&&Pe.includes(De)?De:void 0;u(Be)},[Pe,M,y,a,s,n,o,D,u,c]);const Qt=i.useCallback(De=>{u(De),y&&a&&s&&n&&j(y,a,s,n,De)},[a,n,s,y,j,u]),Vt=De=>{try{f(De),X(!1),y&&S(y,De),ye&&Ne()}catch(Be){console.error("[ModelControls] Handle agent change error:",Be)}},Ft=(De,Be)=>{try{const Le=bt(De,Be,a||void 0);if(Le!=="applied"){Le==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",De):Le==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:De,modelId:Be});return}oe(De,Be),X(!1),ye&&Ne(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(Le){console.error("[ModelControls] Handle model change error:",Le)}},Kt=De=>{const Be=typeof De?.name=="string"?De.name:typeof De?.id=="string"?De.id:"";return Be.length>40?Be.substring(0,37)+"...":Be},Rt=()=>r.find(Be=>Be.id===s)?.name||s,cs=()=>{if(!s||!n||tt.length===0)return"Not selected";const De=tt.find(Be=>Be.id===n);return Kt(De)},Ns=cs(),bs=i.useRef(null),Cs=Jj(bs,[Ns,ye]),Ms=()=>{if(!I){const Be=b.filter(nt=>ha(nt.mode)),Ze=Be.find(nt=>nt.name==="build")||Be[0];return Ze?ps(Ze.name):"Select Agent"}const De=b.find(Be=>Be.name===I);return ps(De?De.name:I)},ps=De=>De.charAt(0).toUpperCase()+De.slice(1),Xt=(De,Be,Le)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:Be,"aria-label":Be,role:"img",children:e.jsx(De,{className:"h-3.5 w-3.5"})},Le),$=i.useCallback(De=>{ue(Be=>{const Le=new Set(Be);return Le.has(De)?Le.delete(De):Le.add(De),Le})},[]),U=i.useCallback(De=>{we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{Q(De)},500)},[]),J=i.useCallback(()=>{we.current&&clearTimeout(we.current)},[]);i.useEffect(()=>()=>{we.current&&clearTimeout(we.current)},[]);const pe=()=>!ye||L!=="model"?null:e.jsx(Ws,{open:!0,onClose:H,title:Ce?.name||cs(),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:Rt()})]}),Ie.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Capabilities"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ie.map(({key:De,icon:Be,label:Le})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Xt(Be,Le,`cap-${De}`),e.jsx("span",{className:"typography-meta text-foreground",children:Le})]},De))})]}),(Qe.length>0||Te.length>0)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[Qe.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Input"}),e.jsx("div",{className:"flex gap-1",children:Qe.map(({key:De,icon:Be,label:Le})=>Xt(Be,`${Le} input`,`input-${De}`))})]}),Te.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Output"}),e.jsx("div",{className:"flex gap-1",children:Te.map(({key:De,icon:Be,label:Le})=>Xt(Be,`${Le} output`,`output-${De}`))})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ar(Ce?.limit?.context)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Output"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ar(Ce?.limit?.output)})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Metadata"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Knowledge"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:pu(Ce?.knowledge)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Release"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:hu(Ce?.release_date)})]})]})]})]})}),Ee=()=>{if(!ye||L!=="agent"||!ne)return null;const De=!!(ne.prompt&&ne.prompt.trim().length>0),Be=ne.model?.providerID&&ne.model?.modelID,Le=ne.temperature!==void 0||ne.topP!==void 0,Ze=je=>{const le=qc(ne.permission)??[],Re=le.some(We=>We.permission===je&&We.pattern!=="*"),_e=tc(le,je)??"ask";return Re?{mode:"ask",label:"Custom"}:_e==="allow"?{mode:"allow",label:"Allow"}:_e==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},nt=Ze("edit"),ke=Ze("bash"),_=Ze("webfetch");return e.jsx(Ws,{open:!0,onClose:H,title:ps(ne.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[ne.description&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsx("div",{className:"typography-meta text-foreground",children:ne.description})}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Mode"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:ne.mode==="primary"?"Primary":ne.mode==="subagent"?"Subagent":ne.mode==="all"?"All":"—"})]}),(Be||Le)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Model"}),Be&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[ne.model.providerID," / ",ne.model.modelID]}),Le&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[ne.temperature!==void 0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Temperature"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ne.temperature})]}),ne.topP!==void 0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Top P"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ne.topP})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Permissions"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ot(nt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:nt.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ot(ke.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ke.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ot(_.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:_.label})]})]})]})]}),De&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(Ca,{className:"h-4 w-4 text-foreground"})]})})]})})},He=()=>{if(!ye)return null;const De=ce.trim(),Be=r.map(Le=>{const Ze=Array.isArray(Le.models)?Le.models:[],nt=De.length===0?!0:Xs(Le.name,De)||Xs(Le.id,De),ke=De.length===0?Ze:Ze.filter(_=>{const je=Kt(_),le=typeof _.id=="string"?_.id:"";return Xs(je,De)||Xs(le,De)});return{provider:Le,providerModels:ke,matchesProvider:nt}}).filter(({matchesProvider:Le,providerModels:Ze})=>Le||Ze.length>0);return e.jsx(Ws,{open:me==="model",onClose:Ne,title:"Select model",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{value:ce,onChange:Le=>he(Le.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),ce&&e.jsx("button",{type:"button",onClick:()=>he(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(to,{className:"h-4 w-4"})})]})}),Be.length===0&&e.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),!ce&&Y.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(Rr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Y.map(({model:Le,providerID:Ze,modelID:nt})=>{const ke=Ze===s&&nt===n,_=h(Ze,nt);return e.jsxs("button",{type:"button",onClick:()=>Ft(Ze,nt),className:R("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",ke?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(gs,{providerId:Ze,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Kt(Le)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(_?.limit?.context||_?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[_?.limit?.context?`${ar(_?.limit?.context)} ctx`:"",_?.limit?.context&&_?.limit?.output?" • ":"",_?.limit?.output?`${ar(_?.limit?.output)} out`:""]})})]},`fav-mobile-${Ze}-${nt}`)})})]}),!ce&&Z.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(Cr,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Z.map(({model:Le,providerID:Ze,modelID:nt})=>{const ke=Ze===s&&nt===n,_=h(Ze,nt);return e.jsxs("button",{type:"button",onClick:()=>Ft(Ze,nt),className:R("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",ke?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(gs,{providerId:Ze,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Kt(Le)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(_?.limit?.context||_?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[_?.limit?.context?`${ar(_?.limit?.context)} ctx`:"",_?.limit?.context&&_?.limit?.output?" • ":"",_?.limit?.output?`${ar(_?.limit?.output)} out`:""]})})]},`recent-mobile-${Ze}-${nt}`)})})]}),Be.map(({provider:Le,providerModels:Ze})=>{if(Ze.length===0&&!De.length)return null;const nt=Le.id===s,ke=ee.has(Le.id)||De.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>$(Le.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":ke,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{providerId:Le.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Le.name}),nt&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),ke?e.jsx(Wt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(tr,{className:"h-3 w-3 text-muted-foreground"})]}),ke&&Ze.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Ze.map(_=>{const je=nt&&_.id===n,le=h(Le.id,_.id),Re=sc(le).slice(0,3),_e=So(le,"input");return e.jsxs("div",{className:R("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 last:border-b-0","rounded-lg transition-colors",!je&&"hover:bg-muted",je?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>Ft(Le.id,_.id),className:R("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary"),children:[e.jsx("div",{className:"flex min-w-0 flex-col",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Kt(_)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(le?.limit?.context||le?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[le?.limit?.context?e.jsxs("span",{children:[ar(le?.limit?.context)," ctx"]}):null,le?.limit?.context&&le?.limit?.output?e.jsx("span",{children:"•"}):null,le?.limit?.output?e.jsxs("span",{children:[ar(le?.limit?.output)," out"]}):null]}),(Re.length>0||_e.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Re,..._e].map(({key:We,icon:qe,label:it})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:it,"aria-label":it,children:e.jsx(qe,{className:"h-3 w-3"})},`meta-${Le.id}-${_.id}-${We}`))})]})]}),e.jsx("button",{type:"button",onClick:We=>{We.preventDefault(),We.stopPropagation(),z(Le.id,_.id)},className:R("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",G(Le.id,_.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":G(Le.id,_.id)?"Unfavorite":"Favorite",title:G(Le.id,_.id)?"Remove from favorites":"Add to favorites",children:G(Le.id,_.id)?e.jsx(Rr,{className:"h-4 w-4"}):e.jsx(Jn,{className:"h-4 w-4"})})]},_.id)})})]},Le.id)})]})})},ft=()=>{if(!ye||!Fe)return null;const De=!o,Be=Le=>{Qt(Le),Ne(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(Ws,{open:me==="variant",onClose:Ne,title:"Thinking",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",De?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>Be(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),De&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),Pe.map(Le=>{const Ze=o===Le,nt=Le.charAt(0).toUpperCase()+Le.slice(1);return e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",Ze?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>Be(Le),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:nt}),Ze&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},Le)})]})})},pt=()=>{if(!ye)return null;const De=b.filter(Be=>ha(Be.mode));return e.jsx(Ws,{open:me==="agent",onClose:Ne,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[De.map(Be=>{const Le=Be.name===I,Ze=Kr(Be.name);return e.jsxs("button",{type:"button",className:R("flex w-full flex-col gap-1 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary agent-list-item",Ze.class,Le?"active":"border-border/40"),onClick:()=>Vt(Be.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:R("h-2 w-2 rounded-full",Ze.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:Le?{color:`var(${Ze.var})`}:void 0,children:ps(Be.name)})]}),Be.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:Be.description})]},Be.name)}),e.jsx("div",{className:"rounded-xl bg-transparent",children:e.jsxs("div",{className:"flex items-center justify-between px-2 py-2",children:[e.jsx("span",{className:R("typography-meta font-medium",rt?"text-muted-foreground":"text-foreground"),children:"Auto-approve edits"}),e.jsx(bn,{checked:Ke,disabled:rt,onCheckedChange:$e})]})})]})})},wt=()=>e.jsx(lt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ce?e.jsxs("div",{className:"flex min-w-[240px] flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-micro font-semibold text-foreground",children:Ce.name||cs()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:Rt()})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Capabilities"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:Ie.length>0?Ie.map(({key:De,icon:Be,label:Le})=>Xt(Be,Le,`cap-${De}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Input"}),e.jsx("div",{className:"flex items-center gap-1.5",children:Qe.length>0?Qe.map(({key:De,icon:Be,label:Le})=>Xt(Be,`${Le} input`,`input-${De}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),e.jsx("div",{className:"flex items-center gap-1.5",children:Te.length>0?Te.map(({key:De,icon:Be,label:Le})=>Xt(Be,`${Le} output`,`output-${De}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Cost ($/1M tokens)"}),Ve.map(De=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:De.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:De.value})]},De.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),et.map(De=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:De.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:De.value})]},De.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Metadata"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Knowledge"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:pu(Ce.knowledge)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Release"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:hu(Ce.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),at=(De,Be,Le,Ze,nt,ke)=>{const _=h(Be,Le),je=sc(_).map(ct=>({...ct,id:`cap-${ct.key}`})),le=[...So(_,"input"),...So(_,"output")],Re=Array.from(new Map(le.map(ct=>[ct.key,ct])).values()).map(ct=>({...ct,id:`mod-${ct.key}`})),_e=[...je,...Re],We=ar(_?.limit?.context),qe=s===Be&&n===Le,it=G(Be,Le),It=Ze==="fav"||Ze==="recent";return e.jsxs("div",{ref:ct=>{se.current[nt]=ct},className:R("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",ke?"bg-accent":"hover:bg-accent/50"),onClick:()=>Ft(Be,Le),onMouseEnter:()=>ie(nt),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[It&&e.jsx(gs,{providerId:Be,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Kt(De)}),_?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:We}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[_e.length>0&&e.jsx("div",{className:R("items-center gap-0.5",ke?"flex":"hidden group-hover:flex"),children:_e.map(({id:ct,icon:Zt,label:gr})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":gr,role:"img",title:gr,children:e.jsx(Zt,{className:"h-2.5 w-2.5"})},ct))}),qe&&e.jsx(Tt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:ct=>{ct.preventDefault(),ct.stopPropagation(),z(Be,Le)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",it?"text-yellow-500":"text-muted-foreground"),"aria-label":it?"Unfavorite":"Favorite",title:it?"Remove from favorites":"Add to favorites",children:it?e.jsx(Rr,{className:"h-3.5 w-3.5"}):e.jsx(Jn,{className:"h-3.5 w-3.5"})})]})]},`${Ze}-${Be}-${Le}`)},_t=(De,Be,Le)=>Le.trim()?Xs(De,Le)||Xs(Be,Le):!0,qt=()=>{const De=Y.filter(({model:le,providerID:Re})=>{const We=r.find(it=>it.id===Re)?.name||Re,qe=Kt(le);return _t(qe,We,de)}),Be=Z.filter(({model:le,providerID:Re})=>{const We=r.find(it=>it.id===Re)?.name||Re,qe=Kt(le);return _t(qe,We,de)}),Le=r.map(le=>{const _e=(Array.isArray(le.models)?le.models:[]).filter(We=>{const qe=Kt(We);return _t(qe,le.name||le.id||"",de)});return{...le,models:_e}}).filter(le=>le.models.length>0),Ze=De.length>0||Be.length>0||Le.length>0,nt=[];De.forEach(({model:le,providerID:Re,modelID:_e})=>{nt.push({model:le,providerID:Re,modelID:_e,section:"fav"})}),Be.forEach(({model:le,providerID:Re,modelID:_e})=>{nt.push({model:le,providerID:Re,modelID:_e,section:"recent"})}),Le.forEach(le=>{le.models.forEach(Re=>{nt.push({model:Re,providerID:le.id,modelID:Re.id,section:"provider"})})});const ke=nt.length,_=le=>{if(le.key==="ArrowDown")le.preventDefault(),le.stopPropagation(),ie(Re=>(Re+1)%Math.max(1,ke)),setTimeout(()=>{const Re=(fe+1)%Math.max(1,ke);se.current[Re]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(le.key==="ArrowUp")le.preventDefault(),le.stopPropagation(),ie(Re=>(Re-1+Math.max(1,ke))%Math.max(1,ke)),setTimeout(()=>{const Re=(fe-1+Math.max(1,ke))%Math.max(1,ke);se.current[Re]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(le.key==="Enter"){le.preventDefault(),le.stopPropagation();const Re=nt[fe];Re&&Ft(Re.providerID,Re.modelID)}else le.key==="Escape"&&(le.preventDefault(),le.stopPropagation(),X(!1))};let je=0;return e.jsxs(dt,{delayDuration:1e3,children:[ye?e.jsxs("button",{type:"button",onClick:()=>K("model"),onTouchStart:()=>U("model"),onTouchEnd:J,onTouchCancel:J,className:R("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",Xe),children:[s?e.jsx(gs,{providerId:s,className:R(st,"flex-shrink-0")}):e.jsx(Fr,{className:R(st,"text-muted-foreground")}),e.jsx("span",{ref:bs,className:R("model-controls__model-label typography-micro font-medium overflow-hidden min-w-0",B?"max-w-[120px]":"max-w-[220px]"),children:e.jsx("span",{className:R("marquee-text",Cs&&"marquee-text--active"),children:Ns})})]}):e.jsxs(ts,{open:ge,onOpenChange:X,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:R("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",Xe),children:[s?e.jsxs(e.Fragment,{children:[e.jsx(gs,{providerId:s,className:R(st,"flex-shrink-0")}),e.jsx(Fr,{className:R(st,"text-primary/60 hidden")})]}):e.jsx(Fr,{className:R(st,"text-muted-foreground")}),e.jsx("span",{ref:bs,className:R("model-controls__model-label overflow-hidden",mt,"font-medium whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:e.jsx("span",{className:R("marquee-text",Cs&&"marquee-text--active"),children:Ns})},`${s}-${n}`)]})})}),e.jsxs(rs,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{type:"text",placeholder:"Search models",value:de,onChange:le=>ae(le.target.value),onKeyDown:_,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(xt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!Ze&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),De.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Lr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Rr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),De.map(({model:le,providerID:Re,modelID:_e})=>{const We=je++;return at(le,Re,_e,"fav",We,fe===We)})]}),Be.length>0&&e.jsxs(e.Fragment,{children:[De.length>0&&e.jsx(Ds,{}),e.jsxs(Lr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Cr,{className:"h-4 w-4"}),"Recent"]}),Be.map(({model:le,providerID:Re,modelID:_e})=>{const We=je++;return at(le,Re,_e,"recent",We,fe===We)})]}),(De.length>0||Be.length>0)&&Le.length>0&&e.jsx(Ds,{}),Le.map((le,Re)=>e.jsxs(i.Fragment,{children:[Re>0&&e.jsx(Ds,{}),e.jsxs(Lr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(gs,{providerId:le.id,className:"h-4 w-4 flex-shrink-0"}),le.name]}),le.models.map(_e=>{const We=je++;return at(_e,le.id,_e.id,"provider",We,fe===We)})]},le.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})]}),wt()]})},ht=()=>{if(!ne)return e.jsx(lt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"No agent selected."})});const De=!!(ne.prompt&&ne.prompt.trim().length>0),Be=ne.model?.providerID&&ne.model?.modelID,Le=ne.temperature!==void 0||ne.topP!==void 0,Ze=je=>{const le=qc(ne.permission)??[],Re=le.some(We=>We.permission===je&&We.pattern!=="*"),_e=tc(le,je)??"ask";return Re?{mode:"ask",label:"Custom"}:_e==="allow"?{mode:"allow",label:"Allow"}:_e==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},nt=Ze("edit"),ke=Ze("bash"),_=Ze("webfetch");return e.jsx(lt,{align:"start",sideOffset:8,className:"max-w-[280px]",children:e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-2.5",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-micro font-semibold text-foreground",children:ps(ne.name)}),ne.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:ne.description})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Mode"}),e.jsx("span",{className:"typography-meta text-foreground",children:ne.mode==="primary"?"Primary":ne.mode==="subagent"?"Subagent":ne.mode==="all"?"All":"—"})]}),(Be||Le)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Model"}),Be?e.jsxs("span",{className:"typography-meta text-foreground",children:[ne.model.providerID," / ",ne.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),Le&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[ne.temperature!==void 0&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Temperature"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ne.temperature})]}),ne.topP!==void 0&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Top P"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ne.topP})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Permissions"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ot(nt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:nt.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ot(ke.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:ke.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ot(_.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:_.label})]})]})]}),De&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(Ca,{className:"h-4 w-4 text-foreground"})]})]})})},Et=()=>{if(!Fe)return null;const De=o??"Default",Be=!o,Le=Be?"text-muted-foreground":"text-[color:var(--status-info)]";return ye?e.jsxs("button",{type:"button",onClick:()=>K("variant"),className:R("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Xe,"cursor-pointer hover:opacity-70"),children:[e.jsx(Mr,{className:R(st,"flex-shrink-0",Le)}),e.jsx("span",{className:R("model-controls__variant-label",mt,"font-medium truncate min-w-0",B&&"max-w-[60px]",Le),children:De})]}):e.jsxs(dt,{delayDuration:800,children:[e.jsxs(ts,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:R("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Xe),children:[e.jsx(Mr,{className:R(st,"flex-shrink-0",Le)}),e.jsx("span",{className:R("model-controls__variant-label",mt,"font-medium min-w-0 truncate",W?"max-w-[180px]":void 0,Le),children:De})]})})}),e.jsxs(rs,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Lr,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(kt,{className:"typography-meta",onSelect:()=>Qt(void 0),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:"Default"}),Be&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),Pe.length>0&&e.jsx(Ds,{}),Pe.map(Ze=>{const nt=o===Ze,ke=Ze.charAt(0).toUpperCase()+Ze.slice(1);return e.jsx(kt,{className:"typography-meta",onSelect:()=>Qt(Ze),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:ke}),nt&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},Ze)})]})]}),e.jsx(lt,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",De]})})]})},Jt=()=>ye?e.jsxs("button",{type:"button",onClick:()=>K("agent"),onTouchStart:()=>U("agent"),onTouchEnd:J,onTouchCancel:J,className:R("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Xe,"cursor-pointer hover:opacity-70"),children:[e.jsx(Sn,{className:R(st,"flex-shrink-0",I?"":"text-muted-foreground"),style:I?{color:`var(${Kr(I).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",mt,"font-medium truncate min-w-0",B&&"max-w-[60px]"),style:I?{color:`var(${Kr(I).var})`}:void 0,children:Ms()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(dt,{delayDuration:1e3,children:[e.jsxs(ts,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Xe),children:[e.jsx(Sn,{className:R(st,"flex-shrink-0",I?"":"text-muted-foreground"),style:I?{color:`var(${Kr(I).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",mt,"font-medium min-w-0 truncate",W?"max-w-[220px]":void 0),style:I?{color:`var(${Kr(I).var})`}:void 0,children:Ms()})]})})}),e.jsxs(rs,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[b.filter(De=>ha(De.mode)).map(De=>e.jsx(kt,{className:"typography-meta",onSelect:()=>Vt(De.name),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:R("h-1 w-1 rounded-full agent-dot",Kr(De.name).class)}),e.jsx("span",{className:"font-medium",children:ps(De.name)})]}),De.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:De.description})]})},De.name)),e.jsx(Ds,{}),e.jsx("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:e.jsx("div",{className:"rounded-xl bg-transparent",children:e.jsxs("div",{className:"flex items-center justify-between px-2 py-2",children:[e.jsx("span",{className:R("typography-meta font-medium",rt?"text-muted-foreground":"text-foreground"),children:"Auto-approve edits"}),e.jsx(bn,{checked:Ke,disabled:rt,onCheckedChange:$e})]})})})]})]}),ht()]})}),Js=R("@container/model-controls flex items-center min-w-0",B&&"w-full",t);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:Js,children:e.jsxs("div",{className:R("flex items-center min-w-0 flex-1 justify-end",Pt,B&&"overflow-hidden"),children:[Et(),qt(),Jt()]})}),He(),ft(),pt(),pe(),Ee()]})},t0=t=>t?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(t):!0,xu=(t,r)=>{if(typeof t!="string"||t.length===0)return{sanitizedText:t,mention:null};const s=r.filter(o=>o.mode&&o.mode!=="primary");if(s.length===0||!t.includes("#"))return{sanitizedText:t,mention:null};let n=null;for(const o of s){const a=new RegExp(`#${o.name}\\b`,"gi");let c;for(;(c=a.exec(t))!==null;){const l=c.index,d=l+c[0].length,u=l>0?t[l-1]:null;if(!t0(u))continue;const m={name:o.name,source:{value:c[0],start:l,end:d}};n||(n=m)}}return n?{sanitizedText:t,mention:n}:{sanitizedText:t,mention:null}},Pp=t=>({id:t.id,content:t.content,status:t.status||"pending",priority:t.priority||"medium"}),Kc=ns()(fs((t,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async s=>{if(s){t({isLoading:!0});try{const n=ve.getState().getDirectoryForSession(s),a=(n?await Oe.withDirectory(n,()=>Oe.getSessionTodos(s)):await Oe.getSessionTodos(s)).map(Pp);t(c=>{const l=new Map(c.sessionTodos);return l.set(s,a),{sessionTodos:l,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),t({isLoading:!1})}}},updateTodos:(s,n)=>{t(o=>{const a=new Map(o.sessionTodos);return a.set(s,n),{sessionTodos:a}})},getTodosForSession:s=>r().sessionTodos.get(s)||[],clearTodos:s=>{t(n=>{const o=new Map(n.sessionTodos);return o.delete(s),{sessionTodos:o}})}}),{name:"todo-store"})),s0=(t,r)=>{const s=r.map(Pp);Kc.getState().updateTodos(t,s)},yu=[{variant:"shine",component:({children:t,className:r,...s})=>e.jsx(Hn.span,{...s,className:R("bg-[linear-gradient(110deg,#bfbfbf,35%,#000,50%,#bfbfbf,75%,#bfbfbf)] dark:bg-[linear-gradient(110deg,#404040,35%,#fff,50%,#404040,75%,#404040)]","bg-[length:200%_100%] bg-clip-text text-transparent",r),initial:{backgroundPosition:"200% 0"},animate:{backgroundPosition:"-200% 0"},transition:{repeat:Number.POSITIVE_INFINITY,duration:2,ease:"linear"},children:t})},{variant:"generate-effect",component:({children:t,className:r,...s})=>typeof t!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:t.split("").map((n,o)=>Ae.createElement(Hn.span,{...s,key:n+String(o),className:R("inline-block whitespace-pre text-primary-foreground",r),initial:{opacity:0,filter:"blur(4px)",rotateX:90,y:5},whileInView:{opacity:1,filter:"blur(0px)",rotateX:0,y:0},transition:{ease:"easeOut",duration:.3,delay:o*.015},viewport:{once:!0}},n))})},{variant:"glitch",component:({children:t,className:r,...s})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...s,className:R("invisible",r),children:t}),e.jsx("span",{...s,className:R("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",r),children:t}),e.jsx("span",{...s,className:R("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",r),children:t})]})},{variant:"hover-enter",component:({children:t,className:r,...s})=>{if(typeof t!="string")return null;const n=.25,o=.025,a=t.split("").map(c=>c===" "?" ":c);return e.jsxs(Hn.span,{...s,className:R("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",r),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((c,l)=>e.jsx(Hn.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:c},String(l)))}),e.jsx("div",{className:R("absolute inset-0"),children:a.map((c,l)=>e.jsx(Hn.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:c},String(l)))})]})}},{variant:"shake",component:({children:t,className:r,...s})=>e.jsx("span",{...s,className:R("text-primary-muted hover:animate-text-shake",r),children:t})},{variant:"hover-decoration",component:({children:t,className:r,...s})=>e.jsx("div",{className:R("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:e.jsx("span",{...s,className:R("text-primary-muted",r),children:t})})}];function rc({variant:t="shine",className:r,...s}){const a=yu.find(c=>c.variant===t)?.component||yu[0].component;return e.jsx(Om,{children:e.jsx(a,{...s,className:r})})}const bu=1500,r0=2e3;function n0({statusText:t,isGenericStatus:r,isWaitingForPermission:s,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:c}){const[l,d]=Ae.useState("idle"),[u,m]=Ae.useState(null),[f,p]=Ae.useState(!1),h=Ae.useRef(0),g=Ae.useRef(null),x=Ae.useRef(null),b=Ae.useRef(null),y=Ae.useRef(null),v=Ae.useRef(!1),S=Ae.useRef(!1),C=Ae.useRef(!1),N=Ae.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null),b.current&&(clearTimeout(b.current),b.current=null)},[]),j=Ae.useCallback((I,A)=>{N(),g.current=null,m(I),p(A),d("showing"),h.current=Date.now(),v.current=!0},[N]),D=Ae.useCallback(()=>{if(x.current)return;const I=Date.now()-h.current,A=Math.max(0,bu-I);x.current=setTimeout(()=>{x.current=null;const P=g.current;P&&j(P.text,P.permission)},A)},[j]),k=Ae.useCallback(I=>{if(N(),g.current=null,!v.current){d("idle"),m(null),c?.(!1);return}if(I==="done"&&o&&y.current===o){d("idle"),m(null),v.current=!1,c?.(!1);return}I==="done"&&o&&(y.current=o),d(I),m(null),c?.(!0),b.current=setTimeout(()=>{b.current=null,d("idle"),v.current=!1,c?.(!1)},r0)},[N,o,c]);if(Ae.useEffect(()=>{if(n&&!C.current){C.current=!0,k("aborted");return}if(C.current=!!n,a&&!S.current){S.current=!0,k("done");return}if(!a&&S.current&&(S.current=!1),!(l==="done"||l==="aborted")&&t){const A=Date.now()-h.current;if(l==="idle"||!u)j(t,!!s);else if(t!==u||!!s!==f){if(r)return;A>=bu?j(t,!!s):(g.current={text:t,permission:!!s},D())}}},[t,s,n,a,l,u,f,j,k,D,r]),Ae.useEffect(()=>()=>N(),[N]),Ae.useEffect(()=>{const I=()=>{typeof document>"u"||document.visibilityState==="visible"&&(l==="done"||l==="aborted")&&(N(),d("idle"),m(null),v.current=!1)};return document.addEventListener("visibilitychange",I),()=>document.removeEventListener("visibilitychange",I)},[l,N]),l==="idle"&&!u)return null;let M,w=!0;l==="done"?(M="Done",w=!1):l==="aborted"?(M="Aborted",w=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const T=w?`${M}...`:M,E=l!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${E?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":M,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:l==="done"?e.jsx(rc,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):l==="aborted"?e.jsx(rc,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(rc,{variant:"shine",className:"typography-ui-header",children:T})})})}const wu={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},o0=({todo:t})=>{const r=wu[t.status]||wu.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:R("flex-1 typography-ui-label",r.textClassName),children:t.content})})},vu=[],a0=({isWorking:t,statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:c,isComplete:l,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=i.useState(!1),h=ve(A=>A.currentSessionId),g=Kc(A=>h?A.sessionTodos.get(h)??vu:vu),x=Kc(A=>A.loadTodos),{isMobile:b}=Me(),y=b||zt();i.useEffect(()=>{h&&x(h)},[h,x]);const v=i.useMemo(()=>{const A={in_progress:0,pending:1,completed:2,cancelled:3};return[...g].filter(P=>P.status!=="cancelled").sort((P,F)=>A[P.status]-A[F.status])},[g]),S=i.useMemo(()=>v.find(A=>A.status==="in_progress")||v.find(A=>A.status==="pending")||null,[v]),C=i.useMemo(()=>{const A=g.filter(F=>F.status!=="cancelled").length;return{completed:g.filter(F=>F.status==="completed").length,total:A}},[g]),N=v.some(A=>A.status==="in_progress"||A.status==="pending"),j=!m&&(o||!a),[D,k]=i.useState(!1),M=t||l||o||D||N||m,w=i.useRef(null);if(i.useEffect(()=>{if(!f)return;const A=P=>{w.current&&!w.current.contains(P.target)&&p(!1)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[f]),!M)return null;const T=()=>p(A=>!A),E=d&&u?e.jsx("button",{type:"button",onClick:u,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:e.jsx(to,{size:18,"aria-hidden":"true"})}):null,I=N?e.jsxs("button",{type:"button",onClick:T,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!y&&S?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:S.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[C.completed,"/",C.total]}),f?e.jsx(mi,{className:"h-3.5 w-3.5"}):e.jsx(Wt,{className:"h-3.5 w-3.5"})]}):null;return e.jsx("div",{className:"chat-column mb-1",style:{containerType:"inline-size"},children:e.jsxs("div",{className:"flex items-center justify-between pr-[2ch] py-0.5 gap-2 h-[1.2rem]",children:[e.jsx("div",{className:"flex-1 flex items-center overflow-hidden min-w-0",children:m?e.jsx("div",{className:"flex h-full items-center text-[var(--status-error)] pl-[2ch]",children:e.jsxs("span",{className:"flex items-center gap-1.5 typography-ui-label",children:[e.jsx(to,{size:16,"aria-hidden":"true"}),"Aborted"]})}):j?e.jsx(n0,{statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,completionId:c??null,isComplete:l,onResultVisibilityChange:k},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:w,children:[E,I,f&&N&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:R("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px]","rounded-xl border border-border bg-background shadow-md","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"Tasks"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[C.completed,"/",C.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:v.map(A=>e.jsx(o0,{todo:A},A.id))})]})]})]})})},$a=t=>!t||typeof t!="object"?!1:!!t.synthetic,ju=t=>!Array.isArray(t)||t.length===0?!1:t.every(r=>$a(r)),i0=t=>!Array.isArray(t)||t.length===0?[]:t.some(s=>!$a(s))&&t.some(n=>$a(n))?t.filter(n=>!$a(n)):t,c0={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function l0(t){const r=ve(s=>!t||!s.sessionActivityPhase?"idle":s.sessionActivityPhase.get(t)??"idle");return i.useMemo(()=>{if(r==="idle")return c0;const s=r==="busy",n=r==="cooldown";return{phase:r,isWorking:s||n,isBusy:s,isCooldown:n}},[r])}function Ll(){const t=ve(r=>r.currentSessionId);return l0(t)}const d0={activity:"idle",hasWorkingContext:!1,hasActiveTools:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,lifecyclePhase:null,statusText:null,isGenericStatus:!0,isWaitingForPermission:!1,canAbort:!1,compactionDeadline:null,activePartType:void 0,activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1},Su=t=>t.role==="assistant",u0=t=>t.type==="reasoning",Tp=t=>t.type==="text",Nu=t=>{if(Tp(t))return t.text;const r=t;if(typeof r.text=="string")return r.text;if(typeof r.content=="string")return r.content;if(typeof r.value=="string")return r.value},ku=t=>(Tp(t)||u0(t),t.time),m0=t=>{if(t.tool)return t.tool;const r=t;return typeof r.name=="string"?r.name:"tool"};function Fp(){const{currentSessionId:t,messages:r,permissions:s,sessionAbortFlags:n}=ve(Un(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:c}=Ll(),l=i.useMemo(()=>t?r.get(t)??[]:[],[t,r]),d=i.useMemo(()=>{if(l.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=l.filter(M=>Su(M.info)&&!ju(M.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const g=[...h].sort((M,w)=>{const T=typeof M.info.time?.created=="number"?M.info.time.created:null,E=typeof w.info.time?.created=="number"?w.info.time.created:null;return T!==null&&E!==null&&T!==E?T-E:M.info.id.localeCompare(w.info.id)}),x=g[g.length-1];let b,y;const v=new Set(["edit","write","apply_patch"]);for(let M=(x.parts??[]).length-1;M>=0;M-=1){const w=x.parts?.[M];if(w)switch(w.type){case"reasoning":{const T=w.time??ku(w);(!T||typeof T.end>"u")&&!b&&(b="reasoning");break}case"tool":{const T=w.state?.status;if((T==="running"||T==="pending")&&!b){const E=m0(w);v.has(E)?b="editing":(b="tool",y=E)}break}case"text":{const T=Nu(w)??"";if(typeof T=="string"&&T.trim().length>0){const E=ku(w);(!E||typeof E.end>"u")&&!b&&(b="text")}break}}}const S={read:"reading file",write:"writing file",edit:"editing file",multiedit:"editing files",apply_patch:"applying patch",bash:"running command",grep:"searching content",glob:"finding files",list:"listing directory",task:"delegating task",webfetch:"fetching URL",websearch:"searching web",codesearch:"web code search",todowrite:"updating todos",todoread:"reading todos",skill:"learning skill",question:"asking question",plan_enter:"switching to planning",plan_exit:"switching to building"},C=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],N=M=>S[M]??`using ${M}`,j=()=>C[Math.floor(Math.random()*C.length)],D=b===void 0,k=b==="editing"?"editing file":b==="tool"&&y?N(y):b==="reasoning"?"thinking":b==="text"?"composing":j();return{activePartType:b,activeToolName:y,statusText:k,isGenericStatus:D}},[l]),u=i.useMemo(()=>{const h=t,g=h?n?.get(h)??null:null,x=!!(g&&!g.acknowledged);return{wasAborted:x,abortActive:x}},[t,n]),m=i.useMemo(()=>{if(u.wasAborted)return{...d0,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,g=o==="busy",x=c;let b="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?b="tooling":b=x?"cooldown":"streaming"),{activity:b,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:g,isCooldown:x,lifecyclePhase:g?"streaming":x?"cooldown":null,statusText:h?d.statusText:null,isGenericStatus:h?d.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:h,compactionDeadline:null,activePartType:h?d.activePartType:void 0,activeToolName:h?d.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:x}},[o,a,c,d,u]),f=i.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||l.length===0)return{isActive:h,characterCount:0};const g=l.filter(y=>Su(y.info)&&!ju(y.parts));if(g.length===0)return{isActive:h,characterCount:0};const x=g[g.length-1];let b=0;return(x.parts??[]).forEach(y=>{if(y.type!=="text")return;const v=Nu(y)??"";typeof v=="string"&&v.trim().length>0&&(b+=v.length)}),{isActive:h,characterCount:b}},[l,a,d.activePartType]),p=i.useMemo(()=>{if(m.wasAborted||m.abortActive)return m;const h=t;return(h?s?.get(h)??[]:[]).length>0?{...m,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:m},[t,s,m]);return{forming:f,working:p}}const f0=8,Cu=[],p0=t=>t==="primary"||t==="all"||t===void 0||t===null,h0=t=>{if(!Array.isArray(t))return null;const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},g0=(t,r)=>{const s=h0(t);if(!(!s||s.length===0)){for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},xa=({onOpenSettings:t,scrollToBottom:r})=>{const[s,n]=i.useState(""),[o,a]=i.useState(!1),[c,l]=i.useState(!1),[d,u]=i.useState(""),[m,f]=i.useState(!1),[p,h]=i.useState(""),[g,x]=i.useState(!1),[b,y]=i.useState(""),[v,S]=i.useState(!1),[C,N]=i.useState(""),[j,D]=i.useState(null),k=i.useRef(null),M=i.useRef(null),w=i.useRef(null),T=i.useRef(null),E=i.useRef(null),I=i.useRef(null),A=ve(_=>_.sendMessage),P=ve(_=>_.currentSessionId),F=ve(_=>_.newSessionDraft?.open),z=ve(_=>_.abortCurrentOperation),G=ve(_=>_.acknowledgeSessionAbort),oe=ve(_=>_.abortPromptSessionId),O=ve(_=>_.abortPromptExpiresAt),q=ve(_=>_.clearAbortPrompt),Y=ve(_=>_.sessionAbortFlags),Z=ve(_=>_.attachedFiles),B=ve(_=>_.addAttachedFile),W=ve(_=>_.addServerFile),te=ve(_=>_.clearAttachedFiles),ye=ve(_=>_.saveSessionAgentSelection),me=ve(_=>_.consumePendingInputText),K=ve(_=>_.pendingInputText),{currentProviderId:L,currentModelId:Q,currentVariant:ce,currentAgentName:he,setAgent:Ne,getVisibleAgents:H}=Je(),we=H(),{isMobile:ee,inputBarOffset:ue,isKeyboardOpen:ge,setTimelineDialogOpen:X,cornerRadius:de}=Me(),{working:ae}=Fp(),[fe,ie]=i.useState(!1),se=i.useRef(null),re=i.useRef(!1),ne=i.useRef(!1),xe=vr(_=>_.queueModeEnabled),Ue=vr(i.useCallback(_=>P?_.queuedMessages[P]??Cu:Cu,[P])),ze=vr(_=>_.addToQueue),Ke=vr(_=>_.clearQueue),{phase:rt}=Ll(),jt=i.useRef(rt),Xe=i.useRef(!1),Ct=i.useCallback(_=>{if(!ee||_.pointerType!=="touch")return;const je=k.current;if(!je||document.activeElement===je)return;_.preventDefault(),_.stopPropagation();const le=document.scrollingElement;le&&le.scrollTop!==0&&(le.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{je.focus({preventScroll:!0})}catch{je.focus()}const Re=je.value.length;try{je.setSelectionRange(Re,Re)}catch{}},[ee]);i.useEffect(()=>{if(K!==null){const _=me();_&&(n(_),setTimeout(()=>{k.current?.focus()},0))}},[K,me]);const st=i.useMemo(()=>{const _=P&&Ye.getState().getSessionAgentSelection(P)||he;if(_)return we.find(je=>je.name===_)},[we,he,P]),mt=i.useMemo(()=>st?g0(st.permission,"edit")??"allow":"deny",[st]),Pt=Ye(i.useCallback(_=>{if(!he)return;const je=P??"__global__";return _.getSessionAgentEditMode(je,he,"ask")},[he,P])),Ot=!!(P&&he),$e=i.useMemo(()=>{if(mt==="allow")return"allow";if(mt!=="ask")return"ask";const _=Ot?Pt??"ask":"ask";return _==="allow"||_==="full"?"allow":"ask"},[mt,Ot,Pt]),be=i.useMemo(()=>kp($e),[$e]),tt=i.useCallback(_=>zt()?`color-mix(in srgb, ${_} 55%, transparent)`:_,[]),Ce=i.useMemo(()=>{const _=zt()?1:2,je={borderRadius:de};if(!be)return{...je,borderWidth:_};const le=be.border??be.text;return{...je,borderColor:tt(le),borderWidth:_}},[be,tt,de]),Ie=s.trim()||Z.length>0,Qe=Ue.length>0,Te=Ie||Qe,Pe=ae.isWorking,Fe=i.useMemo(()=>P?oe===P&&!!O:!1,[oe,O,P]),Ve=i.useCallback(()=>{if(!Ie||!P)return;const _=s.replace(/^\n+|\n+$/g,""),je=Z.map(le=>({...le}));ze(P,{content:_,attachments:je.length>0?je:void 0}),n(""),je.length>0&&te(),ee||k.current?.focus()},[Ie,P,s,Z,ze,te,ee]),et=async _=>{if(_?.preventDefault(),!Te||!P&&!F)return;if(r?.({instant:!0,force:!0}),!L||!Q){console.warn("Cannot send message: provider or model not selected");return}let je="",le=[],Re;const _e=[];for(let it=0;it<Ue.length;it++){const It=Ue[it],{sanitizedText:ct,mention:Zt}=xu(It.content,we);!Re&&Zt?.name&&(Re=Zt.name),it===0?(je=ct,le=It.attachments??[]):_e.push({text:ct,attachments:It.attachments})}if(Ie){const it=s.replace(/^\n+|\n+$/g,""),{sanitizedText:It,mention:ct}=xu(it,we),Zt=Z.map(gr=>({...gr}));!Re&&ct?.name&&(Re=ct.name),Ue.length===0?(je=It,le=Zt):_e.push({text:It,attachments:Zt.length>0?Zt:void 0})}if(!je&&_e.length===0)return;P&&Qe&&Ke(P),n(""),Z.length>0&&te(),ee&&k.current?.blur();const We=je.trimStart();if(We.startsWith("/")){const it=We.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(it==="undo"&&P){await ve.getState().handleSlashUndo(P),r?.({instant:!0,force:!0});return}else if(it==="redo"&&P){await ve.getState().handleSlashRedo(P),r?.({instant:!0,force:!0});return}else if(it==="timeline"&&P){X(!0),n("");return}else if(it==="compact"&&P){try{const{opencodeClient:It}=await vs(async()=>{const{opencodeClient:gr}=await Promise.resolve().then(()=>Oy);return{opencodeClient:gr}},void 0),ct=It.getDirectory();if((await It.getApiClient().session.summarize({sessionID:P,directory:ct||void 0,providerID:L,modelID:Q})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(It){console.error("Failed to compact session:",It),V.error("Failed to compact session")}n("");return}}const qe=[...le,..._e.flatMap(it=>it.attachments??[])];A(je,L,Q,he,le,Re,_e.length>0?_e:void 0,ce).catch(it=>{const It=it instanceof Error?it.message:typeof it=="string"?it:String(it??""),ct=It.toLowerCase();console.error("Message send failed:",It||it);const Zt=ct.includes("timeout")||ct.includes("timed out")||ct.includes("may still be processing")||ct.includes("being processed")||ct.includes("failed to fetch")||ct.includes("networkerror")||ct.includes("network error")||ct.includes("gateway timeout")||ct==="failed to send message";if(ct.includes("payload too large")||ct.includes("413")||ct.includes("entity too large")){V.error("Attachments are too large to send. Please try reducing the number or size of images."),qe.length>0&&pr.setState({attachedFiles:qe});return}Zt||(qe.length>0&&pr.setState({attachedFiles:qe}),V.error(It||"Message failed to send. Attachments restored."))}),ee||k.current?.focus()},ot=i.useRef(et);ot.current=et,i.useEffect(()=>{const _=jt.current==="busy"||jt.current==="cooldown",je=rt==="idle",le=P&&Y.has(P)&&(()=>{const Re=Y.get(P);return Re?Date.now()-Re.timestamp<2e3:!1})();_&&je&&Ue.length>0&&!Xe.current&&!le&&(Xe.current=!0,setTimeout(()=>{P&&L&&Q&&ot.current(),Xe.current=!1},100)),jt.current=rt},[rt,Ue.length,P,L,Q,Y]);const yt=_=>{if(!Tl(_)){if(m&&T.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),T.current.handleKeyDown(_.key);return}if(g&&E.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),E.current.handleKeyDown(_.key);return}if(v&&I.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),I.current.handleKeyDown(_.key);return}if(c&&w.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),w.current.handleKeyDown(_.key);return}if(_.key==="Tab"&&!m&&!g&&!c){_.preventDefault(),Qt();return}if(_.key==="Enter"&&!_.shiftKey&&!ee){_.preventDefault();const je=_.ctrlKey||_.metaKey,le=Ie&&P&&rt!=="idle";xe?je||!le?et():Ve():je&&le?Ve():et()}}},Dt=i.useCallback(()=>{se.current&&(clearTimeout(se.current),se.current=null),ie(!0),se.current=setTimeout(()=>{ie(!1),se.current=null},1800)},[]),bt=i.useCallback(()=>{q(),Dt(),z()},[z,q,Dt]),Qt=()=>{const _=we.filter(_e=>p0(_e.mode));if(_.length<=1)return;const le=(_.findIndex(_e=>_e.name===he)+1)%_.length,Re=_[le];Ne(Re.name),P&&ye(P,Re.name)},Vt=i.useCallback(()=>{const _=k.current;if(!_)return;_.style.height="auto";const je=_.ownerDocument?.defaultView,le=je?je.getComputedStyle(_):null,Re=le?parseFloat(le.lineHeight):NaN,_e=le?parseFloat(le.paddingTop):NaN,We=le?parseFloat(le.paddingBottom):NaN,qe=22,It=Number.isNaN(_e)||Number.isNaN(We)?16:_e+We,Zt=(Number.isNaN(Re)?qe:Re)*f0+It,gr=_.scrollHeight||_.offsetHeight,Ur=Math.min(gr,Zt);_.style.height=`${Ur}px`,_.style.maxHeight=`${Zt}px`,D(Zo=>Zo&&Zo.height===Ur&&Zo.maxHeight===Zt?Zo:{height:Ur,maxHeight:Zt})},[]);i.useLayoutEffect(()=>{Vt()},[Vt,s,ee]);const Ft=i.useCallback((_,je)=>{if(_.startsWith("/")){const qe=_.indexOf(" "),it=_.indexOf(`
166
+ `),It=Math.min(qe===-1?_.length:qe,it===-1?_.length:it);if(je<=It&&qe===-1){const ct=_.substring(1,It);h(ct),f(!0),l(!1),x(!1),S(!1);return}}f(!1);const le=_.substring(0,je),Re=le.lastIndexOf("#");if(Re!==-1){const qe=Re>0?le[Re-1]:null,it=le.substring(Re+1),It=it.includes(" ")||it.includes(`
167
+ `);if((!qe||/\s/.test(qe))&&!It){y(it),x(!0),l(!1);return}}x(!1),y("");const _e=le.lastIndexOf("/");if(_e!==-1){const qe=_e>0?le[_e-1]:null,it=le.substring(_e+1),It=it.includes(" ")||it.includes(`
168
+ `);if((!qe||/\s/.test(qe))&&!It){N(it),S(!0),l(!1),x(!1);return}}S(!1),N("");const We=le.lastIndexOf("@");if(We!==-1){const qe=le.substring(We+1);!qe.includes(" ")&&!qe.includes(`
169
+ `)?(u(qe),l(!0)):l(!1)}else l(!1)},[y,h,u,x,f,l,S,N]),Kt=i.useCallback(_=>{if(!_)return;const je=k.current;if(!je){const qe=s+_;n(qe),Ft(qe,qe.length),requestAnimationFrame(()=>Vt());return}const le=je.selectionStart??s.length,Re=je.selectionEnd??s.length,_e=`${s.substring(0,le)}${_}${s.substring(Re)}`;n(_e);const We=le+_.length;requestAnimationFrame(()=>{const qe=k.current;qe&&(qe.selectionStart=We,qe.selectionEnd=We),Vt()}),Ft(_e,We)},[Vt,s,Ft]),Rt=_=>{const je=_.target.value,le=_.target.selectionStart??je.length;n(je),Vt(),Ft(je,le)},cs=i.useCallback(async _=>{const je=new Map;Array.from(_.clipboardData.files||[]).forEach(We=>{We.type.startsWith("image/")&&je.set(`${We.name}-${We.size}`,We)}),Array.from(_.clipboardData.items||[]).forEach(We=>{if(We.kind==="file"&&We.type.startsWith("image/")){const qe=We.getAsFile();qe&&je.set(`${qe.name}-${qe.size}`,qe)}});const le=Array.from(je.values());if(le.length===0||!P&&!F)return;_.preventDefault();const Re=_.clipboardData.getData("text");Re&&Kt(Re);let _e=0;for(const We of le){const qe=ve.getState().attachedFiles.length;try{await B(We),ve.getState().attachedFiles.length>qe&&(_e+=1)}catch(it){console.error("Clipboard image attach failed",it),V.error(it instanceof Error?it.message:"Failed to attach image from clipboard")}}_e>0&&V.success(`Attached ${_e} image${_e>1?"s":""} from clipboard`)},[B,P,F,Kt]),Ns=_=>{const je=k.current?.selectionStart||0,Re=s.substring(0,je).lastIndexOf("@");if(Re!==-1){const _e=s.substring(0,Re)+_.name+s.substring(je);n(_e)}l(!1),u(""),k.current?.focus()},bs=_=>{const le=k.current?.selectionStart??s.length,_e=s.substring(0,le).lastIndexOf("#");if(_e!==-1){const We=s.substring(0,_e)+`#${_} `+s.substring(le);n(We);const qe=_e+_.length+2;requestAnimationFrame(()=>{k.current&&(k.current.selectionStart=qe,k.current.selectionEnd=qe),Vt(),Ft(We,qe)})}x(!1),y(""),k.current?.focus()},Cs=_=>{const le=k.current?.selectionStart??s.length,_e=s.substring(0,le).lastIndexOf("/");if(_e!==-1){const We=s.substring(0,_e)+`${_} `+s.substring(le);n(We);const qe=_e+_.length+1;requestAnimationFrame(()=>{k.current&&(k.current.selectionStart=qe,k.current.selectionEnd=qe),Vt(),Ft(We,qe)})}S(!1),N(""),k.current?.focus()},Ms=_=>{n(`/${_.name} `);const je=k.current;je&&(je._commandMetadata=_),f(!1),h(""),setTimeout(()=>{k.current&&(k.current.focus(),k.current.setSelectionRange(k.current.value.length,k.current.value.length))},0)};i.useEffect(()=>{P&&k.current&&!ee&&k.current.focus()},[P,ee]),i.useEffect(()=>{oe&&oe!==P&&q()},[oe,P,q]);const ps=_=>{_.preventDefault(),_.stopPropagation(),(P||F)&&!o&&a(!0)},Xt=_=>{_.preventDefault(),_.stopPropagation(),_.currentTarget===_.target&&a(!1)},$=async _=>{if(_.preventDefault(),_.stopPropagation(),a(!1),!P&&!F)return;const je=Array.from(_.dataTransfer.files);let le=0;for(const Re of je){const _e=ve.getState().attachedFiles.length;try{await B(Re),ve.getState().attachedFiles.length>_e&&(le+=1)}catch(We){console.error("File attach failed",We),V.error(We instanceof Error?We.message:"Failed to attach file")}}le>0&&V.success(`Attached ${le} file${le>1?"s":""}`)},U=i.useCallback(async _=>{let je=0;for(const le of _){const Re=ve.getState().attachedFiles.length;try{await W(le.path,le.name),ve.getState().attachedFiles.length>Re&&(je+=1)}catch(_e){console.error("Server file attach failed",_e),V.error(_e instanceof Error?_e.message:"Failed to attach file")}}je>0&&V.success(`Attached ${je} file${je>1?"s":""}`)},[W]),J=i.useRef(null),[pe,Ee]=i.useState(!1),He=i.useCallback(async _=>{let je=0;const le=Array.isArray(_)?_:Array.from(_);for(const Re of le){const _e=ve.getState().attachedFiles.length;try{await B(Re),ve.getState().attachedFiles.length>_e&&(je+=1)}catch(We){console.error("File attach failed",We),V.error(We instanceof Error?We.message:"Failed to attach file")}}je>0&&V.success(`Attached ${je} file${je>1?"s":""}`)},[B]),ft=i.useCallback(async()=>{try{const je=await(await fetch("/api/vscode/pick-files")).json(),le=Array.isArray(je?.files)?je.files:[],Re=Array.isArray(je?.skipped)?je.skipped:[];if(Re.length>0){const We=Re.map(qe=>`${qe?.name||"file"}: ${qe?.reason||"skipped"}`).join(`
170
+ `);V.error(`Some files were skipped:
171
+ ${We}`)}const _e=le.map(We=>{if(!We?.dataUrl)return null;try{const[qe,it]=We.dataUrl.split(","),It=We.mimeType||qe?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!it)return null;const ct=atob(it),Zt=new Uint8Array(ct.length);for(let Ur=0;Ur<ct.length;Ur++)Zt[Ur]=ct.charCodeAt(Ur);const gr=new Blob([Zt],{type:It});return new File([gr],We.name||"file",{type:It})}catch(qe){return console.error("Failed to decode VS Code picked file",qe),null}}).filter(Boolean);_e.length>0&&await He(_e)}catch(_){console.error("VS Code file pick failed",_),V.error(_ instanceof Error?_.message:"Failed to pick files in VS Code")}},[He]),pt=i.useCallback(()=>{if(zt()){ft();return}J.current?.click()},[ft]),wt=i.useCallback(async _=>{const je=_.target.files;je&&(await He(je),_.target.value="")},[He]),at="gap-x-1.5 gap-y-0",_t=zt(),qt=ee?"px-1.5 py-1.5":_t?"px-1.5 py-1":"px-2.5 py-1.5",ht=ee?"h-9 w-9":_t?"h-[22px] w-[22px]":"h-7 w-7",Et=ee?"h-5 w-5":_t?"h-4 w-4":"h-[18px] w-[18px]",Jt=R(ht,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),De=!ee&&Fe&&Pe?e.jsx("button",{type:"button",onClick:bt,className:R(Jt,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(to,{className:R(Et)})}):e.jsx("button",{type:ee?"button":"submit",disabled:!Te||!P&&!F,onPointerDownCapture:_=>{!ee||_.pointerType!=="touch"||!Te||!P&&!F||(ne.current=!0,_.preventDefault(),_.stopPropagation(),et())},onClick:_=>{if(ee){if(ne.current){ne.current=!1;return}_.preventDefault(),et()}},className:R(Jt,Te&&(P||F)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Vo,{className:R(Et)})}),Be=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:J,type:"file",multiple:!0,className:"hidden",onChange:wt,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(qj,{onFilesSelected:U,multiSelect:!0,presentation:ee?"modal":"dropdown",open:pe,onOpenChange:Ee,children:ee?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx("button",{type:"button",className:Jt,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(Vm,{className:R(Et,"text-current")})})}),e.jsxs(rs,{align:"start",children:[e.jsxs(kt,{onSelect:()=>{requestAnimationFrame(()=>pt())},children:[e.jsx(Va,{}),"Attach files"]}),e.jsxs(kt,{onSelect:()=>{requestAnimationFrame(()=>{Ee(!0)})},children:[e.jsx(ox,{}),"Attach from project"]})]})]})]})]}),Le=t?e.jsx("button",{type:"button",onClick:t,className:Jt,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(Sn,{className:R(Et,"text-current")})}):null,Ze=e.jsxs(e.Fragment,{children:[Be,Le]}),nt=ae.statusText;i.useEffect(()=>{const _=!!ae.wasAborted;!re.current&&_&&!fe&&(Dt(),P&&G(P)),re.current=_},[G,P,fe,Dt,ae.wasAborted]),i.useEffect(()=>()=>{se.current&&(clearTimeout(se.current),se.current=null)},[]);const ke=ee&&Pe;return e.jsxs("form",{onSubmit:et,className:R("relative pt-0 pb-2 md:pb-4",ee&&ge?"ios-keyboard-safe-area":"bottom-safe-area"),"data-keyboard-avoid":"true",style:ee&&ue>0&&!ge?{marginBottom:`${ue}px`}:void 0,children:[e.jsx("div",{className:"absolute bottom-full left-0 right-0",children:e.jsx(a0,{isWorking:ae.isWorking,statusText:nt,isGenericStatus:ae.isGenericStatus,isWaitingForPermission:ae.isWaitingForPermission,wasAborted:ae.wasAborted,abortActive:ae.abortActive,completionId:ae.lastCompletionId,isComplete:ae.isComplete,showAbort:ke,onAbort:bt,showAbortStatus:fe})}),e.jsxs("div",{ref:M,className:R("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:ps,onDragLeave:Xt,onDrop:$,children:[o&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-xl",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-flex justify-center",children:e.jsx("button",{type:"button",className:Jt,onClick:()=>pt(),title:"Attach files","aria-label":"Attach files",children:e.jsx(Va,{className:R(Et,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(Hj,{}),e.jsx(Dp,{onEditMessage:_=>{n(_),setTimeout(()=>{k.current?.focus()},0)}}),e.jsxs("div",{className:R("border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:Ce,children:[m&&e.jsx(Ap,{ref:T,searchQuery:p,onCommandSelect:Ms,onClose:()=>f(!1)}),g&&e.jsx(Ep,{ref:E,searchQuery:b,onAgentSelect:bs,onClose:()=>x(!1)}),v&&e.jsx(Ip,{ref:I,searchQuery:C,onSkillSelect:Cs,onClose:()=>S(!1)}),c&&e.jsx(Wj,{ref:w,searchQuery:d,onFileSelect:Ns,onClose:()=>l(!1)}),e.jsx(Fs,{ref:k,"data-chat-input":"true",value:s,onChange:Rt,onKeyDown:yt,onPaste:cs,onPointerDownCapture:Ct,placeholder:P||F?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!P&&!F,className:R("min-h-[52px] resize-none border-0 px-3 shadow-none rounded-b-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent",ee?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:j?`${j.height}px`:void 0,maxHeight:j?`${j.maxHeight}px`:void 0,borderTopLeftRadius:de,borderTopRightRadius:de},rows:1}),e.jsx("div",{className:R("bg-transparent",qt,ee?"flex items-center gap-x-1.5":R("flex items-center justify-between",at)),style:{borderBottomLeftRadius:de,borderBottomRightRadius:de},"data-chat-input-footer":"true",children:ee?e.jsxs("div",{className:"flex w-full items-center gap-x-1.5",children:[e.jsx("div",{className:"flex items-center flex-shrink-0 gap-x-1",children:Ze}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-x-1 min-w-0",children:[e.jsx("div",{className:"flex flex-1 min-w-0 justify-end overflow-hidden",children:e.jsx(gu,{className:R("w-full flex items-center justify-end min-w-0")})}),De]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("flex items-center flex-shrink-0",at),children:Ze}),e.jsxs("div",{className:R("flex items-center flex-1 justify-end",at,"md:gap-x-3"),children:[e.jsx(gu,{className:R("flex-1 min-w-0 justify-end")}),De]})]})})]})]})]})};function nc({className:t,...r}){return e.jsx("div",{"data-slot":"skeleton",className:R("bg-accent animate-pulse rounded-xl",t),...r})}const Mu=(t,r,s,n,o=4)=>{const a=[];for(let c=0;c<o;c++)for(let l=0;l<o;l++){const d=l/o,u=(l+1)/o,m=c/o,f=(c+1)/o,p=(v,S,C)=>v+(S-v)*C,h=(v,S,C,N,j,D)=>{const k=p(v,S,j),M=p(N,C,j);return p(k,M,D)},g={x:h(t.x,r.x,s.x,n.x,d,m),y:h(t.y,r.y,s.y,n.y,d,m)},x={x:h(t.x,r.x,s.x,n.x,u,m),y:h(t.y,r.y,s.y,n.y,u,m)},b={x:h(t.x,r.x,s.x,n.x,u,f),y:h(t.y,r.y,s.y,n.y,u,f)},y={x:h(t.x,r.x,s.x,n.x,d,f),y:h(t.y,r.y,s.y,n.y,d,f)};a.push({path:`M${g.x} ${g.y} L${x.x} ${x.y} L${b.x} ${b.y} L${y.x} ${y.y} Z`,row:c,col:l})}return a},Ol=({className:t="",width:r=70,height:s=70,isAnimated:n=!1})=>{const o=Ci();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const c=a?"white":"black",l=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,h=50,g={x:50,y:h-m},x={x:50-m*f,y:h-m*p},b={x:50+m*f,y:h-m*p},y={x:50,y:h},v={x:50-m*f,y:h+m*p},S={x:50+m*f,y:h+m*p},C={x:50,y:h+m},j=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(g.y+x.y+y.y+b.y)/4})`,D=Mu(x,y,C,v),k=Mu(y,b,S,C),M=Ae.useMemo(()=>{const w=[];for(let T=0;T<32;T++)w.push(.1+Math.random()*.5);return w},[]);return e.jsxs("svg",{width:r,height:s,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,role:"img","aria-label":"OpenChamber logo",children:[e.jsx("path",{d:`M${y.x} ${y.y} L${x.x} ${x.y} L${v.x} ${v.y} L${C.x} ${C.y} Z`,fill:l,stroke:c,strokeWidth:"2",strokeLinejoin:"round"}),D.map((w,T)=>e.jsx("path",{d:w.path,fill:u,opacity:M[T]},`left-${T}`)),e.jsx("path",{d:`M${y.x} ${y.y} L${b.x} ${b.y} L${S.x} ${S.y} L${C.x} ${C.y} Z`,fill:l,stroke:c,strokeWidth:"2",strokeLinejoin:"round"}),k.map((w,T)=>e.jsx("path",{d:w.path,fill:u,opacity:M[T+16]},`right-${T}`)),e.jsx("path",{d:`M${g.x} ${g.y} L${x.x} ${x.y} L${y.x} ${y.y} L${b.x} ${b.y} Z`,fill:"none",stroke:c,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${j} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function x0({children:t,className:r,interval:s=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:c=!0,mode:l="popLayout"}){const[d,u]=Ae.useState(0),m=Ae.Children.toArray(t);Ae.useEffect(()=>{if(!c)return;const p=s*1e3,h=setInterval(()=>{u(g=>{const x=(g+1)%m.length;return a?.(x),x})},p);return()=>clearInterval(h)},[m.length,s,a,c]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:R("relative",r),children:[e.jsx("div",{className:"invisible whitespace-nowrap",children:m.map((p,h)=>e.jsx("div",{className:h===0?"":"absolute",children:p},h))}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(ax,{mode:l,initial:!1,children:e.jsx(Hn.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const y0=["Fix the failing tests","Refactor this to be more readable","Add form validation","Optimize this function","Write tests for this","Explain how this works","Add a new feature","Help me debug this","Review my code","Simplify this logic","Add error handling","Create a new component","Update the documentation","Find the bug here","Improve performance","Add type definitions"],b0=()=>{const t=Ci();let r=!0;t?r=t.currentTheme.metadata.variant!=="light":typeof window<"u"&&(r=window.matchMedia("(prefers-color-scheme: dark)").matches);const s=r?"rgba(255,255,255,0.4)":"rgba(0,0,0,0.4)";return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[e.jsx(Ol,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(x0,{className:"text-body-md",interval:4,transition:{duration:.5},children:y0.map(n=>e.jsxs("span",{style:{color:s},children:['"',n,'…"']},n))})]})},oc=i.memo(b0),w0={'code[class*="language-"]':{color:"#cdccc3",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:"#cdccc3",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0",overflow:"auto"},comment:{color:"#6b6964",fontStyle:"italic"},prolog:{color:"#6b6964"},doctype:{color:"#6b6964"},cdata:{color:"#6b6964"},punctuation:{color:"#6b6963"},property:{color:"#d29470"},tag:{color:"#d8886d"},boolean:{color:"#d39373"},number:{color:"#d39373"},constant:{color:"#6cacd6"},symbol:{color:"#6cacd6"},deleted:{color:"#d98678"},selector:{color:"#81af6c"},"attr-name":{color:"#c2974d"},string:{color:"#81af6c"},char:{color:"#81af6c"},builtin:{color:"#5aa9d9"},inserted:{color:"#81af6c"},operator:{color:"#d29470"},entity:{color:"#edb449",cursor:"help"},url:{color:"#5aa9d9"},".language-css .token.string":{color:"#81af6c"},".style .token.string":{color:"#81af6c"},variable:{color:"#d29470"},atrule:{color:"#c2974d"},"attr-value":{color:"#81af6c"},function:{color:"#5aa9d9"},"class-name":{color:"#c2974d"},keyword:{color:"#d8886d"},regex:{color:"#81af6c"},important:{color:"#d8886d",fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{opacity:.7},title:{color:"#edb449",fontWeight:"bold"},"code-block":{color:"#81af6c"},"code-snippet":{color:"#81af6c"},list:{color:"#d29470"},hr:{color:"#6b6963"},table:{color:"#5aa9d9"},blockquote:{color:"#6b6964",fontStyle:"italic"},strike:{textDecoration:"line-through"}},v0={'code[class*="language-"]':{color:"#403e3c",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:"#403e3c",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0",overflow:"auto"},comment:{color:"#7a756a",fontStyle:"italic"},prolog:{color:"#7a756a"},doctype:{color:"#7a756a"},cdata:{color:"#7a756a"},punctuation:{color:"#6b6963"},property:{color:"#c07845"},tag:{color:"#b96f55"},boolean:{color:"#b97659"},number:{color:"#b97659"},constant:{color:"#4791ba"},symbol:{color:"#4791ba"},deleted:{color:"#c15748"},selector:{color:"#6a9354"},"attr-name":{color:"#9f7d3e"},string:{color:"#6a9354"},char:{color:"#6a9354"},builtin:{color:"#4791ba"},inserted:{color:"#6a9354"},operator:{color:"#c07845"},entity:{color:"#d09930",cursor:"help"},url:{color:"#4791ba"},".language-css .token.string":{color:"#6a9354"},".style .token.string":{color:"#6a9354"},variable:{color:"#c07845"},atrule:{color:"#9f7d3e"},"attr-value":{color:"#6a9354"},function:{color:"#4791ba"},"class-name":{color:"#9f7d3e"},keyword:{color:"#b96f55"},regex:{color:"#6a9354"},important:{color:"#b96f55",fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{opacity:.7},title:{color:"#d09930",fontWeight:"bold"},"code-block":{color:"#6a9354"},"code-snippet":{color:"#6a9354"},list:{color:"#c07845"},hr:{color:"#6b6963"},table:{color:"#4791ba"},blockquote:{color:"#7a756a",fontStyle:"italic"},strike:{textDecoration:"line-through"}};class Jr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Jr.instance||(Jr.instance=new Jr),Jr.instance}recordSessionStart(r){this.sessionStartTimes.set(r,Date.now())}getSessionStartTime(r){return this.sessionStartTimes.get(r)}shouldAnimateMessage(r,s){if(r.role!=="assistant"||this.seenMessageIds.has(r.id))return!1;const n=this.sessionStartTimes.get(s);if(!n)return this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created),!1;const o=r.time.created>n-5e3;return o||(this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created)),o}clearSession(r){this.sessionStartTimes.delete(r)}hasSessionTiming(r){return this.sessionStartTimes.has(r)}hasBeenAnimated(r){return this.seenMessageIds.has(r)}markMessageAsAnimated(r,s){this.seenMessageIds.add(r),this.messageCreationTimes.set(r,s)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function Fi(t){const r=t.colors.syntax,s=t.colors.surface;return{'code[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"0",margin:"0",overflow:"auto"},comment:{color:r.base.comment,fontStyle:"italic"},prolog:{color:r.base.comment},doctype:{color:r.base.comment},cdata:{color:r.base.comment},punctuation:{color:r.tokens?.punctuation||s.mutedForeground},property:{color:r.tokens?.variableProperty||r.base.variable},tag:{color:r.tokens?.tag||r.base.keyword},"attr-name":{color:r.tokens?.tagAttribute||r.base.variable},"attr-value":{color:r.tokens?.tagAttributeValue||r.base.string},boolean:{color:r.tokens?.boolean||r.base.number},number:{color:r.base.number},constant:{color:r.tokens?.constant||r.base.number},symbol:{color:r.tokens?.constant||r.base.number},string:{color:r.base.string},char:{color:r.base.string},function:{color:r.base.function},builtin:{color:r.tokens?.functionBuiltin||r.base.function},"class-name":{color:r.tokens?.className||r.base.type},namespace:{color:r.tokens?.namespace||r.base.type,opacity:.8},keyword:{color:r.base.keyword},atrule:{color:r.base.keyword},selector:{color:r.base.function},operator:{color:r.base.operator},variable:{color:r.base.variable},regex:{color:r.tokens?.regex||r.base.string},url:{color:r.base.function,textDecoration:"underline"},entity:{color:r.base.function,cursor:"help"},".language-css .token.string":{color:r.base.string},".style .token.string":{color:r.base.string},deleted:{color:t.colors.status.error,backgroundColor:t.colors.status.errorBackground},inserted:{color:t.colors.status.success,backgroundColor:t.colors.status.successBackground},title:{color:t.colors.primary.base,fontWeight:"bold"},"code-block":{color:r.base.string},"code-snippet":{color:r.base.string},list:{color:r.base.variable},hr:{color:s.mutedForeground},table:{color:r.base.function},blockquote:{color:s.mutedForeground,fontStyle:"italic"},important:{color:r.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:r.tokens?.decorator||r.base.function},annotation:{color:r.tokens?.decorator||r.base.function}}}const j0=i.createContext(!1),hr=({children:t,className:r,skipAnimation:s})=>{const n=i.useContext(j0),o=s||n,[a,c]=i.useState(o);return i.useEffect(()=>{if(o)return;let l=null;const d=()=>c(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?l=window.requestAnimationFrame(d):d(),()=>{l!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(l)}},[o]),o?e.jsx(e.Fragment,{children:t}):e.jsx("div",{className:R("w-full transition-all duration-300 ease-out",a?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:t})},S0=({isUser:t,providerID:r,agentName:s,modelName:n,variant:o,isDarkTheme:a})=>{const{src:c,onError:l,hasLogo:d}=wp(r);return e.jsx(hr,{children:e.jsx("div",{className:R("mb-2"),children:e.jsx("div",{className:R("flex items-center justify-between gap-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0",children:t?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(rr,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&c?e.jsx("img",{src:c,alt:`${r} logo`,className:"h-4 w-4",style:{filter:a?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:l}):e.jsx(Mr,{className:"h-4 w-4",style:{color:`var(${Kr(s).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:R("font-bold typography-ui-header tracking-tight leading-none",t?"text-primary":"text-foreground"),children:t?"You":n||"Assistant"}),!t&&s&&e.jsxs("div",{className:R("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",Kr(s).class),children:[e.jsx(Sn,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:s})]}),!t&&o&&e.jsxs("div",{className:R("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",o==="Default"?void 0:"agent-info"),style:o==="Default"?{"--agent-color":"var(--muted-foreground)","--agent-color-bg":"var(--muted-foreground)"}:void 0,children:[e.jsx(Mr,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:o.length>0?o[0].toLowerCase()+o.slice(1):o})]})]})]})})})})},N0=i.memo(S0),k0=t=>`https://opencode.ai/docs/agents/#${encodeURIComponent(t)}`,C0=({part:t,messageId:r,agentMention:s})=>{const n=t,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[c,l]=i.useState(!1),[d,u]=i.useState(!1),m=i.useRef(null);i.useEffect(()=>{const h=m.current;if(!h||c)return;const g=()=>{u(h.scrollHeight>h.clientHeight)};g();const x=new ResizeObserver(g);return x.observe(h),()=>x.disconnect()},[a,c]);const f=i.useCallback(()=>{(d||c)&&l(h=>!h)},[d,c]);if(!a||a.trim().length===0)return null;const p=()=>{if(!s?.token||!a.includes(s.token))return a;const h=a.indexOf(s.token),g=a.slice(0,h),x=a.slice(h+s.token.length);return e.jsxs(e.Fragment,{children:[g,e.jsx("a",{href:k0(s.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:b=>b.stopPropagation(),children:s.token}),x]})};return e.jsx("div",{className:R("break-words whitespace-pre-wrap font-sans typography-markdown",!c&&"line-clamp-3",(d||c)&&"cursor-pointer"),ref:m,onClick:f,children:p()},t.id||`${r}-user-text`)},M0=i.memo(C0),Du=(t,r)=>{const s=t[Symbol.toPrimitive];if(typeof s=="function")try{if(s()===r)return t}catch{}try{Object.defineProperty(t,"toString",{value:()=>r,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(t,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0})}catch{}return t},Au=()=>{if(!zt()||typeof window>"u")return Ud;const t=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(t?.light&&t?.dark){const r=Du({...t.light},`vscode-shiki-light:${String(t.light?.name??"theme")}`),s=Du({...t.dark},`vscode-shiki-dark:${String(t.dark?.name??"theme")}`);return[r,s]}return Ud},D0=()=>{const[t,r]=i.useState(Au);return i.useEffect(()=>{if(!zt()||typeof window>"u")return;const s=n=>{r(Au())};return window.addEventListener("openchamber:vscode-shiki-themes",s),()=>window.removeEventListener("openchamber:vscode-shiki-themes",s)},[]),t},Rp=t=>{const r=[],s=[],n=t.querySelector("thead");n&&n.querySelectorAll("th").forEach(c=>r.push(c.innerText.trim()));const o=t.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(c=>{const l=c.querySelectorAll("td"),d=[];l.forEach(u=>d.push(u.innerText.trim())),s.push(d)}),{headers:r,rows:s}},Lp=({headers:t,rows:r})=>{const s=o=>o.includes(",")||o.includes('"')||o.includes(`
172
+ `)?`"${o.replace(/"/g,'""')}"`:o,n=[];return t.length>0&&n.push(t.map(s).join(",")),r.forEach(o=>n.push(o.map(s).join(","))),n.join(`
173
+ `)},A0=({headers:t,rows:r})=>{const s=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return t.length>0&&n.push(t.map(s).join(" ")),r.forEach(o=>n.push(o.map(s).join(" "))),n.join(`
174
+ `)},E0=({headers:t,rows:r})=>{if(t.length===0)return"";const s=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${t.map(s).join(" | ")} |`),n.push(`| ${t.map(()=>"---").join(" | ")} |`),r.forEach(o=>{const a=t.map((c,l)=>s(o[l]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
175
+ `)},I0=(t,r,s)=>{const n=new Blob([r],{type:s}),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)},P0=({tableRef:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(null);i.useEffect(()=>{const l=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[]);const c=async l=>{const d=t.current?.querySelector("table");if(d)try{const u=Rp(d),m=l==="csv"?Lp(u):A0(u);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([m],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),s(!0),o(!1),setTimeout(()=>s(!1),2e3)}catch(u){console.error("Failed to copy table:",u)}};return e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>o(!n),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:r?e.jsx(Tt,{className:"size-3.5"}):e.jsx(nr,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>c("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>c("tsv"),children:"TSV"})]})]})},T0=({tableRef:t})=>{const[r,s]=i.useState(!1),n=i.useRef(null);i.useEffect(()=>{const a=c=>{n.current&&!n.current.contains(c.target)&&s(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const c=t.current?.querySelector("table");if(c)try{const l=Rp(c),d=a==="csv"?Lp(l):E0(l);I0(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),s(!1)}catch(l){console.error("Failed to download table:",l)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>s(!r),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(tn,{className:"size-3.5"})}),r&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("markdown"),children:"Markdown"})]})]})},F0=({children:t,className:r})=>{const s=i.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:s,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(P0,{tableRef:s}),e.jsx(T0,{tableRef:s})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:R("w-full border-collapse border border-border",r),"data-streamdown":"table",children:t})})]})},R0=({children:t,className:r,style:s,...n})=>{const[o,a]=i.useState(!1),c=i.useRef(null),l=i.useMemo(()=>{if(!s)return s;const m={...s},f=g=>{if(typeof g!="string")return{value:void 0,vars:{}};const[x,...b]=g.split(";").map(v=>v.trim()).filter(Boolean),y={};for(const v of b){const S=v.indexOf(":");if(S===-1)continue;const C=v.slice(0,S).trim(),N=v.slice(S+1).trim();!C.startsWith("--")||N.length===0||(y[C]=N)}return{value:x,vars:y}},p=f(s.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[g,x]of Object.entries(p.vars))m[g]=x;const h=f(s.color);h.value&&(m.color=h.value,m["--shiki-light"]=h.value);for(const[g,x]of Object.entries(h.vars))m[g]=x;return m},[s]),d=()=>c.current&&c.current.querySelector("code")?.innerText||"",u=async()=>{const m=d();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:c,children:[e.jsx("pre",{...n,className:R(r),style:l,children:t}),e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:u,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(Tt,{className:"size-3.5"}):e.jsx(nr,{className:"size-3.5"})})})]})},L0={pre:R0,table:F0},kr=({content:t,className:r,variant:s="assistant"})=>{const n=D0(),o=s==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:R("break-words",r),children:e.jsx(ix,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:L0,children:t})})},O0=t=>{let r=t.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},_0=t=>t?t.includes("<file_diagnostics>")||t.includes("This file has errors")||t.includes("please fix"):!1,$0=t=>t?t.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Eu=(t,r)=>!t||typeof t!="object"?String(t):uv(t,r||""),ac=(t,r,s)=>{let n=O0(t);if((r==="edit"||r==="multiedit")&&_0(n)&&(n=$0(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&s?.diff){const o=s.diff;return typeof o=="string"?o:String(o)}return n},B0=(t,r)=>{try{const s=t.trim().split(`
176
+ `).filter(Boolean);if(s.length===0)return null;const n=[];return s.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,c,l]=a,d=Math.floor(c.length/2),u=!l.endsWith("/");n.push({name:l.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:R("w-full min-w-0 font-mono space-y-0.5",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Or.tool.popup,children:n.map((o,a)=>e.jsx("div",{className:"min-w-0",style:{paddingLeft:`${o.depth*20}px`},children:o.isFile?e.jsx("span",{className:"text-foreground/90 block truncate",children:o.name}):e.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[o.name,"/"]})},a))})}catch{return null}},z0=(t,r,s)=>{try{const n=t.trim().split(`
177
+ `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const c=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(c){const[,l,d,u]=c,m=u!==void 0?d:"",f=u!==void 0?u:d;o[l]||(o[l]=[]),o[l].push({lineNum:m,content:f})}}),e.jsxs("div",{className:R("space-y-2 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Or.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,c])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:R("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:c.map((l,d)=>!l.lineNum&&!l.content?null:e.jsxs("div",{className:R("flex items-start gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[l.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",l.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:l.content||" "})]})]},d))})]},a))]})}catch{return null}},H0=(t,r,s)=>{try{const n=t.trim().split(`
178
+ `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(c=>{const l=c.lastIndexOf("/"),d=l>0?c.substring(0,l):"/",u=l>=0?c.substring(l+1):c;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:R("space-y-2 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Or.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(c=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:R("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[c,"/"]}),e.jsx("div",{className:R("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[c].sort().map(l=>e.jsxs("div",{className:R("flex items-center gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:l})]},l))})]},c))]})}catch{return null}},W0=(t,r)=>{try{const s=JSON.parse(t);if(!Array.isArray(s))return null;const n={in_progress:s.filter(a=>a.status==="in_progress"),pending:s.filter(a=>a.status==="pending"),completed:s.filter(a=>a.status==="completed"),cancelled:s.filter(a=>a.status==="cancelled")},o=a=>{const c="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:c,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:c,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:c,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:c,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:R("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Or.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",s.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,c)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||c))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,c)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||c))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tt,{className:"w-3 h-3",style:{color:"var(--status-success)"}}),e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:"Completed"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.completed.map((a,c)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Tt,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||c))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,c)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||c))})]})]})}catch{return null}},U0=(t,r,s)=>{try{return e.jsx("div",{className:R("typography-code max-w-none w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:Or.tool.popup,children:e.jsx(kr,{content:t,variant:"tool"})})}catch{return null}},Op=t=>{const r=t.split(`
179
+ `);let s="";const n=[];let o=0;for(;o<r.length;){const a=r[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(s=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const c=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),l=c?parseInt(c[1]):0,d=c?parseInt(c[2]):0,u=[];let m=l,f=d,p=o+1;for(;p<r.length&&!r[p].startsWith("@@")&&!r[p].startsWith("Index:");){const h=r[p];h.startsWith("+")?(u.push({type:"added",lineNumber:f,content:h.substring(1)}),f++):h.startsWith("-")?(u.push({type:"removed",lineNumber:m,content:h.substring(1)}),m++):h.startsWith(" ")&&(u.push({type:"context",lineNumber:f,content:h.substring(1)}),m++,f++),p++}n.push({file:s,oldStart:l,newStart:d,lines:u}),o=p;continue}o++}return n},Jc=(t,r,s)=>lv(r,t,s),_p=t=>{const r="h-3.5 w-3.5 flex-shrink-0",s=t.toLowerCase();return s==="edit"||s==="multiedit"||s==="apply_patch"||s==="str_replace"||s==="str_replace_based_edit_tool"?e.jsx(Hm,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(Gm,{className:r}):s==="read"||s==="view"||s==="file_read"||s==="cat"?e.jsx(Zn,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"?e.jsx(rn,{className:r}):s==="list"||s==="ls"||s==="dir"||s==="list_files"?e.jsx(lr,{className:r}):s==="search"||s==="grep"||s==="find"||s==="ripgrep"?e.jsx(cx,{className:r}):s==="glob"?e.jsx(lx,{className:r}):s==="fetch"||s==="curl"||s==="wget"||s==="webfetch"?e.jsx(Ac,{className:r}):s==="web-search"||s==="websearch"||s==="search_web"||s==="codesearch"||s==="google"||s==="bing"||s==="duckduckgo"||s==="perplexity"?e.jsx(Ac,{className:r}):s==="todowrite"||s==="todoread"?e.jsx(qm,{className:r}):s==="skill"?e.jsx(Km,{className:r}):s==="question"?e.jsx(dx,{className:r}):s==="plan_enter"?e.jsx(ux,{className:r}):s==="plan_exit"?e.jsx(mx,{className:r}):s.startsWith("git")?e.jsx(Ut,{className:r}):e.jsx(pi,{className:r})},V0=(t,r,s=Date.now())=>{const o=(r?r-t:s-t)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},G0=({start:t,end:r,active:s})=>{const[n,o]=i.useState(()=>Date.now());return i.useEffect(()=>{if(!s)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[s]),e.jsx(e.Fragment,{children:V0(t,r,n)})},q0=t=>{if(!t?.diff||typeof t.diff!="string")return null;const r=t.diff.split(`
180
+ `);let s=0,n=0;for(const o of r)o.startsWith("+")&&!o.startsWith("+++")&&s++,o.startsWith("-")&&!o.startsWith("---")&&n++;return s===0&&n===0?null:{added:s,removed:n}},Ba=(t,r,s)=>{if(s)return t.split("/").pop()||t;if(t.startsWith(r)){const n=t.substring(r.length);return n.startsWith("/")?n.substring(1):n}return t},K0=t=>{const r=t.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!r)return null;const s=[],n=r[1],o=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let a;for(;(a=o.exec(n))!==null;)s.push({question:a[1],answer:a[2]});return s.length>0?s:null},J0=(t,r,s,n)=>{const o=r,a=o.metadata,c=o.input;if(t.tool==="apply_patch"){const d=Array.isArray(a?.files)?a?.files:[],u=d[0],m=u?.relativePath||u?.filePath;return d.length>1?`${d.length} files`:typeof m=="string"?Ba(m,n,s):"Patch"}if(t.tool==="question"&&c?.questions&&Array.isArray(c.questions)){const d=c.questions.length;return`Asked ${d} question${d!==1?"s":""}`}if((t.tool==="edit"||t.tool==="multiedit")&&c){const d=c?.filePath||c?.file_path||c?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return Ba(d,n,s)}if((t.tool==="read"||t.tool==="write")&&c){const d=c?.filePath||c?.file_path||c?.path;if(typeof d=="string")return Ba(d,n,s)}if(t.tool==="bash"&&c?.command&&typeof c.command=="string"){const d=c.command.split(`
181
+ `)[0];return s?d.substring(0,50):d.substring(0,100)}if(t.tool==="task"&&c?.description&&typeof c.description=="string")return s?c.description.substring(0,40):c.description.substring(0,80);if(t.tool==="skill"&&c?.name&&typeof c.name=="string")return c.name;if(t.tool==="plan_enter")return"Switching to planning";if(t.tool==="plan_exit")return"Switching to building";const l=c?.description||a?.description||"title"in r&&r.title||"";return typeof l=="string"?l:""},Qc=({children:t,maxHeightClass:r="max-h-[60vh]",className:s,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(xt,{outerClassName:R("w-full min-w-0 flex-none overflow-hidden",r,n),className:R("tool-output-surface p-2 rounded-xl w-full min-w-0 border border-border/20 bg-transparent",s),disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:t})}),Q0=t=>{const r=t.state?.title;return typeof r=="string"&&r.trim().length>0?r:typeof t.tool=="string"&&t.tool.trim().length>0?t.tool:"tool"},Y0=t=>t.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),X0=({entries:t,isExpanded:r,hasPrevTool:s,hasNextTool:n,output:o,sessionId:a})=>{const c=ve(x=>x.setCurrentSession),l=i.useMemo(()=>t.filter(x=>x.state?.status==="completed"),[t]),d=typeof o=="string"?Y0(o):"",u=d.length>0,[m,f]=i.useState(!1),p=x=>{x.stopPropagation(),a&&c(a)};if(l.length===0&&!u&&!a)return null;const h=r?l:l.slice(-6),g=Math.max(0,l.length-h.length);return e.jsxs("div",{className:R("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',s?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[l.length>0?e.jsx(Qc,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[g>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",g," more…"]}):null,h.map((x,b)=>{const y=typeof x.tool=="string"&&x.tool.trim().length>0?x.tool:"tool",v=Q0(x),S=Cl(y).displayName;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:_p(y)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:S}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:v})]},x.id??`${y}-${b}`)})]})}):null,a&&e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:x=>x.stopPropagation(),onClick:p,children:[e.jsx(Zs,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-primary font-medium",children:"Open subAgent session"})]}),u?e.jsxs("div",{className:R("space-y-1",(l.length>0||a)&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:x=>x.stopPropagation(),onClick:x=>{x.stopPropagation(),f(b=>!b)},children:[m?e.jsx(Wt,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(tr,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?e.jsx(Qc,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(kr,{content:d,variant:"tool"})})}):null]}):null]})},$p=i.memo(({diff:t,syntaxTheme:r,input:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Op(t).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,c)=>e.jsxs("div",{className:R("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(_r,{style:r,language:Er(typeof s?.file_path=="string"?s.file_path:typeof s?.filePath=="string"?s.filePath:n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},c))})]},o))}));$p.displayName="DiffPreview";const Bp=i.memo(({content:t,syntaxTheme:r,filePath:s,displayPath:n})=>{const o=i.useMemo(()=>t.split(`
182
+ `),[t]),a=i.useMemo(()=>Er(s??"")||Jc(t,"write",s?{filePath:s}:void 0),[t,s]),c=Math.max(o.length,1),l=c===1?"line 1":`lines 1-${c}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${l})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(_r,{style:r,language:a||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})});Bp.displayName="WriteInputPreview";const zp=i.memo(({content:t,filePath:r,displayPath:s})=>{const n=Hc(r),o=r.toLowerCase().endsWith(".svg"),a=i.useMemo(()=>o&&!t.startsWith("data:")?`data:image/svg+xml;base64,${btoa(t)}`:t.startsWith("data:")?t:`data:${n};base64,${t}`,[t,n,o]);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-2",children:s}),e.jsx("div",{className:"flex justify-center p-4 bg-muted/10 rounded-lg border border-border/10",children:e.jsx("img",{src:a,alt:s,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})});zp.displayName="ImagePreview";const Hp=i.memo(({part:t,state:r,syntaxTheme:s,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:c})=>{const l=r,d=l.metadata,u=l.input,m=l.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",h=typeof d?.diff=="string"?d.diff:null,g=t.tool==="write"?typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0:void 0,x=t.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,b=t.tool==="write"&&!!x,y=g?Ho(g):!1,v=b?g?Ba(g,o,n):"New file":null,S=i.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&t.tool==="bash"?Eu(u,t.tool):typeof u.content=="string"?u.content??"":Eu(u,t.tool),[u,t.tool]),C=t.tool!=="apply_patch"&&S.trim().length>0,N=(D,k)=>e.jsx(Qc,{maxHeightClass:k?.maxHeightClass,className:k?.className,disableHorizontal:k?.disableHorizontal,outerClassName:k?.outerClassName,children:D}),j=()=>{if(t.tool==="question"){if(r.status==="completed"&&f){const D=K0(p);if(D&&D.length>0)return N(e.jsx("div",{className:"space-y-2",children:D.map((k,M)=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:k.question}),e.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:k.answer})]},M))}),{maxHeightClass:"max-h-[40vh]"})}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(t.tool==="todowrite"||t.tool==="todoread"){if(r.status==="completed"&&f){const D=W0(p,{unstyled:!0});return N(D??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(t.tool==="list"&&f){const D=B0(p,{unstyled:!0});return N(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="grep"&&f){const D=z0(p,n,{unstyled:!0});return N(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="glob"&&f){const D=H0(p,n,{unstyled:!0});return N(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="task"&&f)return N(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(kr,{content:p,variant:"tool"})}));if((t.tool==="web-search"||t.tool==="websearch"||t.tool==="search_web")&&f){const D=U0(p,s,{unstyled:!0});return N(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="codesearch"&&f)return N(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(kr,{content:p,variant:"tool"})}));if(t.tool==="skill"&&f)return N(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(kr,{content:p,variant:"tool"})}));if((t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch")&&h)return N(e.jsx($p,{diff:h,syntaxTheme:s,input:u}),{className:"p-1"});if(f&&p.trim()){if(t.tool==="read"){const D=ac(p,t.tool,d),k=D.split(`
183
+ `),M=typeof u?.offset=="number"?u.offset:0,w=typeof u?.limit=="number"?u.limit:void 0,T=E=>E.trim().startsWith("(");return N(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:k.map((E,I)=>{const A=T(E),P=M+I+1,F=!A&&(w===void 0||I<w);return e.jsxs("div",{className:R("typography-code font-mono flex w-full min-w-0",A&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-3 self-start select-none",children:F?P:""}),e.jsx("div",{className:"flex-1 min-w-0",children:A?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(_r,{style:s,language:Jc(D,t.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:E})})]},I)})}),{className:"p-1"})}return N(e.jsx(_r,{style:s,language:Jc(ac(p,t.tool,d),t.tool,u),PreTag:"div",customStyle:{...Ma.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:ac(p,t.tool,d)}),{className:"p-1"})}return N(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:R("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",c?"before:bottom-[-0.6rem]":"before:bottom-0"),children:t.tool==="todowrite"||t.tool==="todoread"||t.tool==="question"?j():e.jsxs(e.Fragment,{children:[b&&y?e.jsx("div",{className:"my-1",children:N(e.jsx(zp,{content:x,filePath:g,displayPath:v??"New file"}))}):b?e.jsx("div",{className:"my-1",children:N(e.jsx(Bp,{content:x,syntaxTheme:s,filePath:g,displayPath:v??"New file"}))}):C?e.jsx("div",{className:"my-1",children:N(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:S}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,t.tool!=="write"&&r.status==="completed"&&"output"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),j()]}),r.status==="error"&&"error"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]})]})})});Hp.displayName="ToolExpandedContent";const Yc=({part:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:c=!1,hasNextTool:l=!1})=>{const d=t.state,u=vt(P=>P.currentDirectory),m=t.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",p=d.status==="running"||d.status==="pending",h=d.status==="error",g=i.useRef(r);i.useEffect(()=>{!f&&!m||g.current!==r&&(g.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const x=d,b=x.metadata,y=x.input,v=x.time,S=i.useRef({}),C=i.useRef(t.id);if(C.current!==t.id&&(C.current=t.id,S.current={}),m){if(typeof v?.start=="number"){const P=S.current.start;(typeof P!="number"||v.start<P)&&(S.current.start=v.start)}typeof v?.end=="number"&&(S.current.end=v.end)}const N=m?S.current.start??v?.start:v?.start,j=m?S.current.end??v?.end:v?.end,D=i.useMemo(()=>{if(!m)return;const P=b;return typeof P?.sessionId=="string"?P.sessionId:void 0},[m,b]),k=i.useMemo(()=>{if(!m)return[];const P=b?.summary;return Array.isArray(P)?P.filter(F=>typeof F=="object"&&F!==null):[]},[m,b]),M=i.useRef(k.length);i.useEffect(()=>{m&&M.current!==k.length&&(M.current=k.length,a?.("structural"))},[m,a,k.length]);const w=t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch"?q0(b):null,T=J0(t,d,o,u),E=Cl(t.tool).displayName,I=i.useContext(Nl),A=P=>{if(m||!I?.editor){s(t.id);return}let F;if((t.tool==="edit"||t.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(t.tool))&&(F=y?.filePath||y?.file_path||y?.path||b?.filePath||b?.file_path||b?.path),typeof F=="string"){P.stopPropagation();let z=F;F.startsWith("/")||(z=u.endsWith("/")?u+F:u+"/"+F),I.editor.openFile(z)}else s(t.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:A,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:P=>{P.stopPropagation(),s(t.id)},children:[e.jsx("div",{className:R("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&h?{color:"var(--status-error)"}:{},children:_p(t.tool)}),e.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",r&&"opacity-100",!r&&o&&"opacity-0",!r&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:r?e.jsx(Wt,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:E})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[T&&e.jsx("span",{className:R("truncate",o&&"max-w-[120px]"),children:T}),w&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",w.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",w.removed]})]}),typeof N=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(G0,{start:N,end:typeof j=="number"?j:void 0,active:!!(m&&p&&typeof j!="number")})})]})]}),m&&(k.length>0||p||f||D)?e.jsx(X0,{entries:k,isExpanded:r,hasPrevTool:c,hasNextTool:l,output:typeof x.output=="string"?x.output:void 0,sessionId:D}):null,!m&&r?e.jsx(Hp,{part:t,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:c,hasNextTool:l}):null]})},Z0={thinking:{label:"Thinking",Icon:Mr},justification:{label:"Justification",Icon:cl}},eS=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
184
+ `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
185
+ `).trim(),tS=t=>{if(!t)return"";const r=t.trim(),s=r.indexOf(`
186
+ `),n=r.indexOf("."),o=[s>=0?s:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?r.substring(0,a).trim():r},Wp=({text:t,variant:r,onContentChange:s,blockId:n})=>{const[o,a]=i.useState(!1),c=i.useMemo(()=>tS(t),[t]),{label:l,Icon:d}=Z0[r];return i.useEffect(()=>{t.trim().length!==0&&s?.("structural")},[s,o,t]),!t||t.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>a(u=>!u),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:R("absolute inset-0 transition-opacity",o&&"opacity-0",!o&&"group-hover/tool:opacity-0"),children:e.jsx(d,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",o&&"opacity-100",!o&&"opacity-0 group-hover/tool:opacity-100"),children:o?e.jsx(Wt,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:l})]}),c&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:c})})]}),o&&e.jsx("div",{className:R("relative pr-2 pb-2 pt-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:e.jsx(xt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:t})})]})},sS=({part:t,onContentChange:r,messageId:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>eS(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(Wp,{text:a,variant:"thinking",onContentChange:r,blockId:t.id||`${s}-reasoning`}):null},rS=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
187
+ `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
188
+ `).trim(),nS=({part:t,messageId:r,onContentChange:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>rS(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(Wp,{text:a,variant:"justification",onContentChange:s,blockId:t.id||`${r}-justification`}):null},oS=i.memo(nS),Iu=6,aS=t=>[...t].sort((r,s)=>{const n=typeof r.endedAt=="number"?r.endedAt:void 0,o=typeof s.endedAt=="number"?s.endedAt:void 0;return n===void 0&&o===void 0?0:n===void 0?1:o===void 0?-1:n-o}),Pu=t=>{const r={},s=t.filter(n=>n.kind==="tool");return s.forEach((n,o)=>{const a=n.part.id;a&&(r[a]={hasPrev:o>0,hasNext:o<s.length-1})}),r},iS=({parts:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:c,onContentChange:l,diffStats:d})=>{const u=i.useRef(r),[m,f]=i.useState(!1),[p,h]=i.useState(0),g=i.useRef(new Set);i.useEffect(()=>{if(u.current===r)return;const k=u.current===!1;if(u.current=r,l?.("structural"),r&&k){h(w=>w+1),f(!0),g.current.clear();const M=setTimeout(()=>f(!1),50);return()=>clearTimeout(M)}else f(!1)},[r,l]);const x=i.useMemo(()=>aS(t),[t]),b=Pu(x),y=i.useMemo(()=>x.slice(-Iu),[x]),v=i.useMemo(()=>{const k=new Set;return y.forEach(M=>{M.part.id&&k.add(M.part.id)}),k},[y]),S=i.useMemo(()=>Pu(y),[y]),C=Math.max(0,x.length-Iu);if(x.length===0)return null;const N=r?x:y,j=r?b:S,D=C>0;return e.jsx(hr,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl",D&&"cursor-pointer"),onClick:D?s:void 0,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:D?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(ro,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",r&&"opacity-100",!r&&o&&"opacity-0",!r&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:r?e.jsx(Wt,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"})})]}):e.jsx(ro,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),d&&(d.additions>0||d.deletions>0)&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,d.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,d.deletions)]})]})})]}),e.jsxs("div",{className:R("relative pr-2 pb-1 pt-1 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:[!r&&C>0&&e.jsxs("div",{className:"typography-micro text-muted-foreground/70 mb-1 cursor-pointer hover:text-muted-foreground",onClick:s,children:["+",C," more..."]}),N.map((k,M)=>{const w=k.part.id||`group-part-${M}`,T=j[w],E=`${w}-exp${p}`,I=k.part.id?v.has(k.part.id):!1;let A=!1;switch(m&&I?A=!0:!r&&k.part.id&&(g.current.has(k.part.id)?A=!0:g.current.add(k.part.id)),k.kind){case"tool":return e.jsx(hr,{skipAnimation:A,children:e.jsx(Yc,{part:k.part,isExpanded:a.has(w),onToggle:c,syntaxTheme:n,isMobile:o,onContentChange:l,hasPrevTool:T?.hasPrev??!1,hasNextTool:T?.hasNext??!1})},E);case"reasoning":return e.jsx(hr,{skipAnimation:A,children:e.jsx(sS,{part:k.part,messageId:k.messageId,onContentChange:l})},E);case"justification":return e.jsx(hr,{skipAnimation:A,children:e.jsx(oS,{part:k.part,messageId:k.messageId,onContentChange:l})},E);default:return null}})]})]})})},cS=i.memo(iS),_l=t=>{const r=t,s=r.text;return typeof s=="string"?s:r.content||r.value||""},Up=t=>{if(t.type!=="text")return!1;const r=_l(t);return!r||r.trim().length===0},lS=(t,r={})=>{const{includeReasoning:s=!0}=r,n=t.some(o=>!o.synthetic);return t.filter(o=>{const c=!!o.synthetic;return c&&o.type==="text"&&_l(o).includes("<system-reminder>")||c&&n||!s&&o.type==="reasoning"?!1:!(o.type==="patch")})},dS=t=>{const r=t/1e3;if(r<60)return`${r.toFixed(1)}s`;const s=Math.floor(r/60),n=Math.round(r%60);return`${s}m ${n}s`},uS=new Set(["task"]),ya=t=>typeof t=="string"&&uS.has(t.toLowerCase()),mS=({messageId:t,parts:r,isMobile:s,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:c,onShowPopup:l,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=i.useState(!1),h=i.useRef(null),g=i.useMemo(()=>r.filter(k=>k.type!=="text"?!1:!Up(k)),[r]),x=d?.token;let b=!1;const y=!!a,v=!!c,S=!!(n??s),C=!!o,N=i.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),j=i.useCallback(()=>{!S||!y||!C||typeof window>"u"||(N(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[y,N,C,S]);i.useEffect(()=>{C||(p(!1),N())},[N,C]);const D=i.useCallback(k=>{!a||!C||(k.stopPropagation(),k.preventDefault(),a(),S&&j())},[C,S,a,j]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&y&&C?j:void 0,children:[e.jsx("div",{className:"leading-relaxed overflow-hidden text-foreground/90 text-base",children:g.map((k,M)=>{let w;return d&&x&&!b&&_l(k).includes(x)&&(w=d,b=!0),e.jsx(hr,{children:e.jsx(M0,{part:k,messageId:t,isMobile:s,agentMention:w})},`user-text-${M}`)})}),e.jsx(Cp,{files:r,onShowPopup:l}),y&&C||u||m?e.jsxs("div",{className:R("mt-1 flex items-center justify-end gap-2"),children:[u&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Revert to this message",onPointerDown:k=>k.stopPropagation(),onClick:k=>{k.stopPropagation(),u()},children:e.jsx(so,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:k=>k.stopPropagation(),onClick:k=>{k.stopPropagation(),m()},children:e.jsx(Ut,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Fork from here"})]}),y&&C&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{type:"button",variant:"ghost",size:"icon","data-visible":f||v?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:k=>k.stopPropagation(),onClick:D,onFocus:()=>p(!0),onBlur:()=>{v||p(!1)},children:v?e.jsx(Tt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(nr,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy message"})]})]}):null]})},fS=({messageId:t,parts:r,isMessageCompleted:s,messageFinish:n,messageCompletedAt:o,syntaxTheme:a,isMobile:c,hasTouchInput:l,expandedTools:d,onToggleTool:u,onShowPopup:m,streamPhase:f,allowAnimation:p,onContentChange:h,hasTextContent:g=!1,onCopyMessage:x,copiedMessage:b=!1,onAuxiliaryContentComplete:y,showReasoningTraces:v=!1,turnGroupingContext:S,errorMessage:C})=>{const[N,j]=i.useState(!1),D=i.useRef(null),k=!!x,M=!!b,w=!!(l??c),T=!s,E=i.useMemo(()=>r.filter(Te=>!Up(Te)).filter(Te=>Te.type!=="compaction"),[r]),I=i.useMemo(()=>E.filter(Te=>Te.type==="tool"),[E]),A=i.useMemo(()=>E.filter(Te=>Te.type==="text"),[E]),P=ve(Te=>Te.createSessionFromAssistantMessage),F=Me(Te=>Te.openMultiRunLauncherWithPrompt),z=S?.isLastAssistantInTurn??!1,G=n==="stop",oe=I.length>0,O=i.useMemo(()=>I.some(Te=>{const Fe=(Te.state??{})?.status;return Fe==="pending"||Fe==="running"||Fe==="started"}),[I]),q=i.useCallback(Te=>{const Pe=Te.state??{},Fe=Pe?.status;if(Fe==="pending"||Fe==="running"||Fe==="started")return!1;const Ve=Pe?.time??{},et=typeof Ve?.end=="number"?Ve.end:void 0,ot=typeof Ve?.start=="number"?Ve.start:void 0;return!(typeof et!="number"||typeof ot=="number"&&et<ot)},[]),Y=i.useMemo(()=>I.length===0?!0:O?!1:I.every(Te=>q(Te)),[I,O,q]),Z=i.useMemo(()=>E.filter(Te=>Te.type==="reasoning"),[E]),B=i.useMemo(()=>Z.length===0?!0:Z.every(Te=>typeof Te.time?.end=="number"),[Z]),W=typeof n!="string",te=Z.length>0&&oe&&(O||W||!Y),ye=T||oe&&(O||W||!Y),me=T||te,K=oe||Z.length>0,L=A.length===0,Q=K&&L&&!ye&&!me&&Y&&B,ce=i.useRef(!1),he=i.useRef(!1);i.useEffect(()=>{he.current=!1},[t]),i.useEffect(()=>{if(!Q){ce.current=!1;return}ce.current||(ce.current=!0,y?.())},[Q,y]),i.useEffect(()=>{if(T){he.current=!1;return}if(oe){he.current=!1;return}Z.length!==0&&(me||!B||he.current||(he.current=!0,h?.("structural")))},[T,oe,h,B,Z.length,me]);const Ne=!!g&&!T,H=i.useCallback(()=>{D.current!==null&&typeof window<"u"&&(window.clearTimeout(D.current),D.current=null)},[]),we=i.useCallback(()=>{!w||!k||!Ne||typeof window>"u"||(H(),j(!0),D.current=window.setTimeout(()=>{j(!1),D.current=null},1800))},[k,H,Ne,w]);i.useEffect(()=>{Ne||(j(!1),H())},[H,Ne]);const ee=i.useCallback(Te=>{!x||!Ne||(Te.stopPropagation(),Te.preventDefault(),x(),w&&we())},[Ne,w,x,we]),ue=i.useCallback(Te=>{Te.stopPropagation(),Te.preventDefault(),P&&P(t)},[P,t]),ge=i.useCallback(Te=>{Te.stopPropagation(),Te.preventDefault();const Pe=Sl(A);if(!Pe.trim())return;const Fe=`${vw}
189
+
190
+ ${Pe}`;F(Fe)},[A,F]);i.useEffect(()=>()=>{H()},[H]);const X=i.useMemo(()=>{const Te={},Pe=I.filter(Fe=>ya(Fe.tool)||ye?!1:q(Fe));return Pe.forEach((Fe,Ve)=>{Te[Fe.id]={hasPrev:Ve>0,hasNext:Ve<Pe.length-1}}),Te},[I,ye,q]),de=i.useMemo(()=>S?.activityParts??[],[S]),ae=i.useMemo(()=>S?de.filter(Te=>Te.messageId===t):[],[de,t,S]),fe=i.useMemo(()=>S?S.activityGroupSegments.filter(Te=>Te.anchorMessageId===t):[],[t,S]),ie=i.useMemo(()=>{const Te=new Map;return ae.forEach(Pe=>{Te.set(Pe.part,Pe)}),Te},[ae]),se=i.useMemo(()=>S?(v?de:de.filter(Pe=>Pe.kind==="tool")).filter(Pe=>{if(Pe.kind!=="tool")return!0;const Fe=Pe.part.tool;return!ya(Fe)}):[],[de,v,S]),[re,ne]=i.useState(!1);i.useEffect(()=>{if(!S)return;const Te=S.activityGroupSegments.some(Pe=>Pe.afterToolPartId!==null);(se.length>1||Te&&se.length>0)&&ne(!0)},[S,se.length]);const xe=!!(S&&re),Ue=!!(S&&xe&&se.length>0&&fe.length>0),ze=i.useMemo(()=>I.filter(Te=>ya(Te.tool)),[I]),Ke=i.useMemo(()=>{const Te=[],Pe=Ve=>{!S||!Ue||fe.filter(et=>(et.afterToolPartId??null)===Ve).forEach(et=>{const ot=v?et.parts:et.parts.filter(yt=>yt.kind==="tool");ot.length!==0&&Te.push(e.jsx(cS,{parts:ot,isExpanded:S.isGroupExpanded,onToggle:S.toggleGroup,syntaxTheme:a,isMobile:c,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,diffStats:S.diffStats},`progressive-group-${et.id}`))})};Pe(null),ze.forEach(Ve=>{Te.push(e.jsx(hr,{children:e.jsx(Yc,{part:Ve,isExpanded:d.has(Ve.id),onToggle:u,syntaxTheme:a,isMobile:c,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Ve.id}`)),Pe(Ve.id)});const Fe=[];return E.forEach((Ve,et)=>{const ot=ie.get(Ve);if(!ot||!S)return;let yt=null,Dt=null;if(!xe){if(ot.kind==="tool"){const bt=Ve;if(ya(bt.tool))return;const Vt=bt.state?.time,Ft=q(bt);if(!(!ye&&Ft))return;const Rt=X[bt.id];Dt=e.jsx(hr,{children:e.jsx(Yc,{part:bt,isExpanded:d.has(bt.id),onToggle:u,syntaxTheme:a,isMobile:c,onContentChange:h,hasPrevTool:Rt?.hasPrev??!1,hasNextTool:Rt?.hasNext??!1})},`tool-${bt.id}`),yt=Ft&&typeof Vt?.end=="number"?Vt.end:null}Dt&&Fe.push({part:Ve,index:et,endTime:yt,element:Dt})}}),Fe.sort((Ve,et)=>Ve.endTime===null&&et.endTime===null?Ve.index-et.index:Ve.endTime===null?1:et.endTime===null?-1:Ve.endTime-et.endTime),Fe.forEach(({element:Ve})=>{Te.push(Ve)}),Te},[ie,fe,d,c,q,h,m,u,ye,xe,v,a,X,S,E,ze,Ue]),rt=S?.turnId,jt=ve(Te=>Te.currentSessionId),Xe=Nt(Te=>{if(!rt||!jt)return;const Pe=Te.messages.get(jt);if(!Pe)return;const Fe=Pe.find(ot=>ot.info?.id===rt);if(!Fe)return;const et=Fe.info.summary?.body;return typeof et=="string"&&et.trim().length>0?et:void 0}),Ct=typeof S?.summaryBody=="string"&&S.summaryBody.trim().length>0?S.summaryBody:Xe,st=i.useRef(void 0);Ct&&Ct.trim().length>0&&(st.current=Ct);const mt=i.useRef(rt);mt.current!==rt&&(mt.current=rt,st.current=void 0);const Pt=st.current,Ot=S?.isLastAssistantInTurn&&Pt&&Pt.trim().length>0,$e=!!C,be=z&&g&&(G||!!C),[tt,Ce]=i.useState(!1),Ie=i.useMemo(()=>{if(!z||!G)return;const Te=S?.userMessageCreatedAt;if(!(typeof Te!="number"||typeof o!="number")&&!(o<=Te))return dS(o-Te)},[z,G,S?.userMessageCreatedAt,o]),Qe=e.jsxs(e.Fragment,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:Te=>Te.stopPropagation(),onClick:ue,children:e.jsx(fx,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:Te=>Te.stopPropagation(),onClick:ge,children:e.jsx(yp,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),x&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{type:"button",variant:"ghost",size:"icon","data-visible":N||M?"true":void 0,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!Ne&&"opacity-50"),disabled:!Ne,"aria-label":"Copy message text","aria-hidden":!Ne,onPointerDown:Te=>Te.stopPropagation(),onClick:ee,onFocus:()=>{Ne&&j(!0)},onBlur:()=>{M||j(!1)},children:M?e.jsx(Tt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(nr,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:R("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:w&&k&&Ne?we:void 0,children:e.jsxs("div",{children:[e.jsxs("div",{className:"leading-relaxed overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Ke,$e&&e.jsx(hr,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(kr,{content:C??""})})},"assistant-error"),Ot&&e.jsx(hr,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Ce(!0),onMouseLeave:()=>Ce(!1),children:[e.jsx(kr,{content:Pt}),be&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[Ie?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),Ie]}):e.jsx("span",{}),e.jsx("div",{className:R("flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",tt&&"opacity-100 pointer-events-auto"),children:Qe})]})]})},"summary-body")]}),e.jsx(Cp,{files:r,onShowPopup:m}),!Ot&&be&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[Ie?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),Ie]}):e.jsx("span",{}),e.jsx("div",{className:"flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",children:Qe})]})]})})},pS=({isUser:t,...r})=>t?e.jsx(mS,{messageId:r.messageId,parts:r.parts,isMobile:r.isMobile,hasTouchInput:r.hasTouchInput,hasTextContent:r.hasTextContent,onCopyMessage:r.onCopyMessage,copiedMessage:r.copiedMessage,onShowPopup:r.onShowPopup,agentMention:r.agentMention,onRevert:r.onRevert,onFork:r.onFork}):e.jsx(fS,{...r}),Tu=i.memo(pS),ic=t=>{const r=t,s=r?.clientRole,n=r?.role;return r?.userMessageMarker===!0||s==="user"||n==="user"||r?.origin==="user"||r?.source==="user"?{role:"user",isUser:!0}:{role:s||n||"assistant",isUser:!1}},hS=i.lazy(()=>vs(()=>import("./ToolOutputDialog-BSKxzwkK.js"),__vite__mapDeps([2,0,1,3,4]))),gS=new Set(["task","edit","multiedit","write","bash"]),Fu=t=>typeof t=="string"&&gS.has(t.toLowerCase());function cc(t){const r=i.useRef({hasValue:!1,value:void 0});return t!=null&&(!r.current.hasValue||r.current.value!==t)&&(r.current={hasValue:!0,value:t}),r.current.hasValue?r.current.value:t}const Qs=(t,r)=>{if(typeof t=="object"&&t!==null)return t[r]},xS=({message:t,previousMessage:r,nextMessage:s,onContentChange:n,animationHandlers:o,turnGroupingContext:a})=>{const{isMobile:c,hasTouchInput:l}=Gt(),{currentTheme:d}=Wr(),u=i.useRef(null),m=ve(Un(U=>({lifecyclePhase:U.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const J=t.info.sessionID??U.currentSessionId??null;return J?(U.streamingMessageIds.get(J)??null)===t.info.id:!1})(),currentSessionId:U.currentSessionId,getAgentModelForSession:U.getAgentModelForSession,getSessionModelSelection:U.getSessionModelSelection,revertToMessage:U.revertToMessage,forkFromMessage:U.forkFromMessage}))),{lifecyclePhase:f,isStreamingMessage:p,currentSessionId:h,getAgentModelForSession:g,getSessionModelSelection:x,revertToMessage:b,forkFromMessage:y}=m,v=Je(U=>U.providers),{showReasoningTraces:S,toolCallExpansion:C}=Me(Un(U=>({showReasoningTraces:U.showReasoningTraces,toolCallExpansion:U.toolCallExpansion})));i.useEffect(()=>{h&&Jr.getInstance().recordSessionStart(h)},[h]);const[N,j]=i.useState(null),[D,k]=i.useState(!1),[M,w]=i.useState(new Set),[T,E]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{w(new Set)},[t.info.id,C]);const A=i.useMemo(()=>ic(t.info),[t.info]).isUser,P=t.info.sessionID,{currentContextAgent:F,savedSessionAgentSelection:z}=Ye(Un(U=>({currentContextAgent:P?U.currentAgentContext.get(P):void 0,savedSessionAgentSelection:P?U.sessionAgentSelections.get(P):void 0}))),G=i.useMemo(()=>{if(!A)return t.parts;const U=J=>{const pe=J.trim();return!!(pe.startsWith("User has requested to enter plan mode")||pe.startsWith("The plan at "))};return t.parts.filter(J=>{if(!(J?.synthetic===!0))return!0;if(J.type!=="text")return!1;const Ee=J?.text;return typeof Ee=="string"?U(Ee):!1}).map(J=>J.type==="compaction"?{type:"text",text:"/compact"}:J)},[A,t.parts]),oe=i.useMemo(()=>{if(A||!r)return null;const U=Qs(r.info,"clientRole"),J=Qs(r.info,"role");if((typeof U=="string"?U:typeof J=="string"?J:void 0)!=="user")return null;const Ee=Qs(r.info,"mode"),He=Qs(r.info,"agent"),ft=Qs(r.info,"providerID"),pt=Qs(r.info,"modelID"),wt=Qs(r.info,"variant"),at=typeof Ee=="string"&&Ee.trim().length>0?Ee:typeof He=="string"&&He.trim().length>0?He:void 0,_t=typeof ft=="string"&&ft.trim().length>0?ft:void 0,qt=typeof pt=="string"&&pt.trim().length>0?pt:void 0,ht=typeof wt=="string"&&wt.trim().length>0?wt:void 0;return!at&&!_t&&!qt&&!ht?null:{agentName:at,providerId:_t,modelId:qt,variant:ht}},[A,r]),O=i.useMemo(()=>{if(A||!r)return!1;const U=Array.isArray(r.parts)?r.parts:[];for(let J=0;J<U.length;J++){const pe=U[J];if(pe?.type!=="text"||pe?.synthetic!==!0)continue;const Ee=typeof pe.text=="string"?pe.text.trim():"";if(Ee.startsWith("User has requested to enter plan mode")||Ee.startsWith("The plan at "))return!0}return!1},[A,r]),q=i.useMemo(()=>{if(A)return;const U=t.info.time;if(!(typeof U?.completed=="number"&&U.completed>0)&&O&&oe?.agentName)return oe.agentName;const pe=Qs(t.info,"mode");if(typeof pe=="string"&&pe.trim().length>0)return pe;const Ee=Qs(t.info,"agent");if(typeof Ee=="string"&&Ee.trim().length>0)return Ee;if(oe?.agentName)return oe.agentName;if(P)return F||(z??void 0)},[A,t.info,O,oe,P,F,z]),Y=A?null:Qs(t.info,"providerID"),Z=A?null:Qs(t.info,"modelID"),B=i.useMemo(()=>{if(A||!P)return null;if(oe?.providerId&&oe?.modelId)return{providerId:oe.providerId,modelId:oe.modelId};if(q){const J=g(P,q);if(J?.providerId&&J?.modelId)return J}const U=x(P);return U?.providerId&&U?.modelId?U:null},[A,P,q,oe,g,x]),W=i.useMemo(()=>A?null:typeof Y=="string"&&Y.trim().length>0?Y:B?.providerId??null,[A,Y,B]),te=i.useMemo(()=>A?null:typeof Z=="string"&&Z.trim().length>0?Z:B?.modelId??null,[A,Z,B]),ye=i.useMemo(()=>{if(!A&&W&&te&&v.length>0){const U=v.find(J=>J.id===W);if(U?.models&&Array.isArray(U.models)){const Ee=U.models.find(He=>He.id===te)?.name;return typeof Ee=="string"?Ee:void 0}}},[A,W,te,v]),me=i.useMemo(()=>{if(A||!W||!te)return!1;const U=v.find(Ee=>Ee.id===W);if(!U?.models||!Array.isArray(U.models))return!1;const pe=U.models.find(Ee=>Ee.id===te)?.variants;return!!(pe&&Object.keys(pe).length>0)},[A,te,W,v]),K=cc(q),L=cc(W??void 0),Q=cc(ye),ce=K??void 0,he=L??null,Ne=Q??void 0,H=i.useMemo(()=>{const U=t.info.time;return typeof U?.completed=="number"?U.completed:null},[t.info.time]),we=i.useMemo(()=>A?!0:!!(H&&H>0),[A,H]),ee=i.useMemo(()=>{const U=t.info.finish;return typeof U=="string"?U:void 0},[t.info]),ue=i.useMemo(()=>lS(G,{includeReasoning:S}),[G,S]),ge=i.useMemo(()=>A||we?ue:[],[A,we,ue]),X=i.useMemo(()=>A?[]:ue.filter(U=>U.type==="text"),[A,ue]),de=i.useMemo(()=>A?[]:ue.filter(J=>J.type==="tool"),[A,ue]),ae=i.useMemo(()=>{if(C==="collapsed"||C==="activity")return M;const U=new Set;for(const pe of de){const Ee=pe.tool;pe.id&&Fu(Ee)&&U.add(pe.id)}if(a?.isFirstAssistantInTurn)for(const pe of a.activityParts){if(pe.kind!=="tool")continue;const Ee=pe.part;Ee.id&&Fu(Ee.tool)&&U.add(Ee.id)}const J=new Set(U);for(const pe of M)J.has(pe)?J.delete(pe):J.add(pe);return J},[M,C,de,a]),fe=i.useMemo(()=>{if(!A)return;const U=t.parts.find(He=>He.type==="agent");if(!U)return;const J=U,pe=typeof J.name=="string"?J.name:void 0;if(!pe)return;const Ee=J.source&&typeof J.source.value=="string"&&J.source.value.trim().length>0?J.source.value:`#${pe}`;return{name:pe,token:Ee}},[A,t.parts]),ie=typeof ee!="string",se=i.useMemo(()=>A?!1:X.length===0||de.length===0?ie:!0,[X.length,de.length,ie,A]),re=d?.metadata.variant,ne=i.useMemo(()=>re?re==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[re]),xe=i.useMemo(()=>d?Fi(d):ne?w0:v0,[d,ne]),Ue=i.useMemo(()=>A?!1:Jr.getInstance().shouldAnimateMessage(t.info,h||t.info.sessionID),[t.info,h,A]),ze=i.useRef(!1),Ke=i.useMemo(()=>r?ic(r.info):null,[r]),rt=i.useMemo(()=>s?ic(s.info):null,[s]),jt=i.useMemo(()=>A||!rt?!1:!rt.isUser&&rt.role==="assistant",[A,rt]),Xe=i.useMemo(()=>we?"completed":f||(p?"streaming":"completed"),[we,f,p]),Ct=i.useMemo(()=>{if(A)return!0;const U=a?.headerMessageId;if(U){if(t.info.id===U){if(Xe==="completed")return!0;const pe=Xe==="streaming"||Xe==="cooldown",Ee=ze.current;return pe&&!Ee&&(ze.current=!0),Ee||pe}return!1}return Ke?Ke.isUser:!0},[A,Ke,a,Xe,t.info]),st=i.useCallback(U=>{navigator.clipboard.writeText(U),j(U),setTimeout(()=>j(null),2e3)},[]),mt=a?.turnId,{assistantSummaryFromStore:Pt,variantFromTurnStore:Ot}=Nt(Un(U=>{if(!mt||!t.info.sessionID)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const J=U.messages.get(t.info.sessionID);if(!J)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const pe=J.find(pt=>pt.info?.id===mt);if(!pe)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const He=pe.info.summary?.body,ft=pe.info.variant;return{assistantSummaryFromStore:typeof He=="string"&&He.trim().length>0?He:void 0,variantFromTurnStore:typeof ft=="string"&&ft.trim().length>0?ft:void 0}})),$e=A?void 0:Ot??oe?.variant,be=!A&&me?$e??"Default":void 0,tt=typeof a?.summaryBody=="string"&&a.summaryBody.trim().length>0?a.summaryBody:Pt,Ce=i.useRef(void 0);tt&&tt.trim().length>0&&(Ce.current=tt);const Ie=i.useRef(mt);Ie.current!==mt&&(Ie.current=mt,Ce.current=void 0);const Qe=Ce.current,Te=i.useMemo(()=>{if(A)return;const U=t.info?.error;if(!U)return;const J=typeof U.data?.message=="string"?U.data.message:void 0,pe=typeof U.message=="string"?U.message:void 0,Ee=typeof U.name=="string"?U.name:void 0,He=J||pe||Ee;if(He)return`Opencode failed to send message with error:
191
+ \`${He}\``},[A,t.info]),Pe=i.useMemo(()=>A?ge.filter(pe=>pe.type==="text").map(pe=>(pe.text||pe.content||"").trim()).filter(pe=>pe.length>0).join(`
192
+ `).replace(/\n\s*\n+/g,`
193
+ `):Te&&Te.trim().length>0?Te:Qe&&Qe.trim().length>0?Qe:Sl(ge),[Te,Qe,ge,A]),Fe=Pe.length>0,Ve=i.useCallback(async U=>{if(!U)return!1;if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(U),!0}catch{}if(typeof document>"u")return!1;const J=document.createElement("textarea");J.value=U,J.setAttribute("readonly",""),J.style.position="fixed",J.style.top="-1000px",J.style.left="-1000px",document.body.appendChild(J),J.select(),J.setSelectionRange(0,J.value.length);const pe=document.execCommand("copy");return document.body.removeChild(J),pe},[]),et=i.useCallback(async()=>{await Ve(Pe)&&(k(!0),setTimeout(()=>k(!1),2e3))},[Ve,Pe]),ot=i.useCallback(()=>{!P||!t.info.id||b(P,t.info.id)},[P,t.info.id,b]),yt=i.useCallback(()=>{!P||!t.info.id||y(P,t.info.id)},[P,t.info.id,y]),Dt=i.useCallback(U=>{w(J=>{const pe=new Set(J);return pe.has(U)?pe.delete(U):pe.add(U),pe})},[]),bt=o??null,Qt=i.useRef(!1),Vt=i.useRef(!1),Ft=i.useRef(!1),Kt=i.useRef(!1),Rt=i.useRef(!1);i.useEffect(()=>{Vt.current=!1,Ft.current=!1,Kt.current=!1,Rt.current=!1,Qt.current=!1},[t.info.id]);const cs=i.useCallback(()=>{A||Qt.current||(Qt.current=!0,n?.("structural"))},[A,n]),Ns=i.useCallback(U=>{U.image&&E(U)},[]),bs=i.useCallback(U=>{E(J=>({...J,open:U}))},[]),Cs=!!Qs(t.info,"animationSettled"),Ms=Xe==="streaming",ps=i.useMemo(()=>A?!1:ue.some(U=>U.type==="reasoning"),[A,ue]),Xt=Ue&&!Cs&&!Ms,$=!A&&Ue&&X.length>0&&!se;return i.useEffect(()=>{if(bt?.onStreamingCandidate){if(!$){Ft.current&&(ps&&bt?.onReasoningBlock?bt.onReasoningBlock():bt?.onReservationCancelled&&bt.onReservationCancelled(),Ft.current=!1);return}Rt.current||(Rt.current=!0,bt.onStreamingCandidate(),Ft.current=!0)}},[bt,$,ps]),i.useEffect(()=>{bt?.onAnimationStart&&Xt&&(Kt.current||(bt.onAnimationStart(),Kt.current=!0))},[bt,Xt]),i.useEffect(()=>{if(A)return;const U=bt?.onAnimatedHeightChange;if(!U||!(Xt||$))return;const pe=u.current;if(!pe)return;if(typeof window>"u"||typeof ResizeObserver>"u"){U(pe.getBoundingClientRect().height);return}let Ee=null;const He=pt=>{if(typeof window>"u"){U(pt);return}Ee!==null&&window.cancelAnimationFrame(Ee),Ee=window.requestAnimationFrame(()=>{U(pt)})},ft=new ResizeObserver(pt=>{const wt=pt[0];wt&&He(wt.contentRect.height)});return ft.observe(pe),He(pe.getBoundingClientRect().height),()=>{Ee!==null&&(window.cancelAnimationFrame(Ee),Ee=null),ft.disconnect()}},[Xt,A,bt,$]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("group w-full",Ct?"pt-6":"pt-0",A?"pb-4":jt?"pb-0":"pb-8"),"data-message-id":t.info.id,ref:u,children:e.jsx("div",{className:"chat-message-column relative",children:A?ge.length===0?null:e.jsx(hr,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-sm bg-primary/10 dark:bg-primary/10 px-5 py-3 shadow-sm border border-primary/5",children:e.jsx(Tu,{messageId:t.info.id,parts:ge,isUser:A,isMessageCompleted:we,messageFinish:ee,syntaxTheme:xe,isMobile:c,hasTouchInput:l,copiedCode:N,onCopyCode:st,expandedTools:M,onToggleTool:Dt,onShowPopup:Ns,streamPhase:Xe,allowAnimation:Xt,onContentChange:n,shouldShowHeader:!1,hasTextContent:Fe,onCopyMessage:et,copiedMessage:D,showReasoningTraces:S,onAuxiliaryContentComplete:cs,agentMention:fe,onRevert:ot,onFork:A?yt:void 0,errorMessage:Te})})})}):e.jsxs("div",{className:"relative pl-4 ml-1",children:[Ct&&e.jsx(N0,{isUser:A,providerID:he,agentName:ce,modelName:Ne,variant:be,isDarkTheme:ne}),e.jsx(Tu,{messageId:t.info.id,parts:ue,isUser:A,isMessageCompleted:we,messageFinish:ee,messageCompletedAt:H??void 0,syntaxTheme:xe,isMobile:c,hasTouchInput:l,copiedCode:N,onCopyCode:st,expandedTools:ae,onToggleTool:Dt,onShowPopup:Ns,streamPhase:Xe,allowAnimation:Xt,onContentChange:n,shouldShowHeader:Ct,hasTextContent:Fe,onCopyMessage:et,copiedMessage:D,onAuxiliaryContentComplete:cs,showReasoningTraces:S,agentMention:fe,turnGroupingContext:a,errorMessage:Te})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(hS,{popup:T,onOpenChange:bs,syntaxTheme:xe,isMobile:c})})]})},Vp=i.memo(xS),yS=({diff:t,syntaxTheme:r,filePath:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Op(t).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file||s?.split("/").pop()||"file"} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,c)=>e.jsxs("div",{className:R("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(_r,{style:r,language:Er(s||n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},c))})]},o))}),bS=({content:t,syntaxTheme:r,filePath:s})=>{const n=t.split(`
194
+ `),o=Er(s??"")||"text",a=s?.split("/").pop()||"New file",c=Math.max(n.length,1),l=c===1?"line 1":`lines 1-${c}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${l})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(_r,{style:r,language:o,PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},wS=t=>{const r="h-3 w-3",s=t.toLowerCase();return s==="edit"||s==="multiedit"||s==="str_replace"||s==="str_replace_based_edit_tool"?e.jsx(Fr,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(Gm,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?e.jsx(rn,{className:r}):s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?e.jsx(Ac,{className:r}):e.jsx(pi,{className:r})},vS=t=>{const r=t.toLowerCase();return r==="edit"||r==="multiedit"||r==="str_replace"||r==="str_replace_based_edit_tool"?"edit":r==="write"||r==="create"||r==="file_write"?"write":r==="bash"||r==="shell"||r==="cmd"||r==="terminal"||r==="shell_command"?"bash":r==="webfetch"||r==="fetch"||r==="curl"||r==="wget"?"webfetch":t},jS=({permission:t,onResponse:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(!1),{respondToPermission:c}=ve(),{currentTheme:l}=Wr(),d=i.useMemo(()=>Fi(l),[l]),u=async y=>{n(!0);try{await c(t.sessionID,t.id,y),a(!0),r?.(y)}catch{}finally{n(!1)}};if(o)return null;const m=t.permission||"unknown",f=m.toLowerCase(),p=(y,v="")=>{const S=t.metadata[y];return typeof S=="string"?S:typeof S=="number"?String(S):v},h=y=>{const v=t.metadata[y];return typeof v=="number"?v:void 0},g=y=>!!t.metadata[y],x=vS(m),b=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const S=p("command")||p("cmd")||p("script"),C=p("description"),N=p("cwd")||p("working_directory")||p("directory")||p("path"),j=h("timeout");return e.jsxs(e.Fragment,{children:[C&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:C}),N&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Working Directory:"})," ",e.jsx("code",{className:"px-1 py-0.5 bg-muted/30 rounded",children:N})]}),j&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",j,"ms"]}),S&&e.jsx("div",{children:e.jsx(_r,{language:"bash",style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:S})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),C=p("changes")||p("diff"),N=g("replace_all")||g("replaceAll");return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),C&&e.jsx(xt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(yS,{diff:C,syntaxTheme:d,filePath:S})})]})}if(f==="write"||f==="create"||f==="file_write"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),C=p("content")||p("text")||p("data");return C?e.jsx(xt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(bS,{content:C,syntaxTheme:d,filePath:S})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const S=p("url")||p("uri")||p("endpoint"),C=p("method")||"GET",N=t.metadata.headers&&typeof t.metadata.headers=="object"?t.metadata.headers:void 0,j=p("body")||p("data")||p("payload"),D=h("timeout"),k=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[S&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Request:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded",children:C}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:S})]})]}),N&&Object.keys(N).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(xt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(_r,{language:"json",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:JSON.stringify(N,null,2)})})]}),j&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(xt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(_r,{language:typeof j=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof j=="object"?JSON.stringify(j,null,2):String(j)})})]}),(D||k)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[D&&e.jsxs("span",{children:["Timeout: ",D,"ms"]}),D&&k&&e.jsx("span",{children:" • "}),k&&e.jsxs("span",{children:["Response format: ",k]})]})]})}const y=p("command")||p("content")||p("action")||p("operation"),v=p("description");return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),y&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(xt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(y)})})]}),Object.keys(t.metadata).length>0&&!y&&!v&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(xt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:JSON.stringify(t.metadata,null,2)})})]})]})};return e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20 bg-muted/5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-3.5 w-3.5 text-yellow-500"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Permission Required"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[wS(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:x})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[t.patterns.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Patterns:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:t.patterns.join(", ")})]}),b()]}),e.jsxs("div",{className:"px-2 pb-2 sm:pb-1.5 pt-1.5 sm:pt-1 flex flex-col sm:flex-row sm:items-center sm:flex-wrap gap-1.5 border-t border-border/20",children:[e.jsxs("button",{onClick:()=>u("once"),disabled:s,className:R("flex items-center gap-1.5 sm:gap-1 px-3 sm:px-2 py-1.5 sm:py-1 typography-meta font-medium rounded transition-all min-h-[32px] sm:min-h-0 w-full sm:w-auto","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Tt,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),"Allow Once"]}),t.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:s,className:R("flex items-center gap-1.5 sm:gap-1 px-3 sm:px-2 py-1.5 sm:py-1 typography-meta font-medium rounded transition-all min-h-[32px] sm:min-h-0 w-full sm:w-auto","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(Cr,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),(()=>{const y=t.always||t.metadata.always||[];if(y.length===0)return"Always Allow";const S=y.slice(0,2).join(", "),C=y.length>2;return e.jsx("span",{className:"truncate max-w-[180px]",children:C?`Always: ${S}...`:`Always: ${S}`})})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:s,className:R("flex items-center gap-1.5 sm:gap-1 px-3 sm:px-2 py-1.5 sm:py-1 typography-meta font-medium rounded transition-all min-h-[32px] sm:min-h-0 w-full sm:w-auto","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(Cr,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:s,className:R("flex items-center gap-1.5 sm:gap-1 px-3 sm:px-2 py-1.5 sm:py-1 typography-meta font-medium rounded transition-all min-h-[32px] sm:min-h-0 w-full sm:w-auto","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(es,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),"Deny"]}),s&&e.jsx("div",{className:"flex justify-center w-full sm:w-auto sm:ml-auto py-1 sm:py-0 typography-meta text-muted-foreground",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})})]})]})})})},lc="summary",SS=({question:t})=>{const{respondToQuestion:r,rejectQuestion:s}=ve(),[n,o]=i.useState("0"),[a,c]=i.useState(!1),[l,d]=i.useState(!1),[u,m]=i.useState({}),[f,p]=i.useState({}),[h,g]=i.useState({}),x=i.useMemo(()=>t.questions??[],[t.questions]),b=n===lc,y=b?-1:Math.max(0,Math.min(x.length-1,Number(n)||0)),v=b?null:x[y],S=i.useMemo(()=>{if(b)return null;const P=v?.header?.trim();return P&&P.length>0?P:null},[v?.header,b]);i.useEffect(()=>{o("0"),m({}),p({}),g({}),d(!1)},[t.id]);const C=i.useMemo(()=>{const P=x.map((F,z)=>({value:String(z),label:F.header?.trim()||`Q${z+1}`}));return x.length>1&&P.push({value:lc,label:"Summary"}),P},[x]),N=i.useCallback(P=>{if(!!f[P])return(h[P]??"").trim()||"(no answer)";const z=u[P]??[];return z.length>0?z.join(", "):"(no answer)"},[f,h,u]),j=!!v?.multiple,D=u[y]??[],k=!!f[y],M=i.useMemo(()=>{if(x.length===0)return!1;for(let P=0;P<x.length;P+=1){if(!!f[P]){if(!(h[P]??"").trim())return!1;continue}if((u[P]??[]).length===0)return!1}return!0},[f,h,x.length,u]),w=i.useCallback(()=>{const P=[];for(let F=0;F<x.length;F+=1){if(!!f[F]){const G=(h[F]??"").trim();P.push(G?[G]:[]);continue}P.push(u[F]??[])}return P},[f,h,x.length,u]),T=i.useCallback(P=>{v&&(p(F=>({...F,[y]:!1})),m(F=>{const z=F[y]??[];if(j){const oe=z.includes(P)?z.filter(O=>O!==P):[...z,P];return{...F,[y]:oe}}return{...F,[y]:[P]}}))},[y,v,j]),E=i.useCallback(()=>{p(P=>({...P,[y]:!0})),m(P=>({...P,[y]:[]}))},[y]),I=i.useCallback(async()=>{if(M){c(!0);try{const P=w();await r(t.sessionID,t.id,P),d(!0)}catch{}finally{c(!1)}}},[w,t.id,t.sessionID,M,r]),A=i.useCallback(async()=>{c(!0);try{await s(t.sessionID,t.id),d(!0)}catch{}finally{c(!1)}},[t.id,t.sessionID,s]);return l||x.length===0?null:e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Input needed"}),S?e.jsx("span",{className:"ml-auto typography-micro font-medium text-foreground/70 px-1.5 py-0.5 rounded bg-muted/30 border border-border/20",children:S}):null]})}),e.jsxs("div",{className:"px-2 py-2",children:[C.length>1?e.jsx("div",{className:"flex items-center gap-1 mb-2 flex-wrap",children:C.map(P=>{const F=n===P.value,z=P.value===lc;return e.jsxs("button",{type:"button",onClick:()=>o(P.value),className:R("px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1",F?"bg-muted/40 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-muted/20"),children:[z?e.jsx(qm,{className:"h-3 w-3"}):null,P.label]},P.value)})}):null,b?e.jsx("div",{className:"space-y-2",children:x.map((P,F)=>{const z=N(F),G=z!=="(no answer)";return e.jsxs("button",{type:"button",onClick:()=>o(String(F)),className:"w-full text-left rounded px-1.5 py-1 hover:bg-muted/20 transition-colors",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:P.header||`Question ${F+1}`}),e.jsx("div",{className:R("typography-meta",G?"text-foreground":"text-muted-foreground/50 italic"),children:z})]},F)})}):v?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:v.question}),j?e.jsx("div",{className:"typography-micro text-muted-foreground mb-1.5",children:"Select multiple"}):null,e.jsxs("div",{className:"space-y-0.5",children:[v.options.map((P,F)=>{const z=D.includes(P.label),G=/\(recommended\)/i.test(P.label);return e.jsx("button",{type:"button",onClick:()=>T(P.label),disabled:a,className:R("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",z?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5 shrink-0",children:z?e.jsx(px,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(Ec,{className:"h-3.5 w-3.5 text-muted-foreground/50"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:R("typography-meta break-all",z?"text-foreground font-medium":"text-foreground/80"),children:P.label}),G?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),P.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:P.description}):null]})]})},`${F}:${P.label}`)}),e.jsx("button",{type:"button",onClick:E,disabled:a,className:R("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",k?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fo,{className:R("h-3.5 w-3.5",k?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:R("typography-meta",k?"text-foreground font-medium":"text-muted-foreground"),children:"Other…"})]})}),k?e.jsx("div",{className:"pl-6 pr-1 pt-0.5",children:e.jsx("textarea",{ref:P=>{if(P){P.style.height="auto";const F=20,z=F*2,G=F*4;P.style.height=`${Math.min(Math.max(P.scrollHeight,z),G)}px`}},value:h[y]??"",onChange:P=>{const F=P.target;F.style.height="auto";const z=20,G=z*2,oe=z*4;F.style.height=`${Math.min(Math.max(F.scrollHeight,G),oe)}px`,g(O=>({...O,[y]:F.value}))},placeholder:"Your answer",disabled:a,rows:2,className:"w-full bg-transparent border border-border/30 focus:border-primary rounded px-2 py-1 outline-none typography-meta text-foreground placeholder:text-muted-foreground/50 transition-colors resize-none overflow-hidden",autoFocus:!0})}):null]})]}):null]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{type:"button",onClick:I,disabled:a||!M,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-success)/0.1)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(Tt,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:A,disabled:a,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-error)/0.1)] text-[var(--status-error)] hover:bg-[rgb(var(--status-error)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(es,{className:"h-3 w-3"}),"Dismiss"]}),a?e.jsx("div",{className:"ml-auto",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})}):null]})]})})})},NS=t=>{const r=[];let s=null;return t.forEach(n=>{const o=n.info.clientRole??n.info.role;o==="user"?(s={turnId:n.info.id,userMessage:n,assistantMessages:[]},r.push(s)):o==="assistant"&&s&&s.assistantMessages.push(n)}),r},Xo=i.createContext(null),$l=i.createContext(null),Gp=i.createContext(null);let Ru=null;const $n=new Map,kS=t=>{const r=i.useContext(Xo),s=i.useContext($l),n=i.useContext(Gp);return i.useMemo(()=>{if(!r||!s||!n)return;Ru!==r&&($n.clear(),Ru=r);const o=r.messageToTurn.get(t);if(!o||!o.assistantMessages.some(T=>T.info.id===t))return;const c=r.lastTurnId===o.turnId,d=(s.turnUiStates.get(o.turnId)??{isExpanded:r.defaultActivityExpanded}).isExpanded,u=c?`${t}-${d}-${n.sessionIsWorking}`:`${t}-${d}`,m=$n.get(u);if(m)return m;const f=r.turnActivityInfo.get(o.turnId),p=f?.activityParts??[],h=f?.activityGroupSegments??[],g=!!f?.hasTools,x=!!f?.hasReasoning,b=f?.summaryBody,y=f?.diffStats,v=o.assistantMessages[0]?.info.id,S=t===v,C=o.assistantMessages[o.assistantMessages.length-1]?.info.id,N=t===C,j=v,D=c&&n.sessionIsWorking,k=o.userMessage.info.time,M=typeof k?.created=="number"?k.created:void 0,w={turnId:o.turnId,isFirstAssistantInTurn:S,isLastAssistantInTurn:N,summaryBody:b,activityParts:p,activityGroupSegments:h,headerMessageId:j,hasTools:g,hasReasoning:x,diffStats:y,userMessageCreatedAt:M,isWorking:D,isGroupExpanded:d,toggleGroup:()=>s.toggleGroup(o.turnId)};if($n.size>500){const T=$n.keys().next().value;T&&$n.delete(T)}return $n.set(u,w),w},[r,s,n,t])},qp=t=>{const r=i.useContext(Xo);return i.useMemo(()=>r?r.messageNeighbors.get(t)??{}:{},[r,t])},CS=()=>i.useContext(Xo)?.lastTurnMessageIds??new Set,MS=t=>{const r=i.useContext(Xo),s=i.useContext($l);return i.useMemo(()=>{if(!r||!s)return;const n=r.messageToTurn.get(t);if(!n||!n.assistantMessages.some(N=>N.info.id===t))return;const a=r.turnActivityInfo.get(n.turnId),c=a?.activityParts??[],l=a?.activityGroupSegments??[],d=!!a?.hasTools,u=!!a?.hasReasoning,m=a?.summaryBody,f=a?.diffStats,p=n.assistantMessages[0]?.info.id,h=t===p,g=n.assistantMessages[n.assistantMessages.length-1]?.info.id,x=t===g,b=p,y=s.turnUiStates.get(n.turnId)??{isExpanded:r.defaultActivityExpanded},v=n.userMessage.info.time,S=typeof v?.created=="number"?v.created:void 0;return{turnId:n.turnId,isFirstAssistantInTurn:h,isLastAssistantInTurn:x,summaryBody:m,activityParts:c,activityGroupSegments:l,headerMessageId:b,hasTools:d,hasReasoning:u,diffStats:f,userMessageCreatedAt:S,isWorking:!1,isGroupExpanded:y.isExpanded,toggleGroup:()=>s.toggleGroup(n.turnId)}},[r,s,t])},DS=new Set(["task"]),Lu=t=>typeof t=="string"&&DS.has(t.toLowerCase()),AS=t=>{for(const r of t.assistantMessages)if(r.info.finish==="stop"){const n=r.parts.find(o=>o.type==="text");if(n){const o=n.text??n.content;if(typeof o=="string"&&o.trim().length>0)return o}}},ES=t=>{const r=AS(t);let s;const o=t.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let y=0,v=0,S=0;o.forEach(C=>{if(!C)return;const N=typeof C.additions=="number"?C.additions:0,j=typeof C.deletions=="number"?C.deletions:0;(N!==0||j!==0)&&(S+=1),y+=N,v+=j}),S>0&&(s={additions:y,deletions:v,files:S})}let a=!1,c=!1;t.assistantMessages.forEach(y=>{y.parts.forEach(v=>{v.type==="tool"?a=!0:v.type==="reasoning"&&(c=!0)})});const l=[];let d=0;t.assistantMessages.forEach(y=>{const v=y.info.id;y.info.finish,y.parts.forEach(S=>{const C=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-activity-${d++}`;if(S.type==="tool"){const j=S.state?.time,D=typeof j?.end=="number"?j.end:void 0;l.push({id:C,turnId:t.turnId,messageId:v,kind:"tool",part:S,endedAt:D});return}if(S.type==="reasoning"){const N=S.text??S.content;if(typeof N!="string"||N.trim().length===0)return;const j=S.time,D=typeof j?.end=="number"?j.end:void 0;l.push({id:C,turnId:t.turnId,messageId:v,kind:"reasoning",part:S,endedAt:D});return}})});const u=[],m=new WeakMap;l.forEach(y=>{m.set(y.part,y)});const f=new Map,p=[],h=new Map;let g=null;t.assistantMessages.forEach(y=>{const v=y.info.id;y.parts.forEach(S=>{if(S.type==="tool"){const j=S.tool;if(Lu(j)){const D=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-task-${p.length+1}`;f.has(D)||(f.set(D,v),p.push(D)),g=D;return}}const C=m.get(S);if(!C)return;if(C.kind==="tool"){const j=C.part.tool;if(Lu(j))return}const N=h.get(g)??[];N.push(C),h.set(g,N)})});const x=y=>{if(y.length===0)return;const v=new Map;y.forEach(N=>{v.set(N.messageId,(v.get(N.messageId)??0)+1)});let S,C=0;for(const N of t.assistantMessages){const j=v.get(N.info.id)??0;if(j>0&&!S&&(S=N.info.id),C+=j,C>=2)return N.info.id}return S};return[null,...p].forEach(y=>{const v=h.get(y)??[];if(v.length===0)return;const S=y===null?x(v):f.get(y);S&&u.push({id:`${t.turnId}:${S}:${y??"start"}`,anchorMessageId:S,afterToolPartId:y,parts:v})}),{activityParts:l,activityGroupSegments:u,hasTools:a,hasReasoning:c,summaryBody:r,diffStats:s}},IS=t=>{const r=new Map;return t.forEach((s,n)=>{r.set(s.info.id,{previousMessage:n>0?t[n-1]:void 0,nextMessage:n<t.length-1?t[n+1]:void 0})}),r},PS=({messages:t,children:r})=>{const{isWorking:s}=Ll(),n=Me(f=>f.toolCallExpansion),o=n==="activity"||n==="detailed",a=i.useMemo(()=>{const f=NS(t),p=f.length>0?f[f.length-1].turnId:null,h=new Map;f.forEach(y=>{h.set(y.userMessage.info.id,y),y.assistantMessages.forEach(v=>{h.set(v.info.id,y)})});const g=new Map;f.forEach(y=>{g.set(y.turnId,ES(y))});const x=IS(t),b=new Set;if(f.length>0){const y=f[f.length-1];b.add(y.userMessage.info.id),y.assistantMessages.forEach(v=>{b.add(v.info.id)})}return{turns:f,messageToTurn:h,turnActivityInfo:g,lastTurnId:p,lastTurnMessageIds:b,defaultActivityExpanded:o,messageNeighbors:x}},[t,o]),[c,l]=i.useState(()=>new Map);i.useEffect(()=>{l(new Map)},[n]);const d=i.useCallback(f=>{l(p=>{const h=new Map(p),g=h.get(f)??{isExpanded:o};return h.set(f,{isExpanded:!g.isExpanded}),h})},[o]),u=i.useMemo(()=>({turnUiStates:c,toggleGroup:d}),[c,d]),m=i.useMemo(()=>({sessionIsWorking:s}),[s]);return e.jsx(Xo.Provider,{value:a,children:e.jsx($l.Provider,{value:u,children:e.jsx(Gp.Provider,{value:m,children:r})})})},Kp=i.memo(({message:t,onContentChange:r,animationHandlers:s,scrollToBottom:n})=>{const{previousMessage:o,nextMessage:a}=qp(t.info.id),c=MS(t.info.id);return e.jsx(Vp,{message:t,previousMessage:o,nextMessage:a,onContentChange:r,animationHandlers:s,scrollToBottom:n,turnGroupingContext:c})});Kp.displayName="StaticMessageRow";const Jp=i.memo(({message:t,onContentChange:r,animationHandlers:s,scrollToBottom:n})=>{const{previousMessage:o,nextMessage:a}=qp(t.info.id),c=kS(t.info.id);return e.jsx(Vp,{message:t,previousMessage:o,nextMessage:a,onContentChange:r,animationHandlers:s,scrollToBottom:n,turnGroupingContext:c})});Jp.displayName="DynamicMessageRow";const TS=({displayMessages:t,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:n})=>{const o=CS();return e.jsx(e.Fragment,{children:t.map(a=>{const l=o.has(a.info.id)?Jp:Kp;return e.jsx(l,{message:a,onContentChange:r,animationHandlers:s(a.info.id),scrollToBottom:n},a.info.id)})})},FS=({messages:t,permissions:r,questions:s,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:c,onLoadOlder:l,scrollToBottom:d})=>{i.useEffect(()=>{r.length===0&&s.length===0||n("permission")},[r,s,n]);const u=i.useMemo(()=>{const m=new Set;return t.filter(f=>{const p=f.info?.id;if(typeof p=="string"){if(m.has(p))return!1;m.add(p)}return!0}).map(f=>{const p=i0(f.parts);return p===f.parts?f:{...f,parts:p}})},[t]);return e.jsx(PS,{messages:u,children:e.jsxs("div",{children:[a&&e.jsx("div",{className:"flex justify-center py-3",children:c?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:l,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx(TS,{displayMessages:u,onMessageContentChange:n,getAnimationHandlers:o,scrollToBottom:d}),(s.length>0||r.length>0)&&e.jsxs("div",{children:[s.map(m=>e.jsx(SS,{question:m},m.id)),r.map(m=>e.jsx(jS,{permission:m},m.id))]}),e.jsx("div",{className:"flex-shrink-0",style:{height:"10vh"},"aria-hidden":"true"})]})})},RS=i.memo(FS);function LS(...t){return r=>{t.forEach(s=>{typeof s=="function"?s(r):s&&typeof s=="object"&&(s.current=r)})}}const Qp=i.forwardRef(({orientation:t="vertical",offset:r=72,size:s=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:c,className:l,children:d,...u},m)=>{const f=i.useRef(null),p=i.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const g=i.useMemo(()=>{const v={...c};return v["--scroll-shadow-size"]=`${s}px`,v},[s,c]),x=i.useCallback((v,S,C,N,j)=>{const D=`${N}${j.charAt(0).toUpperCase()}${j.slice(1)}Scroll`;S&&C?(v.dataset[D]="true",v.removeAttribute(`data-${N}-scroll`),v.removeAttribute(`data-${j}-scroll`)):(v.dataset[`${N}Scroll`]=String(S),v.dataset[`${j}Scroll`]=String(C),v.removeAttribute(`data-${N}-${j}-scroll`))},[]),b=i.useCallback(v=>{["top","bottom","top-bottom","left","right","left-right"].forEach(S=>{v.removeAttribute(`data-${S}-scroll`)})},[]),y=i.useCallback(()=>{const v=f.current;if(!v)return;if(!n){b(v);return}const S=t==="vertical"?v.scrollTop>r:v.scrollLeft>r;let C=t==="vertical"?v.scrollTop+v.clientHeight+r<v.scrollHeight:v.scrollLeft+v.clientWidth+r<v.scrollWidth;o&&t==="vertical"&&(C=!1),x(v,S,C,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const N=S&&C?"both":S?t==="vertical"?"top":"left":C?t==="vertical"?"bottom":"right":"none";N!==p.current&&(p.current=N,a?.(N))},[b,o,n,r,a,t,x]);return i.useEffect(()=>{const v=f.current;if(!v)return;let S=null;const C=()=>{S===null&&(S=requestAnimationFrame(()=>{S=null,y()}))},N=()=>y(),j=typeof ResizeObserver<"u"?new ResizeObserver(C):null,D=typeof MutationObserver<"u"?new MutationObserver(C):null;return y(),v.addEventListener("scroll",N,{passive:!0}),j?.observe(v),D?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{S!==null&&cancelAnimationFrame(S),v.removeEventListener("scroll",N),j?.disconnect(),D?.disconnect()}},[y]),e.jsx("div",{...u,ref:LS(f,m),className:l,"data-orientation":t,"data-scroll-shadow":h??!0,style:g,children:d})});Qp.displayName="ScrollShadow";const OS=160,_S=({containerRef:t})=>{const[r,s]=i.useState(!0),n=i.useRef(!0),o=i.useRef(!1),a=i.useRef(null),c=i.useRef(null),l=i.useRef(0),d=i.useRef(0),u=i.useRef(!1),m=i.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,c.current=null,u.current=!1},[]),f=i.useCallback(C=>{const N=t.current;if(!N){m();return}c.current===null&&(c.current=C),u.current&&(d.current=N.scrollHeight-N.clientHeight);const j=Math.min(1,(C-c.current)/OS),D=1-Math.pow(1-j,3),k=l.current,M=d.current,w=k+(M-k)*D;if(N.scrollTop=w,j<1){a.current=window.requestAnimationFrame(f);return}N.scrollTop=M,m(),n.current&&(n.current=!1,s(!1))},[m,t,s]),p=i.useCallback((C,N)=>{const j=t.current;if(!j)return;const D=Math.max(0,C),k=N?.instant??!1,M=N?.followBottom??!1;if(o.current=!1,typeof window>"u"||k){m(),j.scrollTop=D;const T=D<=1;n.current!==T&&(n.current=T,s(T));return}if(M&&u.current&&a.current!==null)return;if(m(),Math.abs(D-j.scrollTop)<=.5){j.scrollTop=D;const T=D<=1;n.current!==T&&(n.current=T,s(T));return}l.current=j.scrollTop,d.current=D,c.current=null,u.current=M,a.current=window.requestAnimationFrame(f)},[m,t,f,s]),h=i.useCallback(()=>{o.current=!0},[]),g=i.useCallback(()=>{o.current=!0},[]),x=i.useCallback(()=>o.current,[]),b=i.useCallback(()=>t.current?.scrollTop??0,[t]),y=i.useCallback(()=>t.current?.scrollHeight??0,[t]),v=i.useCallback(()=>t.current?.clientHeight??0,[t]),S=i.useCallback(()=>{const C=t.current;if(!C)return;o.current&&a.current!==null&&m();const N=C.scrollTop<=1;n.current!==N&&(n.current=N,s(N))},[m,t]);return i.useEffect(()=>{const C=t.current;if(C)return C.addEventListener("wheel",g,{passive:!0}),C.addEventListener("touchstart",g,{passive:!0}),()=>{C.removeEventListener("wheel",g),C.removeEventListener("touchstart",g)}},[t,g]),i.useEffect(()=>()=>{m()},[m]),i.useMemo(()=>({handleScroll:S,scrollToPosition:p,forceManualMode:h,isAtTop:r,isManualOverrideActive:x,getScrollTop:b,getScrollHeight:y,getClientHeight:v}),[S,p,h,r,x,b,y,v])},$S=typeof window<"u"?i.useLayoutEffect:i.useEffect,BS=200,zS=250,HS=.1,WS=({currentSessionId:t,sessionMessages:r,updateViewportAnchor:s,isSyncing:n,isMobile:o})=>{const a=i.useRef(null),c=_S({containerRef:a}),l=i.useCallback(()=>{const I=a.current;if(!I||I.clientHeight<=0)return 0;const A=I.clientHeight*HS;return Math.max(24,Math.min(200,A))},[]),[d,u]=i.useState(!1),[m,f]=i.useState(!0),p=i.useRef(null),h=i.useRef(t??null),g=i.useRef(0),x=i.useRef(0),b=i.useRef(!0),y=i.useRef(0);i.useEffect(()=>{h.current=t??null},[t]);const v=i.useCallback(()=>{g.current=Date.now()+BS},[]),S=i.useCallback(()=>{const I=a.current;return I?I.scrollHeight-I.scrollTop-I.clientHeight:0},[]),C=i.useCallback(I=>{b.current!==I&&(b.current=I,f(I))},[]),N=i.useCallback(I=>{const A=a.current;if(!A)return;const P=A.scrollHeight-A.clientHeight;v(),c.scrollToPosition(Math.max(0,P),I)},[v,c]),j=i.useCallback(()=>{const I=a.current;if(!I){u(!1);return}if(!(I.scrollHeight>I.clientHeight)){u(!1);return}const P=S();u(P>l())},[S,l]),D=i.useCallback((I,A)=>{a.current&&(v(),c.scrollToPosition(Math.max(0,I),A))},[v,c]),k=i.useCallback(I=>{a.current&&(C(!0),N(I),u(!1))},[N,C]),M=i.useCallback(I=>{const A=a.current;if(!A||!t)return;const P=Date.now(),F=P<g.current,z=P-x.current<=zS;c.handleScroll(),j();const G=A.scrollTop;I?.isTrusted&&!F&&z&&G<y.current&&b.current&&C(!1),b.current||S()<=l()&&C(!0),y.current=G;const{scrollTop:oe,scrollHeight:O,clientHeight:q}=A,Y=(oe+q/2)/Math.max(O,1),Z=Math.floor(Y*r.length);s(t,Z)},[t,S,l,c,r.length,C,j,s]);i.useEffect(()=>{const I=a.current;if(!I)return;const A=()=>{x.current=Date.now()};return I.addEventListener("scroll",M,{passive:!0}),I.addEventListener("wheel",A,{passive:!0}),I.addEventListener("touchmove",A,{passive:!0}),()=>{I.removeEventListener("scroll",M),I.removeEventListener("wheel",A),I.removeEventListener("touchmove",A)}},[M]),$S(()=>{if(!t||t===p.current)return;p.current=t,Jr.getInstance().recordSessionStart(t),C(!0),u(!1),a.current&&(v(),N({instant:!0}))},[t,v,N,C]),i.useEffect(()=>{if(!b.current||n||!a.current)return;S()>l()&&(v(),N({instant:!0}))},[S,l,n,v,N,r]),i.useEffect(()=>{const I=a.current;if(!I||typeof ResizeObserver>"u")return;const A=new ResizeObserver(()=>{j(),b.current&&S()>l()&&N({instant:!0})});A.observe(I);const P=new MutationObserver(()=>{b.current&&S()>l()&&N({instant:!0})});return P.observe(I,{childList:!0,subtree:!0}),()=>{A.disconnect(),P.disconnect()}},[S,l,N,j]),i.useEffect(()=>{if(typeof window>"u"){j();return}const I=window.requestAnimationFrame(()=>{j()});return()=>{window.cancelAnimationFrame(I)}},[t,r.length,j]);const w=i.useRef(new Map),T=i.useCallback(()=>{j(),b.current&&S()>l()&&N({instant:!0})},[S,l,N,j]),E=i.useCallback(I=>{const A=w.current.get(I);if(A)return A;const P={onChunk:()=>{j(),b.current&&S()>l()&&N({instant:!0})},onComplete:()=>{j()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{j(),b.current&&S()>l()&&N({instant:!0})},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return w.current.set(I,P),P},[S,l,N,j]);return{scrollRef:a,handleMessageContentChange:T,getAnimationHandlers:E,showScrollButton:d,scrollToBottom:k,scrollToPosition:D,isPinned:m}};function US(t){const s=Date.now()-t,n=Math.floor(s/1e3),o=Math.floor(n/60),a=Math.floor(o/60),c=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:c<7?`${c}d ago`:new Date(t).toLocaleDateString()}const VS=({open:t,onOpenChange:r,onScrollToMessage:s})=>{const n=ve(x=>x.currentSessionId),o=Nt(x=>n?x.messages.get(n)||[]:[]),a=ve(x=>x.revertToMessage),c=ve(x=>x.forkFromMessage),l=ve(x=>x.loadSessions),[d,u]=i.useState(null),[m,f]=i.useState(""),p=i.useMemo(()=>o.filter(b=>b.info.role==="user").reverse(),[o]),h=i.useMemo(()=>{if(!m.trim())return p;const x=m.toLowerCase();return p.filter(b=>Ou(b.parts).toLowerCase().includes(x))},[p,m]),g=async x=>{if(n){u(x);try{await c(n,x),await l(),r(!1)}finally{u(null)}}};return n?e.jsx(us,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(xs,{children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(Cr,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Ss,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(St,{placeholder:"Search messages...",value:m,onChange:x=>f(x.target.value),className:"pl-9 w-full"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:h.length===0?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:m?"No messages found":"No messages in this session yet"}):h.map(x=>{const b=Ou(x.parts),y=x.info.time.created,v=US(y),S=p.length-p.indexOf(x);return e.jsxs("div",{className:"group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",onClick:()=>{s?.(x.info.id),r(!1)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:[S,"."]}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:[b||"[No text content]",b&&b.length>=80&&"…"]}),e.jsxs("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground whitespace-nowrap group-hover:hidden",children:v}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:async C=>{C.stopPropagation(),await a(n,x.info.id),r(!1)},children:e.jsx(so,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",onClick:C=>{C.stopPropagation(),g(x.info.id)},disabled:d===x.info.id,children:d===x.info.id?e.jsx(Mt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ut,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Fork from here"})]})]})]})]},x.info.id)})}),e.jsxs("div",{className:"mt-4 p-3 bg-muted/30 rounded-lg",children:[e.jsx("p",{className:"typography-meta text-muted-foreground font-medium mb-2",children:"Actions"}),e.jsxs("div",{className:"flex flex-col gap-1.5 typography-meta text-muted-foreground",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{children:"Click on a message to scroll to it in the conversation"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(so,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Undo to this point (message text will populate input)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function Ou(t){const r=t.find(s=>s.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const Yp=()=>{const{currentSessionId:t,messages:r,permissions:s,questions:n,streamingMessageIds:o,isLoading:a,loadMessages:c,loadMoreMessages:l,updateViewportAnchor:d,sessionMemoryState:u,openNewSessionDraft:m,isSyncing:f,messageStreamStates:p,trimToViewportWindow:h,sessionActivityPhase:g,newSessionDraft:x}=ve(),{isTimelineDialogOpen:b,setTimelineDialogOpen:y}=Me(),v=i.useMemo(()=>t?o.get(t)??null:null,[t,o]),{isMobile:S}=Gt(),C=!!x?.open;i.useEffect(()=>{!t&&!C&&m()},[t,C,m]);const N=i.useMemo(()=>t?r.get(t)||[]:[],[t,r]),j=i.useMemo(()=>t?s.get(t)||[]:[],[t,s]),D=i.useMemo(()=>t?n.get(t)||[]:[],[t,n]);i.useMemo(()=>[...j,...D],[j,D]);const{scrollRef:k,handleMessageContentChange:M,getAnimationHandlers:w,showScrollButton:T,scrollToBottom:E,scrollToPosition:I,isPinned:A}=WS({currentSessionId:t,sessionMessages:N,updateViewportAnchor:d,isSyncing:f,isMobile:S}),F=!!i.useMemo(()=>t?u.get(t)??null:null,[t,u])?.hasMoreAbove,[z,G]=i.useState(!1);i.useEffect(()=>{G(!1)},[t]);const oe=i.useCallback(async()=>{if(!t||z)return;const q=k.current,Y=q?.scrollHeight??null,Z=q?.scrollTop??null;G(!0);try{if(await l(t,"up"),q&&Y!==null&&Z!==null){const B=q.scrollHeight-Y;I(Z+B,{instant:!0})}}finally{G(!1)}},[t,z,l,k,I]),O=i.useCallback(q=>{const Y=k.current;if(!Y)return;const Z=Y.querySelector(`[data-message-id="${q}"]`);if(Z){const B=Y.getBoundingClientRect(),ye=Z.getBoundingClientRect().top-B.top+Y.scrollTop-50;Y.scrollTo({top:ye,behavior:"smooth"})}},[k]);return i.useEffect(()=>{if(!t||(r.has(t)?r.get(t)??[]:[]).length>0)return;(async()=>{try{await c(t)}finally{const B=g?.get(t)??"idle";(B==="busy"||B==="cooldown")&&A||(typeof window>"u"?E():window.requestAnimationFrame(()=>{E()}))}})()},[t,A,c,r,E,g]),!t&&!C?e.jsx("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(oc,{})}):!t&&C?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(oc,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(xa,{scrollToBottom:E})})]}):t?a&&N.length===0&&!v&&!r.has(t)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-message-column space-y-4",children:[1,2,3].map(Y=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(nc,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(nc,{className:"h-4 w-24"}),e.jsx(nc,{className:"h-20 w-full"})]})]},Y))})}),e.jsx(xa,{scrollToBottom:E})]}):N.length===0&&!v?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(oc,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(xa,{scrollToBottom:E})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(Qp,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:k,style:{contain:"strict","--scroll-shadow-size":"48px",transform:"translateZ(0)",willChange:"scroll-position",backfaceVisibility:"hidden"},"data-scroll-shadow":"true","data-scrollbar":"chat",children:e.jsx("div",{className:"relative z-0 min-h-full",children:e.jsx(RS,{messages:N,permissions:j,questions:D,onMessageContentChange:M,getAnimationHandlers:w,hasMoreAbove:F,isLoadingOlder:z,onLoadOlder:oe,scrollToBottom:E})})}),e.jsx(kl,{containerRef:k})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[T&&N.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Se,{variant:"outline",size:"sm",onClick:()=>E({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-accent","aria-label":"Scroll to bottom",children:e.jsx(po,{className:"h-4 w-4"})})}),e.jsx(xa,{scrollToBottom:E})]}),e.jsx(VS,{open:b,onOpenChange:y,onScrollToMessage:O})]}):null};class Xp extends i.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,s){this.setState({error:r,errorInfo:s})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(Pl,{className:"w-full max-w-md",children:[e.jsx(dp,{className:"text-center",children:e.jsxs(up,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(hx,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(mp,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data."}),this.props.sessionId&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Session: ",this.props.sessionId]}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(Se,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ls,{className:"h-4 w-4 mr-2"}),"Reset Chat"]})}),e.jsx("div",{className:"text-xs text-muted-foreground text-center",children:"If the problem persists, try refreshing the page."})]})]})}):this.props.children}}const Po=()=>{const t=ve(r=>r.currentSessionId);return e.jsx(Xp,{sessionId:t||void 0,children:e.jsx(Yp,{})})},_u=new hi,$u=new hi,Bu=new hi,zu=new hi,Hu=t=>{if(!t)return[];const r=Math.max(1,t.start),s=Math.max(r,t.end);return Nx.fromClass(class{decorations;constructor(n){this.decorations=this.build(n)}update(n){(n.docChanged||n.viewportChanged)&&(this.decorations=this.build(n.view))}build(n){const o=new kx;for(let a=r;a<=s&&a<=n.state.doc.lines;a+=1){const c=n.state.doc.line(a);o.add(c.from,c.from,Cx.line({class:"oc-cm-selected-line"}))}return o.finish()}},{decorations:n=>n.decorations})};function Xc({value:t,onChange:r,extensions:s,className:n,readOnly:o,lineNumbersConfig:a,highlightLines:c}){const l=i.useRef(null),d=i.useRef(null),u=i.useRef(t),m=i.useRef(r);return i.useEffect(()=>{u.current=t},[t]),i.useEffect(()=>{m.current=r},[r]),i.useEffect(()=>{if(!l.current)return;const f=gx.create({doc:u.current,extensions:[xx({fixed:!0}),_u.of(Yl(a)),yx(),bx.of(" "),wx.of([vx,...jx,...Sx]),pn.updateListener.of(p=>{if(!p.docChanged)return;const h=p.state.doc.toString();u.current=h,m.current(h)}),$u.of(pn.editable.of(!o)),Bu.of(s??[]),zu.of(Hu(c))]});return d.current=new pn({state:f,parent:l.current}),()=>{d.current?.destroy(),d.current=null}},[]),i.useEffect(()=>{const f=d.current;f&&f.dispatch({effects:[_u.reconfigure(Yl(a)),$u.reconfigure(pn.editable.of(!o)),Bu.reconfigure(s??[]),zu.reconfigure(Hu(c))]})},[s,c,a,o]),i.useEffect(()=>{const f=d.current;if(!f)return;const p=f.state.doc.toString();p!==t&&f.dispatch({changes:{from:0,to:p.length,insert:t}})},[t]),e.jsx("div",{ref:l,className:R("h-full w-full","[&_.cm-editor]:h-full [&_.cm-editor]:w-full","[&_.cm-scroller]:font-mono [&_.cm-scroller]:text-[var(--text-code)] [&_.cm-scroller]:leading-6",n)})}const Zc=({currentMode:t,onToggle:r})=>{const s=t==="preview",n=s?"Switch to edit mode":"Switch to preview mode",o=s?"Edit":"Preview";return e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{variant:"ghost",size:"icon",onClick:r,"aria-label":n,className:"size-8",children:s?e.jsx(Mx,{className:"size-4","aria-hidden":"true"}):e.jsx(Dx,{className:"size-4","aria-hidden":"true"})})}),e.jsx(lt,{sideOffset:8,children:o})]})};function el(t){const r=t.metadata.variant==="dark",s=t.config?.fonts?.mono||"monospace",n=t.colors.syntax.highlights||{},o=t.colors.syntax.tokens||{},a=pn.theme({"&":{backgroundColor:"var(--background)",color:t.colors.syntax.base.foreground,fontSize:"var(--text-code)",lineHeight:"1.5rem"},".cm-scroller":{fontFamily:s,backgroundColor:"var(--background)"},".cm-comment":{color:t.colors.syntax.base.comment},".cm-keyword":{color:t.colors.syntax.base.keyword},".cm-string":{color:t.colors.syntax.base.string},".cm-string-2":{color:o.stringEscape||t.colors.syntax.base.string},".cm-number":{color:t.colors.syntax.base.number},".cm-atom":{color:o.boolean||t.colors.syntax.base.number},".cm-builtin":{color:o.functionCall||t.colors.syntax.base.function},".cm-def":{color:o.variableGlobal||t.colors.syntax.base.variable},".cm-attribute":{color:o.variableOther||o.variableProperty||t.colors.syntax.base.operator},".cm-meta":{color:t.colors.syntax.base.comment},".cm-property":{color:o.variableProperty||t.colors.syntax.base.keyword},".cm-variable":{color:t.colors.syntax.base.variable},".cm-variable-2":{color:o.variableOther||t.colors.syntax.base.function},".cm-variable-3":{color:o.variableGlobal||t.colors.syntax.base.type},".cm-tag":{color:o.tag||t.colors.syntax.base.keyword},".cm-link":{color:o.url||t.colors.syntax.base.keyword,textDecoration:"underline"},".cm-content":{caretColor:t.colors.interactive.cursor},".cm-cursor, .cm-dropCursor":{borderLeftColor:t.colors.interactive.cursor},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:t.colors.interactive.selection},".cm-gutters":{backgroundColor:"var(--background)",color:n.lineNumber||t.colors.syntax.base.comment,borderRight:`1px solid ${t.colors.interactive.border}`,position:"sticky",paddingRight:"8px",left:0,zIndex:2,boxShadow:"0 0 0 var(--background)"},".cm-gutter":{backgroundColor:"var(--background)"},".cm-gutterElement":{backgroundColor:"var(--background)"},".cm-lineNumbers":{backgroundColor:"var(--background)"},".cm-lineNumbers .cm-gutterElement":{paddingLeft:"8px",paddingRight:"8px",minWidth:"42px"},".cm-activeLineGutter":{color:n.lineNumberActive||t.colors.syntax.base.foreground},".cm-activeLine":{backgroundColor:t.colors.surface.overlay},"&.cm-focused":{outline:"none"}},{dark:r}),c=Jm.define([{tag:Ge.comment,color:t.colors.syntax.base.comment},{tag:Ge.docComment,color:o.commentDoc||t.colors.syntax.base.comment},{tag:Ge.keyword,color:t.colors.syntax.base.keyword},{tag:Ge.controlKeyword,color:t.colors.syntax.base.keyword},{tag:Ge.operatorKeyword,color:t.colors.syntax.base.operator},{tag:Ge.moduleKeyword,color:o.keywordImport||t.colors.syntax.base.keyword},{tag:[Ge.definitionKeyword,Ge.modifier],color:o.storageModifier||t.colors.syntax.base.keyword},{tag:Ge.atom,color:o.boolean||t.colors.syntax.base.number},{tag:[Ge.null,Ge.self],color:t.colors.syntax.base.number},{tag:[Ge.meta,Ge.documentMeta],color:t.colors.syntax.base.comment},{tag:Ge.string,color:t.colors.syntax.base.string},{tag:Ge.escape,color:o.stringEscape||t.colors.syntax.base.foreground},{tag:Ge.regexp,color:o.regex||t.colors.syntax.base.string},{tag:Ge.number,color:t.colors.syntax.base.number},{tag:Ge.bool,color:o.boolean||t.colors.syntax.base.number},{tag:Ge.operator,color:t.colors.syntax.base.operator},{tag:[Ge.derefOperator,Ge.updateOperator,Ge.definitionOperator,Ge.typeOperator,Ge.controlOperator],color:t.colors.syntax.base.operator},{tag:[Ge.logicOperator,Ge.bitwiseOperator,Ge.arithmeticOperator],color:t.colors.syntax.base.operator},{tag:[Ge.compareOperator],color:o.diffModified||t.colors.syntax.base.operator},{tag:[Ge.punctuation,Ge.separator,Ge.bracket,Ge.paren,Ge.brace,Ge.squareBracket,Ge.angleBracket],color:o.punctuation||t.colors.syntax.base.comment},{tag:Ge.function(Ge.variableName),color:o.functionCall||t.colors.syntax.base.function},{tag:Ge.function(Ge.definition(Ge.variableName)),color:t.colors.syntax.base.function},{tag:Ge.function(Ge.propertyName),color:o.method||o.functionCall||t.colors.syntax.base.function},{tag:Ge.namespace,color:o.namespace||t.colors.syntax.base.type},{tag:Ge.moduleKeyword,color:o.module||t.colors.syntax.base.keyword},{tag:Ge.macroName,color:o.macro||t.colors.syntax.base.keyword},{tag:Ge.labelName,color:o.label||t.colors.syntax.base.keyword},{tag:Ge.annotation,color:o.decorator||t.colors.syntax.base.keyword},{tag:Ge.propertyName,color:o.variableProperty||t.colors.syntax.base.keyword},{tag:Ge.attributeName,color:o.tagAttribute||t.colors.syntax.base.keyword},{tag:Ge.standard(Ge.variableName),color:o.method||t.colors.syntax.base.function},{tag:Ge.definition(Ge.variableName),color:t.colors.syntax.base.variable},{tag:Ge.local(Ge.variableName),color:t.colors.syntax.base.variable},{tag:Ge.special(Ge.variableName),color:o.variableOther||t.colors.syntax.base.function},{tag:Ge.variableName,color:t.colors.syntax.base.variable},{tag:Ge.special(Ge.string),color:t.colors.syntax.base.string},{tag:Ge.className,color:o.className||t.colors.syntax.base.type},{tag:Ge.typeName,color:t.colors.syntax.base.type},{tag:Ge.constant(Ge.variableName),color:o.constant||t.colors.syntax.base.variable},{tag:Ge.literal,color:o.constant||t.colors.syntax.base.variable},{tag:Ge.tagName,color:o.tag||t.colors.syntax.base.keyword},{tag:Ge.attributeValue,color:o.tagAttributeValue||t.colors.syntax.base.string},{tag:[Ge.heading,Ge.heading1,Ge.heading2,Ge.heading3,Ge.heading4,Ge.heading5,Ge.heading6],color:t.colors.syntax.base.keyword,fontWeight:"600"},{tag:Ge.monospace,color:t.colors.syntax.base.string},{tag:Ge.link,color:o.url||t.colors.syntax.base.keyword,textDecoration:"underline"}]);return[a,Qm(c)]}const tl=ho.define(Ax),Zp=ho.define(Ex),GS=ho.define(Ix),qS=ho.define(Px),KS=ho.define(Tx),JS=ho.define(Fx);function QS(t){const r=t.trim().toLowerCase();switch(r){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return tl;case"toml":return Zp;case"diff":case"patch":return GS;case"json":case"jsonc":case"json5":return nf().language;case"js":case"javascript":return Vn().language;case"jsx":return Vn({jsx:!0}).language;case"ts":case"typescript":return Vn({typescript:!0}).language;case"tsx":return Vn({typescript:!0,jsx:!0}).language;case"yaml":case"yml":return tf().language;case"html":return sf().language;case"css":return rf().language;case"xml":case"svg":return Xm().language;case"py":case"python":return ef().language;case"sql":return Zm().language;case"rs":case"rust":return Ym().language;default:return Lx.matchLanguageName(Ox,r,!0)}}const YS=t=>t.split("/").pop()?.toLowerCase()??"",XS=()=>Qm(Jm.define([{tag:[Ge.heading1,Ge.heading2,Ge.heading3,Ge.heading4,Ge.heading5,Ge.heading6],fontWeight:"600"},{tag:Ge.strong,fontWeight:"600"},{tag:Ge.emphasis,fontStyle:"italic"},{tag:Ge.strikethrough,textDecoration:"line-through"},{tag:[Ge.link,Ge.url],color:"var(--markdown-link, currentColor)",textDecoration:"underline"},{tag:Ge.monospace,color:"var(--markdown-inline-code, currentColor)",backgroundColor:"var(--markdown-inline-code-bg, transparent)"},{tag:Ge.quote,color:"var(--markdown-blockquote, currentColor)",fontStyle:"italic"},{tag:Ge.list,color:"color-mix(in srgb, var(--muted-foreground) 40%, var(--foreground) 60%)"},{tag:Ge.heading,color:"var(--markdown-heading1, currentColor)"}]));function eh(t){const r=t.toLowerCase();switch(YS(r)){case"dockerfile":return qS;case"makefile":case"gnumakefile":return tl}const n=r.lastIndexOf("."),o=n>=0?r.slice(n+1):"";switch(o){case"ts":case"tsx":case"mts":case"cts":return Vn({typescript:!0,jsx:o==="tsx"});case"js":case"jsx":case"mjs":case"cjs":return Vn({typescript:!1,jsx:o==="jsx"});case"json":case"jsonc":case"json5":case"jsonl":case"ndjson":case"geojson":return nf();case"css":case"scss":case"sass":case"less":return rf();case"html":case"htm":return sf();case"md":case"mdx":case"markdown":case"mdown":case"mkd":return[Rx({codeLanguages:QS}),XS()];case"yml":case"yaml":return tf();case"toml":return Zp;case"ini":case"cfg":case"conf":case"config":case"properties":return JS;case"sh":case"bash":case"zsh":case"fish":case"env":return tl;case"py":case"pyw":case"pyi":return ef();case"sql":case"psql":case"plsql":return Zm();case"xml":case"xsl":case"xslt":case"xsd":case"dtd":case"plist":case"svg":return Xm();case"rs":return Ym();case"rb":case"erb":case"rake":case"gemspec":return KS;default:return null}}const To=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},dc=(t,r)=>{const s=To(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},ZS=(t,r,s)=>dc(dc(dc(t,".opencode"),"plans"),`${r}-${s}.md`),eN=(t,r)=>`~/.opencode/plans/${t}-${r}.md`,tN=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},sN=(t,r)=>{const s=To(r.currentDirectory),n=To(r.homeDirectory),o=To(t);return s&&o.startsWith(s+"/")?o.slice(s.length+1):n&&o===n?"~":n&&o.startsWith(n+"/")?`~${o.slice(n.length)}`:o},rN=()=>{const t=ve(L=>L.currentSessionId),r=ve(L=>L.sessions),s=vt(L=>L.homeDirectory),n=Hs(),o=ve(L=>L.sendMessage),{currentProviderId:a,currentModelId:c,currentAgentName:l,currentVariant:d}=Je(),u=Ye(L=>L.getSessionAgentSelection),m=Ye(L=>L.getAgentModelForSession),f=Ye(L=>L.getAgentModelVariantForSession),p=Me(L=>L.setActiveMainTab),{inputBarOffset:h,isKeyboardOpen:g}=Me(),{isMobile:x}=Gt(),{currentTheme:b}=Wr();i.useMemo(()=>Fi(b),[b]);const y=i.useMemo(()=>t?r.find(L=>L.id===t)??null:null,[t,r]),v=i.useMemo(()=>{const L=typeof y?.directory=="string"?y.directory:"";return To(L||"")},[y?.directory]),[S,C]=i.useState(null),N=i.useMemo(()=>!S||!v||!s?S:sN(S,{currentDirectory:v,homeDirectory:s}),[S,v,s]),[j,D]=i.useState(""),[k,M]=i.useState(!1),[w,T]=i.useState(!1),[E,I]=i.useState(!1),[A,P]=i.useState("edit"),F=i.useRef(null),z=i.useRef(null),[G,oe]=i.useState(null),[O,q]=i.useState(""),Y="openchamber:plan:md-viewer-mode";i.useEffect(()=>{try{const L=localStorage.getItem(Y);if(!L)return;const Q=JSON.parse(L);(Q==="preview"||Q==="edit")&&P(Q)}catch{}},[]);const Z=i.useCallback(L=>{P(L);try{localStorage.setItem(Y,JSON.stringify(L))}catch{}},[]),B=i.useRef(!1),W=i.useRef(null);i.useEffect(()=>{const L=()=>{B.current=!1,W.current=null};return document.addEventListener("mouseup",L),()=>document.removeEventListener("mouseup",L)},[]),i.useEffect(()=>{oe(null),q("")},[j]),i.useEffect(()=>{if(!G)return;const L=ce=>{const he=ce.target;document.querySelector("[data-comment-ui]")?.contains(he)||he.closest(".cm-gutterElement")||he.closest("[data-sonner-toast]")||he.closest("[data-sonner-toaster]")||(oe(null),q(""))},Q=window.setTimeout(()=>{document.addEventListener("click",L)},100);return()=>{window.clearTimeout(Q),document.removeEventListener("click",L)}},[G]);const te=i.useCallback((L,Q)=>{const ce=L.split(`
195
+ `),he=Math.max(1,Q.start),Ne=Math.min(ce.length,Q.end);return he>Ne?"":ce.slice(he-1,Ne).join(`
196
+ `)},[]),ye=i.useCallback(async()=>{if(!G||!O.trim()||!t)return;const L=u(t)||l,Q=L?m(t,L):null,ce=Q?.providerId||a,he=Q?.modelId||c;if(!ce||!he)return;const Ne=L&&ce&&he?f(t,L,ce,he)??d:d,H=G.start,we=G.end,ee=te(j,G),ue=N&&N.split("/").pop()||"plan",ge=S&&Er(S)||"markdown",X=`Comment on \`${ue}\` lines ${H}-${we}:
197
+
198
+ \`\`\`${ge}
199
+ ${ee}
200
+ \`\`\`
201
+
202
+ ${O}`;q(""),oe(null),p("chat"),o(X,ce,he,L,void 0,void 0,void 0,Ne).catch(()=>{})},[G,O,t,a,c,l,d,j,S,N,te,o,p,u,m,f]),me=i.useMemo(()=>{const L=[el(b)],Q=eh(S||"plan.md");return Q&&L.push(Q),L.push(pn.lineWrapping),L},[b,S]);i.useEffect(()=>{let L=!1;const Q=async Ne=>{if(n.files?.readFile)return(await n.files.readFile(Ne))?.content??"";const H=await fetch(`/api/fs/read?path=${encodeURIComponent(Ne)}`);if(!H.ok)throw new Error(`Failed to read plan file (${H.status})`);return H.text()},ce=async Ne=>{if(Ne&&(C(null),D("")),!y?.slug||!y?.time?.created||!v){C(null),D("");return}Ne&&M(!0);try{const H=ZS(v,y.time.created,y.slug),we=tN(eN(y.time.created,y.slug),s||null);let ee=null,ue=null;try{ue=await Q(H),ee=H}catch{}if(!ee)try{ue=await Q(we),ee=we}catch{}if(L)return;if(!ee||ue===null){C(null),D("");return}C(ee),D(ue)}catch{if(L)return;C(null),D("")}finally{!L&&Ne&&M(!1)}};ce(!0);const he=window.setInterval(()=>{ce(!1)},3e3);return()=>{L=!0,window.clearInterval(he)}},[v,y?.slug,y?.time?.created,s,n.files]),i.useEffect(()=>()=>{F.current!==null&&window.clearTimeout(F.current),z.current!==null&&window.clearTimeout(z.current)},[]);const K=()=>G?e.jsx("div",{"data-comment-ui":!0,className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-background flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Fs,{value:O,onChange:L=>{q(L.target.value);const Q=L.target;Q.style.height="auto";const he=20*5+8;Q.style.height=`${Math.min(Q.scrollHeight,he)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!x,rows:1,onKeyDown:L=>{L.key==="Enter"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),ye()),L.key==="Escape"&&(L.preventDefault(),oe(null),q(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Plan:",G.start,"-",G.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!x&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Yt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:L=>{O.trim()&&(L.preventDefault(),ye())},onClick:()=>{x||ye()},disabled:!O.trim(),className:R("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",O.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Vo,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return e.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Plan"}),S?e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:N??S,children:N??S}):null]}),S?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Zc,{currentMode:A,onToggle:()=>Z(A==="preview"?"edit":"preview")}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(j),I(!0),z.current!==null&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{I(!1)},1200)}catch{}},className:"h-5 w-5 p-0",title:"Copy plan contents","aria-label":"Copy plan contents",children:E?e.jsx(Tt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(N??S),T(!0),F.current!==null&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{T(!1)},1200)}catch{}},className:"h-5 w-5 p-0",title:`Copy plan path (${N??S})`,"aria-label":`Copy plan path (${N??S})`,children:w?e.jsx(Tt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Ic,{className:"h-4 w-4"})})]}):null]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(xt,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:k?e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Loading…"}):e.jsx("div",{className:"relative h-full",children:e.jsx("div",{className:"h-full",style:{"--oc-plan-comment-pad":G?x?"calc(var(--oc-keyboard-inset, 0px) + 140px)":"140px":"0px"},children:e.jsx("div",{className:"h-full oc-plan-editor",children:A==="preview"?e.jsx("div",{className:"h-full overflow-auto p-3",children:e.jsx(os,{fallback:e.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[e.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:e.jsx(kr,{content:j,className:"typography-markdown-body"})})}):e.jsx(Xc,{value:j,onChange:()=>{},readOnly:!0,className:"h-full [&_.cm-scroller]:pb-[var(--oc-plan-comment-pad)]",extensions:me,highlightLines:G?{start:Math.min(G.start,G.end),end:Math.max(G.start,G.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(L,Q,ce)=>{if(!(ce instanceof MouseEvent)||ce.button!==0)return!1;ce.preventDefault();const he=L.state.doc.lineAt(Q.from).number;if(x&&G&&!ce.shiftKey){const Ne=Math.min(G.start,G.end,he),H=Math.max(G.start,G.end,he);return oe({start:Ne,end:H}),B.current=!1,W.current=null,!0}if(B.current=!0,W.current=he,G&&ce.shiftKey){const Ne=Math.min(G.start,he),H=Math.max(G.end,he);oe({start:Ne,end:H})}else oe({start:he,end:he});return!0},mouseover:(L,Q,ce)=>{if(!(ce instanceof MouseEvent)||ce.buttons!==1||!B.current||W.current===null)return!1;const he=L.state.doc.lineAt(Q.from).number,Ne=Math.min(W.current,he),H=Math.max(W.current,he);return oe({start:Ne,end:H}),!1},mouseup:()=>(B.current=!1,W.current=null,!1)}}})})})})})}),G&&A!=="preview"&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex flex-col justify-end",style:{paddingBottom:x?"var(--oc-keyboard-inset, 0px)":"0px"},children:e.jsx("div",{className:R("pointer-events-auto pb-2 transition-none w-full flex justify-center",x&&g?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:x&&!g&&h>0?`${h}px`:"16px"},"data-keyboard-avoid":"true",children:K()})})]})},Wu=12,nN=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],oN=({isActive:t,burstKey:r=0,className:s,durationMs:n=900,bursts:o=nN,onComplete:a})=>{const c=Ae.useRef(!1);Ae.useEffect(()=>{!t&&c.current&&a?.(),t&&(c.current=!0)},[t,a]);const l=Ae.useMemo(()=>Array.from({length:Wu},(d,u)=>{const m=Math.PI*2*u/Wu;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return t?e.jsx("div",{className:R("fireworks-overlay pointer-events-none",s),"aria-hidden":"true","data-burst-key":r,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:l.map((m,f)=>{const p=m.x*d.radius,h=m.y*d.radius,g={"--translate-x":`${p}px`,"--translate-y":`${h}px`,"--particle-delay":`${m.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:g},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},aN=({durationMs:t=3400}={})=>{const[r,s]=Ae.useState({isActive:!1,cycle:0}),n=Ae.useRef(null),o=Ae.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Ae.useCallback(()=>{o(),s(l=>l.isActive?{...l,isActive:!1}:l)},[o]),c=Ae.useCallback(()=>{o(),s(l=>({isActive:!0,cycle:l.cycle+1})),n.current=window.setTimeout(()=>{s(l=>l.isActive?{...l,isActive:!1}:l),n.current=null},t)},[o,t]);return Ae.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:c,dismissFireworks:a}},th=i.createContext(void 0),Uu=({children:t})=>{const{isActive:r,burstKey:s,triggerFireworks:n,dismissFireworks:o}=aN(),a=i.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(th.Provider,{value:a,children:[t,e.jsx(oN,{isActive:r,burstKey:s})]})},iN=()=>{const t=i.useContext(th);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},co=ns()(fs(qs((t,r)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:s=>{t({selectedProfileId:s})},loadProfiles:async()=>{t({isLoading:!0});const s=r().profiles;try{const n=await zb();return t({profiles:n,isLoading:!1}),!0}catch(n){return console.error("Failed to load git identity profiles:",n),t({profiles:s,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const s=await Gb();if(s&&s.userName&&s.userEmail){const n={id:"global",name:"Global Identity",userName:s.userName,userEmail:s.userEmail,authType:s.sshCommand?"ssh":void 0,sshKey:s.sshCommand?s.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"house"};t({globalIdentity:n})}else t({globalIdentity:null});return!0}catch(s){return console.error("Failed to load global git identity:",s),t({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const s=await Vb();return t({discoveredCredentials:s}),!0}catch(s){return console.error("Failed to discover git credentials:",s),t({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const s=n=>{if(typeof n!="string")return null;const o=n.trim();return o.length>0?o:null};try{let n=null;if(ds()){const o=await zr();n=s(o?.defaultGitIdentityId)}else{const o=Ps()?.settings;if(o)try{const c=(await o.load())?.settings||{};n=s(c.defaultGitIdentityId)}catch{}if(n===null)try{const a=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(a.ok){const c=await a.json().catch(()=>null);n=s(c?.defaultGitIdentityId)}}catch{}}return t({defaultGitIdentityId:n}),!0}catch(n){return console.error("Failed to load default git identity setting:",n),!1}},setDefaultGitIdentityId:async s=>{try{const n=typeof s=="string"?s.trim():"",o=n.length>0?n:"";return await as({defaultGitIdentityId:o}),t({defaultGitIdentityId:o.length>0?o:null}),!0}catch(n){return console.error("Failed to save default git identity setting:",n),!1}},createProfile:async s=>{try{const n={...s,id:s.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:s.color||"keyword",icon:s.icon||"branch"};return await Hb(n),await r().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(s,n)=>{try{const o=r().profiles.find(c=>c.id===s);if(!o)throw new Error("Profile not found");const a={...o,...n};return await Wb(s,a),await r().loadProfiles(),!0}catch(o){return console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async s=>{try{return await Ub(s),r().selectedProfileId===s&&t({selectedProfileId:null}),await r().loadProfiles(),!0}catch(n){return console.error("Failed to delete git identity profile:",n),!1}},getProfileById:s=>{const{profiles:n,globalIdentity:o}=r();return s==="global"?o||void 0:n.find(a=>a.id===s)},getUnimportedCredentials:()=>{const{profiles:s,discoveredCredentials:n}=r();return n.filter(o=>!s.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Ks(()=>js()),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=co);const Os=t=>{const r=t.trim();return r?`'${r.replace(/'/g,"'\\''")}'`:"''"},lo=t=>(t||"").split(/\r?\n/).map(r=>r.trim()).filter(Boolean),Wo=t=>!!t.success,Mn=t=>(t.stdout||"").trim(),uo=t=>(t.stderr||"").trim();async function cN(t){const s=((await Ht("git worktree list --porcelain",t)).stdout||"").split(/\r?\n/),n=[];let o=null;for(const a of s){if(a.startsWith("worktree ")){o&&n.push(o),o={path:a.slice(9).trim(),branchRef:null};continue}o&&a.startsWith("branch ")&&(o.branchRef=a.slice(7).trim())}return o&&n.push(o),n.filter(a=>!!a.path)}async function lN(t){const r=`refs/heads/${t.targetBranch}`,s=new Set(t.excludePaths),o=(await cN(t.repoRoot)).filter(c=>c.branchRef===r).map(c=>c.path).filter(c=>c&&!s.has(c)),a=[];for(const c of o){const l=await Ht("git status --porcelain",c);Mn(l)||a.push(c)}return a}async function sh(t,r){for(const s of r)await Ht("git reset --hard",s).catch(()=>{})}async function dN(t,r){const s=r.trim();if(!s||s==="HEAD")return"HEAD";const n=await Ht(`git show-ref --verify --quiet ${Os(`refs/heads/${s}`)} && echo ok || echo missing`,t);if(Mn(n)==="ok")return s;if(s.startsWith("remotes/")){const c=s.slice(8).split("/"),l=c[0]||"origin",d=c.slice(1).join("/");if(d)return await Ht(`git branch --track ${Os(d)} ${Os(`${l}/${d}`)}`,t),d}const o=await Ht(`git show-ref --verify --quiet ${Os(`refs/remotes/origin/${s}`)} && echo ok || echo missing`,t);return Mn(o)==="ok"&&await Ht(`git branch --track ${Os(s)} ${Os(`origin/${s}`)}`,t),s}async function No(t){const r=t.repoRoot,s=t.sourceBranch.trim(),n=t.targetBranch.trim();if(!s||!n)return{repoRoot:r,sourceBranch:s,targetBranch:n,commits:[]};const o=await dN(r,n),a=await Ht(`git cherry ${Os(o)} ${Os(s)}`,r),c=lo(a.stdout),l=new Set;for(const f of c){const p=f.match(/^\+\s+([0-9a-f]{7,40})\b/i);p&&l.add(p[1])}const d=await Ht(`git rev-list --reverse ${Os(`${o}..${s}`)}`,r),m=lo(d.stdout).filter(f=>l.has(f));return{repoRoot:r,sourceBranch:s,targetBranch:o,commits:m}}async function uN(t,r){const s=await Ht('mkdir -p "$HOME/.config/openchamber/tmp" && mktemp -d "$HOME/.config/openchamber/tmp/oc-integrate-XXXXXX"',t),n=Mn(s);if(!n)throw new Error(uo(s)||"Failed to create temp directory");const o=await Ht(`git worktree add --force ${Os(n)} ${Os(r)}`,t);if(!Wo(o))throw new Error(uo(o)||"Failed to create temp worktree");return n}async function ii(t,r){await Ht(`git worktree remove --force ${Os(r)}`,t).catch(()=>{}),await Ht("git worktree prune",t).catch(()=>{})}async function mN(t){const r=await Ht("git rev-parse --abbrev-ref --symbolic-full-name @{u}",t),s=Mn(r);if(!s)return;await Ht("git fetch",t);const n=await Ht(`git merge --ff-only ${Os(s)}`,t);if(!Wo(n))throw new Error(uo(n)||"Fast-forward failed")}async function ci(t){const r=await Ht("git status --porcelain",t),s=await Ht("git diff --name-only --diff-filter=U",t),n=await Ht("git diff",t),o=await Ht("git show --no-patch --pretty=fuller CHERRY_PICK_HEAD",t),a=await Ht("git show CHERRY_PICK_HEAD",t);return{statusPorcelain:r.stdout||"",unmergedFiles:lo(s.stdout),diff:n.stdout||n.stderr||"",currentPatchMeta:o.stdout||o.stderr||"",currentPatch:a.stdout||a.stderr||""}}async function fN(t){return ci(t)}async function pN(t){const r=await Ht("git rev-parse --verify --quiet CHERRY_PICK_HEAD && echo yes || echo no",t);return Mn(r)==="yes"}async function hN(t){if(t.commits.length===0)return{kind:"noop",reason:"No commits to move"};const r=await uN(t.repoRoot,t.targetBranch);let s=[];try{await mN(r);const n=await Ht("git status --porcelain",r);if(Mn(n))throw new Error("Target branch has local changes; abort integration and retry");const o=await lN({repoRoot:t.repoRoot,targetBranch:t.targetBranch,excludePaths:[r]}).catch(()=>[]);for(s=[...t.commits];s.length>0;){const a=s[0],c=await Ht(`git cherry-pick ${Os(a)}`,r);if(Wo(c)){s.shift();continue}const l=await Ht("git diff --name-only --diff-filter=U",r);if(lo(l.stdout).length>0){const u=await ci(r);return{kind:"conflict",state:{repoRoot:t.repoRoot,tempWorktreePath:r,sourceBranch:t.sourceBranch,targetBranch:t.targetBranch,cleanTargetWorktrees:o,remainingCommits:s,currentCommit:a},details:u}}throw new Error(uo(c)||"Cherry-pick failed")}return await ii(t.repoRoot,r),await sh(t.repoRoot,o).catch(()=>{}),{kind:"success",moved:t.commits.length}}catch(n){throw await ii(t.repoRoot,r).catch(()=>{}),n}}async function gN(t){await Ht("git cherry-pick --abort",t.tempWorktreePath).catch(()=>{}),await ii(t.repoRoot,t.tempWorktreePath)}async function xN(t){const r=await Ht("git cherry-pick --continue",t.tempWorktreePath);if(!Wo(r)){const a=await Ht("git diff --name-only --diff-filter=U",t.tempWorktreePath);if(lo(a.stdout).length>0){const l=await ci(t.tempWorktreePath);return{kind:"conflict",state:t,details:l}}throw new Error(uo(r)||"Cherry-pick continue failed")}const s=t.tempWorktreePath,n=[...t.remainingCommits];n.length>0&&n[0]===t.currentCommit&&n.shift();const o=[...n];for(;o.length>0;){const a=o[0],c=await Ht(`git cherry-pick ${Os(a)}`,s);if(Wo(c)){o.shift();continue}const l=await Ht("git diff --name-only --diff-filter=U",s);if(lo(l.stdout).length>0){const u=await ci(s);return{kind:"conflict",state:{repoRoot:t.repoRoot,tempWorktreePath:s,sourceBranch:t.sourceBranch,targetBranch:t.targetBranch,cleanTargetWorktrees:t.cleanTargetWorktrees,remainingCommits:o,currentCommit:a},details:u}}throw new Error(uo(c)||"Cherry-pick failed")}return await ii(t.repoRoot,t.tempWorktreePath),await sh(t.repoRoot,t.cleanTargetWorktrees).catch(()=>{}),{kind:"success",moved:n.length}}const yN=({repoRoot:t,sourceBranch:r,worktreeMetadata:s,localBranches:n,defaultTargetBranch:o,refreshKey:a,onRefresh:c})=>{const l=ve(w=>w.currentSessionId),d=Me(w=>w.setActiveMainTab),[u,m]=Ae.useState(!0),[f,p]=Ae.useState(o);Ae.useEffect(()=>{p(o)},[o]);const h=!!(t&&r&&f&&f!=="HEAD"&&r!==f),[g,x]=Ae.useState({kind:"idle"}),[b,y]=Ae.useState(!1),[v,S]=Ae.useState([]),C=Ae.useMemo(()=>l?`openchamber.integrate.conflict:${l}`:null,[l]);Ae.useEffect(()=>{if(!C||typeof window>"u")return;const w=window.localStorage.getItem(C);if(w)try{const T=JSON.parse(w);if(!T?.tempWorktreePath||T.repoRoot!==t){window.localStorage.removeItem(C);return}(async()=>{if(!await pN(T.tempWorktreePath).catch(()=>!1)){window.localStorage.removeItem(C);return}const I=await fN(T.tempWorktreePath).catch(()=>null);I&&x({kind:"conflict",state:T,details:I})})()}catch{window.localStorage.removeItem(C)}},[C,t]),Ae.useEffect(()=>{if(!h){x({kind:"idle"});return}let w=!1;return x({kind:"loading"}),(async()=>{try{const T=await No({repoRoot:t,sourceBranch:r,targetBranch:f});if(w)return;if(x({kind:"ready",plan:T}),T.commits.length>0){const A=T.commits.slice(-50).reverse().map(G=>JSON.stringify(G)).join(" "),F=((await Ht(`git show -s --format=%H%x09%h%x09%s ${A}`,t)).stdout||"").split(/\r?\n/).filter(Boolean),z=[];for(const G of F){const[oe,O,q]=G.split(" ");!oe||!O||z.push({sha:oe,short:O,subject:q||""})}w||(S(z),y(!1))}else w||(S([]),y(!1))}catch{w||x({kind:"idle"})}})(),()=>{w=!0}},[h,t,r,f,a]);const N=Ae.useCallback(w=>{l&&ve.getState().setWorktreeMetadata(l,{...s,createdFromBranch:w})},[l,s]),j=Ae.useCallback(async w=>{if(d("chat"),!l){V.error("No active session",{description:"Open a chat session first."});return}const{currentProviderId:T,currentModelId:E,currentAgentName:I,currentVariant:A}=Je.getState(),P=Nt.getState().lastUsedProvider,F=T||P?.providerID,z=E||P?.modelID;if(!F||!z){V.error("No model selected");return}const G=`Resolve cherry-pick conflicts and keep intent of commit ${w.state.currentCommit} onto branch ${w.state.targetBranch}. After edits, report if I can continue process.`,oe=`Worktree commit integration is in progress.
203
+ - Repo root: ${w.state.repoRoot}
204
+ - Temp target worktree: ${w.state.tempWorktreePath}
205
+ - Source branch: ${w.state.sourceBranch}
206
+ - Target branch: ${w.state.targetBranch}
207
+
208
+ Goal:
209
+ - Resolve conflicts inside the temp target worktree directory.
210
+ - Do NOT change intent of the commit being applied.
211
+ - After edits, say whether I can click "Continue".
212
+ `,O=`Cherry-pick conflict context (JSON)
213
+ ${JSON.stringify({repoRoot:w.state.repoRoot,tempWorktreePath:w.state.tempWorktreePath,sourceBranch:w.state.sourceBranch,targetBranch:w.state.targetBranch,currentCommit:w.state.currentCommit,remainingCommits:w.state.remainingCommits,statusPorcelain:w.details.statusPorcelain,unmergedFiles:w.details.unmergedFiles,currentPatchMeta:w.details.currentPatchMeta,currentPatch:w.details.currentPatch,diff:w.details.diff},null,2)}`;Nt.getState().sendMessage(G,F,z,I??void 0,l,void 0,null,[{text:oe,synthetic:!0},{text:O,synthetic:!0}],A).catch(q=>{const Y=q instanceof Error?q.message:String(q);V.error("Failed to send message",{description:Y})})},[l,d]),D=Ae.useCallback(async()=>{if(g.kind==="ready"){if(g.plan.commits.length===0){V.message("No commits to move");return}x({kind:"running",plan:g.plan});try{const w=await hN(g.plan);if(w.kind==="success"){V.success("Commits moved",{description:`${w.moved} commit${w.moved===1?"":"s"} into ${g.plan.targetBranch}`});const T=await No(g.plan);x({kind:"ready",plan:T}),c?.();return}w.kind==="conflict"&&(V.error("Cherry-pick conflict",{description:"Resolve conflicts, then Continue."}),x({kind:"conflict",state:w.state,details:w.details}),C&&typeof window<"u"&&window.localStorage.setItem(C,JSON.stringify(w.state)))}catch(w){const T=w instanceof Error?w.message:String(w);V.error("Failed to move commits",{description:T});const E=await No({repoRoot:t,sourceBranch:r,targetBranch:f}).catch(()=>null);x(E?{kind:"ready",plan:E}:{kind:"idle"})}}},[g,c,t,r,f,C]),k=Ae.useCallback(async()=>{if(g.kind==="conflict")try{await gN(g.state),V.message("Cherry-pick aborted"),C&&typeof window<"u"&&window.localStorage.removeItem(C)}finally{const w=await No({repoRoot:t,sourceBranch:r,targetBranch:f}).catch(()=>null);x(w?{kind:"ready",plan:w}:{kind:"idle"})}},[g,t,r,f,C]),M=Ae.useCallback(async()=>{if(g.kind==="conflict")try{const w=await xN(g.state);if(w.kind==="success"){V.success("Cherry-pick finished");const T=await No({repoRoot:t,sourceBranch:r,targetBranch:f}).catch(()=>null);x(T?{kind:"ready",plan:T}:{kind:"idle"}),C&&typeof window<"u"&&window.localStorage.removeItem(C),c?.();return}w.kind==="conflict"&&(x({kind:"conflict",state:w.state,details:w.details}),C&&typeof window<"u"&&window.localStorage.setItem(C,JSON.stringify(w.state)))}catch(w){const T=w instanceof Error?w.message:String(w);V.error("Cherry-pick continue failed",{description:T})}},[g,t,r,f,c,C]);return!t||!r?null:e.jsxs(Pn,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(xo,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(_x,{className:"size-4 text-muted-foreground"}),e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:"Re-integrate commits"}),g.kind==="ready"&&g.plan.commits.length>0?e.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:[g.plan.commits.length," to move"]}):null]}),e.jsx("div",{className:"flex items-center gap-2",children:g.kind==="loading"||g.kind==="running"?e.jsx(Mt,{className:"size-4 animate-spin text-muted-foreground"}):null})]}),e.jsx(Tn,{children:e.jsx("div",{className:"border-t border-border/40",children:e.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Move commits"}),e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[r," → ",f]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsxs(Se,{variant:"outline",size:"sm",className:"gap-1.5",children:["Target",e.jsx("span",{className:"max-w-[160px] truncate font-mono text-xs text-muted-foreground",children:f}),e.jsx(Wt,{className:"size-4 opacity-60"})]})}),e.jsx(rs,{align:"end",className:"w-72 p-0 max-h-(--radix-dropdown-menu-content-available-height) flex flex-col overflow-hidden",children:e.jsxs(Mi,{className:"h-full min-h-0",children:[e.jsx(Di,{placeholder:"Search branches..."}),e.jsxs(Ai,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Ei,{children:"No branches found."}),e.jsx(Xr,{heading:"Local branches",children:n.map(w=>e.jsx(ws,{value:w,onSelect:()=>{p(w),N(w)},children:w},w))})]})]})})]}),g.kind==="ready"?e.jsx(Se,{size:"sm",onClick:()=>{D()},disabled:!h||g.plan.commits.length===0,children:"Move"}):g.kind==="loading"?e.jsx(Se,{size:"sm",variant:"outline",disabled:!0,children:"Checking…"}):g.kind==="running"?e.jsx(Se,{size:"sm",variant:"outline",disabled:!0,children:"Moving…"}):null]}),g.kind==="ready"&&g.plan.commits.length===0&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:"No commits to move."}),g.kind==="ready"&&g.plan.commits.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"typography-meta text-foreground",children:["Commits to move",e.jsxs("span",{className:"text-muted-foreground",children:[" (",g.plan.commits.length,")"]})]}),v.length>0&&g.plan.commits.length>5&&e.jsx("button",{type:"button",onClick:()=>y(w=>!w),className:"typography-micro text-muted-foreground hover:text-foreground",children:b?"Show less":"Show all"})]}),e.jsxs("div",{className:"space-y-1",children:[(b?v:v.slice(0,5)).map(w=>e.jsxs("div",{className:"flex items-baseline gap-2 min-w-0",children:[e.jsx("span",{className:"font-mono text-xs text-muted-foreground flex-shrink-0",children:w.short}),e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:w.subject||w.sha})]},w.sha)),v.length===0&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Preview unavailable."}),g.plan.commits.length>v.length&&e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["Showing first ",v.length," commits."]})]})]}),g.kind==="conflict"&&e.jsxs("div",{className:"rounded-md border border-border/60 bg-background/60 p-3 space-y-2",children:[e.jsxs("div",{className:"typography-meta text-foreground",children:["Conflicts in ",g.details.unmergedFiles.length," files"]}),e.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:["Current commit: ",e.jsx("span",{className:"font-mono",children:g.state.currentCommit.slice(0,7)})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.details.unmergedFiles.slice(0,6).map(w=>e.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:w},w)),g.details.unmergedFiles.length>6&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",g.details.unmergedFiles.length-6," more"]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(Se,{size:"sm",variant:"ghost",className:"h-7 px-2 py-0 typography-meta",onClick:()=>{k()},children:"Abort"}),e.jsx(Se,{size:"sm",variant:"secondary",className:"h-7 px-2 py-0 typography-meta",onClick:()=>{j({state:g.state,details:g.details})},children:"Resolve with AI"}),e.jsx(Se,{size:"sm",className:"h-7 px-2 py-0 typography-meta",onClick:()=>{M()},children:"Continue"})]})]})]})})})]})},bN=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),wN=({currentBranch:t,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:o,onCreate:a,disabled:c=!1})=>{const[l,d]=i.useState(!1),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,g]=i.useState(""),[x,b]=i.useState(!1),y=i.useRef(null),v=i.useMemo(()=>bN(h),[h]),S=i.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(w=>w.toLowerCase().includes(M)):r},[u,r]),C=i.useMemo(()=>{const M=u.toLowerCase();return M?s.filter(w=>w.toLowerCase().includes(M)):s},[u,s]),N=M=>{if(M===t){d(!1);return}o(M),d(!1),m("")},j=()=>{p(!0),setTimeout(()=>y.current?.focus(),50)},D=async()=>{if(!(!v||x)){b(!0);try{await a(v),g(""),p(!1),d(!1)}finally{b(!1)}}},k=()=>{g(""),p(!1)};return i.useEffect(()=>{l||(m(""),p(!1),g(""))},[l]),e.jsxs(ts,{open:l,onOpenChange:d,children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:c,children:[e.jsx(Ut,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:t||"Detached HEAD"}),e.jsx(Wt,{className:"size-4 opacity-60"})]})})}),e.jsxs(lt,{sideOffset:8,children:["Switch branch (",r.length," local · ",s.length," remote)"]})]}),e.jsx(rs,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Mi,{className:"h-full min-h-0",children:[e.jsx(Di,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(Ai,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Ei,{children:"No branches found."}),e.jsx(Xr,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:y,placeholder:"New branch name",value:h,onChange:M=>g(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),D()):M.key==="Escape"&&(M.preventDefault(),k())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:D,disabled:!v||x,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:x?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(ls,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:k,disabled:x,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(es,{className:"size-4"})})]}):e.jsxs(ws,{onSelect:j,children:[e.jsx(ls,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(ri,{}),e.jsxs(Xr,{heading:"Local branches",children:[S.map(M=>e.jsxs(ws,{onSelect:()=>N(M),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:M}),(n?.[M]?.ahead||n?.[M]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[M].ahead||0," ahead ·"," ",n[M].behind||0," behind"]})]}),t===M&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${M}`)),S.length===0&&e.jsx(ws,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(ri,{}),e.jsxs(Xr,{heading:"Remote branches",children:[C.map(M=>e.jsx(ws,{onSelect:()=>N(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),C.length===0&&e.jsx(ws,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},vN=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),jN=({currentBranch:t,onRename:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(t||""),[c,l]=i.useState(!1),d=i.useRef(null),u=()=>{!t||!r||(a(t),n(!0),setTimeout(()=>d.current?.focus(),0))},m=async()=>{if(!t||!r||!o.trim())return;const h=vN(o);if(h===t){n(!1);return}l(!0);try{await r(t,h),n(!1),a("")}finally{l(!1)}},f=()=>{n(!1),a("")},p=h=>{h.key==="Enter"?(h.preventDefault(),m()):h.key==="Escape"&&(h.preventDefault(),f())};return s?e.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:e.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:h=>{h.preventDefault(),m()},children:[e.jsx(Ut,{className:"size-4 text-primary"}),e.jsx("input",{ref:d,value:o,onChange:h=>a(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:p,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:c,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(Tt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:c,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(es,{className:"size-4"})})]})}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 h-8",children:[e.jsx(Ut,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate typography-ui-label font-normal text-foreground",children:t||"Detached HEAD"})]}),r&&t&&e.jsx(Se,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(fo,{className:"size-4"})})]})},SN=({syncAction:t,onFetch:r,onPull:s,onPush:n,disabled:o})=>{const a=o||t!==null;return e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[t==="fetch"?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(en,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(lt,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:s,disabled:a,children:[t==="pull"?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(po,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(lt,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[t==="push"?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(eo,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(lt,{sideOffset:8,children:"Push changes"})]})]})},NN={branch:Ut,briefcase:ml,house:ul,graduation:dl,code:sr,heart:of,user:rr},kN={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function rh(t){return t&&kN[t]||"var(--primary)"}const Vu=({icon:t,className:r,colorToken:s})=>{const n=NN[t??"branch"]??rr;return e.jsx(n,{className:r,style:{color:rh(s)}})},CN=({activeProfile:t,identities:r,onSelect:s,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(ts,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:rh(t?.color)},disabled:o,children:[n?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(Vu,{icon:t?.icon,colorToken:t?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:t?.name||"No identity"}),e.jsx(Wt,{className:"size-4 opacity-60"})]})})}),e.jsxs(lt,{sideOffset:8,className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:t?.userName||"Unknown user"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:t?.userEmail||"No email configured"})]})]}),e.jsx(rs,{align:"end",className:"w-64",children:r.length===0?e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):r.map(a=>e.jsx(kt,{onSelect:()=>s(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Vu,{icon:a.icon,colorToken:a.color,className:"size-4"}),e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:a.name}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:a.userEmail})]})]})},a.id))})]})},MN=({status:t,localBranches:r,remoteBranches:s,branchInfo:n,syncAction:o,onFetch:a,onPull:c,onPush:l,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:h,isApplyingIdentity:g,isWorktreeMode:x})=>t?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[x?e.jsx(jN,{currentBranch:t.current,onRename:m}):e.jsx(wN,{currentBranch:t.current,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:d,onCreate:u}),(!!t.tracking||t.ahead>0||t.behind>0)&&e.jsxs(dt,{delayDuration:800,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 px-1.5 typography-meta text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(eo,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:t.ahead})]}),!!t.tracking&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(po,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:t.behind})]})]})}),e.jsx(lt,{sideOffset:8,children:t.tracking?`Upstream: ${t.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(SN,{syncAction:o,onFetch:a,onPull:c,onPush:l,disabled:!t}),e.jsx("div",{className:"flex-1"}),e.jsx(CN,{activeProfile:f,identities:p,onSelect:h,isApplying:g})]}):null,DN=({behind:t,onPull:r,isPulling:s})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx(ol,{className:"size-10 text-emerald-500/60 mb-4"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:"Working tree clean"}),e.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:"All changes have been committed"}),t>0&&e.jsxs(Se,{variant:"outline",onClick:r,disabled:s,children:[s?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(po,{className:"size-4"}),"Pull ",t," commit",t===1?"":"s"]})]}),nh={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},AN=nh.M;function EN(t){const r=t.index?.trim(),s=t.working_dir?.trim();return r&&r!=="?"?r.charAt(0):s?s.charAt(0):r?.charAt(0)||s?.charAt(0)||"M"}function IN(t){const r=EN(t);return nh[r]??AN}const PN=i.memo(function({file:r,checked:s,onToggle:n,onViewDiff:o,onRevert:a,isReverting:c,stats:l}){const d=Ae.useMemo(()=>IN(r),[r]),u=d.description,m=l?.insertions??0,f=l?.deletions??0,p=Ae.useCallback(x=>{x.key===" "?(x.preventDefault(),n()):x.key==="Enter"&&(x.preventDefault(),o())},[n,o]),h=Ae.useCallback(x=>{x.preventDefault(),x.stopPropagation(),n()},[n]),g=Ae.useCallback(x=>{x.preventDefault(),x.stopPropagation(),a()},[a]);return e.jsx("li",{children:e.jsxs("div",{className:"group flex items-center gap-2 px-3 py-1.5 hover:bg-sidebar/40 cursor-pointer",role:"button",tabIndex:0,onClick:o,onKeyDown:p,children:[e.jsx("button",{type:"button",onClick:h,"aria-pressed":s,"aria-label":`Select ${r.path}`,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s?e.jsx(Nn,{className:"size-4 text-primary"}):e.jsx(kn,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:d.color},title:u,"aria-label":u,children:d.code}),e.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left"},title:r.path,children:r.path}),e.jsxs("span",{className:"shrink-0 typography-micro",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",m]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",f]})]}),e.jsxs(dt,{delayDuration:200,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:g,disabled:c,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:c?e.jsx(Mt,{className:"size-3.5 animate-spin"}):e.jsx(so,{className:"size-3.5"})})}),e.jsx(lt,{sideOffset:8,children:"Revert changes"})]})]})})}),TN=({changeEntries:t,selectedPaths:r,diffStats:s,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:c,onViewDiff:l,onRevertFile:d})=>{const u=r.size,m=t.length;return e.jsxs("section",{className:"flex flex-col rounded-xl border border-border/60 bg-background/70",children:[e.jsxs("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Changes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[u,"/",m]}),m>0&&e.jsxs(e.Fragment,{children:[e.jsx(Se,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(Se,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:c,disabled:u===0,children:"None"})]})]})]}),e.jsx(xt,{outerClassName:"flex-1 min-h-0 max-h-[30vh]",className:"w-full",children:e.jsx("ul",{className:"divide-y divide-border/60",children:t.map(f=>e.jsx(PN,{file:f,checked:r.has(f.path),stats:s?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>l(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function Dn({className:t,variant:r,...s}){return e.jsx(Se,{variant:r,size:"sm",className:R("h-7 px-2 py-0",t),...s})}const uc=38,Gu=200,FN=({value:t,onChange:r,placeholder:s="Commit message",disabled:n=!1})=>{const o=i.useRef(null);return i.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${uc}px`;const c=Math.min(Math.max(a.scrollHeight,uc),Gu);a.style.height=`${c}px`},[t]),e.jsx(Fs,{ref:o,value:t,onChange:a=>r(a.target.value),placeholder:s,rows:1,disabled:n,className:R("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:uc,maxHeight:Gu}})},RN=({highlights:t,onInsert:r,onClear:s})=>{if(t.length===0)return null;const n=()=>{r(),s()};return e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground",children:"AI highlights"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(po,{className:"size-4"})})}),e.jsx(lt,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:t.map((o,a)=>e.jsx("li",{className:"typography-meta text-foreground",children:o},a))})]})},LN=({selectedCount:t,commitMessage:r,onCommitMessageChange:s,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:c,isGeneratingMessage:l,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f,gitmojiEnabled:p,onOpenGitmojiPicker:h})=>{const g=t>0,x=r.trim()&&g&&m===null,{isMobile:b}=Gt();return e.jsxs(Pn,{open:g,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"flex w-full items-center justify-between px-3 py-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:g?`${t} file${t===1?"":"s"} selected`:"No files selected"})]}),e.jsx(Tn,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(RN,{highlights:n,onInsert:o,onClear:a}),e.jsx(FN,{value:r,onChange:s,placeholder:"Commit message",disabled:m!==null}),p&&e.jsxs(Se,{variant:"outline",size:"sm",onClick:h,className:"w-fit",type:"button",children:[e.jsx($x,{className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"@container/commit-actions flex items-center gap-2 min-w-0",children:[e.jsxs(Se,{variant:"outline",size:"sm",onClick:c,disabled:l||m!==null||t===0||f,type:"button","aria-label":"Generate",className:"commit-actions__btn",children:[l?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(ll,{className:"size-4 text-primary"}),e.jsx("span",{className:"commit-actions__label",children:"Generate"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Dn,{variant:"outline",onClick:d,disabled:!x||l,className:"commit-actions__btn whitespace-nowrap","aria-label":"Commit",children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Mt,{className:"size-4 animate-spin"}),e.jsx("span",{className:"commit-actions__label",children:"Committing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(ol,{className:"size-4"}),e.jsx("span",{className:"commit-actions__label",children:"Commit"})]})}),b?e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{variant:"default",size:"sm",onClick:u,disabled:!x||l,className:"h-7 w-7 p-0","aria-label":"Commit & Push",children:m==="commitAndPush"?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(eo,{className:"size-4"})})}),e.jsx(lt,{side:"top",children:e.jsx("p",{children:"Commit & Push"})})]}):e.jsx(Dn,{variant:"default",onClick:u,disabled:!x||l,className:"commit-actions__btn","aria-label":"Commit & Push",children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Mt,{className:"size-4 animate-spin"}),e.jsx("span",{className:"commit-actions__label commit-actions__label--long",children:"Pushing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(eo,{className:"size-4"}),e.jsx("span",{className:"commit-actions__label commit-actions__label--long",children:"Commit & Push"})]})})]})]})})]})};function qu(t){const r=new Date(t);return Number.isNaN(r.getTime())?t:r.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ON(t){switch(t){case"A":return"text-emerald-500";case"D":return"text-red-500";case"M":return"text-amber-500";case"R":return"text-blue-500";default:return"text-muted-foreground"}}const _N=({entry:t,isExpanded:r,onToggle:s,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:s,className:R("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",r?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[e.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:t.message}),e.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[e.jsx("span",{className:"truncate min-w-[3ch]",title:t.author_name,children:t.author_name}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("span",{className:"truncate min-w-0",title:qu(t.date),children:qu(t.date)})]}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:c=>{c.stopPropagation(),a(t.hash)},children:e.jsx(nr,{className:"size-3"})})}),e.jsx(lt,{sideOffset:8,children:"Copy SHA"})]})]})]})]}),r&&e.jsx("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:o?e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx(Mt,{className:"size-4 animate-spin text-muted-foreground"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Loading files..."})]}):n.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:"No files"}):e.jsx("ul",{className:"space-y-0.5 py-2",children:n.map(c=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:R("font-semibold w-3 text-center",ON(c.changeType)),children:c.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:c.path,children:c.path}),!c.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",c.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",c.deletions]})]}),c.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},c.path))})})]}),$N=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],BN=({log:t,isLogLoading:r,logMaxCount:s,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:c,loadingCommitHashes:l,onCopyHash:d})=>{const[u,m]=i.useState(!0);return t?e.jsxs(Pn,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(xo,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"History"}),e.jsxs("div",{className:"flex items-center gap-2",children:[u&&e.jsx("div",{onClick:f=>f.stopPropagation(),onPointerDown:f=>f.stopPropagation(),children:e.jsxs(As,{value:String(s),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Es,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:r,children:e.jsx(Cn,{placeholder:"Commits"})}),e.jsx(Is,{children:$N.map(f=>e.jsx(Bt,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(mi,{className:"size-4 text-muted-foreground"}):e.jsx(Wt,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(Tn,{children:e.jsx(xt,{outerClassName:"min-h-0 max-h-[50vh]",className:"w-full",children:t.all.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"No commits found"})}):e.jsx("ul",{className:"divide-y divide-border/60",children:t.all.map(f=>e.jsx(_N,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:c.get(f.hash)??[],isLoadingFiles:l.has(f.hash),onCopyHash:d},f.hash))})})})]}):null},zN=t=>{switch(t){case"success":return"bg-[color:var(--status-success)]";case"failure":return"bg-[color:var(--status-error)]";case"pending":return"bg-[color:var(--status-warning)]";default:return"bg-muted-foreground/40"}},Ku=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase()),mc=new Map,Ju=async t=>{if(typeof window>"u")return;const r=window.opencodeDesktop;if(r?.openExternal)try{const s=await r.openExternal(t);if(s&&typeof s=="object"&&"success"in s&&s.success===!0)return}catch{}try{window.open(t,"_blank","noopener,noreferrer")}catch{}},HN=({directory:t,branch:r,baseBranch:s})=>{const{github:n}=Hs(),o=Bs(fe=>fe.status),a=Bs(fe=>fe.hasChecked),c=Me(fe=>fe.setSettingsDialogOpen),l=Me(fe=>fe.setSidebarSection),d=Me(fe=>fe.setActiveMainTab),u=ve(fe=>fe.currentSessionId),m=i.useCallback(()=>{l("settings"),c(!0)},[c,l]),f=i.useMemo(()=>`${t}::${r}`,[t,r]),p=i.useMemo(()=>mc.get(f)??null,[f]),[h,g]=i.useState(p?.isOpen??!0),[x,b]=i.useState(!1),[y,v]=i.useState(null),[S,C]=i.useState(null),[N,j]=i.useState(()=>p?.title??Ku(r)),[D,k]=i.useState(()=>p?.body??""),[M,w]=i.useState(()=>p?.draft??!1),[T,E]=i.useState("squash"),[I,A]=i.useState(!1),[P,F]=i.useState(!1),[z,G]=i.useState(!1),[oe,O]=i.useState(!1),[q,Y]=i.useState(!1),[Z,B]=i.useState(null),[W,te]=i.useState(!1),ye=!!(t&&r&&s&&r!==s),me=y?.pr??null,K=i.useCallback(async()=>{if(!n?.prContext){V.error("GitHub runtime API unavailable");return}if(me){Y(!0),te(!0);try{const fe=await n.prContext(t,me.number,{includeDiff:!1,includeCheckDetails:!0});B(fe)}catch(fe){const ie=fe instanceof Error?fe.message:String(fe);V.error("Failed to load check details",{description:ie})}finally{te(!1)}}},[t,n,me]),L=i.useCallback(fe=>{const ie=fe.status||"unknown",se=fe.conclusion??void 0,re=se?`${ie} / ${se}`:ie,ne=fe.app?.name||fe.app?.slug;return e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground truncate",children:fe.name}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:ne?`${ne} · ${re}`:re}),fe.output?.summary?e.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap line-clamp-4 mt-2",children:fe.output.summary}):null,fe.job?.steps&&fe.job.steps.length>0?e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Steps"}),e.jsx("div",{className:"space-y-1",children:fe.job.steps.map((xe,Ue)=>{const ze=(xe.conclusion||"").toLowerCase(),Ke=ze&&!["success","neutral","skipped"].includes(ze);return e.jsxs("div",{className:"typography-micro flex items-center gap-2 rounded px-2 py-1 "+(Ke?"bg-destructive/10 text-destructive":"text-muted-foreground"),children:[e.jsx("span",{className:"truncate",children:xe.name}),xe.conclusion?e.jsx("span",{className:"ml-auto flex-shrink-0",children:xe.conclusion}):null]},`${xe.name}-${Ue}`)})})]}):null]}),fe.detailsUrl?e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:e.jsxs("a",{href:fe.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Zs,{className:"size-4"}),"Open"]})}):null]})},[]),Q=i.useCallback(async()=>{if(d("chat"),!n?.prContext){V.error("GitHub runtime API unavailable");return}if(!t||!me)return;if(!u){V.error("No active session",{description:"Open a chat session first."});return}const{currentProviderId:fe,currentModelId:ie,currentAgentName:se,currentVariant:re}=Je.getState(),ne=Nt.getState().lastUsedProvider,xe=fe||ne?.providerID,Ue=ie||ne?.modelID;if(!xe||!Ue){V.error("No model selected");return}try{const ze=await n.prContext(t,me.number,{includeDiff:!1,includeCheckDetails:!0}),rt=(ze.checkRuns??[]).filter(st=>{const mt=typeof st.conclusion=="string"?st.conclusion.toLowerCase():"";return mt?!["success","neutral","skipped"].includes(mt):!1});if(rt.length===0){V.message("No failed checks");return}const jt="Review these PR failed checks and propose likely fixes. Do not implement until I confirm.",Xe=`Use the attached checks payload.
214
+ - Summarize what is failing.
215
+ - Identify likely root cause(s).
216
+ - Propose a minimal fix plan and verification steps.
217
+ - No speculation: ask for missing info if needed.`,Ct=`GitHub PR failed checks (JSON)
218
+ ${JSON.stringify({repo:ze.repo??null,pr:ze.pr??null,failedChecks:rt},null,2)}`;Nt.getState().sendMessage(jt,xe,Ue,se??void 0,u,void 0,null,[{text:Xe,synthetic:!0},{text:Ct,synthetic:!0}],re).catch(st=>{const mt=st instanceof Error?st.message:String(st);V.error("Failed to send message",{description:mt})})}catch(ze){const Ke=ze instanceof Error?ze.message:String(ze);V.error("Failed to load checks",{description:Ke})}},[u,t,n,me,d]),ce=i.useCallback(async()=>{if(d("chat"),!n?.prContext){V.error("GitHub runtime API unavailable");return}if(!t||!me)return;if(!u){V.error("No active session",{description:"Open a chat session first."});return}const{currentProviderId:fe,currentModelId:ie,currentAgentName:se,currentVariant:re}=Je.getState(),ne=Nt.getState().lastUsedProvider,xe=fe||ne?.providerID,Ue=ie||ne?.modelID;if(!xe||!Ue){V.error("No model selected");return}try{const ze=await n.prContext(t,me.number,{includeDiff:!1,includeCheckDetails:!1}),Ke=ze.issueComments??[],rt=ze.reviewComments??[];if(Ke.length+rt.length===0){V.message("No PR comments");return}const Xe="Review these PR comments and propose the required changes and next actions. Do not implement until I confirm.",Ct=`Use the attached comments payload.
219
+ - Identify required vs optional changes.
220
+ - Call out intent/implementation mismatch if present.
221
+ - Propose a minimal plan and verification steps.
222
+ - No speculation: ask for missing info if needed.`,st=`GitHub PR comments (JSON)
223
+ ${JSON.stringify({repo:ze.repo??null,pr:ze.pr??null,issueComments:Ke,reviewComments:rt},null,2)}`;Nt.getState().sendMessage(Xe,xe,Ue,se??void 0,u,void 0,null,[{text:Ct,synthetic:!0},{text:st,synthetic:!0}],re).catch(mt=>{const Pt=mt instanceof Error?mt.message:String(mt);V.error("Failed to send message",{description:Pt})})}catch(ze){const Ke=ze instanceof Error?ze.message:String(ze);V.error("Failed to load PR comments",{description:Ke})}},[u,t,n,me,d]),he=i.useCallback(async()=>{if(ye){if(a&&o?.connected===!1){v({connected:!1}),C(null),b(!1);return}if(!n?.prStatus){v(null),C("GitHub runtime API unavailable");return}b(!0),C(null);try{const fe=await n.prStatus(t,r);v(fe),fe.connected===!1&&C(null)}catch(fe){const ie=fe instanceof Error?fe.message:String(fe);C(ie||"Failed to load PR status")}finally{b(!1)}}},[r,ye,t,n,a,o]);i.useEffect(()=>{const fe=mc.get(f)??null;j(fe?.title??Ku(r)),k(fe?.body??""),w(fe?.draft??!1),g(fe?.isOpen??!0),he()},[r,he,f]),i.useEffect(()=>{a&&o?.connected===!1&&(v({connected:!1}),C(null))},[a,o]),i.useEffect(()=>{!t||!r||mc.set(f,{title:N,body:D,draft:M,isOpen:h})},[f,N,D,M,h,t,r]);const Ne=i.useCallback(async()=>{if(!I&&t){A(!0);try{const fe=await _b(t,{base:s,head:r});fe.title?.trim()&&j(fe.title.trim()),fe.body?.trim()&&k(fe.body.trim()),V.success("PR description generated")}catch(fe){const ie=fe instanceof Error?fe.message:String(fe);V.error("Failed to generate description",{description:ie})}finally{A(!1)}}},[s,r,t,I]),H=i.useCallback(async()=>{if(!n?.prCreate){V.error("GitHub runtime API unavailable");return}const fe=N.trim();if(!fe){V.error("Title is required");return}F(!0);try{const ie=await n.prCreate({directory:t,title:fe,head:r,base:s,...D.trim()?{body:D}:{},draft:M});V.success("PR created"),v(se=>se&&{...se,pr:ie}),await he()}catch(ie){const se=ie instanceof Error?ie.message:String(ie);V.error("Failed to create PR",{description:se})}finally{F(!1)}},[s,D,r,t,M,n,he,N]),we=i.useCallback(async fe=>{if(!n?.prMerge){V.error("GitHub runtime API unavailable");return}G(!0);try{const ie=await n.prMerge({directory:t,number:fe.number,method:T});ie.merged?V.success("PR merged"):V.message("PR not merged",{description:ie.message||"Not mergeable"}),await he()}catch(ie){const se=ie instanceof Error?ie.message:String(ie);V.error("Merge failed",{description:se}),fe.url&&Ju(fe.url)}finally{G(!1)}},[t,n,T,he]),ee=i.useCallback(async fe=>{if(!n?.prReady){V.error("GitHub runtime API unavailable");return}O(!0);try{await n.prReady({directory:t,number:fe.number}),V.success("Marked ready for review"),await he()}catch(ie){const se=ie instanceof Error?ie.message:String(ie);V.error("Failed to mark ready",{description:se}),fe.url&&Ju(fe.url)}finally{O(!1)}},[t,n,he]);if(!ye)return null;const ue=y?.repo?.url||null,ge=y?.checks??null,X=!!y?.canMerge,de=!!y?.connected,ae=a&&y?.connected===!1;return e.jsxs(Pn,{open:h,onOpenChange:g,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(xo,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ua,{className:"size-4 text-muted-foreground"}),e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:"Pull Request"}),me?e.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",me.number]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[x?e.jsx(Mt,{className:"size-4 animate-spin text-muted-foreground"}):null,ge?e.jsxs("span",{className:"inline-flex items-center gap-2 typography-micro text-muted-foreground",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${zN(ge.state)}`}),ge.total>0?`${ge.success}/${ge.total} checks`:`${ge.state} checks`]}):null]})]}),e.jsx(Tn,{children:e.jsx("div",{className:"border-t border-border/40",children:e.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[ae?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground",children:"GitHub not connected. Connect your GitHub account in settings."}),e.jsx(Se,{variant:"outline",size:"sm",onClick:m,className:"w-fit",children:"Open settings"})]}):null,S?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"PR status unavailable"}),e.jsx("div",{className:"typography-meta text-muted-foreground break-words",children:S}),ue?e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:e.jsxs("a",{href:ue,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Zs,{className:"size-4"}),"Open Repo"]})}):null]}):null,me?e.jsx("div",{className:"flex flex-col gap-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground truncate",children:me.title}),e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[me.state,me.draft?" (draft)":"",me.mergeable===!1?" · not mergeable":"",typeof me.mergeableState=="string"&&me.mergeableState?` · ${me.mergeableState}`:""]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[ge?e.jsxs(Se,{variant:"outline",size:"sm",onClick:K,disabled:W,children:[W?e.jsx(Mt,{className:"size-4 animate-spin"}):null,"Check details"]}):null,ge?.failure?e.jsx(Se,{variant:"outline",size:"sm",onClick:Q,children:"Send failed checks to chat"}):null,e.jsx(Se,{variant:"outline",size:"sm",onClick:ce,children:"Send PR comments to chat"})]}),X&&me.draft?e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Draft PRs must be marked ready before merge."}):null,X?null:e.jsx("div",{className:"typography-micro text-muted-foreground",children:"No merge permission; use Open in GitHub."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:me.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Zs,{className:"size-4"}),"Open"]})}),X&&me.draft&&me.state==="open"?e.jsxs(Se,{variant:"outline",size:"sm",onClick:()=>ee(me),disabled:oe||z,children:[oe?e.jsx(Mt,{className:"size-4 animate-spin"}):null,"Ready"]}):null,X?e.jsxs(e.Fragment,{children:[e.jsxs("select",{className:"h-8 rounded-md border border-border bg-background px-2 typography-meta",value:T,onChange:fe=>E(fe.target.value),disabled:z||me.state!=="open",children:[e.jsx("option",{value:"squash",children:"Squash"}),e.jsx("option",{value:"merge",children:"Merge"}),e.jsx("option",{value:"rebase",children:"Rebase"})]}),e.jsxs(Se,{size:"sm",onClick:()=>we(me),disabled:z||oe||me.state!=="open"||me.draft,children:[z?e.jsx(Mt,{className:"size-4 animate-spin"}):null,"Merge"]})]}):null]})]})}):e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Create PR"}),e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[r," → ",s]})]}),ue?e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ue,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Zs,{className:"size-4"}),"Repo"]})}):null]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Title"}),e.jsx(St,{value:N,onChange:fe=>j(fe.target.value),placeholder:"PR title"})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Description"}),e.jsx(Fs,{value:D,onChange:fe=>k(fe.target.value),className:"min-h-[110px] bg-background/80",placeholder:"What changed and why"})]}),e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":M,onClick:()=>w(fe=>!fe),onKeyDown:fe=>{(fe.key===" "||fe.key==="Enter")&&(fe.preventDefault(),w(ie=>!ie))},children:[e.jsx("button",{type:"button",onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),w(ie=>!ie)},"aria-label":"Toggle draft PR",className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:M?e.jsx(Nn,{className:"size-4 text-primary"}):e.jsx(kn,{className:"size-4"})}),e.jsx("span",{className:"typography-ui-label text-foreground select-none",children:"Draft"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Se,{variant:"outline",size:"sm",onClick:Ne,disabled:I||P,children:[I?e.jsx(Mt,{className:"size-4 animate-spin"}):e.jsx(ll,{className:"size-4 text-primary"}),"Generate"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(Se,{size:"sm",onClick:H,disabled:P||!de,children:[P?e.jsx(Mt,{className:"size-4 animate-spin"}):null,"Create PR"]})]})]})]})})}),e.jsx(us,{open:q,onOpenChange:Y,children:e.jsxs(ms,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(xs,{children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-5 w-5"}),"Check Details"]}),e.jsx(Ss,{children:me?`PR #${me.number}`:"Pull request"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[W?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Mt,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):null,W?null:e.jsx("div",{className:"space-y-3",children:Array.isArray(Z?.checkRuns)&&Z?.checkRuns.length>0?Z.checkRuns.map((fe,ie)=>e.jsx("div",{className:"rounded-md border border-border/60 p-3",children:L(fe)},`${fe.name}-${ie}`)):e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No check details available."})})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx("div",{className:"flex-1"}),e.jsx(Se,{variant:"outline",onClick:()=>Y(!1),children:"Close"})]})]})})]})},oh="gitmojiCache",WN=1e3*60*60*24*7,ah="1",UN="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Qu={feat:":sparkles:",feature:":sparkles:",fix:":bug:",bug:":bug:",hotfix:":ambulance:",docs:":memo:",documentation:":memo:",style:":lipstick:",refactor:":recycle:",perf:":zap:",performance:":zap:",test:":white_check_mark:",tests:":white_check_mark:",build:":construction_worker:",ci:":green_heart:",chore:":wrench:",revert:":rewind:",wip:":construction:",security:":lock:",release:":bookmark:",merge:":twisted_rightwards_arrows:",mv:":truck:",move:":truck:",rename:":truck:",remove:":fire:",delete:":fire:",add:":sparkles:",create:":sparkles:",implement:":sparkles:",update:":recycle:",improve:":zap:",optimize:":zap:",upgrade:":arrow_up:",downgrade:":arrow_down:",deploy:":rocket:",init:":tada:",initial:":tada:"},ih=t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.emoji=="string"&&typeof r.code=="string"&&typeof r.description=="string"},VN=()=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(oh);if(!t)return null;const r=JSON.parse(t);return!r||r.version!==ah||typeof r.fetchedAt!="number"||!Array.isArray(r.gitmojis)?null:{gitmojis:r.gitmojis.filter(ih),fetchedAt:r.fetchedAt,version:r.version}}catch{return null}},GN=t=>{if(!(typeof window>"u"))try{const r={gitmojis:t,fetchedAt:Date.now(),version:ah};localStorage.setItem(oh,JSON.stringify(r))}catch{return}},qN=t=>Date.now()-t.fetchedAt<WN,KN=(t,r)=>{const s=t.toLowerCase(),n=/^([a-z]+)(?:\(.*\))?!?:/,o=s.match(n);if(o){const l=o[1],d=Qu[l];if(d)return r.find(u=>u.code===d)||null}const a=s.split(" ")[0],c=Qu[a];return c&&r.find(l=>l.code===c)||null},Yu=new Map,JN=()=>{const{git:t}=Hs(),r=Yo(),{currentSessionId:s,worktreeMetadata:n}=ve(),o=s?n.get(s)??void 0:void 0,{profiles:a,globalIdentity:c,defaultGitIdentityId:l,loadProfiles:d,loadGlobalIdentity:u,loadDefaultGitIdentityId:m}=co(),f=ep(r??null),p=Xf(r??null),h=Zf(r??null),g=nv(r??null),x=ov(r??null),b=is($=>$.isLoadingStatus),y=is($=>$.isLoadingLog),{setActiveDirectory:v,fetchAll:S,fetchStatus:C,fetchBranches:N,fetchLog:j,fetchIdentity:D,setLogMaxCount:k}=is(),M=i.useMemo(()=>r?Yu.get(r)??null:null,[r]),w=Je($=>$.settingsGitmojiEnabled),T=Lt($=>$.getActiveProject()),E=i.useMemo(()=>{const $=T?.worktreeDefaults?.baseBranch;return typeof $=="string"&&$.trim().length>0?$.trim():"main"},[T?.worktreeDefaults?.baseBranch]),[I,A]=i.useState(M?.commitMessage??""),[P,F]=i.useState(!1),[z,G]=i.useState(null),[oe,O]=i.useState(null),[q,Y]=i.useState(25),[Z,B]=i.useState(!1),{triggerFireworks:W}=iN(),te=i.useRef(new Map),ye=i.useRef(0),me=i.useCallback(()=>{ye.current+=1,B(!0)},[]),K=i.useCallback(()=>{ye.current=Math.max(0,ye.current-1),ye.current===0&&B(!1)},[]),[L,Q]=i.useState(()=>new Set(M?.selectedPaths??[])),[ce,he]=i.useState(!1),[Ne,H]=i.useState(new Set),[we,ee]=i.useState(0),[ue,ge]=i.useState(!1),[X,de]=i.useState(M?.generatedHighlights??[]),ae=o?.projectDirectory||null,fe=p?.current||null,ie=i.useMemo(()=>{const $=p?.tracking;return $?$.startsWith("origin/"):!0},[p?.tracking]),se=i.useMemo(()=>{const $=o?.createdFromBranch;if(typeof $=="string"&&$.trim().length>0)return $.trim();const U=T?.worktreeDefaults?.baseBranch;return typeof U=="string"&&U.trim().length>0?U.trim():"main"},[o?.createdFromBranch,T?.worktreeDefaults?.baseBranch]),re=i.useCallback(()=>{de([])},[]),[ne,xe]=i.useState(new Set),[Ue,ze]=i.useState(new Map),[Ke,rt]=i.useState(new Set),[jt,Xe]=i.useState(null),[Ct,st]=i.useState([]),[mt,Pt]=i.useState(""),Ot=i.useCallback($=>{navigator.clipboard.writeText($).then(()=>{V.success("Commit hash copied")}).catch(()=>{V.error("Failed to copy")})},[]),$e=i.useCallback($=>{xe(U=>{const J=new Set(U);return J.has($)?J.delete($):J.add($),J})},[]);i.useEffect(()=>{if(!r||!t)return;const $=Array.from(ne).filter(U=>!Ue.has(U)&&!Ke.has(U));if($.length!==0){rt(U=>{const J=new Set(U);for(const pe of $)J.add(pe);return J});for(const U of $)t.getCommitFiles(r,U).then(J=>{ze(pe=>new Map(pe).set(U,J.files))}).catch(J=>{console.error("Failed to fetch commit files:",J),ze(pe=>new Map(pe).set(U,[]))}).finally(()=>{rt(J=>{const pe=new Set(J);return pe.delete(U),pe})})}},[ne,r,t,Ue,Ke]),i.useEffect(()=>{r&&Yu.set(r,{directory:r,selectedPaths:Array.from(L),commitMessage:I,generatedHighlights:X})},[I,r,L,X]),i.useEffect(()=>{d(),u(),m()},[d,u,m]),i.useEffect(()=>{if(!r||!t?.getRemoteUrl){Xe(null);return}t.getRemoteUrl(r).then(Xe).catch(()=>Xe(null))},[r,t]),i.useEffect(()=>{if(!w){st([]);return}let $=!1;const U=VN();return U&&(st(U.gitmojis),qN(U))?()=>{$=!0}:((async()=>{try{const pe=await fetch(UN);if(!pe.ok)throw new Error(`Failed to load gitmojis: ${pe.statusText}`);const Ee=await pe.json(),He=Array.isArray(Ee.gitmojis)?Ee.gitmojis.filter(ih):[];$||(st(He),GN(He))}catch(pe){$||console.warn("Failed to load gitmoji list:",pe)}})(),()=>{$=!0})},[w]),i.useEffect(()=>{r&&(v(r),is.getState().directories.get(r)?.status||S(r,t,{force:!0}))},[r,v,S,t]);const be=i.useCallback(async($=!0)=>{if(r)try{await Promise.all([C(r,t),N(r,t)])}catch(U){if($){const J=U instanceof Error?U.message:"Failed to refresh repository state";V.error(J)}}},[r,t,C,N]),tt=i.useCallback(async()=>{r&&await j(r,t,q)},[r,t,j,q]),Ce=i.useCallback(async()=>{r&&await D(r,t)},[r,t,D]);i.useEffect(()=>{if(!r||!t?.hasLocalIdentity||f!==!0)return;const $=typeof l=="string"?l.trim():"";if(!$||$==="global"||te.current.get(r)===$)return;let J=!1;return(async()=>{try{const Ee=await t.hasLocalIdentity?.(r);if(J||Ee===!0)return;me(),await t.setGitIdentity(r,$),te.current.set(r,$),await Ce()}catch(Ee){console.warn("Failed to auto-apply default git identity:",Ee)}finally{J||K()}})(),()=>{J=!0}},[me,r,l,K,t,f,Ce]);const Ie=i.useMemo(()=>{if(!p)return[];const $=p.files??[],U=new Map;for(const J of $)U.set(J.path,J);return Array.from(U.values()).sort((J,pe)=>J.path.localeCompare(pe.path))},[p]);i.useEffect(()=>{if(!p||Ie.length===0){Q(new Set),he(!1);return}Q($=>{const U=new Set,J=$??new Set;for(const pe of Ie)J.has(pe.path)?U.add(pe.path):ce||U.add(pe.path);return U})},[p,Ie,ce]);const Qe=async $=>{if(r){G($);try{if($==="fetch")await t.gitFetch(r),V.success("Fetched latest updates");else if($==="pull"){const U=await t.gitPull(r);V.success(`Pulled ${U.files.length} file${U.files.length===1?"":"s"}`)}else $==="push"&&(await t.gitPush(r),V.success("Pushed to remote"));await be(!1),await tt()}catch(U){const J=U instanceof Error?U.message:`Failed to ${$==="pull"?"pull":$}`;V.error(J)}finally{G(null)}}},Te=async($={})=>{if(!r)return;if(!I.trim()){V.error("Please enter a commit message");return}const U=Array.from(L).sort();if(U.length===0){V.error("Select at least one file to commit");return}const J=$.pushAfter?"commitAndPush":"commit";O(J);try{await t.createGitCommit(r,I.trim(),{files:U}),V.success("Commit created successfully"),A(""),Q(new Set),he(!1),re(),await be(),$.pushAfter?(await t.gitPush(r),V.success("Pushed to remote"),W(),await be(!1)):await be(!1),await tt(),ee(pe=>pe+1)}catch(pe){const Ee=pe instanceof Error?pe.message:"Failed to create commit";V.error(Ee)}finally{O(null)}},Pe=i.useCallback(async()=>{if(r){if(L.size===0){V.error("Select at least one file to describe");return}ge(!0);try{const{message:$}=await t.generateCommitMessage(r,Array.from(L)),U=$.subject?.trim()??"",J=Array.isArray($.highlights)?$.highlights:[];if(U){let pe=U;if(w&&Ct.length>0){const Ee=KN(U,Ct);if(Ee){const{code:He,emoji:ft}=Ee;!U.startsWith(He)&&!U.startsWith(ft)&&(pe=`${He} ${U}`)}}A(pe)}de(J),V.success("Commit message generated")}catch($){const U=$ instanceof Error?$.message:"Failed to generate commit message";V.error(U)}finally{ge(!1)}}},[r,L,t,w,Ct]),Fe=async $=>{if(!r||!p)return;const U=p.current??null;try{await t.createBranch(r,$,U??"HEAD"),V.success(`Created branch ${$}`);let J=!1;try{await t.checkoutBranch(r,$),await t.gitPush(r,{remote:"origin",branch:$,options:["--set-upstream"]}),J=!0}catch(pe){const Ee=pe instanceof Error?pe.message:"Unable to push new branch to origin.";V.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Ee]})})}finally{if(U)try{await t.checkoutBranch(r,U)}catch(pe){console.warn("Failed to restore original branch after creation:",pe)}}await be(),await tt(),J&&V.success(`Upstream set for ${$}`)}catch(J){const pe=J instanceof Error?J.message:"Failed to create branch";throw V.error(pe),J}},Ve=async($,U)=>{if(r)try{await t.renameBranch(r,$,U),V.success(`Renamed branch ${$} to ${U}`),await be(),await tt()}catch(J){const pe=J instanceof Error?J.message:`Failed to rename branch ${$} to ${U}`;V.error(pe)}},et=async $=>{if(!r)return;const U=$.replace(/^remotes\//,"");if(p?.current!==U)try{await t.checkoutBranch(r,U),V.success(`Checked out ${U}`),await be(),await tt()}catch(J){const pe=J instanceof Error?J.message:`Failed to checkout ${U}`;V.error(pe)}},ot=async $=>{if(r){me();try{await t.setGitIdentity(r,$.id),V.success(`Applied "${$.name}" to repository`),await Ce()}catch(U){const J=U instanceof Error?U.message:"Failed to apply git identity";V.error(J)}finally{K()}}},yt=i.useMemo(()=>h?.all?h.all.filter($=>!$.startsWith("remotes/")).sort():[],[h]),Dt=i.useMemo(()=>h?.all?h.all.filter($=>$.startsWith("remotes/")).map($=>$.replace(/^remotes\//,"")).sort():[],[h]),bt=i.useMemo(()=>{const $=new Map;c&&$.set(c.id,c);let U=null;if(jt)try{let J=jt.trim();J.startsWith("git@")&&(J=`https://${J.slice(4).replace(":","/")}`),J.endsWith(".git")&&(J=J.slice(0,-4));const pe=new URL(J);U=pe.hostname+pe.pathname}catch{}for(const J of a){if(J.authType!=="token"){$.set(J.id,J);continue}const pe=J.host;if(!pe){$.set(J.id,J);continue}if(!pe.includes("/")){$.set(J.id,J);continue}U&&U===pe&&$.set(J.id,J)}return Array.from($.values())},[a,c,jt]),Qt=i.useMemo(()=>{if(x?.userName&&x?.userEmail){const $=a.find(U=>U.userName===x.userName&&U.userEmail===x.userEmail);return $||(c&&c.userName===x.userName&&c.userEmail===x.userEmail?c:{id:"local-config",name:x.userName,userName:x.userName,userEmail:x.userEmail,sshKey:x.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return c??null},[x,a,c]),Vt=Ie.length,Ft=L.size,Kt=b||z!==null||oe!==null,Rt=Vt>0,cs=$=>{Q(U=>{const J=new Set(U);return J.has($)?J.delete($):J.add($),J}),he(!0)},Ns=()=>{const $=new Set(Ie.map(U=>U.path));Q($),he(!0)},bs=()=>{Q(new Set),he(!0)},Cs=i.useCallback(async $=>{if(r){H(U=>{const J=new Set(U);return J.add($),J});try{await t.revertGitFile(r,$),V.success(`Reverted ${$}`),await be(!1)}catch(U){const J=U instanceof Error?U.message:"Failed to revert changes";V.error(J)}finally{H(U=>{const J=new Set(U);return J.delete($),J})}}},[r,be,t]),Ms=i.useCallback(()=>{if(X.length===0)return;const $=X.map(U=>U.trim()).filter(Boolean);if($.length===0){re();return}A(U=>{const J=U.trim(),pe=J.length>0?`
224
+
225
+ `:"";return`${J}${pe}${$.join(`
226
+ `)}`.trim()})},[X,re]),ps=i.useCallback(($,U)=>{const J=U||$;A(pe=>{const Ee=pe.trimStart();return Ee.startsWith($)||U&&Ee.startsWith(U)?pe:`${J.endsWith(" ")?J:`${J} `}${pe}`.trimStart()}),Pt(""),F(!1)},[]),Xt=i.useCallback($=>{Y($),r&&(k(r,$),j(r,t,$))},[r,k,j,t]);return r?b&&f===null?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Mt,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):f===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Ut,{className:"mb-3 size-6 text-muted-foreground"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:"Not a Git repository"}),e.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:"Choose a different directory or initialize Git to use this workspace."})]}):e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background","data-keyboard-avoid":"true",children:[e.jsx(MN,{status:p,localBranches:yt,remoteBranches:Dt,branchInfo:h?.branches,syncAction:z,onFetch:()=>Qe("fetch"),onPull:()=>Qe("pull"),onPush:()=>Qe("push"),onCheckoutBranch:et,onCreateBranch:Fe,onRenameBranch:Ve,activeIdentityProfile:Qt,availableIdentities:bt,onSelectIdentity:ot,isApplyingIdentity:Z,isWorktreeMode:!!o}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"p-3",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[Rt?e.jsx(TN,{changeEntries:Ie,selectedPaths:L,diffStats:p?.diffStats,revertingPaths:Ne,onToggleFile:cs,onSelectAll:Ns,onClearSelection:bs,onViewDiff:$=>Me.getState().navigateToDiff($),onRevertFile:Cs}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(DN,{behind:p?.behind??0,onPull:()=>Qe("pull"),isPulling:z==="pull"})}),Ie.length>0&&e.jsx(LN,{selectedCount:Ft,commitMessage:I,onCommitMessageChange:A,generatedHighlights:X,onInsertHighlights:Ms,onClearHighlights:re,onGenerateMessage:Pe,isGeneratingMessage:ue,onCommit:()=>Te({pushAfter:!1}),onCommitAndPush:()=>Te({pushAfter:!0}),commitAction:oe,isBusy:Kt,gitmojiEnabled:w,onOpenGitmojiPicker:()=>F(!0)})]}),o&&ae&&fe&&ie?e.jsx(yN,{repoRoot:ae,sourceBranch:fe,worktreeMetadata:o,localBranches:yt,defaultTargetBranch:se,refreshKey:we,onRefresh:()=>{r&&(C(r,t),N(r,t),j(r,t,q))}}):null,r&&p?.current&&p?.tracking?e.jsx(HN,{directory:r,branch:p.current,baseBranch:E}):null,e.jsx(BN,{log:g,isLogLoading:y,logMaxCount:q,onLogMaxCountChange:Xt,expandedCommitHashes:ne,onToggleCommit:$e,commitFilesMap:Ue,loadingCommitHashes:Ke,onCopyHash:Ot})]})}),e.jsx(us,{open:P,onOpenChange:F,children:e.jsxs(ms,{className:"max-w-md p-0 overflow-hidden",children:[e.jsx(xs,{className:"px-4 pt-4",children:e.jsx(ys,{children:"Pick a gitmoji"})}),e.jsxs(Mi,{className:"h-[420px]",children:[e.jsx(Di,{placeholder:"Search gitmojis...",value:mt,onValueChange:Pt}),e.jsxs(Ai,{children:[e.jsx(Ei,{children:"No gitmojis found."}),e.jsx(Xr,{children:(Ct.length===0?[]:Ct.filter($=>{const U=mt.trim().toLowerCase();return U?$.emoji.includes(U)||$.code.toLowerCase().includes(U)||$.description.toLowerCase().includes(U):!0})).map($=>e.jsxs(ws,{onSelect:()=>ps($.emoji,$.code),children:[e.jsx("span",{className:"text-lg",children:$.emoji}),e.jsx("span",{className:"typography-ui-label text-foreground",children:$.code}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:$.description})]},$.code))})]})]})]})})]}):e.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"Select a session or directory to view repository details."})})},QN=1e6;function un(t){let r=t.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const ba=t=>({directory:t,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),Xu=ns((t,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:s=>{const n=un(s);return r().sessions.get(n)},setTerminalSession:(s,n)=>{const o=un(s);t(a=>{const c=new Map(a.sessions),l=c.get(o),u=!l||l.terminalSessionId!==n.sessionId?ba(o):l??ba(o);return c.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:c}})},setConnecting:(s,n)=>{const o=un(s);t(a=>{const c=new Map(a.sessions),l=c.get(o)??ba(o);return c.set(o,{...l,isConnecting:n,updatedAt:Date.now()}),{sessions:c}})},appendToBuffer:(s,n)=>{if(!n)return;const o=un(s);t(a=>{const c=new Map(a.sessions),l=c.get(o)??ba(o),d=a.nextChunkId,u={id:d,data:n},m=[...l.bufferChunks,u];let f=l.bufferLength+n.length;for(;f>QN&&m.length>1;){const h=m.shift();if(!h)break;f-=h.data.length}const p=m.map(h=>h.data).join("");return c.set(o,{...l,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:c,nextChunkId:d+1}})},clearTerminalSession:s=>{const n=un(s);t(o=>{const a=new Map(o.sessions),c=a.get(n);return c&&a.set(n,{...c,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:s=>{const n=un(s);t(o=>{const a=new Map(o.sessions),c=a.get(n);return c?(a.set(n,{...c,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:s=>{const n=un(s);t(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{t({sessions:new Map,nextChunkId:1})}})),ch=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),YN=[{id:"ibm-plex-sans",label:"IBM Plex Sans",description:"Humanist sans-serif for optimal readability in the interface.",stack:'"IBM Plex Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}],XN=[{id:"ibm-plex-mono",label:"IBM Plex Mono",description:"Balanced monospace for code blocks and technical content.",stack:'"IBM Plex Mono", "SFMono-Regular", "Menlo", monospace'}],lh=t=>Object.fromEntries(t.map(r=>[r.id,r])),Zu=lh(YN),mn=lh(XN),ZN="ibm-plex-sans",za="ibm-plex-mono";function ek(t){const{colors:r}=t,s=r.syntax.base;return{background:r.surface.background,foreground:s.foreground,cursor:r.interactive.cursor,cursorAccent:r.surface.background,selectionBackground:r.interactive.selection,selectionForeground:r.interactive.selectionForeground,selectionInactiveBackground:r.interactive.selection+"50",black:r.surface.muted,red:r.status.error,green:r.status.success,yellow:r.status.warning,blue:s.function,magenta:s.keyword,cyan:s.type,white:s.foreground,brightBlack:s.comment,brightRed:r.status.error,brightGreen:r.status.success,brightYellow:r.status.warning,brightBlue:s.function,brightMagenta:s.keyword,brightCyan:s.type,brightWhite:r.surface.elevatedForeground}}function tk(t,r,s,n){const a=`${t}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!0,fontSize:r,lineHeight:1.15,fontFamily:a,allowTransparency:!1,theme:{background:s.background,foreground:s.foreground,cursor:s.cursor,cursorAccent:s.cursorAccent,selectionBackground:s.selectionBackground,selectionForeground:s.selectionForeground,black:s.black,red:s.red,green:s.green,yellow:s.yellow,blue:s.blue,magenta:s.magenta,cyan:s.cyan,white:s.white,brightBlack:s.brightBlack,brightRed:s.brightRed,brightGreen:s.brightGreen,brightYellow:s.brightYellow,brightBlue:s.brightBlue,brightMagenta:s.brightMagenta,brightCyan:s.brightCyan,brightWhite:s.brightWhite},scrollback:5e4,ghostty:n}}let fc=null;function sk(){return fc||(fc=Hx.load()),fc}function rk(t){if(typeof window>"u")return null;const r=[t,...Array.from(t.querySelectorAll("*"))];let s=null;for(const n of r){const a=window.getComputedStyle(n).overflowY;if(!(a!=="auto"&&a!=="scroll")){if(n.scrollHeight-n.clientHeight>2)return n;s||(s=n)}}return s}const sl=i.forwardRef(({sessionKey:t,chunks:r,onInput:s,onResize:n,theme:o,fontFamily:a,fontSize:c,className:l,enableTouchScroll:d},u)=>{const m=i.useRef(null),f=i.useRef(null),p=i.useRef(null),h=i.useRef(null),g=i.useRef(s),x=i.useRef(n),b=i.useRef(null),y=i.useRef(""),v=i.useRef(null),S=i.useRef(!1),C=i.useRef(null),N=i.useRef(null),j=i.useRef(null),D=i.useRef(0),k=i.useRef(null),[,M]=i.useReducer(O=>O+1,0),[w,T]=i.useReducer(O=>O+1,0);g.current=s,x.current=n;const E=i.useCallback((O,q)=>{const Y=k.current,Z=m.current;if(!Y||!Z)return;const B=Z.getBoundingClientRect(),W=B.left+B.width/2,te=B.top+B.height-12,ye=typeof O=="number"?O:W,me=typeof q=="number"?q:te,K=8,L=Math.max(K,Math.min(B.width-K,ye-B.left)),Q=Math.max(K,Math.min(B.height-K,me-B.top));Y.style.left=`${L}px`,Y.style.top=`${Q}px`,Y.style.bottom="";try{Y.focus({preventScroll:!0})}catch{try{Y.focus()}catch{}}},[]),I=i.useCallback(async()=>{if(typeof window>"u"||typeof document>"u")return;const O=window.getSelection();if(!O)return;const q=O.toString();if(!q.trim())return;const Y=m.current;if(!Y)return;const Z=O.anchorNode,B=O.focusNode;if(!(Z&&!Y.contains(Z))&&!(B&&!Y.contains(B))){try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(q);return}}catch{}try{const W=document.createElement("textarea");W.value=q,W.style.position="fixed",W.style.opacity="0",document.body.appendChild(W),W.focus(),W.select(),document.execCommand("copy"),document.body.removeChild(W)}catch{}}},[]),A=i.useCallback(()=>{y.current="",v.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(v.current),v.current=null,S.current=!1,C.current=null},[]),P=i.useCallback(()=>{const O=h.current,q=p.current,Y=m.current;if(!O||!q||!Y)return;const Z=Y.getBoundingClientRect();if(!(Z.width<24||Z.height<24))try{O.fit();const B={cols:q.cols,rows:q.rows},W=b.current;(!W||W.cols!==B.cols||W.rows!==B.rows)&&(b.current=B,x.current(B.cols,B.rows))}catch{}},[]),F=i.useCallback(()=>{if(S.current)return;const O=p.current;if(!O){A();return}if(!y.current)return;const q=y.current;y.current="",S.current=!0,O.write(q,()=>{S.current=!1,y.current&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,F()}):F())})},[A]),z=i.useCallback(()=>{v.current===null&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,F()}):F())},[F]),G=i.useCallback(O=>{O&&(y.current+=O,z())},[z]),oe=i.useCallback(()=>{if(N.current?.(),N.current=null,j.current!==null&&typeof window<"u"&&(window.clearTimeout(j.current),j.current=null),!d){D.current=0;return}const O=m.current;if(!O)return;const q=p.current;if(!q)return;D.current=0;const Y=2.2,Z=2.8,B=25,W=.25,te=8,ye=.05,me=.015,K={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},L=()=>typeof performance<"u"?performance.now():Date.now(),Q=Math.max(12,Math.round(c*1.35));let ce=0;const he=ae=>{if(!ae)return!1;const fe=q.getViewportY(),ie=ce+ae,se=Math.trunc(ie/Q);return ce=ie-se*Q,se!==0&&q.scrollLines(se),q.getViewportY()!==fe},Ne=()=>{K.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(K.rafId),K.rafId=null},H={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const ae=Object.assign(K,{pointerId:null,startX:null,startY:null,moved:!1}),fe=6,ie=xe=>{if(xe.pointerType==="touch"){Ne(),ae.pointerId=xe.pointerId,ae.startX=xe.clientX,ae.startY=xe.clientY,ae.moved=!1,ae.lastY=xe.clientY,ae.lastTime=L(),ae.velocity=0;try{O.setPointerCapture(xe.pointerId)}catch{}}},se=xe=>{if(xe.pointerType!=="touch"||ae.pointerId!==xe.pointerId)return;if(ae.startX!==null&&ae.startY!==null&&!ae.moved){const mt=xe.clientX-ae.startX,Pt=xe.clientY-ae.startY;Math.hypot(mt,Pt)>=fe&&(ae.moved=!0)}if(ae.lastY===null){ae.lastY=xe.clientY,ae.lastTime=L();return}const Ue=ae.lastY,ze=ae.lastTime??L(),Ke=L();ae.lastY=xe.clientY,ae.lastTime=Ke;const rt=Ue-xe.clientY;if(Math.abs(rt)<1)return;const jt=Math.max(Ke-ze,8),Xe=Y+Math.min(Z,Math.abs(rt)/B),Ct=rt*Xe,st=Ct/jt;ae.velocity=ae.velocity*(1-W)+st*W,ae.velocity>te?ae.velocity=te:ae.velocity<-te&&(ae.velocity=-te),ae.moved&&(xe.cancelable&&xe.preventDefault(),xe.stopPropagation()),he(Ct)},re=xe=>{if(xe.pointerType!=="touch"||ae.pointerId!==xe.pointerId)return;const Ue=!ae.moved;ae.pointerId=null,ae.startX=null,ae.startY=null,ae.moved=!1,ae.lastY=null,ae.lastTime=null;try{O.releasePointerCapture(xe.pointerId)}catch{}if(Ue){E(xe.clientX,xe.clientY);return}if(typeof window>"u")return;if(Math.abs(ae.velocity)<ye){ae.velocity=0;return}let ze=L();const Ke=()=>{const rt=L(),jt=Math.max(rt-ze,8);ze=rt;const Xe=he(ae.velocity*jt)??!1,Ct=Math.sign(ae.velocity),st=Math.max(0,Math.abs(ae.velocity)-me*jt);if(ae.velocity=st*Ct,!Xe||st<=ye){Ne(),ae.velocity=0;return}ae.rafId=window.requestAnimationFrame(Ke)};ae.rafId=window.requestAnimationFrame(Ke)};O.addEventListener("pointerdown",ie,H),O.addEventListener("pointermove",se,H),O.addEventListener("pointerup",re,H),O.addEventListener("pointercancel",re,H);const ne=O.style.touchAction;O.style.touchAction="manipulation",N.current=()=>{Ne(),j.current!==null&&typeof window<"u"&&(window.clearTimeout(j.current),j.current=null),D.current=0,O.removeEventListener("pointerdown",ie,H),O.removeEventListener("pointermove",se,H),O.removeEventListener("pointerup",re,H),O.removeEventListener("pointercancel",re,H),O.style.touchAction=ne};return}const ee=6,ue=ae=>{ae.touches.length===1&&(Ne(),K.lastY=ae.touches[0].clientY,K.lastTime=L(),K.velocity=0,K.startX=ae.touches[0].clientX,K.startY=ae.touches[0].clientY,K.didMove=!1)},ge=ae=>{if(ae.touches.length!==1){K.lastY=null,K.lastTime=null,K.velocity=0,K.startX=null,K.startY=null,K.didMove=!1,Ne();return}const fe=ae.touches[0].clientX,ie=ae.touches[0].clientY;if(K.startX!==null&&K.startY!==null&&!K.didMove){const jt=fe-K.startX,Xe=ie-K.startY;Math.hypot(jt,Xe)>=ee&&(K.didMove=!0)}if(K.lastY===null){K.lastY=ie,K.lastTime=L();return}const se=K.lastY,re=K.lastTime??L(),ne=L();K.lastY=ie,K.lastTime=ne;const xe=se-ie;if(Math.abs(xe)<1)return;const Ue=Math.max(ne-re,8),ze=Y+Math.min(Z,Math.abs(xe)/B),Ke=xe*ze,rt=Ke/Ue;K.velocity=K.velocity*(1-W)+rt*W,K.velocity>te?K.velocity=te:K.velocity<-te&&(K.velocity=-te),K.didMove&&(ae.preventDefault(),ae.stopPropagation()),he(Ke)},X=ae=>{const fe=!K.didMove;K.lastY=null,K.lastTime=null;const ie=K.velocity;if(K.startX=null,K.startY=null,K.didMove=!1,fe){const ne=ae.changedTouches?.[0];E(ne?.clientX,ne?.clientY);return}if(typeof window>"u")return;if(Math.abs(ie)<ye){K.velocity=0;return}let se=L();const re=()=>{const ne=L(),xe=Math.max(ne-se,8);se=ne;const Ue=he(K.velocity*xe)??!1,ze=Math.sign(K.velocity),Ke=Math.max(0,Math.abs(K.velocity)-me*xe);if(K.velocity=Ke*ze,!Ue||Ke<=ye){Ne(),K.velocity=0;return}K.rafId=window.requestAnimationFrame(re)};K.rafId=window.requestAnimationFrame(re)};O.addEventListener("touchstart",ue,H),O.addEventListener("touchmove",ge,H),O.addEventListener("touchend",X,H),O.addEventListener("touchcancel",X,H);const de=O.style.touchAction;O.style.touchAction="manipulation",N.current=()=>{Ne(),j.current!==null&&typeof window<"u"&&(window.clearTimeout(j.current),j.current=null),D.current=0,O.removeEventListener("touchstart",ue,H),O.removeEventListener("touchmove",ge,H),O.removeEventListener("touchend",X,H),O.removeEventListener("touchcancel",X,H),O.style.touchAction=de}},[d,E,c]);return i.useEffect(()=>{let O=!1,q=null,Y=null,Z=[];const B=m.current;return B?(B.tabIndex=0,(async()=>{try{const te=await sk();if(O)return;const ye=tk(a,c,o,te),me=new Bx(ye),K=new zx;q=me,p.current=me,h.current=K,me.loadAddon(K),me.open(B),T();const L=rk(B);L?(L.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=L,M()):f.current=null,P(),oe(),me.focus(),Z=[me.onData(Q=>{g.current(Q)})],Y=new ResizeObserver(()=>{P()}),Y.observe(B),typeof window<"u"&&window.setTimeout(()=>{P()},0)}catch{}})(),()=>{O=!0,N.current?.(),N.current=null,Z.forEach(te=>te.dispose()),Y?.disconnect(),q?.dispose(),p.current=null,h.current=null,f.current=null,b.current=null,A()}):void 0},[P,a,c,oe,o,A]),i.useEffect(()=>{const O=p.current;O&&(O.reset(),A(),b.current=null,P(),O.focus())},[t,w,P,A]),i.useEffect(()=>(oe(),()=>{N.current?.(),N.current=null}),[oe,t]),i.useEffect(()=>{const O=p.current;if(!O)return;if(r.length===0){C.current!==null&&(O.reset(),A(),P());return}const q=C.current;let Y;if(q===null)Y=r;else{const Z=r.findIndex(B=>B.id===q);Y=Z>=0?r.slice(Z+1):r}Y.length>0&&G(Y.map(Z=>Z.data).join("")),C.current=r[r.length-1].id},[r,w,G,P,A]),i.useImperativeHandle(u,()=>({focus:()=>{if(d){E();return}p.current?.focus()},clear:()=>{const O=p.current;O&&(O.reset(),A(),P())},fit:()=>{P()}}),[d,E,P,A]),e.jsxs("div",{ref:m,className:R("relative h-full w-full terminal-viewport-container",l),style:{backgroundColor:o.background},onClick:O=>{d?E(O.clientX,O.clientY):p.current?.focus()},onMouseUp:()=>{I()},onTouchEnd:()=>{I()},children:[d?e.jsx("textarea",{ref:k,inputMode:"text",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,"aria-hidden":"true",style:{position:"absolute",left:0,top:0,width:1,height:1,opacity:0,zIndex:1,background:"transparent",color:"transparent",caretColor:"transparent",resize:"none",overflow:"hidden",whiteSpace:"nowrap",border:"none",padding:0,margin:0,outline:"none"},onInput:O=>{const q=String(O.currentTarget.value||"");if(!q)return;const Y=q.replace(/\r\n|\r|\n/g,"\r");g.current(Y),O.currentTarget.value=""},onKeyDown:O=>{O.key==="Backspace"&&(O.currentTarget.value||g.current(""))}}):null,f.current&&!d?e.jsx(kl,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});sl.displayName="TerminalViewport";const em=13,nk={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},wa={ctrl:"5",cmd:"3"},ok={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},ak=(t,r)=>{if(r)switch(t){case"arrow-up":return`\x1B[1;${wa[r]}A`;case"arrow-down":return`\x1B[1;${wa[r]}B`;case"arrow-right":return`\x1B[1;${wa[r]}C`;case"arrow-left":return`\x1B[1;${wa[r]}D`}return nk[t]??null},ik=()=>{const{terminal:t}=Hs(),{currentTheme:r}=Wr(),{monoFont:s}=ch(),{isMobile:n,hasTouchInput:o}=Gt(),{currentSessionId:a,newSessionDraft:c}=ve(),l=a!==null||c?.open===!0,d=Yo()??null,{homeDirectory:u}=vt(),m=i.useMemo(()=>d?u?d===u?"~":d.startsWith(u+"/")?"~"+d.slice(u.length):d:d:"",[d,u]),f=Xu(),p=f.sessions,h=f.setTerminalSession,g=f.setConnecting,x=f.appendToBuffer,b=f.clearTerminalSession,y=f.removeTerminalSession,v=f.clearBuffer,S=i.useMemo(()=>{if(d)return p.get(d)},[p,d]),C=S?.terminalSessionId??null,N=S?.bufferChunks??[],j=S?.bufferLength??0,D=S?.isConnecting??!1,k=C,[M,w]=i.useState(null),[T,E]=i.useState(!1),[I,A]=i.useState(null),[P,F]=i.useState(!1),z=i.useRef(null),G=i.useRef(null),oe=i.useRef(k),O=i.useRef(d),q=i.useRef(null),Z=Me(ge=>ge.activeMainTab)==="terminal";i.useEffect(()=>{oe.current=k},[k]),i.useEffect(()=>{O.current=d},[d]),i.useEffect(()=>{!n&&I!==null&&A(null)},[n,I,A]),i.useEffect(()=>{!k&&I!==null&&A(null)},[k,I,A]);const B=i.useCallback(()=>{z.current?.(),z.current=null,G.current=null},[]);i.useEffect(()=>()=>{B(),oe.current=null},[B]);const W=i.useCallback(ge=>{if(G.current===ge)return;B();const X=t.connect(ge,{onEvent:de=>{const ae=O.current;if(ae)switch(de.type){case"connected":{(de.runtime||de.ptyBackend)&&console.log(`[Terminal] connected runtime=${de.runtime??"unknown"} pty=${de.ptyBackend??"unknown"}`),g(ae,!1),w(null),E(!1),q.current?.focus();break}case"reconnecting":{const fe=de.attempt??0,ie=de.maxAttempts??3;w(`Reconnecting (${fe}/${ie})...`),E(!1);break}case"data":{de.data&&x(ae,de.data);break}case"exit":{const fe=typeof de.exitCode=="number"?de.exitCode:null,ie=typeof de.signal=="number"?de.signal:null;x(ae,`\r
227
+ [Process exited${fe!==null?` with code ${fe}`:""}${ie!==null?` (signal ${ie})`:""}]\r
228
+ `),b(ae),g(ae,!1),w("Terminal session ended"),E(!1),B();break}}},onError:(de,ae)=>{const fe=O.current;if(!fe)return;const ie=ae?`Connection failed: ${de.message}`:de.message||"Terminal stream connection error";w(ie),E(!!ae),ae&&(g(fe,!1),B(),y(fe))}},ok);z.current=()=>{X.close(),G.current=null},G.current=ge},[x,b,B,y,g,t,w]);i.useEffect(()=>{let ge=!1;if(!d){w(l?"No working directory available for terminal.":"Select a session to open the terminal."),B();return}return(async()=>{const de=d;if(!O.current||O.current!==de)return;let fe=Xu.getState().getTerminalSession(de)?.terminalSessionId??null;if(!fe){w(null),E(!1),g(de,!0);try{const ie=await t.createSession({cwd:de});if(ge){try{await t.close(ie.sessionId)}catch{}return}h(de,ie),fe=ie.sessionId}catch(ie){ge||(w(ie instanceof Error?ie.message:"Failed to start terminal session"),E(!0),g(de,!1));return}}!fe||ge||(oe.current=fe,W(fe))})(),()=>{ge=!0,oe.current=null,B()}},[l,d,k,y,g,h,W,B,t]);const te=i.useCallback(async()=>{if(!d||P)return;F(!0),w(null),E(!1),B();const ge=oe.current;try{if(t.restartSession&&ge){const X=await t.restartSession(ge,{cwd:d});h(d,X),oe.current=X.sessionId,W(X.sessionId)}else{if(ge)try{await t.close(ge)}catch{}y(d)}}catch(X){w(X instanceof Error?X.message:"Failed to restart terminal"),E(!0)}finally{F(!1)}},[d,P,B,t,h,W,y]),ye=i.useCallback(async()=>{if(d&&!P){F(!0),w(null),E(!1),B();try{t.forceKill&&await t.forceKill({cwd:d})}catch{}y(d),v(d),q.current?.clear(),await new Promise(ge=>setTimeout(ge,100));try{g(d,!0);const ge=await t.createSession({cwd:d});h(d,ge),oe.current=ge.sessionId,W(ge.sessionId)}catch(ge){w(ge instanceof Error?ge.message:"Failed to create terminal"),E(!0),g(d,!1)}finally{F(!1)}}},[d,P,B,t,y,v,g,h,W]),me=i.useCallback(()=>{if(!d)return;v(d),q.current?.clear(),q.current?.focus();const ge=oe.current;ge&&t.sendInput(ge,"\f").catch(X=>{w(X instanceof Error?X.message:"Failed to refresh prompt")})},[v,d,w,t]),K=i.useCallback(ge=>{if(!ge)return;let X=ge,de=!1;if(I&&ge.length>0){const fe=ge[0];if(fe.length===1&&/[a-zA-Z]/.test(fe)){const ie=fe.toUpperCase();(I==="ctrl"||I==="cmd")&&(X=String.fromCharCode(ie.charCodeAt(0)&31),de=!0)}de||(de=!0)}const ae=oe.current;ae&&(t.sendInput(ae,X).catch(fe=>{w(fe instanceof Error?fe.message:"Failed to send input")}),de&&(A(null),q.current?.focus()))},[I,A,t]),L=i.useCallback((ge,X)=>{const de=oe.current;de&&t.resize({sessionId:de,cols:ge,rows:X}).catch(()=>{})},[t]),Q=i.useCallback(ge=>{A(X=>X===ge?null:ge),q.current?.focus()},[A]),ce=i.useCallback(ge=>{const X=ak(ge,I);X&&(K(X),A(null),q.current?.focus())},[I,K,A]);i.useEffect(()=>{if(!n||!I||!k)return;const ge=X=>{if(X.repeat)return;const de=X.key;if(!de||de==="Control"||de==="Meta"||de==="Alt"||de==="Shift")return;const ae=de.length===1?de.toLowerCase():de,fe=X.code??"",ie=fe.startsWith("Key")&&fe.length===4?fe.slice(3).toUpperCase():null,se=de.length===1&&/[a-zA-Z]/.test(de)?de.toUpperCase():ie,re={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc",tab:"tab",enter:"enter",arrowup:"arrow-up",arrowdown:"arrow-down",arrowleft:"arrow-left",arrowright:"arrow-right",escape:"esc"};if(ae in re){X.preventDefault(),X.stopPropagation(),ce(re[ae]);return}if(I==="ctrl"&&se&&se.length===1&&se>="A"&&se<="Z"){const ne=String.fromCharCode(se.charCodeAt(0)&31);X.preventDefault(),X.stopPropagation(),K(ne),A(null),q.current?.focus()}};return window.addEventListener("keydown",ge),()=>{window.removeEventListener("keydown",ge)}},[I,ce,K,n,A,k]);const he=i.useMemo(()=>{const ge=mn[za].stack;if(typeof window>"u")return(mn[s]??mn[za]).stack;const de=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return de&&de.trim().length>0?de.trim():(mn[s]??mn[za]).stack??ge},[s]),Ne=i.useMemo(()=>ek(r),[r]),H=i.useMemo(()=>`${d??"no-dir"}::${k??"pending"}`,[d,k]);i.useEffect(()=>{if(!Z)return;const ge=q.current;if(!ge)return;const X=()=>{ge.fit()};if(typeof window<"u"){const de=window.requestAnimationFrame(()=>{X(),ge.focus()}),ae=[220,400].map(fe=>window.setTimeout(X,fe));return()=>{window.cancelAnimationFrame(de),ae.forEach(fe=>window.clearTimeout(fe))}}X()},[Z,H,k]);const we=M?.includes("Reconnecting"),ee=M?we?e.jsx(Wx,{size:20,className:"text-amber-400"}):e.jsx(es,{size:20,className:"text-destructive"}):k&&!D&&!P?e.jsx(Ca,{size:20,className:"text-emerald-400"}):D||P?e.jsx(Ec,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Ec,{size:20,className:"text-muted-foreground"});if(!l)return e.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal"});if(!d)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[e.jsx("p",{children:"No working directory available for this session."}),e.jsx("button",{onClick:te,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const ue=!k||D||P;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:m})}),e.jsxs("div",{className:"flex items-center gap-2",children:[ee,e.jsxs(Se,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:me,disabled:!j,title:"Clear output",type:"button",children:[e.jsx(zs,{size:16}),"Clear"]}),e.jsxs(Se,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:te,disabled:P,title:"Restart terminal session",type:"button",children:[e.jsx(Ls,{size:16,className:R((D||P)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(Se,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>ce("esc"),disabled:ue,children:"Esc"}),e.jsxs(Se,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ce("tab"),disabled:ue,children:[e.jsx(Xl,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Se,{type:"button",size:"sm",variant:I==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>Q("ctrl"),disabled:ue,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Se,{type:"button",size:"sm",variant:I==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>Q("cmd"),disabled:ue,children:[e.jsx(En,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Se,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ce("arrow-up"),disabled:ue,children:[e.jsx(eo,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Se,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ce("arrow-left"),disabled:ue,children:[e.jsx(af,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Se,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ce("arrow-down"),disabled:ue,children:[e.jsx(po,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Se,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ce("arrow-right"),disabled:ue,children:[e.jsx(Xl,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Se,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ce("enter"),disabled:ue,children:[e.jsx(so,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Ne.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:Z?n?e.jsx(sl,{ref:ge=>{q.current=ge},sessionKey:H,chunks:N,onInput:K,onResize:L,theme:Ne,fontFamily:he,fontSize:em,enableTouchScroll:o},H):e.jsx(xt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(sl,{ref:ge=>{q.current=ge},sessionKey:H,chunks:N,onInput:K,onResize:L,theme:Ne,fontFamily:he,fontSize:em,enableTouchScroll:o},H)}):null}),M&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2",children:[e.jsx("span",{children:M}),T&&e.jsx(Se,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ye,disabled:P,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},ck=t=>t.slice().sort((r,s)=>r.type!==s.type?r.type==="directory"?-1:1:r.name.localeCompare(s.name)),ir=t=>t.replace(/\\/g,"/"),lk=new Set(["node_modules"]),dk=t=>lk.has(t),uk=t=>{const r=ir(t);return r==="node_modules"||r.endsWith("/node_modules")||r.includes("/node_modules/")},ko=2e5,mk=new Set(["js","jsx","ts","tsx","mjs","cjs","mts","cts","html","htm","xhtml","css","scss","sass","less","styl","stylus","vue","svelte","astro","sh","bash","zsh","fish","ps1","psm1","bat","cmd","py","pyw","pyx","pxd","pxi","rb","erb","rake","gemspec","php","phtml","php3","php4","php5","phps","java","kt","kts","scala","sc","groovy","gradle","c","h","cpp","cc","cxx","hpp","hxx","hh","m","mm","cs","fs","fsx","fsi","go","rs","swift","dart","lua","pl","pm","pod","r","R","rmd","jl","hs","lhs","ex","exs","erl","hrl","clj","cljs","cljc","edn","lisp","cl","el","scm","ss","rkt","ml","mli","re","rei","nim","zig","v","cr","main.kts","sql","psql","plsql","graphql","gql","sol","asm","s","S","mk","nix","tf","tfvars","pp","ansible"]),fk=new Set(["json","jsonc","json5","jsonl","ndjson","geojson","yaml","yml","toml","xml","xsl","xslt","xsd","dtd","plist","ini","cfg","conf","config","env","properties","csv","tsv","lock"]),pk=new Set(["png","jpg","jpeg","gif","svg","webp","ico","icns","bmp","tiff","tif","psd","ai","eps","raw","cr2","nef","heic","heif","avif","jxl"]),hk=new Set(["md","mdx","markdown","mdown","mkd","txt","text","rtf","doc","docx","odt","pdf","rst","adoc","asciidoc","org","tex","latex","bib"]),tm=t=>{const r=t?.toLowerCase();return r&&mk.has(r)?e.jsx(sr,{className:"h-4 w-4 flex-shrink-0 text-blue-500"}):r&&fk.has(r)?e.jsx(sr,{className:"h-4 w-4 flex-shrink-0 text-yellow-500"}):r&&pk.has(r)?e.jsx(Ar,{className:"h-4 w-4 flex-shrink-0 text-green-500"}):r&&hk.has(r)?e.jsx(Zn,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(Zn,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})},Bn=t=>{if(!t)return!1;const r=t.toLowerCase().split(".").pop();return r==="md"||r==="markdown"},gk=()=>{const{files:t,runtime:r}=Hs(),{currentTheme:s}=Wr();i.useMemo(()=>Fi(s),[s]);const{isMobile:n,screenWidth:o}=Gt(),a=Go(),c=bi(),l=Yo()??"",d=ir(l),u=wi(ke=>ke.searchFiles),[m,f]=i.useState(""),p=Ti(m,200),h=i.useRef(null),[g,x]=i.useState(!1),[b,y]=i.useState(n),[v,S]=i.useState(!1),[C,N]=i.useState(new Set),[j,D]=i.useState({}),k=i.useRef(new Set),M=i.useRef(new Set),[w,T]=i.useState([]),[E,I]=i.useState(!1),[A,P]=i.useState(null),[F,z]=i.useState(""),[G,oe]=i.useState(!1),[O,q]=i.useState(null),[Y,Z]=i.useState(""),[B,W]=i.useState(""),[te,ye]=i.useState(!1),[me,K]=i.useState(!1),L=i.useRef(null),Q=i.useRef(null),ce=i.useRef(!1),he=i.useRef(null),Ne=i.useRef(null),[H,we]=i.useState(null),[ee,ue]=i.useState(null),[ge,X]=i.useState(""),[de,ae]=i.useState(!1),[fe,ie]=i.useState(null),[se,re]=i.useState(!1),[ne,xe]=i.useState(!1),[Ue,ze]=i.useState("edit"),Ke=!!t.writeFile,rt=!!t.createDirectory,jt=!!t.rename,Xe=!!t.delete,Ct=i.useCallback((ke,_)=>{we(ke),ue(_),X(ke==="rename"&&_.name||""),ae(!1)},[]),[st,mt]=i.useState(null),[Pt,Ot]=i.useState(""),$e=i.useRef(!1),be=i.useRef(null),tt=ve(ke=>ke.sendMessage),Ce=ve(ke=>ke.currentSessionId),{currentProviderId:Ie,currentModelId:Qe,currentAgentName:Te,currentVariant:Pe}=Je(),Fe=Ye(ke=>ke.getSessionAgentSelection),Ve=Ye(ke=>ke.getAgentModelForSession),et=Ye(ke=>ke.getAgentModelVariantForSession),ot=Me(ke=>ke.setActiveMainTab),yt=Me(ke=>ke.setMainTabGuard),{inputBarOffset:Dt,isKeyboardOpen:bt}=Me();i.useEffect(()=>{const ke=()=>{$e.current=!1,be.current=null};return document.addEventListener("mouseup",ke),()=>document.removeEventListener("mouseup",ke)},[]),i.useEffect(()=>{mt(null),Ot(""),yt(null),W(""),ye(!1)},[A?.path,yt]),i.useEffect(()=>()=>{he.current!==null&&window.clearTimeout(he.current),Ne.current!==null&&window.clearTimeout(Ne.current)},[]),i.useEffect(()=>{if(!st)return;const ke=je=>{const le=je.target;document.querySelector("[data-comment-ui]")?.contains(le)||le.closest(".cm-gutterElement")||le.closest("[data-sonner-toast]")||le.closest("[data-sonner-toaster]")||(mt(null),Ot(""))},_=setTimeout(()=>{document.addEventListener("click",ke)},100);return()=>{clearTimeout(_),document.removeEventListener("click",ke)}},[st]);const Qt=i.useCallback((ke,_)=>{const je=ke.split(`
229
+ `),le=Math.max(1,_.start),Re=Math.min(je.length,_.end);return le>Re?"":je.slice(le-1,Re).join(`
230
+ `)},[]),Vt=i.useCallback(async()=>{if(!st||!Pt.trim()||!A)return;if(!Ce){V.error("Select a session to send comment");return}const ke=Fe(Ce)||Te,_=ke?Ve(Ce,ke):null,je=_?.providerId||Ie,le=_?.modelId||Qe;if(!je||!le){V.error("Select a model to send comment");return}const Re=ke&&je&&le?et(Ce,ke,je,le)??Pe:Pe,_e=Qt(F,st),We=Er(A.path)||"text",qe=A.name,it=st.start,It=st.end,ct=`Comment on \`${qe}\` lines ${it}-${It}:
231
+ \`\`\`${We}
232
+ ${_e}
233
+ \`\`\`
234
+
235
+ ${Pt}`;Ot(""),mt(null),ot("chat"),tt(ct,je,le,ke,void 0,void 0,void 0,Re).catch(Zt=>{console.error("Failed to send comment",Zt)})},[st,Pt,A,F,Ce,Ie,Qe,Te,Pe,Qt,tt,ot,Fe,Ve,et]),Ft=i.useCallback((ke,_)=>{const je=_.filter(le=>le&&typeof le.name=="string"&&le.name.length>0).filter(le=>a||!le.name.startsWith(".")).filter(le=>c||!dk(le.name)).map(le=>{const Re=le.name,_e=ir(le.path||`${ke}/${Re}`),We=le.isDirectory?"directory":"file",qe=We==="file"&&Re.includes(".")?Re.split(".").pop()?.toLowerCase():void 0;return{name:Re,path:_e,type:We,extension:qe}});return ck(je)},[c,a]),Kt=i.useCallback(async ke=>{const _=ir(ke.trim());if(_&&!(k.current.has(_)||M.current.has(_))){M.current=new Set(M.current),M.current.add(_);try{const je=!c;let le;r.isDesktop?le=(await t.listDirectory(_,{respectGitignore:je})).entries.map(We=>({name:We.name,path:We.path,isDirectory:We.isDirectory})):le=(await Oe.listLocalDirectory(_,{respectGitignore:je})).map(We=>({name:We.name,path:We.path,isDirectory:We.isDirectory}));const Re=Ft(_,le);k.current=new Set(k.current),k.current.add(_),D(_e=>({..._e,[_]:Re}))}catch{D(je=>({...je,[_]:je[_]??[]}))}finally{M.current=new Set(M.current),M.current.delete(_)}}},[t,Ft,r.isDesktop,c]),Rt=i.useCallback(async()=>{const ke=ir(l.trim());ke&&(k.current=new Set,M.current=new Set,N(new Set),D({}),await Kt(ke))},[l,Kt]);i.useEffect(()=>{l&&(Rt(),P(null),z(""),q(null),Z(""),x(!1))},[l,Rt]),i.useEffect(()=>{l&&Rt()},[l,Rt,c]);const cs="openchamber:files:md-viewer-mode";i.useEffect(()=>{try{const ke=localStorage.getItem(cs);if(ke){const _=JSON.parse(ke);(_==="preview"||_==="edit")&&ze(_)}}catch{}},[]);const Ns=i.useCallback(ke=>{ze(ke);try{localStorage.setItem(cs,JSON.stringify(ke))}catch{}},[]),bs=i.useCallback(()=>Ue,[Ue]),Cs=i.useCallback(async ke=>{if(ke?.preventDefault(),!(!ee||!H)){ae(!0);try{if(H==="createFile"){if(!ge.trim())throw new Error("Filename is required");const _=ee.path,je=_?`${_}/`:"",le=ir(`${je}${ge.trim()}`);if(!t.writeFile)throw new Error("Write not supported");(await t.writeFile(le,"")).success&&(V.success("File created"),await Rt())}else if(H==="createFolder"){if(!ge.trim())throw new Error("Folder name is required");const _=ee.path,je=_?`${_}/`:"",le=ir(`${je}${ge.trim()}`);(await t.createDirectory(le)).success&&(V.success("Folder created"),await Rt())}else if(H==="rename"){if(!ge.trim())throw new Error("Name is required");const _=ee.path,je=_.split("/").slice(0,-1).join("/"),le=je?`${je}/`:"",Re=ir(`${le}${ge.trim()}`);t.rename?(await t.rename(_,Re)).success&&(V.success("Renamed successfully"),await Rt(),A?.path===_&&P(null)):V.error("Rename not supported")}else H==="delete"&&(t.delete?(await t.delete(ee.path)).success&&(V.success("Deleted successfully"),await Rt(),(A?.path===ee.path||A?.path.startsWith(ee.path+"/"))&&(P(null),z(""))):V.error("Delete not supported"));we(null)}catch(_){V.error(_ instanceof Error?_.message:"Operation failed")}finally{ae(!1)}}},[H,ee,ge,t,Rt,A]),Ms=i.useCallback((ke,_)=>{const je=ke.trim().toLowerCase();if(!je)return 0;const le=_.toLowerCase();let Re=0,_e=-1,We=0;for(let qe=0;qe<je.length;qe+=1){const it=je[qe];if(!it||it===" ")continue;const It=le.indexOf(it,_e+1);if(It===-1)return null;const ct=It-_e-1;if(ct===0?We+=1:We=0,Re+=10,Re+=Math.max(0,18-It),Re-=Math.max(0,ct),It===0)Re+=12;else{const Zt=le[It-1];(Zt==="/"||Zt==="_"||Zt==="-"||Zt==="."||Zt===" ")&&(Re+=10)}Re+=We>0?12:0,_e=It}return Re+=Math.max(0,24-Math.round(le.length/3)),Re},[]);i.useEffect(()=>{l&&Rt()},[l,Rt,c]),i.useEffect(()=>{if(!l){T([]),I(!1);return}const ke=p.trim();if(!ke){T([]),I(!1);return}const _=ke.toLowerCase();let je=!1;return I(!0),u(l,ke,150,{includeHidden:a,respectGitignore:!c}).then(le=>{if(je)return;const _e=le.filter(qe=>c||!uk(qe.path)).map(qe=>{const it=qe.relativePath||qe.name||qe.path,It=Ms(_,it);return It===null?null:{hit:qe,score:It,labelLength:it.length}}).filter(Boolean);_e.sort((qe,it)=>it.score-qe.score||qe.labelLength-it.labelLength||qe.hit.path.localeCompare(it.hit.path));const We=_e.map(({hit:qe})=>({name:qe.name,path:ir(qe.path),type:"file",extension:qe.extension,relativePath:qe.relativePath}));T(We)}).catch(()=>{je||T([])}).finally(()=>{je||I(!1)}),()=>{je=!0}},[l,p,Ms,u,a,c]);const ps=i.useCallback(async ke=>{if(t.readFile)return(await t.readFile(ke)).content??"";const _=await fetch(`/api/fs/read?path=${encodeURIComponent(ke)}`);if(!_.ok){const je=await _.json().catch(()=>({error:_.statusText}));throw new Error(je.error||"Failed to read file")}return _.text()},[t]),Xt=i.useMemo(()=>F.length>ko?`${F.slice(0,ko)}
236
+
237
+ … truncated …`:F,[F]),$=i.useMemo(()=>B!==Xt,[B,Xt]),U=i.useCallback(async()=>{if(!A||!t.writeFile){V.error("Saving not supported");return}if($){ye(!0);try{if(!(await t.writeFile(A.path,B))?.success)throw new Error("Failed to write file");z(B)}catch(ke){V.error(ke instanceof Error?ke.message:"Save failed")}finally{ye(!1)}}},[B,t,$,A]);i.useEffect(()=>{if(!$){yt(null);return}const ke=_=>ce.current?(ce.current=!1,!0):(K(!0),Q.current=_,!1);return yt(ke),()=>{Me.getState().mainTabGuard===ke&&yt(null)}},[$,yt]),i.useEffect(()=>{const ke=_=>{$s(_)&&_.key.toLowerCase()==="s"&&(_.preventDefault(),te||U())};return window.addEventListener("keydown",ke),()=>window.removeEventListener("keydown",ke)},[te,U]);const J=i.useCallback(async ke=>{if(ce.current)ce.current=!1;else if($){K(!0),L.current=ke;return}P(ke),q(null),Z("");const _=Ho(ke.path);n&&x(!0);const je=ke.path.toLowerCase().endsWith(".svg");if(r.isDesktop&&_&&!je){z(""),oe(!0);return}if(!r.isDesktop&&_&&!je){z(""),oe(!1);return}oe(!0);try{const le=await ps(ke.path);z(le),W(le.length>ko?`${le.slice(0,ko)}
238
+
239
+ … truncated …`:le)}catch(le){z(""),W(""),q(le instanceof Error?le.message:"Failed to read file")}finally{oe(!1)}},[$,n,ps,r.isDesktop]),pe=i.useCallback(()=>{const ke=L.current,_=Q.current;if(L.current=null,Q.current=null,ce.current=!0,K(!1),W(Xt),ke){J(ke);return}_&&(yt(null),Me.getState().setActiveMainTab(_))},[Xt,J,yt]),Ee=i.useCallback(async()=>{const ke=L.current,_=Q.current;if(L.current=null,Q.current=null,ce.current=!0,K(!1),await U(),ke){await J(ke);return}_&&(yt(null),Me.getState().setActiveMainTab(_))},[J,U,yt]),He=i.useCallback(async ke=>{const _=ir(ke);N(je=>{const le=new Set(je);return le.has(_)?le.delete(_):le.add(_),le}),k.current.has(_)||await Kt(_)},[Kt]),ft=i.useCallback((ke,_)=>{const je=j[ke]??[];return je.map((le,Re)=>{const _e=le.type==="directory",We=_e&&C.has(le.path),qe=A?.path===le.path,it=_e&&M.current.has(le.path),It=Re===je.length-1;return e.jsxs("li",{className:"relative",children:[_>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),It&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),e.jsxs("div",{className:"group relative flex items-center",onContextMenu:ct=>{!jt&&!Ke&&!rt&&!Xe||(ct.preventDefault(),ie(le.path))},children:[e.jsxs("button",{type:"button",onClick:()=>{_e?He(le.path):J(le)},className:R("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",qe?"bg-accent/70":"hover:bg-accent/40"),children:[_e?it?e.jsx(Mt,{className:"h-4 w-4 flex-shrink-0 animate-spin"}):We?e.jsx(Ux,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):e.jsx(Vx,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):tm(le.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:le.path,children:le.name})]}),(jt||Ke||rt||Xe)&&e.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 focus-within:opacity-100",children:e.jsxs(ts,{open:fe===le.path,onOpenChange:ct=>ie(ct?le.path:null),children:[e.jsx(ss,{asChild:!0,children:e.jsx(Se,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(Gx,{className:"h-4 w-4"})})}),e.jsxs(rs,{align:"end",onCloseAutoFocus:()=>ie(null),children:[jt&&e.jsxs(kt,{onClick:ct=>{ct.stopPropagation(),Ct("rename",le)},children:[e.jsx(fo,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(kt,{onClick:ct=>{ct.stopPropagation(),navigator.clipboard.writeText(le.path),V.success("Path copied")},children:[e.jsx(nr,{className:"mr-2 h-4 w-4"})," Copy Path"]}),_e&&(Ke||rt)&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),Ke&&e.jsxs(kt,{onClick:ct=>{ct.stopPropagation(),Ct("createFile",le)},children:[e.jsx(Zl,{className:"mr-2 h-4 w-4"})," New File"]}),rt&&e.jsxs(kt,{onClick:ct=>{ct.stopPropagation(),Ct("createFolder",le)},children:[e.jsx(Dc,{className:"mr-2 h-4 w-4"})," New Folder"]})]}),Xe&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),e.jsxs(kt,{onClick:ct=>{ct.stopPropagation(),Ct("delete",le)},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]})})]}),_e&&We&&e.jsx("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:ft(le.path,_+1)})]},le.path)})},[j,C,J,A?.path,He,Ct,Ke,rt,jt,Xe,fe,ie]),pt=!!(A?.path&&Ho(A.path)),wt=!!(A?.path&&A.path.toLowerCase().endsWith(".svg")),at=i.useMemo(()=>{if(!A?.path)return"";const ke=ir(A.path);if(d&&ke.startsWith(d)){const _=ke.slice(d.length);return _.startsWith("/")?_.slice(1):_}return ke},[A?.path,d]),_t=!!(A&&(!pt||wt)&&F.length>0),qt=!!(A&&at.length>0),ht=!!(A&&!pt&&t.writeFile&&F.length<=ko),Et=i.useMemo(()=>{if(!A?.path)return[el(s)];const ke=[el(s)],_=eh(A.path);return _&&ke.push(_),b&&ke.push(pn.lineWrapping),ke},[s,A?.path,b]),Jt=A?.path&&pt?r.isDesktop?wt?`data:${Hc(A.path)};utf8,${encodeURIComponent(F)}`:Y:wt?`data:${Hc(A.path)};utf8,${encodeURIComponent(F)}`:`/api/fs/raw?path=${encodeURIComponent(A.path)}`:"";i.useEffect(()=>{let ke=!1;return(async()=>{if(!r.isDesktop||!A?.path||!pt||wt){Z("");return}q(null);try{if(t.readFileBinary){const _e=await t.readFileBinary(A.path);ke||Z(_e.dataUrl);return}const le=(await vs(()=>import("./vendor-.bun-Bui932eM.js").then(_e=>_e.dk),__vite__mapDeps([0,1]))).convertFileSrc;if(!le)return;const Re=le(A.path,"asset");ke||Z(Re)}catch(je){ke||(Z(""),q(je instanceof Error?je.message:"Failed to read file"))}finally{ke||oe(!1)}})(),()=>{ke=!0}},[t,pt,wt,r.isDesktop,A?.path]);const Js=()=>e.jsx(us,{open:!!H,onOpenChange:ke=>!ke&&we(null),children:e.jsxs(ms,{children:[e.jsxs(xs,{children:[e.jsxs(ys,{children:[H==="createFile"&&"Create File",H==="createFolder"&&"Create Folder",H==="rename"&&"Rename",H==="delete"&&"Delete"]}),e.jsxs(Ss,{children:[H==="createFile"&&`Create a new file in ${ee?.path??"root"}`,H==="createFolder"&&`Create a new folder in ${ee?.path??"root"}`,H==="rename"&&`Rename ${ee?.name}`,H==="delete"&&`Are you sure you want to delete ${ee?.name}? This action cannot be undone.`]})]}),H!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(St,{value:ge,onChange:ke=>X(ke.target.value),placeholder:H==="rename"?"New name":"Name",onKeyDown:ke=>{ke.key==="Enter"&&Cs()},autoFocus:!0})}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"outline",onClick:()=>we(null),disabled:de,children:"Cancel"}),e.jsx(Se,{variant:H==="delete"?"destructive":"default",onClick:()=>{Cs()},disabled:de||H!=="delete"&&!ge.trim(),children:de?e.jsx(Mt,{className:"animate-spin"}):H==="delete"?"Delete":"Confirm"})]})]})}),De=()=>!st||!A?null:e.jsx("div",{"data-comment-ui":!0,className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-background flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Fs,{value:Pt,onChange:ke=>{Ot(ke.target.value);const _=ke.target;_.style.height="auto";const le=20*5+8;_.style.height=`${Math.min(_.scrollHeight,le)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!n,rows:1,onKeyDown:ke=>{ke.key==="Enter"&&(ke.metaKey||ke.ctrlKey)&&(ke.preventDefault(),Vt()),ke.key==="Escape"&&(ke.preventDefault(),mt(null),Ot(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[A.name,":",st.start,"-",st.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!n&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Yt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:ke=>{Pt.trim()&&(ke.preventDefault(),Vt())},onClick:()=>{n||Vt()},disabled:!Pt.trim(),className:R("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",Pt.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Vo,{className:"h-[18px] w-[18px]"})})]})]})]})}),Be=e.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[e.jsx(us,{open:me,onOpenChange:ke=>{ke||K(!0)},children:e.jsxs(ms,{showCloseButton:!1,className:"max-w-md",children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Unsaved changes"}),e.jsx(Ss,{children:"Save your edits before continuing?"})]}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"outline",onClick:()=>{Ee()},disabled:te,className:"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]",children:"Save changes"}),e.jsx(Se,{variant:"destructive",onClick:pe,children:"Discard"})]})]})}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[n&&g&&e.jsx("button",{type:"button",onClick:()=>x(!1),"aria-label":"Back",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(al,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label font-medium truncate",children:A?A.name:"Select a file"}),A&&!n&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:at,children:at})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ht&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>{U()},disabled:!$||te,className:"h-5 w-5 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Yt()}+S)`,"aria-label":`Save (${Yt()}+S)`,children:te?e.jsx(Mt,{className:"h-4 w-4 animate-spin"}):e.jsx(ed,{className:"h-4 w-4"})}),ht&&A&&!pt&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),A&&!pt&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>y(!b),className:R("h-5 w-5 p-0 transition-opacity",b?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:b?"Disable line wrap":"Enable line wrap",children:e.jsx(Cc,{className:"size-4"})}),(_t||qt||A&&Bn(A.path))&&(ht||A&&!pt)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),A&&Bn(A.path)&&e.jsx(Zc,{currentMode:bs(),onToggle:()=>Ns(bs()==="preview"?"edit":"preview")}),_t&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(F),re(!0),he.current!==null&&window.clearTimeout(he.current),he.current=window.setTimeout(()=>{re(!1)},1200)}catch{V.error("Copy failed")}},className:"h-5 w-5 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:se?e.jsx(Tt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Wa,{className:"h-4 w-4"})}),qt&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(at),xe(!0),Ne.current!==null&&window.clearTimeout(Ne.current),Ne.current=window.setTimeout(()=>{xe(!1)},1200)}catch{V.error("Copy failed")}},className:"h-5 w-5 p-0",title:`Copy file path (${at})`,"aria-label":`Copy file path (${at})`,children:ne?e.jsx(Tt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Ic,{className:"h-4 w-4"})}),A&&!n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>S(!v),className:"h-5 w-5 p-0",title:v?"Exit fullscreen":"Fullscreen","aria-label":v?"Exit fullscreen":"Fullscreen",children:v?e.jsx(td,{className:"h-4 w-4"}):e.jsx(qx,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(xt,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:A?G?e.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Mt,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):O?e.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:O}):pt?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("img",{src:Jt,alt:A?.name??"Image",className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"})}):A&&Bn(A.path)&&bs()==="preview"?e.jsxs("div",{className:"h-full overflow-auto p-3",children:[F.length>500*1024&&e.jsxs("div",{className:"mb-3 rounded-md border border-warning/20 bg-warning/10 px-3 py-2 text-sm text-warning",children:["⚠️ This file is large (",Math.round(F.length/1024),"KB). Preview may be limited."]}),e.jsx(os,{fallback:e.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[e.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:e.jsx(kr,{content:F,className:"typography-markdown-body"})})]}):e.jsx("div",{className:"h-full",children:e.jsx(Xc,{value:B,onChange:W,extensions:Et,className:"h-full",highlightLines:st?{start:Math.min(st.start,st.end),end:Math.max(st.start,st.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(ke,_,je)=>{if(!(je instanceof MouseEvent)||je.button!==0)return!1;je.preventDefault();const le=ke.state.doc.lineAt(_.from).number;if(n&&st&&!je.shiftKey){const Re=Math.min(st.start,st.end,le),_e=Math.max(st.start,st.end,le);return mt({start:Re,end:_e}),$e.current=!1,be.current=null,!0}if($e.current=!0,be.current=le,st&&je.shiftKey){const Re=Math.min(st.start,le),_e=Math.max(st.end,le);mt({start:Re,end:_e})}else mt({start:le,end:le});return!0},mouseover:(ke,_,je)=>{if(!(je instanceof MouseEvent)||je.buttons!==1||!$e.current||be.current===null)return!1;const le=ke.state.doc.lineAt(_.from).number,Re=Math.min(be.current,le),_e=Math.max(be.current,le);return mt({start:Re,end:_e}),!1},mouseup:()=>($e.current=!1,be.current=null,!1)}}})}):e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}),st&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex flex-col justify-end",style:{paddingBottom:n?"var(--oc-keyboard-inset, 0px)":"0px"},children:e.jsx("div",{className:R("pointer-events-auto pb-2 transition-none w-full flex justify-center",n&&bt?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:n&&!bt&&Dt>0?`${Dt}px`:"16px"},"data-keyboard-avoid":"true",children:De()})})]}),Le=!!(d&&j[d]),Ze=e.jsxs("section",{className:R("flex min-h-0 flex-col overflow-hidden",n?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[e.jsx("div",{className:R("flex flex-col gap-2 py-2",n?"px-3":"px-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Vs,{className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(St,{ref:h,value:m,onChange:ke=>f(ke.target.value),placeholder:"Search files…",className:"h-8 pl-8 pr-8 typography-meta"}),m.trim().length>0&&e.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{f(""),h.current?.focus()},children:e.jsx(es,{className:"h-4 w-4"})})]}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>Ct("createFile",{path:l,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File",children:e.jsx(Zl,{className:"h-4 w-4"})}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>Ct("createFolder",{path:l,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder",children:e.jsx(Dc,{className:"h-4 w-4"})}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>{Rt()},className:"h-8 w-8 p-0 flex-shrink-0",children:e.jsx(en,{className:"h-4 w-4"})})]})}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:R("py-2",n?"px-3":"px-2"),children:e.jsx("ul",{className:"flex flex-col",children:E?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(Mt,{className:"h-4 w-4 animate-spin"}),"Searching…"]}):w.length>0?w.map(ke=>{const _=A?.path===ke.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{J(ke)},className:R("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",_?"bg-accent/70":"hover:bg-accent/40"),children:[tm(ke.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:ke.path,children:ke.relativePath??ke.path})]})},ke.path)}):Le?ft(d,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading…"})})})]}),nt=v&&A&&e.jsxs("div",{className:"absolute inset-0 z-50 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-4 py-2 flex-shrink-0",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label font-medium truncate",children:A.name}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:at,children:at})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ht&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>{U()},disabled:!$||te,className:"h-6 w-6 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Yt()}+S)`,"aria-label":`Save (${Yt()}+S)`,children:te?e.jsx(Mt,{className:"h-4 w-4 animate-spin"}):e.jsx(ed,{className:"h-4 w-4"})}),ht&&!pt&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),!pt&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>y(!b),className:R("h-6 w-6 p-0 transition-opacity",b?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:b?"Disable line wrap":"Enable line wrap",children:e.jsx(Cc,{className:"size-4"})}),(_t||qt||Bn(A.path))&&(ht||!pt)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),Bn(A.path)&&e.jsx(Zc,{currentMode:bs(),onToggle:()=>Ns(bs()==="preview"?"edit":"preview")}),_t&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(F),re(!0),he.current!==null&&window.clearTimeout(he.current),he.current=window.setTimeout(()=>{re(!1)},1200)}catch{V.error("Copy failed")}},className:"h-6 w-6 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:se?e.jsx(Tt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Wa,{className:"h-4 w-4"})}),qt&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(at),xe(!0),Ne.current!==null&&window.clearTimeout(Ne.current),Ne.current=window.setTimeout(()=>{xe(!1)},1200)}catch{V.error("Copy failed")}},className:"h-6 w-6 p-0",title:`Copy file path (${at})`,"aria-label":`Copy file path (${at})`,children:ne?e.jsx(Tt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Ic,{className:"h-4 w-4"})}),e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>S(!1),className:"h-6 w-6 p-0",title:"Exit fullscreen","aria-label":"Exit fullscreen",children:e.jsx(td,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(xt,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:G?e.jsxs("div",{className:"p-4 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Mt,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):O?e.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:O}):pt?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("img",{src:Jt,alt:A.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"})}):Bn(A.path)&&bs()==="preview"?e.jsxs("div",{className:"h-full overflow-auto p-4",children:[F.length>500*1024&&e.jsxs("div",{className:"mb-3 rounded-md border border-warning/20 bg-warning/10 px-3 py-2 text-sm text-warning",children:["This file is large (",Math.round(F.length/1024),"KB). Preview may be limited."]}),e.jsx(os,{fallback:e.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[e.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:e.jsx(kr,{content:F,className:"typography-markdown-body"})})]}):e.jsx("div",{className:"h-full",children:e.jsx(Xc,{value:B,onChange:W,extensions:Et,className:"h-full"})})})})]});return e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[Js(),nt,n?g?Be:Ze:e.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[o>=1024&&e.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:Ze}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:Be})]})]})},dh=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:cl},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Mr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:En},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:Km},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:ro},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Ut},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:vn}],xk={},yk={},bk={};dh.forEach(t=>{xk[t.id]=t.label,yk[t.id]=t.description,bk[t.id]=t});const wk=t=>{if(!Array.isArray(t))return[];const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},vk=t=>{const r=new Map;for(const s of t)!s.permission||s.permission==="invalid"||s.pattern&&r.set(`${s.permission}::${s.pattern}`,s);return Array.from(r.values())},sm=t=>{const r=vk(wk(t));if(r.length===0)return;const s={};for(const o of r)o.permission&&((s[o.permission]||={})[o.pattern]=o.action);const n={};for(const[o,a]of Object.entries(s)){const c=Object.keys(a);if(c.length===1&&c[0]==="*"){n[o]=a["*"];continue}n[o]=a}return Object.keys(n).length>0?n:void 0},jk=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedAgentName:a,agents:c,setSelectedAgent:l,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=cn(),{setSidebarOpen:p}=Me(),{isMobile:h}=Gt(),[g,x]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||x(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=g?"bg-transparent":b?"bg-background":"bg-sidebar",v=()=>{const E="new-agent";let I=E,A=1;for(;c.some(P=>P.name===I);)I=`${E}-${A}`,A++;d({name:I,scope:"user"}),l(I),t?.(),h&&p(!1)},S=async E=>{if(hn(E)){V.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${E.name}"?`)&&(await m(E.name)?V.success(`Agent "${E.name}" deleted successfully`):V.error("Failed to delete agent"))},C=async E=>{hn(E)&&window.confirm(`Are you sure you want to reset agent "${E.name}" to its default configuration?`)&&(await m(E.name)?V.success(`Agent "${E.name}" reset to default`):V.error("Failed to reset agent"))},N=E=>{const I=E.name;let A=1,P=`${I}-copy`;for(;c.some(oe=>oe.name===P);)A++,P=`${I}-copy-${A}`;const F=E,z=E.model?.providerID&&E.model?.modelID?`${E.model.providerID}/${E.model.modelID}`:null,G=E;d({name:P,scope:F.scope||"user",description:E.description,model:z,temperature:E.temperature,top_p:E.topP,prompt:E.prompt,mode:E.mode,permission:sm(E.permission),disable:G.disable}),l(P),h&&p(!1)},j=E=>{o(E.name),s(E)},D=async()=>{if(!r)return;const E=n.trim().replace(/\s+/g,"-");if(!E){V.error("Agent name is required");return}if(E===r.name){s(null);return}if(c.some(F=>F.name===E)){V.error("An agent with this name already exists");return}const I=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,A=r;await u({name:E,description:r.description,model:I,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:sm(r.permission),disable:A.disable,scope:A.scope})?await m(r.name)?(V.success(`Agent renamed to "${E}"`),l(E)):V.error("Failed to remove old agent after rename"):V.error("Failed to rename agent"),s(null)},k=E=>{switch(E){case"primary":return e.jsx(Sn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(lf,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(cf,{className:"h-3 w-3 text-primary"});default:return null}},M=c.filter(E=>!Af(E)),w=M.filter(hn),T=M.filter(E=>!hn(E));return e.jsxs("div",{className:R("flex h-full flex-col",y),children:[e.jsx("div",{className:R("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",M.length]}),e.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(ls,{className:"size-4"})})]})}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:M.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Fo,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No agents configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[w.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Agents"}),w.map(E=>e.jsx(rm,{agent:E,isSelected:a===E.name,onSelect:()=>{l(E.name),t?.(),h&&p(!1)},onReset:()=>C(E),onDuplicate:()=>N(E),getAgentModeIcon:k},E.name))]}),T.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Agents"}),T.map(E=>e.jsx(rm,{agent:E,isSelected:a===E.name,onSelect:()=>{l(E.name),t?.(),h&&p(!1)},onRename:()=>j(E),onDelete:()=>S(E),onDuplicate:()=>N(E),getAgentModeIcon:k},E.name))]})]})}),e.jsx(us,{open:r!==null,onOpenChange:E=>!E&&s(null),children:e.jsxs(ms,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Agent"}),e.jsxs(Ss,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(St,{value:n,onChange:E=>o(E.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:E=>{E.key==="Enter"&&D()}}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Dn,{onClick:D,children:"Rename"})]})]})})]})},rm=({agent:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:c,getAgentModeIcon:l})=>{const d=t;return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:s,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t.name}),l(t.mode),(d.scope||hn(t))&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:hn(t)?"system":d.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(Se,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(nn,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(kt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(fo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(kt,{onClick:u=>{u.stopPropagation(),c()},children:[e.jsx(nr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(kt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(kt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Ts({className:t,variant:r,...s}){return e.jsx(Se,{variant:r,size:"sm",className:R("h-6 px-2 text-xs",t),...s})}const Sk=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Nk=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=Sk.format(t);return r.endsWith(".0")?r.slice(0,-2):r},Bl=({providerId:t,modelId:r,onChange:s,className:n,allowedProviderIds:o})=>{const{providers:a,modelsMetadata:c}=Je(),l=Me(B=>B.isMobile),{toggleFavoriteModel:d,isFavoriteModel:u,addRecentModel:m}=Me(),{favoriteModelsList:f,recentModelsList:p}=Fl(),{isMobile:h}=Gt(),g=l||h,[x,b]=i.useState(!1),[y,v]=i.useState(new Set),[S,C]=i.useState(!1),[N,j]=i.useState(""),[D,k]=i.useState(0),M=i.useRef([]),w=i.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),T=i.useMemo(()=>w?a.filter(B=>w.has(String(B.id))):a,[a,w]),E=()=>b(!1),I=B=>{v(W=>{const te=new Set(W);return te.has(B)?te.delete(B):te.add(B),te})};i.useEffect(()=>{S||(j(""),k(0))},[S]),i.useEffect(()=>{k(0)},[N]);const A=B=>{const W=B?.name||B?.id||"",te=String(W);return te.length>40?te.substring(0,37)+"...":te},P=(B,W)=>{const te=`${B}/${W}`;return c.get(te)},F=(B,W)=>{s(B,W),B&&W&&m(B,W),C(!1)},z=(B,W)=>{if(!N.trim())return!0;const te=N.toLowerCase();return B.toLowerCase().includes(te)||W.toLowerCase().includes(te)},G=(B,W,te,ye,me,K)=>{const L=P(W,te),Q=Nk(L?.limit?.context),ce=t===W&&r===te,he=u(W,te),Ne=ye==="fav"||ye==="recent";return e.jsxs("div",{ref:H=>{M.current[me]=H},className:R("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",K?"bg-accent":"hover:bg-accent/50"),onClick:()=>F(W,te),onMouseEnter:()=>k(me),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[Ne&&e.jsx(gs,{providerId:W,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(B)}),Q?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:Q}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[ce&&e.jsx(Tt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),d(W,te)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",he?"text-yellow-500":"text-muted-foreground"),"aria-label":he?"Unfavorite":"Favorite",title:he?"Remove from favorites":"Add to favorites",children:he?e.jsx(Rr,{className:"h-3.5 w-3.5"}):e.jsx(Jn,{className:"h-3.5 w-3.5"})})]})]},`${ye}-${W}-${te}`)},oe=f.filter(({model:B,providerID:W})=>{if(w&&!w.has(W))return!1;const ye=a.find(K=>K.id===W)?.name||W,me=A(B);return z(me,ye)}),O=p.filter(({model:B,providerID:W})=>{if(w&&!w.has(W))return!1;const ye=a.find(K=>K.id===W)?.name||W,me=A(B);return z(me,ye)}),q=T.map(B=>{const te=(Array.isArray(B.models)?B.models:[]).filter(ye=>{const me=A(ye);return z(me,B.name||B.id||"")});return{...B,models:te}}).filter(B=>B.models.length>0),Y=oe.length>0||O.length>0||q.length>0,Z=()=>g?e.jsx(Ws,{open:x,onClose:E,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[f.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Favorites"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:B,providerID:W,modelID:te})=>{const ye=W===t&&te===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",ye?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{F(W,te),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{providerId:W,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(B)})]})}),e.jsx("button",{onClick:me=>{me.preventDefault(),me.stopPropagation(),d(W,te)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-yellow-500 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Unfavorite",children:e.jsx(Rr,{className:"h-4 w-4"})})]},`fav-mobile-${W}-${te}`)})})]}),p.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Recents"}),e.jsx("div",{className:"border-t border-border/20",children:p.map(({model:B,providerID:W,modelID:te})=>{const ye=W===t&&te===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",ye?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{F(W,te),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{providerId:W,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(B)})]})}),e.jsx("button",{onClick:me=>{me.preventDefault(),me.stopPropagation(),d(W,te)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Favorite",children:e.jsx(Jn,{className:"h-4 w-4"})})]},`recent-mobile-${W}-${te}`)})})]}),T.map(B=>{const W=Array.isArray(B.models)?B.models:[];if(W.length===0)return null;const te=B.id===t,ye=y.has(B.id);return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left",onClick:()=>I(B.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{providerId:B.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:B.name}),te&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),ye?e.jsx(Wt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(tr,{className:"h-3 w-3 text-muted-foreground"})]}),ye&&e.jsx("div",{className:"border-t border-border/20",children:W.map(me=>{const K=B.id===t&&me.id===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",K?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{F(B.id,me.id),E()},children:e.jsx("span",{className:"font-medium truncate",children:A(me)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),d(B.id,me.id)},className:R("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",u(B.id,me.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":u(B.id,me.id)?"Unfavorite":"Favorite",children:u(B.id,me.id)?e.jsx(Rr,{className:"h-4 w-4"}):e.jsx(Jn,{className:"h-4 w-4"})}),K&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},me.id)})})]},B.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{F("",""),E()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[g?e.jsxs("button",{type:"button",onClick:()=>b(!0),className:R("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[t?e.jsx(gs,{providerId:t,className:"h-3.5 w-3.5"}):e.jsx(Fr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:t&&r?`${t}/${r}`:"Select model..."})]}),e.jsx(Wt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(ts,{open:S,onOpenChange:C,children:[e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",n),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(gs,{providerId:t,className:"h-3 w-3 flex-shrink-0"}),e.jsx(Fr,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Fr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:t&&r?`${t}/${r}`:"Not selected"}),e.jsx(Wt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(rs,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const B=[];oe.forEach(({model:me,providerID:K,modelID:L})=>{B.push({model:me,providerID:K,modelID:L,section:"fav"})}),O.forEach(({model:me,providerID:K,modelID:L})=>{B.push({model:me,providerID:K,modelID:L,section:"recent"})}),q.forEach(me=>{me.models.forEach(K=>{B.push({model:K,providerID:me.id,modelID:K.id,section:"provider"})})});const W=B.length,te=me=>{if(me.key==="ArrowDown"){me.preventDefault(),me.stopPropagation();const K=(D+1)%Math.max(1,W);k(K),setTimeout(()=>{M.current[K]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(me.key==="ArrowUp"){me.preventDefault(),me.stopPropagation();const K=(D-1+Math.max(1,W))%Math.max(1,W);k(K),setTimeout(()=>{M.current[K]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(me.key==="Enter"){me.preventDefault(),me.stopPropagation();const K=B[D];K&&F(K.providerID,K.modelID)}else me.key==="Escape"&&(me.preventDefault(),me.stopPropagation(),C(!1))};let ye=0;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{type:"text",placeholder:"Search models",value:N,onChange:me=>j(me.target.value),onKeyDown:te,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(xt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:R("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>F("",""),children:[e.jsx(es,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!t&&!r&&e.jsx(Tt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Ds,{}),!Y&&N&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),oe.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Lr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Rr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),oe.map(({model:me,providerID:K,modelID:L})=>{const Q=ye++;return G(me,K,L,"fav",Q,D===Q)})]}),O.length>0&&e.jsxs(e.Fragment,{children:[oe.length>0&&e.jsx(Ds,{}),e.jsxs(Lr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Cr,{className:"h-4 w-4"}),"Recent"]}),O.map(({model:me,providerID:K,modelID:L})=>{const Q=ye++;return G(me,K,L,"recent",Q,D===Q)})]}),(oe.length>0||O.length>0)&&q.length>0&&e.jsx(Ds,{}),q.map((me,K)=>e.jsxs(i.Fragment,{children:[K>0&&e.jsx(Ds,{}),e.jsxs(Lr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(gs,{providerId:me.id,className:"h-4 w-4 flex-shrink-0"}),me.name]}),me.models.map(L=>{const Q=ye++;return G(L,me.id,L.id,"provider",Q,D===Q)})]},me.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()})]}),Z()]})},nm=["*","read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop","question","plan_enter","plan_exit"],Ha=t=>t==="allow"||t==="ask"||t==="deny",fn=(t,r)=>`${t}::${r}`,An=t=>{const r=new Map;for(const s of t)!s.permission||s.permission==="invalid"||s.pattern&&Ha(s.action)&&r.set(fn(s.permission,s.pattern),{permission:s.permission,pattern:s.pattern,action:s.action});return Array.from(r.values())},va=t=>{const r=new Map;for(const s of An(t))r.set(fn(s.permission,s.pattern),s);return r},om=t=>[...t].sort((r,s)=>{const n=r.permission.localeCompare(s.permission);return n!==0?n:r.pattern.localeCompare(s.pattern)}),kk=(t,r)=>{const s=om(An(t)),n=om(An(r));return s.length!==n.length?!1:s.every((o,a)=>{const c=n[a];return o.permission===c.permission&&o.pattern===c.pattern&&o.action===c.action})},Ck=t=>t.find(s=>s.permission==="*"&&s.pattern==="*")?.action??"allow",Mk=(t,r)=>An(t).filter(s=>!(s.permission==="*"&&s.pattern==="*")).filter(s=>s.pattern!=="*"||s.action!==r),Dk=t=>{if(Ha(t))return[{permission:"*",pattern:"*",action:t}];if(!t||typeof t!="object"||Array.isArray(t))return[];const r=[];for(const[s,n]of Object.entries(t))if(s!=="__originalKeys"){if(Ha(n)){r.push({permission:s,pattern:"*",action:n});continue}if(n&&typeof n=="object"&&!Array.isArray(n))for(const[o,a]of Object.entries(n))Ha(a)&&r.push({permission:s,pattern:o,action:a})}return r},Ak=(t,r)=>{const s=An(r),n={};for(const a of s)(n[a.permission]||={})[a.pattern]=a.action;const o={"*":t};for(const[a,c]of Object.entries(n))if(a!=="*"){if(Object.keys(c).length===1&&c["*"]){o[a]=c["*"];continue}o[a]=c}return o},Ek=()=>{const{selectedAgentName:t,getAgentByName:r,createAgent:s,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:c}=cn();Je();const l=t?r(t):null,d=!!(a&&a.name===t&&!l),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,g]=i.useState(""),[x,b]=i.useState("subagent"),[y,v]=i.useState(""),[S,C]=i.useState(void 0),[N,j]=i.useState(void 0),[D,k]=i.useState(""),[M,w]=i.useState("allow"),[T,E]=i.useState([]),[I,A]=i.useState([]),[P,F]=i.useState(""),[z,G]=i.useState("*"),[oe,O]=i.useState(!1),[q,Y]=i.useState(!1),Z=i.useRef(null),B=vt(se=>se.currentDirectory??null),[W,te]=i.useState([]),ye=zo(se=>se.permissions);i.useEffect(()=>{let se=!1;return(async()=>{const ne=await Oe.listToolIds({directory:B});if(se)return;const xe=new Set(["write","patch","multiedit"]),Ue=ne.map(ze=>typeof ze=="string"?ze.trim():"").filter(Boolean).filter(ze=>ze!=="*").filter(ze=>ze!=="invalid").filter(ze=>!xe.has(ze));te(Array.from(new Set(Ue)).sort((ze,Ke)=>ze.localeCompare(Ke)))})(),()=>{se=!0}},[B]);const me=i.useMemo(()=>{const se=new Set;for(const re of o){const ne=An(Array.isArray(re.permission)?re.permission:[]);for(const xe of ne)xe.permission&&xe.permission!=="*"&&xe.permission!=="invalid"&&se.add(xe.permission)}for(const re of ye.values())for(const ne of re){const xe=ne.permission?.trim();xe&&xe!=="invalid"&&se.add(xe)}for(const re of W)se.add(re);return Array.from(se).sort((re,ne)=>re.localeCompare(ne))},[o,ye,W]),K=i.useMemo(()=>va(T),[T]),L=i.useMemo(()=>va(I),[I]),Q=i.useCallback(se=>L.get(fn(se,"*"))?.action,[L]),ce=i.useCallback(se=>I.filter(re=>re.permission===se&&re.pattern!=="*").sort((re,ne)=>re.pattern.localeCompare(ne.pattern)),[I]),he=i.useMemo(()=>{const se=new Set;for(const re of nm)se.add(re);for(const re of me)se.add(re);return Array.from(se).sort((re,ne)=>re.localeCompare(ne))},[me]),Ne=i.useCallback(se=>{const re=se==="*"?M:Q(se)??M,ne=ce(se),xe=!1,Ue=ne.reduce((Ke,rt)=>(Ke[rt.action]=(Ke[rt.action]??0)+1,Ke),{allow:0,ask:0,deny:0}),ze=["allow","ask","deny"].filter(Ke=>Ue[Ke]>0).map(Ke=>`${Ue[Ke]} ${Ke}`).join(", ");return{defaultAction:re,patternRulesCount:ne.length,patternSummary:ze,hasDefaultHint:xe}},[ce,Q,M]),H=i.useMemo(()=>{const se=new Set;for(const re of nm)se.add(re);for(const re of me)se.add(re);return Array.from(se).sort((re,ne)=>re.localeCompare(ne))},[me]),we=i.useCallback((se,re,ne)=>{A(xe=>{const Ue=va(xe);return Ue.set(fn(se,re),{permission:se,pattern:re,action:ne}),Array.from(Ue.values())})},[]),ee=i.useCallback((se,re)=>{A(ne=>{const xe=va(ne);return xe.delete(fn(se,re)),Array.from(xe.values())})},[]),ue=i.useCallback((se,re)=>{const ne=K.get(fn(se,re));if(ne){we(se,re,ne.action);return}ee(se,re)},[K,ee,we]),ge=i.useCallback((se,re,ne)=>{we(se,re,ne)},[we]),X=i.useCallback(se=>{w(se),A(re=>re.filter(ne=>!(ne.pattern==="*"&&ne.action===se)))},[]),de=i.useCallback(se=>{const re=P.trim();if(!re){V.error("Permission name is required");return}const ne=z.trim()||"*";if(re==="*"&&ne==="*"){X(se),F(""),G("*");return}ne==="*"&&re!=="*"&&se===M?ee(re,"*"):we(re,ne,se),F(""),G("*")},[M,P,z,ee,X,we]),ae=i.useCallback(se=>se==="*"?"Default":se==="webfetch"?"WebFetch":se==="websearch"?"WebSearch":se==="codesearch"?"CodeSearch":se==="doom_loop"?"Doom Loop":se==="external_directory"?"External Directory":se==="todowrite"?"TodoWrite":se==="todoread"?"TodoRead":se.split(/[_-]+/g).filter(Boolean).map(re=>re.charAt(0).toUpperCase()+re.slice(1)).join(" "),[]);i.useEffect(()=>{F(""),G("*");const se=re=>{const ne=An(re),xe=Ck(ne),Ue=Mk(ne,xe);return w(xe),E(Ue),A(Ue),{global:xe,rules:Ue}};if(d&&a){const re=a.name||"",ne=a.scope||"user",xe=a.description||"",Ue=a.mode||"subagent",ze=a.model||"",Ke=a.temperature,rt=a.top_p,jt=a.prompt||"";m(re),p(ne),g(xe),b(Ue),v(ze),C(Ke),j(rt),k(jt);const Xe=Dk(a.permission),Ct=se(Xe);Z.current={draftName:re,draftScope:ne,description:xe,mode:Ue,model:ze,temperature:Ke,topP:rt,prompt:jt,globalPermission:Ct.global,permissionRules:Ct.rules};return}if(l&&t===l.name){const re=l.description||"",ne=l.mode||"subagent",xe=l.model?.providerID&&l.model?.modelID?`${l.model.providerID}/${l.model.modelID}`:"",Ue=l.temperature,ze=l.topP,Ke=l.prompt||"";g(re),b(ne),v(xe),C(Ue),j(ze),k(Ke);const rt=se(Array.isArray(l.permission)?l.permission:[]);Z.current={draftName:"",draftScope:"user",description:re,mode:ne,model:xe,temperature:Ue,topP:ze,prompt:Ke,globalPermission:rt.global,permissionRules:rt.rules}}},[a,d,l,t]);const fe=i.useMemo(()=>{const se=Z.current;return se?!!(d&&(u!==se.draftName||f!==se.draftScope)||h!==se.description||x!==se.mode||y!==se.model||S!==se.temperature||N!==se.topP||D!==se.prompt||M!==se.globalPermission||!kk(I,se.permissionRules)):!1},[h,u,f,M,d,x,y,I,D,S,N]),ie=async()=>{const se=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!se){V.error("Agent name is required");return}if(d&&o.some(re=>re.name===se)){V.error("An agent with this name already exists");return}Y(!0);try{const re=y.trim(),ne=Ak(M,I),xe={name:se,description:h.trim()||void 0,mode:x,model:re===""?null:re,temperature:S,top_p:N,prompt:D.trim()||void 0,permission:ne,scope:d?f:void 0};let Ue;d?(Ue=await s(xe),Ue&&c(null)):Ue=await n(se,xe),Ue?V.success(d?"Agent created successfully":"Agent updated successfully"):V.error(d?"Failed to create agent":"Failed to update agent")}catch(re){console.error("Error saving agent:",re);const ne=re instanceof Error&&re.message?re.message:"An error occurred while saving";V.error(ne)}finally{Y(!1)}};return t?e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Agent":t})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure agent identity and behavior mode"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"@"}),e.jsx(St,{value:u,onChange:se=>m(se.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(As,{value:f,onValueChange:se=>p(se),children:[e.jsxs(Es,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(rr,{className:"h-4 w-4"}):e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Is,{align:"end",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rr,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Available in all projects"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Fs,{value:h,onChange:se=>g(se.target.value),placeholder:"What does this agent do?",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Mode"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsxs(Ts,{variant:x==="primary"?"default":"outline",onClick:()=>b("primary"),className:R("gap-2",x==="primary"?void 0:"text-foreground"),children:[e.jsx(Sn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Ts,{variant:x==="subagent"?"default":"outline",onClick:()=>b("subagent"),className:R("gap-2",x==="subagent"?void 0:"text-foreground"),children:[e.jsx(cf,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Ts,{variant:x==="all"?"default":"outline",onClick:()=>b("all"),className:R("gap-2",x==="all"?void 0:"text-foreground"),children:[e.jsx(lf,{className:"h-3 w-3"}),"All"]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Primary: main agent, Subagent: helper agent, All: both modes"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and generation parameters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(Bl,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(se,re)=>{v(se&&re?`${se}/${re}`:"")}})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Temperature",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Controls randomness in responses.",e.jsx("br",{}),"Higher values make output more creative and unpredictable,",e.jsx("br",{}),"lower values make it more focused and deterministic."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const re=Math.max(0,(S!==void 0?S:.7)-.1);C(parseFloat(re.toFixed(1)))},className:"absolute left-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(yo,{className:"h-3.5 w-3.5"})}),e.jsx(St,{type:"text",inputMode:"decimal",value:S!==void 0?S:"",onChange:se=>{const re=se.target.value;if(re===""){C(void 0);return}const ne=parseFloat(re);!isNaN(ne)&&ne>=0&&ne<=2&&C(ne)},onBlur:se=>{const re=se.target.value;if(re!==""){const ne=parseFloat(re);if(!isNaN(ne)){const xe=Math.max(0,Math.min(2,ne));C(parseFloat(xe.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const re=Math.min(2,(S!==void 0?S:.7)+.1);C(parseFloat(re.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(ls,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Top P",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Controls diversity via nucleus sampling.",e.jsx("br",{}),"Lower values focus on most likely tokens,",e.jsx("br",{}),"higher values consider more possibilities."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const re=Math.max(0,(N!==void 0?N:.9)-.1);j(parseFloat(re.toFixed(1)))},className:"absolute left-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(yo,{className:"h-3.5 w-3.5"})}),e.jsx(St,{type:"text",inputMode:"decimal",value:N!==void 0?N:"",onChange:se=>{const re=se.target.value;if(re===""){j(void 0);return}const ne=parseFloat(re);!isNaN(ne)&&ne>=0&&ne<=1&&j(ne)},onBlur:se=>{const re=se.target.value;if(re!==""){const ne=parseFloat(re);if(!isNaN(ne)){const xe=Math.max(0,Math.min(1,ne));j(parseFloat(xe.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const re=Math.min(1,(N!==void 0?N:.9)+.1);j(parseFloat(re.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(ls,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"System Prompt"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Override the default system prompt for this agent"})]}),e.jsx(Fs,{value:D,onChange:se=>k(se.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Tool Access"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"OpenCode v1.1.1+ configures tool access via the permissions below."})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>O(se=>!se),className:"h-8",children:oe?"Hide":"Edit"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:oe?"Set a global default; tools only saved when different from global.":"Summary shows default actions; edit to manage granular rules."})]}),oe?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"All Rules"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Each rule is shown as permission + pattern. Editing updates the action only."})]}),e.jsx("div",{className:"rounded-lg border border-border/40",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:"Global"}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:"*"})]}),e.jsxs(As,{value:M,onValueChange:se=>X(se),children:[e.jsx(Es,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:M})}),e.jsxs(Is,{children:[e.jsx(Bt,{value:"allow",className:"pr-2 [&>span:first-child]:hidden",children:"Allow"}),e.jsx(Bt,{value:"ask",className:"pr-2 [&>span:first-child]:hidden",children:"Ask"}),e.jsx(Bt,{value:"deny",className:"pr-2 [&>span:first-child]:hidden",children:"Deny"})]})]})]})}),e.jsx("div",{className:"space-y-6",children:he.filter(se=>se!=="*").map(se=>{const re=ae(se),{defaultAction:ne,patternRulesCount:xe,patternSummary:Ue}=Ne(se),ze=Q(se),Ke=ze??"global",rt=ce(se),jt=["allow","ask","deny"].filter(Xe=>Xe!==M);return e.jsxs("div",{className:"rounded-lg border border-border/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:re}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:se})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[xe>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Global: ",ne]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:ne}),xe>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Patterns: ",Ue]}):null]})]}),e.jsxs("div",{className:"space-y-2 border-t border-border/40 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Pattern"}),e.jsx("span",{className:"typography-micro font-mono text-foreground",children:"*"}),ze?e.jsxs(Se,{size:"sm",variant:"outline",onClick:()=>ue(se,"*"),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(yo,{className:"h-3 w-3"}),"Revert"]}):null]}),e.jsxs(As,{value:Ke,onValueChange:Xe=>{if(Xe==="global"){ee(se,"*");return}we(se,"*",Xe)},children:[e.jsx(Es,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:Ke==="global"?"Global":Ke})}),e.jsxs(Is,{children:[e.jsx(Bt,{value:"global",className:"pr-2 [&>span:first-child]:hidden",children:"Global"}),jt.map(Xe=>e.jsx(Bt,{value:Xe,className:"pr-2 [&>span:first-child]:hidden",children:Xe.charAt(0).toUpperCase()+Xe.slice(1)},Xe))]})]})]}),rt.map(Xe=>{const Ct=fn(Xe.permission,Xe.pattern),st=K.get(Ct),mt=!st,Pt=!!(st&&st.action!==Xe.action);return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Pattern"}),e.jsx("span",{className:"typography-micro font-mono text-foreground",children:Xe.pattern}),mt?e.jsx("span",{className:"typography-micro text-emerald-500",children:"New"}):null,Pt?e.jsx("span",{className:"typography-micro text-amber-500",children:"Modified"}):null,mt?e.jsxs(Se,{size:"sm",variant:"outline",onClick:()=>ee(Xe.permission,Xe.pattern),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(yo,{className:"h-3 w-3"}),"Remove"]}):Pt?e.jsxs(Se,{size:"sm",variant:"outline",onClick:()=>ue(Xe.permission,Xe.pattern),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(yo,{className:"h-3 w-3"}),"Revert"]}):null]}),e.jsxs(As,{value:Xe.action,onValueChange:Ot=>ge(Xe.permission,Xe.pattern,Ot),children:[e.jsx(Es,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:Xe.action})}),e.jsxs(Is,{children:[e.jsx(Bt,{value:"allow",className:"pr-2 [&>span:first-child]:hidden",children:"Allow"}),e.jsx(Bt,{value:"ask",className:"pr-2 [&>span:first-child]:hidden",children:"Ask"}),e.jsx(Bt,{value:"deny",className:"pr-2 [&>span:first-child]:hidden",children:"Deny"})]})]})]},Ct)})]})]},se)})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Add Rule"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose a permission key, set a pattern, and pick an action."}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs(As,{value:P,onValueChange:F,children:[e.jsx(Es,{className:"h-8 min-h-8 w-full sm:w-64",children:P?e.jsx("span",{className:"truncate",children:ae(P)}):e.jsx("span",{className:"text-muted-foreground",children:"Permission…"})}),e.jsx(Is,{children:H.map(se=>e.jsx(Bt,{value:se,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:ae(se)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:se})]})},se))})]}),e.jsx(St,{value:z,onChange:se=>G(se.target.value),placeholder:"Pattern (e.g. *)",className:"h-8 sm:w-64 font-mono"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>de("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>de("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>de("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})]})]}):e.jsx("div",{className:"rounded-lg border border-border/40 divide-y divide-border/40",children:he.map(se=>{const{defaultAction:re,patternRulesCount:ne,patternSummary:xe,hasDefaultHint:Ue}=Ne(se),ze=ae(se),Ke=Ue?`${re} (env blocked)`:re;return e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:ze}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:se})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[ne>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Global: ",Ke]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:Ke}),ne>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Patterns: ",xe]}):null]})]},se)})}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Se,{size:"sm",variant:"default",onClick:ie,disabled:q||!fe,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(gi,{className:"h-3 w-3"}),q?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Fo,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select an agent from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})},Ik=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedCommandName:a,commands:c,setSelectedCommand:l,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=an(),{setSidebarOpen:p}=Me(),{isMobile:h}=Gt(),[g,x]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||x(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=g?"bg-transparent":b?"bg-background":"bg-sidebar",v=()=>{const w="new-command";let T=w,E=1;for(;c.some(I=>I.name===T);)T=`${w}-${E}`,E++;d({name:T,scope:"user"}),l(T),t?.(),h&&p(!1)},S=async w=>{if(Gn(w)){V.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${w.name}"?`)&&(await m(w.name)?V.success(`Command "${w.name}" deleted successfully`):V.error("Failed to delete command"))},C=async w=>{Gn(w)&&window.confirm(`Are you sure you want to reset command "${w.name}" to its default configuration?`)&&(await m(w.name)?V.success(`Command "${w.name}" reset to default`):V.error("Failed to reset command"))},N=w=>{const T=w.name;let E=1,I=`${T}-copy`;for(;c.some(A=>A.name===I);)E++,I=`${T}-copy-${E}`;d({name:I,scope:w.scope||"user",description:w.description,template:w.template,agent:w.agent,model:w.model,subtask:w.subtask}),l(I),h&&p(!1)},j=w=>{o(w.name),s(w)},D=async()=>{if(!r)return;const w=n.trim().replace(/\s+/g,"-");if(!w){V.error("Command name is required");return}if(w===r.name){s(null);return}if(c.some(E=>E.name===w)){V.error("A command with this name already exists");return}await u({name:w,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(V.success(`Command renamed to "${w}"`),l(w)):V.error("Failed to remove old command after rename"):V.error("Failed to rename command"),s(null)},k=c.filter(Gn),M=c.filter(w=>!Gn(w));return e.jsxs("div",{className:R("flex h-full flex-col",y),children:[e.jsx("div",{className:R("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",c.length]}),e.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(ls,{className:"size-4"})})]})}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:c.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(rn,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No commands configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[k.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Commands"}),[...k].sort((w,T)=>w.name.localeCompare(T.name)).map(w=>e.jsx(am,{command:w,isSelected:a===w.name,onSelect:()=>{l(w.name),t?.(),h&&p(!1)},onReset:()=>C(w),onDuplicate:()=>N(w)},w.name))]}),M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Commands"}),[...M].sort((w,T)=>w.name.localeCompare(T.name)).map(w=>e.jsx(am,{command:w,isSelected:a===w.name,onSelect:()=>{l(w.name),t?.(),h&&p(!1)},onRename:()=>j(w),onDelete:()=>S(w),onDuplicate:()=>N(w)},w.name))]})]})}),e.jsx(us,{open:r!==null,onOpenChange:w=>!w&&s(null),children:e.jsxs(ms,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Command"}),e.jsxs(Ss,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(St,{value:n,onChange:w=>o(w.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:w=>{w.key==="Enter"&&D()}}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Dn,{onClick:D,children:"Rename"})]})]})})]})},am=({command:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:c})=>e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:s,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-normal truncate text-foreground",children:["/",t.name]}),(t.scope||Gn(t))&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:Gn(t)?"system":t.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(Se,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(nn,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(kt,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(fo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(kt,{onClick:l=>{l.stopPropagation(),c()},children:[e.jsx(nr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(kt,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(kt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),uh=({agentName:t,onChange:r,className:s})=>{const{loadAgents:n,getVisibleAgents:o}=cn(),a=o(),c=Me(g=>g.isMobile),{isMobile:l}=Gt(),d=c||l,[u,m]=i.useState(!1);i.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=g=>{r(g)},h=()=>d?e.jsx(Ws,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(g=>{const x=g.name===t;return e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",x?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(g.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:g.name}),g.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:g.description})]}),x&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},g.name)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{p(""),f()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No agent (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[d?e.jsxs("button",{type:"button",onClick:()=>m(!0),className:R("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",s),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:t||"Select agent..."})]}),e.jsx(Wt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",s),children:[e.jsx(Fo,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:t||"Not selected"}),e.jsx(Wt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(rs,{className:"max-w-[300px]",children:[a.map(g=>e.jsx(kt,{className:"typography-meta",onSelect:()=>p(g.name),children:e.jsx("span",{className:"font-medium",children:g.name})},g.name)),e.jsx(kt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},Pk=()=>{const{selectedCommandName:t,getCommandByName:r,createCommand:s,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:c}=an(),l=t?r(t):null,d=!!(a&&a.name===t&&!l),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,g]=i.useState(""),[x,b]=i.useState(""),[y,v]=i.useState(""),[S,C]=i.useState(""),[N,j]=i.useState(!1),[D,k]=i.useState(!1),M=i.useRef(null);i.useEffect(()=>{if(d&&a){const E=a.name||"",I=a.scope||"user",A=a.description||"",P=a.agent||"",F=a.model||"",z=a.template||"",G=a.subtask||!1;m(E),p(I),g(A),b(P),v(F),C(z),j(G),M.current={draftName:E,draftScope:I,description:A,agent:P,model:F,template:z,subtask:G}}else if(l){const E=l.description||"",I=l.agent||"",A=l.model||"",P=l.template||"",F=l.subtask||!1;g(E),b(I),v(A),C(P),j(F),M.current={draftName:"",draftScope:"user",description:E,agent:I,model:A,template:P,subtask:F}}},[l,d,t,o,a]);const w=i.useMemo(()=>{const E=M.current;return E?!!(d&&(u!==E.draftName||f!==E.draftScope)||h!==E.description||x!==E.agent||y!==E.model||S!==E.template||N!==E.subtask):!1},[x,h,u,f,d,y,N,S]),T=async()=>{const E=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!E){V.error("Command name is required");return}if(!S.trim()){V.error("Command template is required");return}if(d&&o.some(I=>I.name===E)){V.error("A command with this name already exists");return}k(!0);try{const I=x.trim(),A=y.trim(),P=S.trim(),F={name:E,description:h.trim()||void 0,agent:I===""?null:I,model:A===""?null:A,template:P,subtask:N,scope:d?f:void 0};let z;d?(z=await s(F),z&&c(null)):z=await n(E,F),z?V.success(d?"Command created successfully":"Command updated successfully"):V.error(d?"Failed to create command":"Failed to update command")}catch(I){console.error("Error saving command:",I),V.error("An error occurred while saving")}finally{k(!1)}};return t?e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Command":`/${t}`})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure command identity and metadata"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Command Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"/"}),e.jsx(St,{value:u,onChange:E=>m(E.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(As,{value:f,onValueChange:E=>p(E),children:[e.jsxs(Es,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(rr,{className:"h-4 w-4"}):e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Is,{align:"end",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rr,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Available in all projects"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Fs,{value:h,onChange:E=>g(E.target.value),placeholder:"What does this command do?",rows:3})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model & Agent Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and agent for command execution"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(uh,{agentName:x,onChange:E=>b(E)}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Agent to execute this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(Bl,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(E,I)=>{v(E&&I?`${E}/${I}`:"")}}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default model for this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",checked:N,onChange:E=>j(E.target.checked),className:"sr-only"}),e.jsx("div",{className:R("w-5 h-5 rounded border-2 flex items-center justify-center",N?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:N&&e.jsx(Tt,{className:"w-3 h-3 text-primary-foreground"})})]}),"Force Subagent Invocation"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Force command to run in a subagent context"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["When enabled, this command will always execute in a subagent context,",e.jsx("br",{}),"even if triggered from main agent.",e.jsx("br",{}),"Useful for isolating command logic and maintaining clean separation of concerns."]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Command Template"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Define the prompt template for this command. Use $ARGUMENTS for user input."})]}),e.jsx(Fs,{value:S,onChange:E=>C(E.target.value),placeholder:`Your command template here...
240
+
241
+ Use $ARGUMENTS to reference user input.
242
+ Use !\`shell command\` to inject shell output.
243
+ Use @filename to include file contents.`,rows:12,className:"font-mono typography-meta"}),e.jsxs("div",{className:"typography-meta text-muted-foreground/80 space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Template Features:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 ml-2",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"$ARGUMENTS"}),e.jsx("span",{children:"- User input after command"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Replaced with everything the user types after the command name.",e.jsx("br",{}),'Example: "/deploy staging" makes $ARGUMENTS = "staging"']})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"!`command`"}),e.jsx("span",{children:"- Inject shell command output"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Executes shell command and replaces this placeholder with its output.",e.jsx("br",{}),"Example: !`git branch --show-current` gets current branch name"]})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"@filename"}),e.jsx("span",{children:"- Include file contents"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Replaces with the full contents of the specified file.",e.jsx("br",{}),"Example: @package.json includes the package.json content in the prompt"]})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Se,{size:"sm",variant:"default",onClick:T,disabled:D||!w,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(gi,{className:"h-3 w-3"}),D?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(rn,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a command from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})},Tk=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedSkillName:a,skills:c,setSelectedSkill:l,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=fr(),{setSidebarOpen:h}=Me(),{isMobile:g}=Gt(),[x,b]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||b(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const v=x?"bg-transparent":y?"bg-background":"bg-sidebar",S=()=>{const w="new-skill";let T=w,E=1;for(;c.some(I=>I.name===T);)T=`${w}-${E}`,E++;d({name:T,scope:"user",description:""}),l(T),t?.(),g&&h(!1)},C=async w=>{window.confirm(`Are you sure you want to delete skill "${w.name}"?`)&&(await m(w.name)?V.success(`Skill "${w.name}" deleted successfully`):V.error("Failed to delete skill"))},N=async w=>{const T=w.name;let E=1,I=`${T}-copy`;for(;c.some(P=>P.name===I);)E++,I=`${T}-copy-${E}`;const A=await p(w.name);if(!A){V.error("Failed to load skill details for duplication");return}d({name:I,scope:w.scope||"user",description:(A.sources.md.fields.includes("description"),""),instructions:""}),l(I),g&&h(!1)},j=w=>{o(w.name),s(w)},D=async()=>{if(!r)return;const w=n.trim().replace(/\s+/g,"-").toLowerCase();if(!w){V.error("Skill name is required");return}if(w===r.name){s(null);return}if(c.some(I=>I.name===w)){V.error("A skill with this name already exists");return}if(!await p(r.name)){V.error("Failed to load skill details"),s(null);return}await u({name:w,description:"Renamed skill",scope:r.scope})?await m(r.name)?(V.success(`Skill renamed to "${w}"`),l(w)):V.error("Failed to remove old skill after rename"):V.error("Failed to rename skill"),s(null)},k=c.filter(w=>w.scope==="project"),M=c.filter(w=>w.scope==="user");return e.jsxs("div",{className:R("flex h-full flex-col",v),children:[e.jsx("div",{className:R("border-b px-3",g?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",c.length]}),e.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:S,children:e.jsx(ls,{className:"size-4"})})]})}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:c.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(df,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No skills configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[k.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Project Skills"}),k.map(w=>e.jsx(im,{skill:w,isSelected:a===w.name,onSelect:()=>{l(w.name),t?.(),g&&h(!1)},onRename:()=>j(w),onDelete:()=>C(w),onDuplicate:()=>N(w)},w.name))]}),M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"User Skills"}),M.map(w=>e.jsx(im,{skill:w,isSelected:a===w.name,onSelect:()=>{l(w.name),t?.(),g&&h(!1)},onRename:()=>j(w),onDelete:()=>C(w),onDuplicate:()=>N(w)},w.name))]})]})}),e.jsx(us,{open:r!==null,onOpenChange:w=>!w&&s(null),children:e.jsxs(ms,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Skill"}),e.jsxs(Ss,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(St,{value:n,onChange:w=>o(w.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:w=>{w.key==="Enter"&&D()}}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Dn,{onClick:D,children:"Rename"})]})]})})]})},im=({skill:t,isSelected:r,onSelect:s,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsx("button",{onClick:s,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t.name}),e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:t.scope}),t.source==="claude"&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"claude"})]})}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(Se,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(nn,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(kt,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(fo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(kt,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(nr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(kt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function mh({tabs:t,value:r,onValueChange:s,className:n,isInteractive:o=!0,animate:a=!0}){const c=i.useRef(null),l=i.useRef(null),d=i.useCallback(()=>{const u=c.current,m=l.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:h}=m,g=Math.max(0,Math.min(100,p/f*100)),x=Math.max(0,Math.min(100,(p+h)/f*100));u.style.clipPath=`inset(0 ${Number(100-x).toFixed(2)}% 0 ${Number(g).toFixed(2)}% round 8px)`},[]);return i.useLayoutEffect(()=>{d()},[d,r,t.length]),i.useEffect(()=>{const u=c.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:R("relative isolate w-full",n),children:[e.jsx("div",{ref:c,"aria-hidden":!0,className:R("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:"flex h-9 items-center gap-1 rounded-lg bg-accent px-1.5 text-accent-foreground",children:t.map(u=>{const m=u.icon;return e.jsxs("div",{className:"flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold",children:[m?e.jsx(m,{className:"h-4 w-4"}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})}),e.jsx("div",{className:"relative z-20 flex h-9 items-center gap-1 rounded-lg bg-muted/20 px-1.5",children:t.map(u=>{const m=r===u.value,f=u.icon;return e.jsxs("button",{ref:m?l:null,type:"button",onClick:()=>{o&&s(u.value)},className:R("flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold transition-colors duration-150",m?"text-accent-foreground":"text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1 focus-visible:ring-offset-background"),"aria-pressed":m,"aria-disabled":!o,tabIndex:o?0:-1,children:[f?e.jsx(f,{className:R("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const Fk=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,Rk=t=>{const r=t.trim(),s=r.match(/^git@github\.com:([^/\s]+)\/([^\s#]+)$/i);if(s)return`${s[1]}/${s[2].replace(/\.git$/i,"")}`;const n=r.match(/^https?:\/\/github\.com\/([^/\s]+)\/([^\s#]+)$/i);if(n)return`${n[1]}/${n[2].replace(/\.git$/i,"")}`;const o=r.match(/^([^/\s]+)\/([^/\s]+)(?:\/.+)?$/);return o?`${o[1]}/${o[2].replace(/\.git$/i,"")}`:r},Lk=async()=>{try{if(ds())return await zr();const t=Ps()?.settings;if(t)return(await t.load())?.settings||{};const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return r.ok?await r.json().catch(()=>null):null}catch{return null}},Ok=({open:t,onOpenChange:r})=>{const{scanRepo:s,loadCatalog:n,isScanning:o}=qo(),a=co(w=>w.defaultGitIdentityId),c=co(w=>w.loadDefaultGitIdentityId),[l,d]=i.useState(""),[u,m]=i.useState(""),[f,p]=i.useState(""),[h,g]=i.useState([]),[x,b]=i.useState(null),[y,v]=i.useState(!1),[S,C]=i.useState([]),[N,j]=i.useState(null);i.useEffect(()=>{t&&(d(""),m(""),p(""),b(null),v(!1),C([]),j(null),c(),(async()=>{const w=await Lk(),T=Array.isArray(w?.skillCatalogs)?w?.skillCatalogs:[];g(T||[])})())},[t,c]);const D=i.useMemo(()=>{const w=u.trim(),T=f.trim();return h.some(E=>{const I=(E.source||"").trim(),A=(E.subpath||"").trim();return I===w&&A===T})},[h,u,f]),k=async()=>{const w=u.trim();if(!w){V.error("Repository source is required");return}l.trim()||d(Rk(w)),v(!1),b(null);const T=await s({source:w,subpath:f.trim()||void 0,gitIdentityId:N||void 0});if(!T.ok){if(T.error?.kind==="authRequired"){if(zt()){V.error("Private repositories are not supported in VS Code yet");return}const I=T.error.identities||[];if(C(I),!N&&I.length>0){const A=a&&a!=="global"&&I.some(P=>P.id===a)?a:I[0].id;j(A)}V.error("Authentication required. Select a Git identity and scan again.");return}V.error(T.error?.message||"Failed to scan repository");return}const E=T.items?.length||0;if(b(E),E===0){V.error("No skills found in this repository"),v(!1);return}C([]),v(!0),V.success(`Found ${E} skill(s)`)},M=async()=>{const w=l.trim(),T=u.trim(),E=f.trim();if(!w){V.error("Catalog name is required");return}if(!T){V.error("Repository source is required");return}if(!y){V.error("Scan the repository before adding this catalog");return}if(D){V.error("This catalog already exists");return}const I={id:Fk(),label:w,source:T,...E?{subpath:E}:{},...N?{gitIdentityId:N}:{}},A=[...h,I];try{await as({skillCatalogs:A}),g(A),V.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(P){V.error(P instanceof Error?P.message:"Failed to save catalog")}};return e.jsx(us,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Add skills catalog"}),e.jsxs(Ss,{children:["Add a Git repository as a new catalog source. OpenChamber will scan it for folders containing ",e.jsx("code",{className:"font-mono",children:"SKILL.md"}),"."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Catalog name"}),e.jsx(St,{value:l,onChange:w=>d(w.target.value),placeholder:"e.g. Team Skills"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Repository"}),e.jsx(St,{value:u,onChange:w=>{m(w.target.value),v(!1),b(null)},placeholder:"owner/repo or git@github.com:owner/repo.git"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Public repos work everywhere. Private repos require SSH identity (Desktop/Web only)."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Optional subpath"}),e.jsx(St,{value:f,onChange:w=>{p(w.target.value),v(!1),b(null)},placeholder:"e.g. skills"})]}),S.length>0&&!zt()?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Authentication required"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:"Select a Git identity (SSH key) that can access this repository."}),e.jsx("div",{className:"mt-2",children:e.jsxs(As,{value:N||"",onValueChange:w=>j(w),children:[e.jsx(Es,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:S.find(w=>w.id===N)?.name||"Choose identity"})}),e.jsx(Is,{align:"start",children:S.map(w=>e.jsx(Bt,{value:w.id,className:"pr-2 [&>span:first-child]:hidden",children:w.name},w.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,x!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",x," skill(s) found"]}):null,D?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(Se,{variant:"outline",onClick:()=>{k()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(Um,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Se,{variant:"default",onClick:()=>{M()},disabled:!y||D||!l.trim()||!u.trim(),children:"Add catalog"})]})]})})},_k=({open:t,onOpenChange:r,conflicts:s,onConfirm:n})=>{const[o,a]=i.useState({});i.useEffect(()=>{if(!t)return;const d={};for(const u of s)d[u.skillName]="skip";a(d)},[t,s]);const c=d=>{const u={};for(const m of s)u[m.skillName]=d;a(u)},l=s.length>0&&s.every(d=>o[d.skillName]);return e.jsx(us,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Skills already exist"}),e.jsx(Ss,{children:"Some selected skills are already installed in this scope. Choose whether to skip or overwrite them."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[s.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{variant:"outline",size:"sm",onClick:()=>c("skip"),children:"Skip all"}),e.jsx(Se,{variant:"outline",size:"sm",onClick:()=>c("overwrite"),children:"Overwrite all"})]})]}),e.jsx("div",{className:"space-y-2",children:s.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label truncate",children:d.skillName}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Installed in ",d.scope," scope"]})]}),e.jsxs(As,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Es,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(Is,{align:"end",children:[e.jsx(Bt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Bt,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Dn,{onClick:()=>n(o),disabled:!l,children:"Continue"})]})]})})},$k=({open:t,onOpenChange:r,item:s})=>{const{installSkills:n,isInstalling:o}=qo(),[a,c]=i.useState("user"),[l,d]=i.useState(!1),[u,m]=i.useState([]),[f,p]=i.useState(null);i.useEffect(()=>{t&&(c("user"),d(!1),m([]),p(null))},[t]);const h=async g=>{const x={skillDir:g.skillDir};s?.clawdhub&&(x.clawdhub={slug:s.clawdhub.slug,version:s.clawdhub.version});const b=await n({source:g.source,subpath:g.subpath,gitIdentityId:s?.gitIdentityId,scope:g.scope,selections:[x],conflictPolicy:"prompt",conflictDecisions:g.conflictDecisions});if(b.ok){V.success("Skill installed successfully"),r(!1);return}if(b.error?.kind==="conflicts"){p({source:g.source,subpath:g.subpath,scope:g.scope,skillDir:g.skillDir}),m(b.error.conflicts),d(!0);return}if(b.error?.kind==="authRequired"){V.error(b.error.message||"Authentication required");return}V.error(b.error?.message||"Failed to install skill")};return s?e.jsxs(e.Fragment,{children:[e.jsx(us,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Install skill"}),e.jsxs(Ss,{children:["Install ",e.jsx("span",{className:"font-semibold text-foreground",children:s.skillName})," into user or project scope."]})]}),e.jsx("div",{className:"space-y-3",children:s.warnings?.length?e.jsxs("div",{className:"rounded-lg border bg-muted/30 px-3 py-2",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Warnings"}),e.jsx("ul",{className:"mt-1 space-y-1",children:s.warnings.map(g=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:g},g))})]}):null}),e.jsxs(Gs,{className:"flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-center",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(As,{value:a,onValueChange:g=>c(g),children:[e.jsx(Es,{className:"!h-9 w-full sm:w-36 justify-between",children:e.jsxs("span",{className:"flex flex-1 items-center gap-2 justify-start",children:[a==="user"?e.jsx(rr,{className:"h-4 w-4"}):e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Is,{align:"start",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rr,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]})})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(Se,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Se,{className:"w-full sm:w-auto",variant:"default",disabled:o||!s.installable,onClick:()=>{h({source:s.repoSource,subpath:s.repoSubpath,scope:a,skillDir:s.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(_k,{open:l,onOpenChange:d,conflicts:u,onConfirm:g=>{f&&(h({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:g}),d(!1))}})]}):null},Bk=async()=>{try{if(ds())return await zr();const t=Ps()?.settings;if(t)return(await t.load())?.settings||{};const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return r.ok?await r.json().catch(()=>null):null}catch{return null}},zk=({mode:t,onModeChange:r})=>{const{sources:s,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:c,loadSource:l,loadMoreClawdHub:d,isLoadingCatalog:u,isLoadingSource:m,isLoadingMore:f,loadedSourceIds:p,clawdhubHasMoreBySource:h,lastCatalogError:g}=qo(),[x,b]=i.useState(""),[y,v]=i.useState(!1),[S,C]=i.useState(!1),[N,j]=i.useState(null),[D,k]=i.useState(!1);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{o&&(p[o]||l(o))},[o,p,l]);const M=i.useMemo(()=>o?n[o]||[]:[],[n,o]),w=i.useMemo(()=>{const F=x.trim().toLowerCase();return F?M.filter(z=>{const G=z.skillName.toLowerCase(),oe=(z.description||"").toLowerCase(),O=(z.frontmatterName||"").toLowerCase();return G.includes(F)||oe.includes(F)||O.includes(F)}):M},[M,x]),T=i.useMemo(()=>s.find(F=>F.id===o)||null,[s,o]),E=!!(o&&o.startsWith("custom:")),I=T?.source==="clawdhub:registry"||T?.sourceType==="clawdhub",A=!!(o&&(h[o]??!0)),P=async()=>{if(!(!o||!E)&&window.confirm("Remove this catalog?")){k(!0);try{const F=await Bk(),G=(Array.isArray(F?.skillCatalogs)?F?.skillCatalogs:[]).filter(oe=>oe.id!==o);await as({skillCatalogs:G}),await c({refresh:!0})}finally{k(!1)}}};return e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(mh,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:t,onValueChange:r,animate:!1}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Skills Catalog"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Browse curated repositories and install skills into your OpenCode configuration."})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Source"}),e.jsxs(As,{value:o||"",onValueChange:F=>a(F),children:[e.jsx(Es,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:T?.label||"Select source"})}),e.jsx(Is,{align:"start",children:s.map(F=>e.jsx(Bt,{value:F.id,className:"pr-2 [&>span:first-child]:hidden",children:F.label},F.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Se,{type:"button",variant:"outline",onClick:()=>{o?l(o,{refresh:!0}):c({refresh:!0})},disabled:u||m,className:"gap-2",children:[e.jsx(en,{className:"h-4 w-4"}),"Refresh"]}),E?e.jsxs(Se,{type:"button",variant:"outline",onClick:()=>{P()},disabled:D,className:"gap-2",children:[e.jsx(zs,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Se,{type:"button",variant:"default",onClick:()=>v(!0),className:"gap-2",children:[e.jsx(ls,{className:"h-4 w-4"}),"Add catalog"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(St,{value:x,onChange:F=>b(F.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:u?"Loading…":`${w.length} skill(s)`})]}),g?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Catalog error"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:g.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:w.length===0&&!m?e.jsxs("div",{className:"py-10 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"No skills found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Try a different search or refresh the catalog"})]}):m?e.jsx("div",{className:"py-10 text-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Loading skills…"})}):e.jsxs(e.Fragment,{children:[w.map(F=>{const z=F.installed?.isInstalled,G=F.installed?.scope;return e.jsx("div",{className:"rounded-lg border bg-muted/10 px-3 py-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"typography-ui-label truncate",children:F.skillName}),z?e.jsxs("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:["installed (",G||"unknown",")"]}):null,F.installable?null:e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"not installable"})]}),F.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:F.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),F.clawdhub?e.jsxs("div",{className:"typography-micro text-muted-foreground mt-1 flex items-center gap-3",children:[F.clawdhub.owner?e.jsxs("span",{children:["by ",F.clawdhub.owner]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tn,{className:"h-3 w-3"}),F.clawdhub.downloads?.toLocaleString()??0]}),(F.clawdhub.stars??0)>0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jn,{className:"h-3 w-3"}),F.clawdhub.stars]}):null,e.jsxs("span",{children:["v",F.clawdhub.version]})]}):null,F.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:F.warnings.join(" · ")}):null]}),e.jsx(Se,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!F.installable,onClick:()=>{j(F),C(!0)},children:"Install"})]})},`${F.sourceId}:${F.skillDir}`)}),I&&A?e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(Se,{type:"button",variant:"outline",onClick:()=>{d()},disabled:f||m,children:f?"Loading…":"Load more"})}):null]})}),e.jsx(Ok,{open:y,onOpenChange:v}),e.jsx($k,{open:S,onOpenChange:C,item:N})]})})},Hk=()=>{const{selectedSkillName:t,getSkillByName:r,getSkillDetail:s,createSkill:n,updateSkill:o,skills:a,skillDraft:c,setSkillDraft:l,setSelectedSkill:d}=fr(),u=t?r(t):null,m=!!(c&&c.name===t&&!u),f=!!(t&&!u&&!c),[p,h]=i.useState("manual");i.useEffect(()=>{!m&&p!=="manual"&&h("manual")},[m,p]),i.useEffect(()=>{f&&d(null)},[f,d]);const g=m?e.jsx(mh,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[x,b]=i.useState(""),[y,v]=i.useState("user"),[S,C]=i.useState(""),[N,j]=i.useState(""),[D,k]=i.useState([]),[M,w]=i.useState([]),[T,E]=i.useState(!1),[I,A]=i.useState(!1),[P,F]=i.useState(""),[z,G]=i.useState(""),[oe,O]=i.useState(!1),[q,Y]=i.useState(""),[Z,B]=i.useState(""),[W,te]=i.useState(null),[ye,me]=i.useState(!1),[K,L]=i.useState(""),Q=m?x.trim()!==""||S.trim()!==""||N.trim()!==""||M.length>0:S!==P||N!==z,ce=W?Z!==K:q.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&c)b(c.name||""),v(c.scope||"user"),C(c.description||""),j(c.instructions||""),F(""),G(""),k([]),w(c.pendingFiles||[]);else if(t&&u){A(!0);try{const ge=await s(t);if(ge){const X=ge.sources.md;C(X.description||""),j(X.instructions||""),F(X.description||""),G(X.instructions||""),k(X.supportingFiles||[])}}catch(ge){console.error("Failed to load skill details:",ge)}finally{A(!1)}}})()},[u,m,t,a,c,s,p]);const he=async()=>{const ue=m?x.trim().replace(/\s+/g,"-").toLowerCase():t?.trim();if(!ue){V.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(ue)||ue.length>64){V.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!S.trim()){V.error("Description is required");return}if(m&&a.some(ge=>ge.name===ue)){V.error("A skill with this name already exists");return}E(!0);try{const ge={name:ue,description:S.trim(),instructions:N.trim()||void 0,scope:m?y:void 0,supportingFiles:m&&M.length>0?M:void 0};let X;m?(X=await n(ge),X&&(l(null),w([]),d(ue))):(X=await o(ue,ge),X&&(F(S.trim()),G(N.trim()))),X?V.success(m?"Skill created successfully":"Skill updated successfully"):V.error(m?"Failed to create skill":"Failed to update skill")}catch(ge){console.error("Error saving skill:",ge),V.error("An error occurred while saving")}finally{E(!1)}},Ne=()=>{te(null),Y(""),B(""),L(""),O(!0)},H=async ue=>{if(te(ue),Y(ue),m){const X=M.find(de=>de.path===ue)?.content||"";B(X),L(X),O(!0);return}if(t){me(!0),O(!0);try{const{readSupportingFile:ge}=fr.getState(),X=await ge(t,ue);B(X||""),L(X||"")}catch{V.error("Failed to load file content"),B(""),L("")}finally{me(!1)}}},we=async()=>{if(!q.trim()){V.error("File name is required");return}const ue=q.trim(),ge=W!==null;if(m){if(ge)w(ae=>ae.map(fe=>fe.path===W?{path:ue,content:Z}:fe)),V.success(`File "${ue}" updated`);else{if(M.some(ae=>ae.path===ue)){V.error("A file with this name already exists");return}w(ae=>[...ae,{path:ue,content:Z}]),V.success(`File "${ue}" added`)}O(!1),te(null);return}if(!t){V.error("No skill selected");return}const{writeSupportingFile:X}=fr.getState();if(await X(t,ue,Z)){V.success(ge?`File "${ue}" updated`:`File "${ue}" created`),O(!1),te(null);const ae=await s(t);ae&&k(ae.sources.md.supportingFiles||[])}else V.error(ge?"Failed to update file":"Failed to create file")},ee=async ue=>{if(m){w(ge=>ge.filter(X=>X.path!==ue)),V.success(`File "${ue}" removed`);return}if(t&&window.confirm(`Are you sure you want to delete "${ue}"?`)){const{deleteSupportingFile:ge}=fr.getState();if(await ge(t,ue)){V.success(`File "${ue}" deleted`);const de=await s(t);de&&k(de.sources.md.supportingFiles||[])}else V.error("Failed to delete file")}};return m&&p==="external"?e.jsx(zk,{mode:p,onModeChange:h}):!t&&!c||f?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(df,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a skill from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})}):I?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Loading skill details..."})})}):e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[m?g:null,e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:m?"New Skill":t}),u&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:[u.scope==="project"?"Project":"User"," skill",u.source==="claude"&&" (Claude-compatible)"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure skill identity and description"})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Skill Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{value:x,onChange:ue=>b(ue.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(As,{value:y,onValueChange:ue=>v(ue),children:[e.jsxs(Es,{className:"!h-9 w-auto gap-1.5",children:[y==="user"?e.jsx(rr,{className:"h-4 w-4"}):e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:y})]}),e.jsxs(Is,{align:"end",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rr,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Available in all projects"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Lowercase letters, numbers, and hyphens only. Cannot start or end with hyphen."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Description ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Fs,{value:S,onChange:ue=>C(ue.target.value),placeholder:"Brief description of what this skill does...",rows:2,className:"max-h-32 resize-none"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The agent uses this to decide when to load the skill"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Instructions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Detailed instructions for the agent when this skill is loaded"})]}),e.jsx(Fs,{value:N,onChange:ue=>j(ue.target.value),placeholder:"Step-by-step instructions, guidelines, or reference content...",rows:12,className:"font-mono typography-meta max-h-80 resize-y"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Supporting Files"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Reference documentation, scripts, or templates"})]}),e.jsxs(Se,{variant:"outline",size:"sm",onClick:Ne,className:"gap-1.5",children:[e.jsx(ls,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const ue=m?M:D;return ue.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-2",children:m?'No files yet. Use "Add File" to include reference materials.':'No supporting files. Use "Add File" to include reference materials.'}):e.jsx("div",{className:"space-y-2",children:ue.map(ge=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg border bg-muted/30 hover:bg-muted/50 cursor-pointer transition-colors",onClick:()=>H(ge.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(jr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:ge.path}),m&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"pending"})]}),e.jsx(Se,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:X=>{X.stopPropagation(),ee(ge.path)},children:e.jsx(zs,{className:"h-3.5 w-3.5"})})]},ge.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Se,{size:"sm",variant:"default",onClick:he,disabled:T||!Q,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(gi,{className:"h-3 w-3"}),T?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(us,{open:oe,onOpenChange:ue=>{O(ue),ue||te(null)},children:e.jsxs(ms,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(xs,{className:"flex-shrink-0",children:[e.jsx(ys,{children:W?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ss,{children:W?"Modify the file content":"Create a new file in the skill directory"})]}),ye?e.jsx("div",{className:"flex-1 flex items-center justify-center py-8",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Loading file content..."})}):e.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"File Path"}),e.jsx(St,{value:q,onChange:ue=>Y(ue.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:W!==null}),!W&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Relative path within the skill directory. Subdirectories will be created automatically."})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-h-0 flex flex-col",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:"Content"}),e.jsx(Fs,{value:Z,onChange:ue=>B(ue.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>{O(!1),te(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Dn,{onClick:we,disabled:ye||!ce,children:W?"Save Changes":"Create File"})]})]})})]})})},Wk="__add_provider__",Uk=({onItemSelect:t})=>{const r=Je(u=>u.providers),s=Je(u=>u.selectedProviderId),n=Je(u=>u.setSelectedProvider),{isMobile:o}=Gt(),[a,c]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||c(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",d),children:[e.jsx("div",{className:R("border-b px-3",o?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",r.length]}),e.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(Wk),t?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(ls,{className:"size-4"})})]})}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:r.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(ro,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No providers found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Check your OpenCode configuration"})]}):r.map(u=>{const m=Array.isArray(u.models)?u.models.length:0,f=u.id===s;return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",f?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{type:"button",onClick:()=>{n(u.id),t?.()},className:"flex min-w-0 flex-1 items-center gap-2 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsx(gs,{providerId:u.id,className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 min-w-0 text-foreground",children:u.name||u.id}),e.jsx("span",{className:"typography-micro text-muted-foreground/60 flex-shrink-0",children:m})]})},u.id)})})]})},Vk=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),cm=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const r=Vk.format(t);return r.endsWith(".0")?r.slice(0,-2):r},zn="__add_provider__",mo=t=>typeof t=="object"&&t!==null,lm=t=>{const r=typeof t.type=="string"?t.type:"",s=`${t.name??""} ${t.label??""}`.toLowerCase(),n=`${r} ${s}`.toLowerCase();return n.includes("oauth")?"oauth":n.includes("api")?"api":r.toLowerCase()},Gk=t=>{if(!mo(t))return{};const r={};for(const[s,n]of Object.entries(t))Array.isArray(n)&&(r[s]=n.filter(o=>mo(o)));return r},qk=t=>{if(typeof t=="string")return{id:t};if(!mo(t))return null;const r=typeof t.id=="string"&&t.id||typeof t.providerID=="string"&&t.providerID||typeof t.slug=="string"&&t.slug||typeof t.name=="string"&&t.name;if(!r)return null;const s=typeof t.name=="string"?t.name:void 0;return{id:r,name:s}},Kk=t=>{let r=[];Array.isArray(t)?r=t:mo(t)&&(Array.isArray(t.all)?r=t.all:Array.isArray(t.providers)&&(r=t.providers));const s=r.map(o=>qk(o)).filter(o=>!!o),n=new Set;return s.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},Jk=()=>{const t=Je(H=>H.providers),r=Je(H=>H.selectedProviderId),s=Je(H=>H.setSelectedProvider),n=Je(H=>H.getModelMetadata),[o,a]=i.useState({}),[c,l]=i.useState(!1),[d,u]=i.useState({}),[m,f]=i.useState(null),[p,h]=i.useState(""),[g,x]=i.useState(null),[b,y]=i.useState({}),[v,S]=i.useState({}),[C,N]=i.useState([]),[j,D]=i.useState(!1),[k,M]=i.useState(null),[w,T]=i.useState(""),[E,I]=i.useState(""),[A,P]=i.useState(!1),[F,z]=i.useState({}),[G,oe]=i.useState(!1);i.useEffect(()=>{!r&&t.length>0&&s(t[0].id)},[t,r,s]),i.useEffect(()=>{let H=!0;return(async()=>{l(!0);try{const ee=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!ee.ok)throw new Error(`Auth methods request failed (${ee.status})`);const ue=await ee.json().catch(()=>({}));if(!H)return;a(Gk(ue))}catch(ee){if(!H)return;console.error("Failed to load provider auth methods:",ee),V.error("Failed to load provider authentication methods")}finally{H&&l(!1)}})(),()=>{H=!1}},[]),i.useEffect(()=>{let H=!0;return(async()=>{D(!0),M(null);try{const ee=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!ee.ok)throw new Error(`Provider list request failed (${ee.status})`);const ue=await ee.json().catch(()=>({}));if(!H)return;N(Kk(ue))}catch(ee){if(!H)return;console.error("Failed to load available providers:",ee),M("Unable to load provider list")}finally{H&&D(!1)}})(),()=>{H=!1}},[]);const O=i.useMemo(()=>new Set(t.map(H=>H.id)),[t]),q=i.useMemo(()=>C.filter(H=>!O.has(H.id)),[C,O]);i.useEffect(()=>{if(r===zn){if(!w&&q.length>0){T(q[0].id);return}w&&!q.some(H=>H.id===w)&&T(q[0]?.id??"")}},[r,w,q]),i.useEffect(()=>{if(r===zn){oe(!0);return}oe(!1)},[r]),i.useEffect(()=>{if(!r||r===zn)return;let H=!1;return(async()=>{try{const ee=await fetch(`/api/provider/${encodeURIComponent(r)}/source`,{method:"GET",headers:{Accept:"application/json"}}),ue=await ee.json().catch(()=>null);if(!ee.ok)throw new Error(ue?.error||"Failed to load provider sources");const ge=ue?.sources??ue?.data?.sources;!H&&ge&&z(X=>({...X,[r]:ge}))}catch(ee){H||console.error("Failed to load provider sources:",ee)}})(),()=>{H=!0}},[r]);const Y=t.find(H=>H.id===r),Z=r?F[r]:void 0,B=async H=>{const we=d[H]?.trim()??"";if(!we){V.error("API key is required");return}const ee=`api:${H}`;f(ee);try{const ue=await fetch(`/api/auth/${encodeURIComponent(H)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:we})}),ge=await ue.json().catch(()=>null);if(!ue.ok){const X=ge?.error||"Failed to save API key";throw new Error(X)}V.success("API key saved"),u(X=>({...X,[H]:""})),await Ao({scopes:["providers"],mode:"active"}),s(H)}catch(ue){console.error("Failed to save API key:",ue),V.error("Failed to save API key")}finally{f(null)}},W=async(H,we)=>{const ee=`oauth:${H}:${we}`;f(ee);try{const ue=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:we})}),ge=await ue.json().catch(()=>null);if(!ue.ok){const re=ge?.error||"Failed to start OAuth flow";throw new Error(re)}const X=mo(ge)?ge:{},de=mo(X.data)?X.data:X,ae=typeof de.url=="string"&&de.url||typeof de.verification_uri_complete=="string"&&de.verification_uri_complete||typeof de.verification_uri=="string"&&de.verification_uri||void 0,fe=typeof de.instructions=="string"&&de.instructions||typeof de.message=="string"&&de.message||void 0,ie=typeof de.user_code=="string"&&de.user_code||typeof de.code=="string"&&de.code||typeof de.userCode=="string"&&de.userCode||void 0;if(!ae&&!fe&&!ie)throw new Error("No OAuth details returned");const se=`${H}:${we}`;S(re=>({...re,[se]:{url:ae,instructions:fe,userCode:ie}})),ae&&window.open(ae,"_blank","noopener,noreferrer"),x({providerId:H,methodIndex:we}),V.message("Complete the OAuth flow in your browser")}catch(ue){console.error("Failed to start OAuth flow:",ue),V.error("Failed to start OAuth flow")}finally{f(null)}},te=async(H,we)=>{const ee=`${H}:${we}`,ue=b[ee]?.trim(),ge=`oauth-complete:${H}:${we}`;f(ge);try{const X={method:we};ue&&(X.code=ue);const de=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),ae=await de.json().catch(()=>null);if(!de.ok){const fe=ae?.error||"Failed to complete OAuth flow";throw new Error(fe)}V.success("OAuth connection completed"),y(fe=>({...fe,[ee]:""})),x(null),await Ao({scopes:["providers"],mode:"active"}),s(H)}catch(X){console.error("Failed to complete OAuth flow:",X),V.error("Failed to complete OAuth flow")}finally{f(null)}},ye=async H=>{try{await navigator.clipboard.writeText(H),V.success("OAuth link copied")}catch(we){console.error("Failed to copy OAuth link:",we),V.error("Failed to copy OAuth link")}},me=async H=>{try{await navigator.clipboard.writeText(H),V.success("Device code copied")}catch(we){console.error("Failed to copy device code:",we),V.error("Failed to copy device code")}},K=async H=>{const we=`disconnect:${H}`;f(we);try{const ee=await fetch(`/api/provider/${encodeURIComponent(H)}/auth?scope=all`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),ue=await ee.json().catch(()=>null);if(!ee.ok){const ge=ue?.error||"Failed to disconnect provider";throw new Error(ge)}V.success("Provider disconnected"),await Ao({scopes:["providers"],mode:"active"})}catch(ee){console.error("Failed to disconnect provider:",ee),V.error("Failed to disconnect provider")}finally{f(null)}},L=r===zn;if(!L&&t.length===0)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(ro,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"No providers detected"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Check your OpenCode configuration"})]})});if(L)return e.jsx(xt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Connect provider"}),e.jsx("p",{className:"typography-body text-muted-foreground",children:"Choose a provider to connect and set up its authentication."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Provider"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select a provider that is not connected yet."})]}),j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):k?e.jsx("p",{className:"typography-meta text-muted-foreground",children:k}):q.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(ts,{open:A,onOpenChange:H=>{P(H),H||I("")},children:[e.jsx(ss,{asChild:!0,children:e.jsxs("button",{type:"button",className:R("flex w-fit items-center justify-between gap-2 rounded-lg border border-input bg-transparent px-3 py-2 typography-ui-label","hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[e.jsx("span",{className:w?"text-foreground":"text-muted-foreground",children:w?q.find(H=>H.id===w)?.name||w:"Select provider"}),e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(rs,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:H=>H.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:H=>H.stopPropagation(),children:[e.jsx(Vs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:E,onChange:H=>I(H.target.value),onKeyDown:H=>H.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(xt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const H=q.filter(we=>{const ee=E.toLowerCase();return(we.name||we.id).toLowerCase().includes(ee)||we.id.toLowerCase().includes(ee)});return H.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):H.map(we=>e.jsxs(kt,{onSelect:()=>{T(we.id),P(!1),I("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:we.name||we.id}),w===we.id&&e.jsx(Tt,{className:"h-4 w-4 text-primary"})]},we.id))})()})]})]})]}),w&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),c?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{type:"password",value:d[w]??"",onChange:H=>u(we=>({...we,[w]:H.target.value})),placeholder:"sk-..."}),e.jsx(Se,{size:"sm",onClick:()=>B(w),disabled:m===`api:${w}`,className:"h-8",children:m===`api:${w}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by OpenChamber."})]}),(()=>{const we=(o[w]??[]).filter(ee=>lm(ee)==="oauth");return we.length===0?null:e.jsx("div",{className:"space-y-3",children:we.map((ee,ue)=>{const ge=ee.label||ee.name||`OAuth method ${ue+1}`,X=`${w}:${ue}`,de=g?.providerId===w&&g?.methodIndex===ue;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:ge}),(ee.description||ee.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(ee.description||ee.help)})]}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>W(w,ue),disabled:m===`oauth:${w}:${ue}`,className:"h-8",children:"Connect"})]}),v[X]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[X]?.instructions}),v[X]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:v[X]?.userCode,readOnly:!0}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>me(v[X]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[X]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:v[X]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[X]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>ye(v[X]?.url??""),className:"h-8",children:"Copy link"})]})]}),de&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:b[X]??"",onChange:ae=>y(fe=>({...fe,[X]:ae.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Se,{size:"sm",onClick:()=>te(w,ue),disabled:m===`oauth-complete:${w}:${ue}`,className:"h-8",children:m===`oauth-complete:${w}:${ue}`?"Saving…":"Complete"})]})]},`${w}-${ge}`)})})})()]})]})]})});if(!Y)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(ro,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a provider from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Review details and configure auth"})]})});const Q=Array.isArray(Y.models)?Y.models:[],he=(o[Y.id]??[]).filter(H=>lm(H)==="oauth"),Ne=Q.filter(H=>{const we=typeof H?.name=="string"?H.name:"",ee=typeof H?.id=="string"?H.id:"",ue=p.trim().toLowerCase();return ue?we.toLowerCase().includes(ue)||ee.toLowerCase().includes(ue):!0});return e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{providerId:Y.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:Y.name||Y.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",Y.id]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),r!==zn&&e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>oe(H=>!H),className:"h-8",children:G?"Hide":"Reconnect"})]}),!G&&r!==zn?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Connected. Use Reconnect to update credentials."}):c?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{type:"password",value:d[Y.id]??"",onChange:H=>u(we=>({...we,[Y.id]:H.target.value})),placeholder:"sk-..."}),e.jsx(Se,{size:"sm",onClick:()=>B(Y.id),disabled:m===`api:${Y.id}`,className:"h-8",children:m===`api:${Y.id}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by OpenChamber."})]}),he.length>0&&e.jsx("div",{className:"space-y-3",children:he.map((H,we)=>{const ee=H.label||H.name||`OAuth method ${we+1}`,ue=`${Y.id}:${we}`,ge=g?.providerId===Y.id&&g?.methodIndex===we;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:ee}),(H.description||H.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(H.description||H.help)})]}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>W(Y.id,we),disabled:m===`oauth:${Y.id}:${we}`,className:"h-8",children:"Connect"})]}),v[ue]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[ue]?.instructions}),v[ue]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:v[ue]?.userCode,readOnly:!0}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>me(v[ue]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[ue]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:v[ue]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Se,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[ue]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>ye(v[ue]?.url??""),className:"h-8",children:"Copy link"})]})]}),ge&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:b[ue]??"",onChange:X=>y(de=>({...de,[ue]:X.target.value})),placeholder:"Paste authorization code"}),e.jsx(Se,{size:"sm",onClick:()=>te(Y.id,we),disabled:m===`oauth-complete:${Y.id}:${we}`,className:"h-8",children:m===`oauth-complete:${Y.id}:${we}`?"Saving…":"Complete"})]})]},`${Y.id}-${ee}`)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Connection"}),Z&&(Z.auth.exists||Z.user.exists||Z.project.exists||Z.custom?.exists)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Configured in: ",[Z.auth.exists?"auth credentials":null,Z.user.exists?"user config":null,Z.project.exists?"project config":null,Z.custom?.exists?"custom config":null].filter(Boolean).join(", ")]}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>K(Y.id),disabled:m===`disconnect:${Y.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${Y.id}`?"Disconnecting…":"Disconnect provider"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Models"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Browse and filter models exposed by this provider."})]}),e.jsx(St,{value:p,onChange:H=>h(H.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:Ne.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):Ne.map(H=>{const we=typeof H?.id=="string"?H.id:"",ee=typeof H?.name=="string"?H.name:we,ue=we?n(Y.id,we):void 0,ge=cm(ue?.limit?.context),X=cm(ue?.limit?.output),de=[];return ue?.tool_call&&de.push({key:"tools",icon:pi,label:"Tool calling"}),ue?.reasoning&&de.push({key:"reasoning",icon:Mr,label:"Reasoning"}),ue?.attachment&&de.push({key:"image",icon:Ar,label:"Image input"}),e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate flex-1 min-w-0",children:ee}),(ge||X)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[ge?`${ge} ctx`:"",ge&&X?" · ":"",X?`${X} out`:""]}),de.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:de.map(({key:ae,icon:fe,label:ie})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:ie,"aria-label":ie,children:e.jsx(fe,{className:"h-3 w-3"})},ae))})]},we)})})]})]})})},Qk={branch:Ut,briefcase:ml,house:ul,graduation:dl,code:sr,heart:of},Yk={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Xk=({onItemSelect:t})=>{const{selectedProfileId:r,defaultGitIdentityId:s,profiles:n,globalIdentity:o,setSelectedProfile:a,deleteProfile:c,loadProfiles:l,loadGlobalIdentity:d,loadDiscoveredCredentials:u,loadDefaultGitIdentityId:m,setDefaultGitIdentityId:f,getUnimportedCredentials:p}=co(),{setSidebarOpen:h}=Me(),{isMobile:g}=Gt(),[x,b]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||b(typeof window.opencodeDesktop<"u")},[]);const v=p();i.useEffect(()=>{l(),d(),u(),m()},[l,d,u,m]);const S=k=>{a(`import:${k.host}:${k.username}`),t?.(),g&&h(!1)},C=x?"bg-transparent":y?"bg-background":"bg-sidebar",N=()=>{a("new"),t?.(),g&&h(!1)},j=async k=>{window.confirm(`Are you sure you want to delete profile "${k.name}"?`)&&(await c(k.id)?V.success(`Profile "${k.name}" deleted successfully`):V.error("Failed to delete profile"))},D=async k=>{const M=s===k?null:k;if(!await f(M)){V.error("Failed to update default identity");return}V.success(M?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:R("flex h-full flex-col",C),children:[e.jsx("div",{className:R("border-b px-3",g?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",n.length]}),e.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:N,"aria-label":"Create new profile",children:e.jsx(ls,{className:"size-4"})})]})}),e.jsxs(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"System Default"}),e.jsx(dm,{profile:o,isSelected:r==="global",isDefault:s==="global",onSelect:()=>{a("global"),t?.(),g&&h(!1)},onToggleDefault:()=>D("global"),onDelete:void 0,isReadOnly:!0})]}),n.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),n.length===0&&!o&&v.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ut,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:n.map(k=>e.jsx(dm,{profile:k,isSelected:r===k.id,isDefault:s===k.id,onSelect:()=>{a(k.id),t?.(),g&&h(!1)},onToggleDefault:()=>D(k.id),onDelete:()=>j(k)},k.id))}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Discovered Credentials"}),e.jsx("p",{className:"px-2 pb-2 typography-micro text-muted-foreground/60",children:"Found in ~/.git-credentials"}),v.map(k=>e.jsx(eC,{credential:k,onImport:()=>S(k)},`${k.host}-${k.username}`))]})]})]})},dm=({profile:t,isSelected:r,isDefault:s=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:c=!1})=>{const l=Qk[t.icon||"branch"]||Ut,d=Yk[t.color||""],u=t.authType||"ssh";return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:n,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l,{className:"w-4 h-4 flex-shrink-0",style:{color:d}}),e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t.name}),e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:u}),s&&e.jsx("span",{className:"typography-micro text-primary bg-primary/12 px-1 rounded flex-shrink-0 leading-none pb-px border border-primary/25",children:"default"})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:u==="token"&&t.host?t.host:t.userEmail})]}),(o||!c&&a)&&e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(Se,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100","aria-label":"Profile actions",children:e.jsx(nn,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(kt,{onClick:m=>{m.stopPropagation(),o()},children:s?"Unset default":"Set as default"}),!c&&a&&e.jsxs(kt,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},Zk=t=>{const r=t.split("/");return r.length>=3?r[r.length-1]:t},eC=({credential:t,onImport:r})=>{const s=Zk(t.host),n=t.host.includes("/");return e.jsx("div",{className:"group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 hover:dark:bg-accent/40 hover:bg-primary/6",children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:s})}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n?t.host:t.username})]}),e.jsxs(Se,{size:"sm",variant:"ghost",onClick:r,className:"h-6 px-2 text-xs gap-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:[e.jsx(tn,{className:"h-3 w-3"}),"Import"]})]})})},um=[{key:"keyword",label:"Green",cssVar:"var(--syntax-keyword)"},{key:"error",label:"Red",cssVar:"var(--status-error)"},{key:"string",label:"Cyan",cssVar:"var(--syntax-string)"},{key:"function",label:"Orange",cssVar:"var(--syntax-function)"},{key:"type",label:"Yellow",cssVar:"var(--syntax-type)"}],tC=[{key:"branch",Icon:Ut,label:"Branch"},{key:"briefcase",Icon:ml,label:"Work"},{key:"house",Icon:ul,label:"Personal"},{key:"graduation",Icon:dl,label:"School"},{key:"code",Icon:sr,label:"Code"}],sC=()=>{const{selectedProfileId:t,getProfileById:r,createProfile:s,updateProfile:n,deleteProfile:o}=co(),a=i.useMemo(()=>{if(t?.startsWith("import:")){const[,A,P]=t.split(":");return{host:A,username:P}}return null},[t]),c=i.useMemo(()=>t&&t!=="new"&&!a?r(t):null,[t,r,a]),l=t==="new"||a!==null,d=t==="global",[u,m]=i.useState(""),[f,p]=i.useState(""),[h,g]=i.useState(""),[x,b]=i.useState("ssh"),[y,v]=i.useState(""),[S,C]=i.useState(""),[N,j]=i.useState("keyword"),[D,k]=i.useState("branch"),[M,w]=i.useState(!1);i.useEffect(()=>{if(a){const A=a.host.split("/"),P=A.length>=3?A[A.length-1]:a.host;m(P),p(a.username),g(""),b("token"),v(""),C(a.host),j("string"),k("code")}else l?(m(""),p(""),g(""),b("ssh"),v(""),C(""),j("keyword"),k("branch")):c&&(m(c.name),p(c.userName),g(c.userEmail),b(c.authType||"ssh"),v(c.sshKey||""),C(c.host||""),j(c.color||"keyword"),k(c.icon||"branch"))},[c,l,t,a]);const T=async()=>{if(!f.trim()||!h.trim()){V.error("User name and email are required");return}if(x==="token"&&!S.trim()){V.error("Host is required for token-based authentication");return}w(!0);try{const A={name:u.trim()||f.trim(),userName:f.trim(),userEmail:h.trim(),authType:x,sshKey:x==="ssh"&&y.trim()||null,host:x==="token"&&S.trim()||null,color:N,icon:D};let P;if(l)P=await s(A);else if(t)P=await n(t,A);else return;P?V.success(l?"Profile created successfully":"Profile updated successfully"):V.error(l?"Failed to create profile":"Failed to update profile")}catch(A){console.error("Error saving profile:",A),V.error("An error occurred while saving")}finally{w(!1)}},E=async()=>{if(!(!t||l)&&confirm("Are you sure you want to delete this profile?"))try{await o(t)?V.success("Profile deleted successfully"):V.error("Failed to delete profile")}catch(A){console.error("Error deleting profile:",A),V.error("An error occurred while deleting")}},I=i.useMemo(()=>um.find(P=>P.key===N)?.cssVar||"var(--syntax-keyword)",[N]);return t?e.jsx(xt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:a?"Import Credential":l?"New Git Profile":d?"Global Identity":u||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:a?`Import token credential for ${a.host} - please fill in your email address`:l?"Create a new Git identity profile for your repositories":d?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!d&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Profile Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Basic profile settings and display name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Display Name"}),e.jsx(St,{value:u,onChange:A=>m(A.target.value),placeholder:"Work Profile, Personal, etc."}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Friendly name to identify this profile (optional, defaults to user name)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Color"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:um.map(A=>e.jsx("button",{onClick:()=>j(A.key),className:R("w-8 h-8 rounded-lg border-2 transition-all",N===A.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:A.cssVar},title:A.label},A.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Icon"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:tC.map(A=>{const P=A.Icon;return e.jsx("button",{onClick:()=>k(A.key),className:R("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",D===A.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:A.label,children:e.jsx(P,{className:"w-4 h-4",style:{color:I}})},A.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["The name that will appear in Git commit messages.",e.jsx("br",{}),"This is the author name shown in git log and GitHub/GitLab interfaces."]})]})]}),e.jsx(St,{value:f,onChange:A=>p(A.target.value),placeholder:"John Doe",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.name configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Email ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["The email address for Git commits.",e.jsx("br",{}),"This should match your email in GitHub/GitLab",e.jsx("br",{}),"to ensure proper attribution of commits."]})]})]}),e.jsx(St,{type:"email",value:h,onChange:A=>g(A.target.value),placeholder:"john@example.com",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Authentication Type",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["SSH: Uses SSH key for authentication",e.jsx("br",{}),"Token: Uses personal access token from ~/.git-credentials"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>b("ssh"),className:R("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",x==="ssh"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx(Kx,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>b("token"),className:R("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",x==="token"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx(Jx,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"Token (HTTPS)"})]})]})]}),x==="ssh"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["SSH Key Path",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Path to SSH private key used for Git authentication.",e.jsx("br",{}),"This key will be used for SSH Git operations.",e.jsx("br",{}),"Common paths: ~/.ssh/id_rsa, ~/.ssh/id_ed25519"]})]})]}),e.jsx(St,{value:y,onChange:A=>v(A.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),x==="token"&&!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Host ",e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["The Git host this credential applies to.",e.jsx("br",{}),"Token will be read from ~/.git-credentials for this host.",e.jsx("br",{}),"Examples: github.com, gitlab.com"]})]})]}),e.jsx(St,{value:S,onChange:A=>C(A.target.value),placeholder:"github.com",required:!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git host for token authentication (from ~/.git-credentials)"})]}),!d&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!l&&e.jsxs(Se,{size:"sm",variant:"destructive",onClick:E,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(zs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:R("flex gap-2",l&&"ml-auto"),children:e.jsxs(Se,{size:"sm",variant:"default",onClick:T,disabled:M,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(gi,{className:"h-3 w-3"}),M?"Saving...":"Save Profile"]})})]})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(rr,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a profile from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})};function pc(t,r,s){return Math.min(s,Math.max(r,t))}const xn=Ae.forwardRef(({value:t,onValueChange:r,min:s=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:c,onBlur:l,onKeyDown:d,disabled:u,...m},f)=>{const p=Ae.useRef(null);Ae.useImperativeHandle(f,()=>p.current);const[h,g]=Ae.useState(()=>String(t));Ae.useEffect(()=>{document.activeElement!==p.current&&g(String(t))},[t]);const x=Ae.useCallback(()=>{p.current?.focus()},[]),b=Ae.useCallback(w=>{const T=pc(w,s,n);r(T),g(String(T))},[n,s,r]),y=Ae.useCallback(()=>{const w=Number(h);return Number.isFinite(w)?w:t},[h,t]),v=Ae.useCallback(()=>{b(y()+o),x()},[b,y,x,o]),S=Ae.useCallback(()=>{b(y()-o),x()},[b,y,x,o]),C=w=>{const T=w.target.value;g(T);const E=Number(T);Number.isFinite(E)&&r(pc(E,s,n))},N=w=>{const T=Number(h);if(!Number.isFinite(T))g(String(t));else{const E=pc(T,s,n);E!==T&&r(E),g(String(E))}l?.(w)},j=w=>{if(w.key==="ArrowUp"){w.preventDefault(),v();return}if(w.key==="ArrowDown"){w.preventDefault(),S();return}d?.(w)},D=y(),k=u||D<=s,M=u||D>=n;return e.jsxs("div",{className:R("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",c),children:[e.jsx("input",{...m,ref:p,type:"number",inputMode:"numeric",min:Number.isFinite(s)?s:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:h,onChange:C,onBlur:N,onKeyDown:j,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:R("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:M,onClick:v,className:R("flex flex-1 items-center justify-center","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(mi,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:k,onClick:S,className:R("flex flex-1 items-center justify-center border-t border-border","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(Wt,{className:"h-3.5 w-3.5"})})]})]})});xn.displayName="NumberInput";const rC=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],mm=[{value:"collapsed",label:"Collapsed",description:"Activity and tools start collapsed"},{value:"activity",label:"Summary",description:"Activity expanded, tools collapsed"},{value:"detailed",label:"Detailed",description:"Activity expanded, key tools expanded"}],fm=[{id:"dynamic",label:"Dynamic",description:"New files inline, modified files side-by-side. Responsive inline fallback only in Dynamic mode."},{id:"inline",label:"Always inline",description:"Show all file diffs as a single unified view."},{id:"side-by-side",label:"Always side-by-side",description:"Compare original and modified files next to each other."}],pm=[{id:"single",label:"Single file",description:"Show one file at a time in the Diff tab."},{id:"stacked",label:"All files",description:"Stack all changed files together in the Diff tab."}],zl=({visibleSettings:t})=>{const{isMobile:r}=Gt(),s=Go(),n=Me(w=>w.showReasoningTraces),o=Me(w=>w.setShowReasoningTraces),a=Me(w=>w.showTextJustificationActivity),c=Me(w=>w.setShowTextJustificationActivity),l=Me(w=>w.toolCallExpansion),d=Me(w=>w.setToolCallExpansion),u=Me(w=>w.fontSize),m=Me(w=>w.setFontSize),f=Me(w=>w.padding),p=Me(w=>w.setPadding),h=Me(w=>w.cornerRadius),g=Me(w=>w.setCornerRadius),x=Me(w=>w.inputBarOffset),b=Me(w=>w.setInputBarOffset),y=Me(w=>w.diffLayoutPreference),v=Me(w=>w.setDiffLayoutPreference),S=Me(w=>w.diffViewMode),C=Me(w=>w.setDiffViewMode),N=vr(w=>w.queueModeEnabled),j=vr(w=>w.setQueueMode),{themeMode:D,setThemeMode:k}=Wr(),M=w=>t?t.includes(w):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[M("theme")&&!zt()&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Theme Mode"})}),e.jsx("div",{className:"flex gap-1 w-fit",children:rC.map(w=>e.jsx(Ts,{variant:D===w.value?"default":"outline",className:R(D===w.value?void 0:"text-foreground"),onClick:()=>k(w.value),children:w.label},w.value))})]}),M("fontSize")&&!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Font Size"})}),e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:u,onChange:w=>m(Number(w.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(xn,{value:u,onValueChange:m,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>m(100),disabled:u===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset font size",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]})]}),M("spacing")&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Spacing"})}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:f,onChange:w=>p(Number(w.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Spacing percentage"}),e.jsx("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:f}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>p(100),disabled:f===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:f,onChange:w=>p(Number(w.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(xn,{value:f,onValueChange:p,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>p(100),disabled:f===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]})]}),M("cornerRadius")&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Input Field Corner Radius"})}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"32",step:"1",value:h,onChange:w=>g(Number(w.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Corner radius in pixels"}),e.jsxs("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:[h,"px"]}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>g(12),disabled:h===12,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset corner radius",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"0",max:"32",step:"1",value:h,onChange:w=>g(Number(w.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Corner radius in pixels"}),e.jsx(xn,{value:h,onValueChange:g,min:0,max:32,step:1,"aria-label":"Corner radius in pixels"}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>g(12),disabled:h===12,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset corner radius",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]})]}),M("inputBarOffset")&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Input Bar Offset"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Raise the input bar to avoid screen obstructions."})]}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"100",step:"5",value:x,onChange:w=>b(Number(w.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Input bar offset in pixels"}),e.jsxs("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:[x,"px"]}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>b(0),disabled:x===0,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"0",max:"100",step:"5",value:x,onChange:w=>b(Number(w.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Input bar offset in pixels"}),e.jsx(xn,{value:x,onValueChange:b,min:0,max:100,step:5,"aria-label":"Input bar offset in pixels"}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>b(0),disabled:x===0,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]})]}),M("toolOutput")&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Default Tool Output"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:mm.find(w=>w.value===l)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:mm.map(w=>e.jsx(Ts,{variant:l===w.value?"default":"outline",className:R(l===w.value?void 0:"text-foreground"),onClick:()=>d(w.value),children:w.label},w.value))})]}),M("diffLayout")&&!r&&!zt()&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff layout (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose the default layout for file diffs. You can still override layout per file from the Diff tab."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:fm.map(w=>e.jsx(Ts,{variant:y===w.id?"default":"outline",className:R(y===w.id?void 0:"text-foreground"),onClick:()=>v(w.id),children:w.label},w.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:fm.find(w=>w.id===y)?.description})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff view (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose whether the Diff tab defaults to a single file or all files."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:pm.map(w=>e.jsx(Ts,{variant:S===w.id?"default":"outline",className:R(S===w.id?void 0:"text-foreground"),onClick:()=>C(w.id),children:w.label},w.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:pm.find(w=>w.id===S)?.description})]})]}),M("dotfiles")&&!zt()&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Hidden files (Chat)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Show or hide dotfiles in file lists and directory pickers."})]}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx("div",{className:"flex gap-1 w-fit",children:[{id:"hide",label:"Hide",value:!1},{id:"show",label:"Show",value:!0}].map(w=>e.jsx(Ts,{variant:s===w.value?"default":"outline",className:R(s===w.value?void 0:"text-foreground"),onClick:()=>gl(w.value),children:w.label},w.id))})})]}),M("reasoning")&&e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:n,onChange:w=>o(w.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),M("textJustificationActivity")&&e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:a,onChange:w=>c(w.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show text justification in activity"})]}),M("queueMode")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:N,onChange:w=>j(w.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Queue messages by default"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5",children:N?`Enter queues messages, ${Yt()}+Enter sends immediately.`:`Enter sends immediately, ${Yt()}+Enter queues messages.`})]})]})},hm="https://github.com/btriapitsyn/openchamber",nC=800,fh=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),o=xi(),{isMobile:a}=Gt(),c=o.info?.currentVersion||"unknown",l=i.useRef(!1);i.useEffect(()=>{if(o.checking)n(!0),l.current=!0;else if(s){const u=setTimeout(()=>{n(!1),l.current&&!o.available&&!o.error&&(V.success("You are on the latest version"),l.current=!1)},nC);return()=>clearTimeout(u)}},[o.checking,s,o.available,o.error]);const d=o.checking||s;return a?e.jsxs("div",{className:"w-full space-y-2",children:[e.jsxs("button",{onClick:()=>Ao(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ls,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["v",c]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:R("typography-meta text-muted-foreground/60 hover:text-muted-foreground disabled:cursor-default",d&&"animate-pulse [animation-duration:1s]"),children:"Check updates"}),!d&&o.available&&e.jsxs("button",{onClick:()=>r(!0),className:"flex items-center gap-1 typography-meta text-primary hover:underline",children:[e.jsx(tn,{className:"h-3.5 w-3.5"}),"Update"]})]}),o.error&&e.jsx("p",{className:"typography-micro text-destructive truncate",children:o.error}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("a",{href:hm,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Qr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(uf,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Discord"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Pc,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Uc,{open:t,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]}):e.jsxs("div",{className:"w-full space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"About OpenChamber"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Version"}),e.jsx("div",{className:"typography-ui-header font-mono",children:c})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ka,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Checking..."})]}),!o.checking&&o.available&&e.jsxs("button",{onClick:()=>r(!0),className:R("flex items-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(tn,{className:"h-4 w-4"}),"Update to ",o.info?.version]}),!o.checking&&!o.available&&!o.error&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"})]}),o.error&&e.jsx("p",{className:"typography-meta text-destructive",children:o.error}),e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:o.checking,className:R("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:"Check for updates"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("a",{href:hm,target:"_blank",rel:"noopener noreferrer",className:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Qr,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Pc,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Uc,{open:t,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]})},oC=1440*60*1e3,ph=5,gm=1440*60*1e3,hc=t=>t.time?.updated??t.time?.created??0,xm=({sessions:t,currentSessionId:r,cutoffDays:s,keepRecent:n=ph,now:o=Date.now()})=>{if(!Array.isArray(t)||s<=0)return[];const a=o-s*oC,c=[...t].sort((d,u)=>hc(u)-hc(d)),l=new Set(c.slice(0,n).map(d=>d.id));return c.filter(d=>{if(!d?.id||l.has(d.id)||d.id===r||d.share)return!1;const u=hc(d);return u?u<a:!1}).map(d=>d.id)},hh=t=>{const r=t?.autoRun!==!1,s=ve(x=>x.sessions),n=ve(x=>x.currentSessionId),o=ve(x=>x.isLoading),a=ve(x=>x.deleteSessions),c=Me(x=>x.autoDeleteEnabled),l=Me(x=>x.autoDeleteAfterDays),d=Me(x=>x.autoDeleteLastRunAt),u=Me(x=>x.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),h=i.useMemo(()=>l<=0?[]:xm({sessions:s,currentSessionId:n,cutoffDays:l}),[l,n,s]),g=i.useCallback(async({force:x=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!c||l<=0)&&!x)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const b=Date.now();if(!x&&d&&b-d<gm)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(s.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const y=xm({sessions:s,currentSessionId:n,cutoffDays:l,now:b});if(y.length===0)return u(b),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(y,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[l,c,d,n,a,o,s,u]);return i.useEffect(()=>{if(!r||!c||l<=0||o||s.length===0)return;const x=Date.now();d&&x-d<gm||g()},[l,c,d,r,o,s.length,g]),{candidates:h,isRunning:m,runCleanup:g,keepRecentCount:ph}},gc=1,xc=365,gh=()=>{const{isMobile:t}=Gt(),r=Me(p=>p.autoDeleteEnabled),s=Me(p=>p.autoDeleteAfterDays),n=Me(p=>p.setAutoDeleteEnabled),o=Me(p=>p.setAutoDeleteAfterDays),[a,c]=i.useState(String(s));i.useEffect(()=>{c(String(s))},[s]);const{candidates:l,isRunning:d,runCleanup:u}=hh({autoRun:!1}),m=l.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){V.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&V.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&V.error(`Failed to delete ${p.failedIds.length} session${p.failedIds.length===1?"":"s"}`)},[u]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session retention"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Automatically delete inactive sessions based on their last activity.",e.jsx("br",{}),"You can also run a one-time cleanup without enabling auto-cleanup.",e.jsx("br",{}),"Keeps the most recent 5 sessions, and never deletes shared sessions."]})]})]})}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:r,onChange:p=>n(p.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Enable auto-cleanup"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[t?e.jsx("input",{type:"number",inputMode:"numeric",value:a,onChange:p=>{const h=p.target.value;if(c(h),h.trim()==="")return;const g=Number(h);if(!Number.isFinite(g))return;const x=Math.min(xc,Math.max(gc,Math.round(g)));o(x)},onBlur:()=>{if(a.trim()===""){c(String(s));return}const p=Number(a);if(!Number.isFinite(p)){c(String(s));return}const h=Math.min(xc,Math.max(gc,Math.round(p)));o(h),c(String(h))},"aria-label":"Retention period in days",className:"h-8 w-16 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(xn,{value:s,onValueChange:o,min:gc,max:xc,step:1,"aria-label":"Retention period in days"}),e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"days since last activity"})]}),e.jsx(Ts,{type:"button",variant:"outline",onClick:f,disabled:d,children:d?"Cleaning up...":"Run cleanup now"})]}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Eligible for deletion right now: ",m]})]})},aC=10,iC=500,cC=20,lC=500,dC=30,uC=1e3,mC=()=>{const{isMobile:t}=Gt(),r=Me(h=>h.memoryLimitHistorical),s=Me(h=>h.memoryLimitViewport),n=Me(h=>h.memoryLimitActiveSession),o=Me(h=>h.setMemoryLimitHistorical),a=Me(h=>h.setMemoryLimitViewport),c=Me(h=>h.setMemoryLimitActiveSession),[l,d]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let g=null;if(ds())g=await zr();else{const x=Ps()?.settings;if(x)try{const y=(await x.load())?.settings;y&&(g={memoryLimitHistorical:typeof y.memoryLimitHistorical=="number"?y.memoryLimitHistorical:void 0,memoryLimitViewport:typeof y.memoryLimitViewport=="number"?y.memoryLimitViewport:void 0,memoryLimitActiveSession:typeof y.memoryLimitActiveSession=="number"?y.memoryLimitActiveSession:void 0})}catch{}if(!g){const b=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});b.ok&&(g=await b.json())}}g&&(typeof g.memoryLimitHistorical=="number"&&o(g.memoryLimitHistorical),typeof g.memoryLimitViewport=="number"&&a(g.memoryLimitViewport),typeof g.memoryLimitActiveSession=="number"&&c(g.memoryLimitActiveSession))}catch(g){console.warn("Failed to load memory limits settings:",g)}finally{d(!1)}})()},[o,a,c]);const u=i.useCallback(async(h,g)=>{try{if(await as({[h]:g}),!ds()){const x=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({[h]:g})});x.ok||console.warn(`Failed to save ${h} to server:`,x.status,x.statusText)}}catch(x){console.warn(`Failed to save ${h}:`,x)}},[]),m=i.useCallback(h=>{o(h),u("memoryLimitHistorical",h)},[o,u]),f=i.useCallback(h=>{a(h),u("memoryLimitViewport",h)},[a,u]),p=i.useCallback(h=>{c(h),u("memoryLimitActiveSession",h)},[c,u]);return l?null:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Message Memory"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Control how many messages are kept in memory for performance optimization.",e.jsx("br",{}),"Lower values use less memory but may require reloading older messages."]})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(yc,{label:"Initial load limit",description:"Messages loaded when opening a session",value:r,defaultValue:gn.HISTORICAL_MESSAGES,min:aC,max:iC,onChange:m,isMobile:t}),e.jsx(yc,{label:"Background trim limit",description:"Max messages kept when switching away",value:s,defaultValue:gn.VIEWPORT_MESSAGES,min:cC,max:lC,onChange:f,isMobile:t}),e.jsx(yc,{label:"Active session limit",description:"Max messages for active session",value:n,defaultValue:$c,min:dC,max:uC,onChange:p,isMobile:t})]})]})},yc=({label:t,description:r,value:s,defaultValue:n,min:o,max:a,onChange:c,isMobile:l})=>{const[d,u]=i.useState(String(s));i.useEffect(()=>{u(String(s))},[s]);const m=i.useCallback(h=>{const g=h.target.value;if(u(g),g.trim()==="")return;const x=Number(g);if(!Number.isFinite(x))return;const b=Math.min(a,Math.max(o,Math.round(x)));c(b)},[o,a,c]),f=i.useCallback(()=>{if(d.trim()===""){u(String(s));return}const h=Number(d);if(!Number.isFinite(h)){u(String(s));return}const g=Math.min(a,Math.max(o,Math.round(h)));c(g),u(String(g))},[d,s,o,a,c]),p=s===n;return e.jsx("div",{className:"flex flex-col gap-1",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:t}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:r})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!p&&e.jsxs("span",{className:"typography-meta text-muted-foreground/60",children:["(default: ",n,")"]}),l?e.jsx("input",{type:"number",inputMode:"numeric",value:d,onChange:m,onBlur:f,"aria-label":t,className:"h-8 w-20 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(xn,{value:s,onValueChange:c,min:o,max:a,step:10,"aria-label":t})]})]})})},ym="opencode",bm="big-pickle",fC=(t,r)=>{if(t){const o=t.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(r.find(o=>o.id===ym)?.models.some(o=>o.id===bm))return{providerId:ym,modelId:bm};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},xh=()=>{const t=Je(T=>T.setProvider),r=Je(T=>T.setModel),s=Je(T=>T.setAgent),n=Je(T=>T.setCurrentVariant),o=Je(T=>T.setSettingsDefaultModel),a=Je(T=>T.setSettingsDefaultVariant),c=Je(T=>T.setSettingsDefaultAgent),l=Je(T=>T.settingsAutoCreateWorktree),d=Je(T=>T.setSettingsAutoCreateWorktree),u=Je(T=>T.providers),[m,f]=i.useState(),[p,h]=i.useState(),[g,x]=i.useState(),[b,y]=i.useState(!0),v=i.useMemo(()=>fC(m,u),[m,u]),S=i.useMemo(()=>zt(),[]);i.useEffect(()=>{(async()=>{try{let E=null;if(ds())E=await zr();else{const I=Ps()?.settings;if(I)try{const P=(await I.load())?.settings;P&&(E={defaultModel:typeof P.defaultModel=="string"?P.defaultModel:void 0,defaultVariant:typeof P.defaultVariant=="string"?P.defaultVariant:void 0,defaultAgent:typeof P.defaultAgent=="string"?P.defaultAgent:void 0})}catch{}if(!E){const A=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});A.ok&&(E=await A.json())}}if(E){const I=typeof E.defaultModel=="string"&&E.defaultModel.trim().length>0?E.defaultModel.trim():void 0,A=typeof E.defaultVariant=="string"&&E.defaultVariant.trim().length>0?E.defaultVariant.trim():void 0,P=typeof E.defaultAgent=="string"&&E.defaultAgent.trim().length>0?E.defaultAgent.trim():void 0;I!==void 0&&f(I),A!==void 0&&h(A),P!==void 0&&x(P)}}catch(E){console.warn("Failed to load defaults settings:",E)}finally{y(!1)}})()},[]);const C=i.useCallback(async(T,E)=>{const I=T&&E?`${T}/${E}`:void 0;f(I),h(void 0),a(void 0),n(void 0),o(I),T&&E&&u.find(P=>P.id===T)&&(t(T),r(E));try{if(await as({defaultModel:I??"",defaultVariant:""}),!ds()){const A=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:I})});A.ok||console.warn("Failed to save default model to server:",A.status,A.statusText)}}catch(A){console.warn("Failed to save default model:",A)}},[u,n,t,r,o,a]),N="__default__",j=i.useCallback(async T=>{const E=T===N?void 0:T||void 0;h(E),a(E),n(E);try{await as({defaultVariant:E??""})}catch(I){console.warn("Failed to save default variant:",I)}},[n,a]),D=i.useCallback(async T=>{const E=T||void 0;x(E),c(E),T&&s(T);try{await as({defaultAgent:E??""})}catch(I){console.warn("Failed to save default agent:",I)}},[s,c]),k=i.useMemo(()=>{if(!v.providerId||!v.modelId)return[];const I=u.find(A=>A.id===v.providerId)?.models.find(A=>A.id===v.modelId)?.variants;return I?Object.keys(I):[]},[v.modelId,v.providerId,u]),M=k.length>0;i.useEffect(()=>{!M&&p&&(h(void 0),a(void 0),n(void 0),as({defaultVariant:""}).catch(()=>{}))},[p,n,a,M]);const w=i.useCallback(async T=>{const E=T.target.checked;d(E);try{await as({autoCreateWorktree:E})}catch(I){console.warn("Failed to save auto create worktree setting:",I)}},[d]);return b?null:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session Defaults"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:"Configure default behaviors for new sessions."})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default model"}),e.jsx(Bl,{providerId:v.providerId,modelId:v.modelId,onChange:C})]}),M&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default thinking"}),e.jsxs(As,{value:p??N,onValueChange:j,children:[e.jsx(Es,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Cn,{placeholder:"Thinking"})}),e.jsxs(Is,{children:[e.jsx(Bt,{value:N,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),k.map(T=>e.jsx(Bt,{value:T,className:"pr-2 [&>span:first-child]:hidden",children:T},T))]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default agent"}),e.jsx(uh,{agentName:g||"",onChange:D})]})]}),(v.providerId||g)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",v.providerId&&e.jsxs("span",{className:"text-foreground",children:[v.providerId,"/",v.modelId,M?` (${p??"default"})`:""]}),v.providerId&&g&&" / ",g&&e.jsx("span",{className:"text-foreground",children:g})]}),!S&&e.jsxs("div",{className:"pt-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:l,onChange:w}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Always create worktree for new sessions"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5 mt-1",children:l?`New session (Worktree): ${Yt()} + N • New session (Standard): Shift + ${Yt()} + N`:`New session (Standard): ${Yt()} + N • New session (Worktree): Shift + ${Yt()} + N`})]})]})},pC=()=>{const t=Je(c=>c.settingsGitmojiEnabled),r=Je(c=>c.setSettingsGitmojiEnabled),s=bi(),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let l=null;if(ds())l=await zr();else{const d=Ps()?.settings;if(d)try{const m=(await d.load())?.settings;m&&(l={gitmojiEnabled:typeof m.gitmojiEnabled=="boolean"?m.gitmojiEnabled:void 0})}catch{}if(!l){const u=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});u.ok&&(l=await u.json())}}l&&typeof l.gitmojiEnabled=="boolean"&&r(l.gitmojiEnabled)}catch(l){console.warn("Failed to load git settings:",l)}finally{o(!1)}})()},[r]);const a=i.useCallback(async c=>{const l=c.target.checked;r(l);try{await as({gitmojiEnabled:l})}catch(d){console.warn("Failed to save gitmoji setting:",d)}},[r]);return n?null:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit Messages"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:"Configure how commit messages are generated."})]})]})}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:t,onChange:a}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Enable gitmoji picker"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5",children:"Adds a gitmoji selector to the Git commit message input."})]})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Files Overview"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Show gitignored files in the Files browser pane only."})]}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:s,onChange:c=>xf(c.target.checked)}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Display gitignored files"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5",children:"Toggles gitignored files in the Files tree and search results."})]})})]})},hC=()=>{const t=Lt(O=>O.getActiveProject()),r=Lt(O=>O.updateWorktreeDefaults),s=t?.path??null,n=t?.worktreeDefaults,o=Zf(s),{sessions:a,getWorktreeMetadata:c}=ve(),l=vt(O=>O.homeDirectory),[d,u]=i.useState(n?.baseBranch??"HEAD"),[m,f]=i.useState([]),[p,h]=i.useState(!1),[g,x]=i.useState(!1),[b,y]=i.useState(null),[v,S]=i.useState(null),[C,N]=i.useState([]),[j,D]=i.useState(!1),k=i.useMemo(()=>!t?.id||!s?null:{id:t.id,path:s},[t?.id,s]),M=i.useCallback(async()=>{if(!(!k||b===!1))try{const O=await $o(k);N(O)}catch{}},[k,b]);i.useEffect(()=>{if(!s)return;let O=!1;return x(!0),y(null),S(null),(async()=>{try{const q=await Hr(s);if(O||(y(q),!q))return;const Y=await wl(s);if(O)return;S({all:Y.all,current:Y.current})}catch{}finally{O||x(!1)}})(),()=>{O=!0}},[s]),i.useEffect(()=>{if(!k){N([]),D(!1);return}if(b===!1){N([]),D(!1);return}let O=!1;return D(!0),N([]),(async()=>{try{const q=await $o(k);if(O)return;N(q)}catch{}finally{O||D(!1)}})(),()=>{O=!0}},[k,b]),i.useEffect(()=>{if(!k)return;let O=!1;return h(!0),(async()=>{try{const q=await go(k);O||f(q.length>0?q:[""])}catch{O||f([""])}finally{O||h(!1)}})(),()=>{O=!0}},[k]),i.useEffect(()=>{u(n?.baseBranch??"HEAD")},[n]);const w=v??o,T=i.useMemo(()=>{const O=[],q=w?.current?`Current (HEAD: ${w.current})`:"Current (HEAD)";return O.push({value:"HEAD",label:q,group:"special"}),w&&(w.all.filter(B=>!B.startsWith("remotes/")).sort((B,W)=>B.localeCompare(W)).forEach(B=>{O.push({value:B,label:B,group:"local"})}),w.all.filter(B=>B.startsWith("remotes/")).map(B=>B.replace(/^remotes\//,"")).sort((B,W)=>B.localeCompare(W)).forEach(B=>{O.push({value:B,label:B,group:"remote"})})),O},[w]),E=i.useCallback(O=>{u(O),t?.id&&r(t.id,{baseBranch:O})},[t?.id,r]),I=i.useCallback((O,q)=>{f(Y=>{const Z=[...Y];return Z[O]=q,Z})},[]),A=i.useCallback(()=>{f(O=>[...O,""])},[]),P=i.useCallback(async O=>{if(!k)return;const q=O.filter(Y=>Y.trim().length>0);await zf(k,q)},[k]),F=i.useCallback(O=>{f(q=>{const Y=q.filter((Z,B)=>B!==O);return P(Y),Y.length>0?Y:[""]})},[P]),z=i.useCallback(()=>{P(m)},[P,m]),G=i.useCallback(O=>{const q=O.path.replace(/\\/g,"/").replace(/\/+$/,""),Y=a.filter(me=>{if(c(me.id)?.path===O.path)return!0;const L=me.directory;return!!(L&&L.replace(/\\/g,"/").replace(/\/+$/,"")===q)}),Z=new Set(Y.map(me=>me.id)),B=me=>{const K=a.filter(Q=>{const ce=Q.parentID;return ce&&me.has(ce)});if(K.length===0)return[];const L=new Set(K.map(Q=>Q.id));return[...K,...B(L)]},W=B(Z),te=new Set,ye=[...Y,...W].filter(me=>te.has(me.id)?!1:(te.add(me.id),!0));io.requestDelete({sessions:ye,mode:"worktree",worktree:O})},[a,c]),oe=i.useMemo(()=>a.map(O=>O.id).join(","),[a]);return i.useEffect(()=>{b&&s&&M()},[oe,b,s,M]),s?b===!1?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Worktree settings are only available for Git repositories."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Base branch"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:"Default branch to create new worktrees from."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default branch for new worktree branches"})]}),g?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs(As,{value:d,onValueChange:E,children:[e.jsx(Es,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Cn,{placeholder:"Select a branch"})}),e.jsxs(Is,{children:[e.jsxs(wn,{children:[e.jsx(Xn,{children:"Default"}),T.filter(O=>O.group==="special").map(O=>e.jsx(Bt,{value:O.value,children:O.label},O.value))]}),T.some(O=>O.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(oi,{}),e.jsxs(wn,{children:[e.jsx(Xn,{children:"Local branches"}),T.filter(O=>O.group==="local").map(O=>e.jsx(Bt,{value:O.value,children:O.label},O.value))]})]}),T.some(O=>O.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(oi,{}),e.jsxs(wn,{children:[e.jsx(Xn,{children:"Remote branches"}),T.filter(O=>O.group==="remote").map(O=>e.jsx(Bt,{value:O.value,children:O.label},O.value))]})]})]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Setup commands"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Run automatically inside the new worktree directory when a worktree is created.",e.jsx("br",{}),"Use ",e.jsx("code",{className:"font-mono text-xs bg-sidebar-accent/50 px-1 rounded",children:"$ROOT_PROJECT_PATH"})," for the project root."]})]}),p?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[m.map((O,q)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(St,{value:O,onChange:Y=>I(q,Y.target.value),onBlur:z,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{F(q)},className:"flex-shrink-0 flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(es,{className:"h-4 w-4"})})]},q)),e.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(ls,{className:"h-3.5 w-3.5"}),"Add command"]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Existing worktrees"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ks,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["SDK worktrees live outside the repo (OpenCode-managed). Legacy ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})," worktrees are still supported. Deleting a worktree also removes linked sessions."]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Manage worktrees for this project"})]}),j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):C.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"No worktrees found for this project"}):e.jsx("div",{className:"space-y-1",children:C.map(O=>e.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-sidebar-accent/30 transition-colors group",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("p",{className:"typography-meta text-foreground truncate min-w-0",children:O.label||O.branch||"Detached HEAD"}),e.jsx("span",{className:"typography-micro text-muted-foreground/60 px-1.5 py-[1px] rounded bg-sidebar-accent/40 flex-shrink-0 self-center leading-none",children:O.source==="sdk"?"OpenCode":"OpenChamber"})]}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:O.source==="sdk"?Yr(O.path,l):O.relativePath||O.path})]}),e.jsx("button",{type:"button",onClick:()=>G(O),className:"flex-shrink-0 flex h-7 w-7 items-center justify-center rounded text-muted-foreground/50 hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover:opacity-100 transition-opacity focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete worktree ${O.branch||O.label}`,children:e.jsx(zs,{className:"h-4 w-4"})})]},O.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},gC=()=>{const t=Me(j=>j.nativeNotificationsEnabled),r=Me(j=>j.setNativeNotificationsEnabled),s=Me(j=>j.notificationMode),n=Me(j=>j.setNotificationMode),[o,a]=i.useState("default"),[c,l]=i.useState(!1),[d,u]=i.useState(!1),[m,f]=i.useState(!1);i.useEffect(()=>{typeof Notification<"u"&&a(Notification.permission);const j=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;l(j),(async()=>{if(!j){u(!1);return}try{const k=await navigator.serviceWorker.getRegistration();if(!k){u(!1);return}const M=await k.pushManager.getSubscription();u(!!M)}catch{u(!1)}})()},[]);const p=async j=>{if(j&&typeof Notification<"u"&&Notification.permission==="default")try{const D=await Notification.requestPermission();a(D),D==="granted"?r(!0):V.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(D){console.error("Failed to request notification permission:",D),V.error("Failed to request notification permission")}else r(!!(j&&o==="granted"))},h=typeof Notification<"u"&&Notification.permission==="granted",g=j=>{const D="=".repeat((4-j.length%4)%4),k=(j+D).replace(/-/g,"+").replace(/_/g,"/"),M=atob(k),w=new Uint8Array(M.length);for(let T=0;T<M.length;T+=1)w[T]=M.charCodeAt(T);return w},x=async(j,D,k)=>{let M=null;const w=new Promise((T,E)=>{M=setTimeout(()=>{E(new Error(k))},D)});try{return await Promise.race([j,w])}finally{M&&clearTimeout(M)}},b=async j=>{if(j.active)return;const D=j.installing||j.waiting;D&&D.state!=="activated"&&await x(new Promise(k=>{const M=()=>{D.state==="activated"&&(D.removeEventListener("statechange",M),k())};D.addEventListener("statechange",M),M()}),15e3,"Service worker activation timed out")},y=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const j=[{label:"no-options",opts:null},{label:"scope-root",opts:{scope:"/"}},{label:"type-classic",opts:{type:"classic"}},{label:"type-classic-scope",opts:{type:"classic",scope:"/"}},{label:"updateViaCache-none",opts:{type:"classic",updateViaCache:"none",scope:"/"}}];let D=null;for(const k of j)try{const M=k.opts?navigator.serviceWorker.register("/sw.js",k.opts):navigator.serviceWorker.register("/sw.js");return await x(M,1e4,`Service worker registration timed out (${k.label})`)}catch(M){D=M}throw D instanceof Error?D:new Error("Service worker registration failed")},v=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const j=await navigator.serviceWorker.getRegistration();if(j)return j;const D=await y();try{await D.update()}catch{}return await b(D),D},S=j=>{const D=j,k=[`type=${typeof j}`,`toString=${String(j)}`,`name=${String(D?.name??"")}`,`message=${String(D?.message??"")}`];let M="";try{M=JSON.stringify(j)}catch{}return{summary:k.filter(Boolean).join(" | "),json:M,stack:typeof D?.stack=="string"?D.stack:""}},C=async()=>{if(!c){V.error("Push notifications not supported");return}const j=Ps();if(!j?.push){V.error("Push API not available");return}f(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const A=await Notification.requestPermission();if(a(A),A!=="granted"){V.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){V.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}const D=await j.push.getVapidPublicKey();if(!D?.publicKey){V.error("Failed to load push key");return}const k=await v();await b(k);const M=await k.pushManager.getSubscription();if(!("pushManager"in k)||!k.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const T=(M??await x(k.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:g(D.publicKey)}),15e3,"Push subscription timed out")).toJSON(),E=T.keys;if(!T.endpoint||!E?.p256dh||!E.auth)throw new Error("Push subscription missing keys");if(!(await x(j.push.subscribe({endpoint:T.endpoint,keys:{p256dh:E.p256dh,auth:E.auth},origin:typeof window<"u"?window.location.origin:void 0}),15e3,"Push subscribe request timed out"))?.ok){V.error("Failed to enable background notifications");return}u(!0),V.success("Background notifications enabled")}catch(D){console.error("[Push] Enable failed:",D);const k=S(D);V.error("Failed to enable background notifications",{description:k.summary})}finally{f(!1)}},N=async()=>{if(!c){u(!1);return}const j=Ps();if(!j?.push){V.error("Push API not available");return}f(!0);try{const k=await(await v()).pushManager.getSubscription();if(!k){u(!1);return}const M=k.endpoint;await k.unsubscribe(),await j.push.unsubscribe({endpoint:M}),u(!1),V.success("Background notifications disabled")}finally{f(!1)}};return mr()?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Foreground Notifications"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Uses the browser Notification API while OpenChamber is open."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Enable foreground notifications"}),e.jsx(bn,{checked:t&&h,onCheckedChange:p,className:"data-[state=checked]:bg-status-info"})]}),t&&h&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Notify even when visible"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"When off, only notifies when the tab is hidden or the window is not focused."})]}),e.jsx(bn,{checked:s==="always",onCheckedChange:j=>n(j?"always":"hidden-only"),className:"data-[state=checked]:bg-status-info"})]}),o==="denied"&&e.jsx("p",{className:"typography-micro text-destructive",children:"Notification permission denied. Enable notifications in your browser settings."}),o==="granted"&&!t&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Permission granted, but foreground notifications are disabled."}),e.jsxs("div",{className:"space-y-1 pt-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Background Notifications (Push)"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Uses push notifications; works when OpenChamber is closed."})]}),c?e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Desktop Chrome/Edge and Android support push in the browser. iOS requires an installed PWA."}):e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Push not supported in this browser."}),c&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Enable background notifications"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Opens chat with /?session=<id> deep link."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&e.jsx("div",{className:"text-muted-foreground",children:e.jsx(xp,{size:"sm"})}),e.jsx(bn,{checked:d,disabled:m,onCheckedChange:j=>{j?C():N()},className:"data-[state=checked]:bg-status-info"})]})]})]}):null},xC=()=>{const t=Ps()?.github,r=Bs(j=>j.status),s=Bs(j=>j.isLoading),n=Bs(j=>j.hasChecked),o=Bs(j=>j.refreshStatus),a=Bs(j=>j.setStatus),c=i.useCallback(async j=>{if(typeof window>"u")return;const D=window.opencodeDesktop;if(D?.openExternal)try{const k=await D.openExternal(j);if(k&&typeof k=="object"&&"success"in k&&k.success===!0)return}catch{}try{window.open(j,"_blank","noopener,noreferrer")}catch{}},[]),[l,d]=i.useState(!1),[u,m]=i.useState(null),[f,p]=i.useState(null),h=i.useRef(null),g=i.useCallback(()=>{h.current!=null&&(window.clearInterval(h.current),h.current=null),p(null)},[]);i.useEffect(()=>((async()=>{try{n||await o(t)}catch(j){console.warn("Failed to load GitHub auth status:",j)}})(),()=>{g()}),[n,o,t,g]);const x=i.useCallback(async()=>{d(!0);try{const j=t?await t.authStart():await(async()=>{const k=await fetch("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),M=await k.json().catch(()=>null);if(!k.ok||!M||!("deviceCode"in M))throw new Error(M?.error||k.statusText);return M})();m(j),p(Math.max(1,j.interval)*1e3);const D=j.verificationUriComplete||j.verificationUri;c(D)}catch(j){console.error("Failed to start GitHub connect:",j),Ys.error("Failed to start GitHub connect")}finally{d(!1)}},[c,t]),b=i.useCallback(async j=>{if(t)return t.authComplete(j);const D=await fetch("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:j})}),k=await D.json().catch(()=>null);if(!D.ok||!k)throw new Error(k?.error||D.statusText);return k},[t]);i.useEffect(()=>{if(!(!u?.deviceCode||!f)&&h.current==null)return h.current=window.setInterval(()=>{(async()=>{try{const j=await b(u.deviceCode);if(j.connected){Ys.success("GitHub connected"),m(null),g(),await o(t,{force:!0});return}j.status==="slow_down"&&p(D=>D?D+5e3:5e3),(j.status==="expired_token"||j.status==="access_denied")&&(Ys.error(j.error||"GitHub authorization failed"),m(null),g())}catch(j){console.warn("GitHub polling failed:",j)}})()},f),()=>{h.current!=null&&(window.clearInterval(h.current),h.current=null)}},[u,f,b,o,t,g]);const y=i.useCallback(async()=>{d(!0);try{if(g(),m(null),t)await t.authDisconnect();else{const j=await fetch("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}});if(!j.ok)throw new Error(j.statusText)}Ys.success("GitHub disconnected"),await o(t,{force:!0})}catch(j){console.error("Failed to disconnect GitHub:",j),Ys.error("Failed to disconnect GitHub")}finally{d(!1)}},[o,t,g]),v=i.useCallback(async j=>{if(j){d(!0);try{const D=t?await t.authActivate(j):await(async()=>{const k=await fetch("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:j})}),M=await k.json().catch(()=>null);if(!k.ok||!M)throw new Error(M?.error||k.statusText);return M})();a(D),Ys.success("GitHub account switched")}catch(D){console.error("Failed to switch GitHub account:",D),Ys.error("Failed to switch GitHub account")}finally{d(!1)}}},[t,a]);if(s)return null;const S=!!r?.connected,C=r?.user,N=r?.accounts??[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"GitHub"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Connect a GitHub account for in-app PR and issue workflows."})]}),S?e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border bg-background/50 px-4 py-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-4",children:[C?.avatarUrl?e.jsx("img",{src:C.avatarUrl,alt:C.login?`${C.login} avatar`:"GitHub avatar",className:"h-14 w-14 shrink-0 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-14 w-14 shrink-0 rounded-full border border-border/60 bg-muted"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-header font-semibold text-foreground truncate",children:C?.name?.trim()||C?.login||"GitHub"}),C?.email?e.jsx("div",{className:"typography-body text-muted-foreground truncate",children:C.email}):null,e.jsxs("div",{className:"mt-1 flex items-center gap-2 typography-meta text-muted-foreground truncate",children:[e.jsx(Qr,{className:"h-4 w-4"}),e.jsx("span",{className:"font-mono",children:C?.login||"unknown"})]}),r?.scope?e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:["Scopes: ",r.scope]}):null]})]}),e.jsx(Se,{variant:"outline",onClick:y,disabled:l,children:"Disconnect"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-background/50 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Not connected"}),e.jsx(Se,{onClick:x,disabled:l,children:"Connect"})]}),S?e.jsx("div",{className:"flex justify-end",children:e.jsx(Se,{variant:"ghost",onClick:x,disabled:l,children:"Add account"})}):null,N.length>1?e.jsxs("div",{className:"space-y-2 rounded-lg border bg-background/50 p-3",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Accounts"}),e.jsx("div",{className:"space-y-2",children:N.map(j=>{const D=j.user,k=!!j.current;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-border/40 bg-background/70 px-3 py-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[D?.avatarUrl?e.jsx("img",{src:D.avatarUrl,alt:D.login?`${D.login} avatar`:"GitHub avatar",className:"h-8 w-8 shrink-0 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/60 bg-muted",children:e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground truncate",children:D?.name?.trim()||D?.login||"GitHub"}),D?.login?e.jsx("div",{className:"typography-micro text-muted-foreground truncate font-mono",children:D.login}):null]})]}),k?e.jsx("span",{className:"typography-micro text-primary",children:"Active"}):e.jsx(Se,{size:"sm",variant:"ghost",onClick:()=>v(j.id),disabled:l,children:"Use"})]},j.id)})})]}):null,u?e.jsxs("div",{className:"space-y-3 rounded-lg border bg-background/50 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Authorize OpenChamber"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:"In GitHub, enter this code:"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-mono text-lg tracking-widest text-foreground",children:u.userCode}),e.jsx(Se,{variant:"outline",asChild:!0,children:e.jsx("a",{href:u.verificationUriComplete||u.verificationUri,target:"_blank",rel:"noopener noreferrer",children:"Open GitHub"})})]}),e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Waiting for approval… (auto-refresh)"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(Se,{variant:"ghost",disabled:l,onClick:()=>{g(),m(null)},children:"Cancel"})})]}):null]})},yC=({section:t})=>{const{isMobile:r}=Gt(),s=r&&mr();if(!t)return e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"openchamber-page-body mx-auto max-w-3xl space-y-3 p-3 sm:space-y-6 sm:p-6",children:[e.jsx(zl,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(xh,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gh,{})}),s&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(fh,{})})]})});const n=()=>{switch(t){case"visual":return e.jsx(bC,{});case"chat":return e.jsx(wC,{});case"sessions":return e.jsx(vC,{});case"git":return e.jsx(jC,{});case"github":return e.jsx(SC,{});case"notifications":return e.jsx(NC,{});default:return null}};return e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsx("div",{className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})})},bC=()=>e.jsx(zl,{visibleSettings:["theme","fontSize","spacing","cornerRadius","inputBarOffset"]}),wC=()=>e.jsx(zl,{visibleSettings:["toolOutput","diffLayout","dotfiles","reasoning","textJustificationActivity","queueMode"]}),vC=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(xh,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gh,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(mC,{})})]}),jC=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(pC,{}),e.jsxs("div",{className:"border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1 mb-4",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Worktree"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Configure worktree branch defaults and manage existing worktrees."})]}),e.jsx(hC,{})]})]}),SC=()=>zt()?null:e.jsx(xC,{}),NC=()=>e.jsx(gC,{}),kC=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]},{id:"git",label:"Git",items:["Commit Messages","Worktree"],hideInVSCode:!0},{id:"github",label:"GitHub",items:["Connect","PRs","Issues"],hideInVSCode:!0},{id:"notifications",label:"Notifications",items:["Native"],webOnly:!0}],CC=({selectedSection:t,onSelectSection:r})=>{const{isMobile:s}=Gt(),n=s&&mr(),[o,a]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=i.useMemo(()=>zt(),[]),l=i.useMemo(()=>mr(),[]);i.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=i.useMemo(()=>kC.filter(m=>!(m.webOnly&&!l||m.hideInVSCode&&c)),[l,c]),u=o?"bg-transparent":c?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",u),children:[e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:d.map(m=>{const f=t===m.id;return e.jsx("div",{className:R("group relative rounded-md px-1.5 py-1 transition-all duration-200",f?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{onClick:()=>r(m.id),className:"w-full text-left flex flex-col gap-0 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"typography-ui-label font-normal text-foreground",children:m.label}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 leading-tight",children:m.items.join(" · ")})]})},m.id)})}),n&&e.jsx("div",{className:"border-t px-3 py-4",children:e.jsx(fh,{})})]})},MC=t=>{let r=dh.filter(o=>o.id!=="sessions");t&&(r=r.filter(o=>o.id!=="git-identities"));const s=r.find(o=>o.id==="settings"),n=r.filter(o=>o.id!=="settings");return s?[s,...n]:r},bc=200,wc=500,DC=264,AC=940,rl=({onClose:t,forceMobile:r})=>{const s=Gt(),n=r??s.isMobile,o=Me(L=>L.sidebarSection),a=Me(L=>L.setSidebarSection),c=i.useMemo(()=>o!=="sessions"?o:"settings",[o]),l=i.useCallback(L=>{a(L)},[a]),[d,u]=i.useState("visual"),[m,f]=i.useState(!1),[p,h]=i.useState(()=>typeof window<"u"?Math.min(wc,Math.max(bc,Math.floor(window.innerWidth*.2))):DC),[g,x]=i.useState(!1),[b,y]=i.useState(!1),[v,S]=i.useState(0),C=i.useRef(null),N=i.useRef(0),j=i.useRef(p),[D,k]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),M=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),w=i.useMemo(()=>zt(),[]),T=i.useMemo(()=>MC(w),[w]);i.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{const L=C.current;if(!L)return;const Q=new ResizeObserver(ce=>{for(const he of ce)S(he.contentRect.width)});return Q.observe(L),S(L.clientWidth),()=>Q.disconnect()},[]);const E=Lt(L=>L.projects),I=Lt(L=>L.activeProjectId),A=Lt(L=>L.setActiveProject),P=i.useMemo(()=>[...E].sort((L,Q)=>(L.label||L.path).localeCompare(Q.label||Q.path)),[E]),F=i.useMemo(()=>P.length===0?null:P.find(L=>L.id===I)??P[0],[I,P]),z=i.useCallback(L=>L.replace(/[-_]/g," ").replace(/\b\w/g,Q=>Q.toUpperCase()),[]),G=i.useMemo(()=>{if(!F)return"Project";const L=F.label&&F.label.trim().length>0?F.label:F.path.split("/").filter(Boolean).pop()||F.path;return z(L)},[F,z]),oe=P.length>0&&!w,O=v===0||v>=AC;i.useEffect(()=>{if(c==="agents"){setTimeout(()=>{cn.getState().loadAgents()},0);return}if(c==="commands"){setTimeout(()=>{an.getState().loadCommands()},0);return}c==="skills"&&(fr.getState().loadSkills(),qo.getState().loadCatalog())},[I,c]),i.useEffect(()=>{if(typeof window>"u")return;const L=()=>{if(!g){const Q=Math.min(wc,Math.max(bc,Math.floor(window.innerWidth*.2)));h(Q)}};return window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[g]),i.useEffect(()=>{if(!b)return;const L=ce=>{const he=ce.clientX-N.current,Ne=Math.min(wc,Math.max(bc,j.current+he));h(Ne),x(!0)},Q=()=>y(!1);return window.addEventListener("pointermove",L),window.addEventListener("pointerup",Q,{once:!0}),()=>{window.removeEventListener("pointermove",L),window.removeEventListener("pointerup",Q)}},[b]);const q=L=>{y(!0),N.current=L.clientX,j.current=p,L.preventDefault()},Y=i.useCallback(async L=>{if(!L.target.closest("button, a, input, select, textarea")&&L.button===0&&D)try{const{getCurrentWindow:Q}=await vs(async()=>{const{getCurrentWindow:he}=await import("./vendor-.bun-Bui932eM.js").then(Ne=>Ne.dl);return{getCurrentWindow:he}},__vite__mapDeps([0,1]));await Q().startDragging()}catch(Q){console.error("Failed to start window dragging:",Q)}},[D]),Z=i.useCallback(async L=>{if(L.button===0&&D)try{const{getCurrentWindow:Q}=await vs(async()=>{const{getCurrentWindow:he}=await import("./vendor-.bun-Bui932eM.js").then(Ne=>Ne.dl);return{getCurrentWindow:he}},__vite__mapDeps([0,1]));await Q().startDragging()}catch(Q){console.error("Failed to start window dragging:",Q)}},[D]),B=i.useCallback(L=>{l(L),f(!1)},[l]),W=i.useCallback(()=>{n&&f(!0)},[n]),te=()=>{switch(c){case"settings":return e.jsx(CC,{selectedSection:d,onSelectSection:L=>{u(L),W()}});case"agents":return e.jsx(jk,{onItemSelect:W});case"commands":return e.jsx(Ik,{onItemSelect:W});case"skills":return e.jsx(Tk,{onItemSelect:W});case"providers":return e.jsx(Uk,{onItemSelect:W});case"git-identities":return e.jsx(Xk,{onItemSelect:W});default:return null}},ye=()=>{switch(c){case"agents":return e.jsx(Ek,{});case"commands":return e.jsx(Pk,{});case"skills":return e.jsx(Hk,{});case"providers":return e.jsx(Jk,{});case"git-identities":return e.jsx(sC,{});case"settings":return e.jsx(yC,{section:d});default:return null}},me=Yt(),K=i.useMemo(()=>D&&M?"pl-[5.75rem]":"",[D,M]);return e.jsxs("div",{ref:C,className:R("flex h-full flex-col overflow-hidden bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:Y,className:R("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&K,D?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80"),style:{borderColor:"var(--interactive-border)"},children:[n&&m&&e.jsx("button",{type:"button",onClick:()=>f(!1),"aria-label":"Back",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(al,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:R("flex items-center",n?"gap-1":"h-full"),children:e.jsx("div",{className:R("flex items-center gap-1",!n&&"p-1 bg-background/50 rounded-lg"),children:T.map(({id:L,label:Q,icon:ce})=>{const he=c===L,Ne=ce;return n?e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{onClick:()=>B(L),className:R("relative flex h-9 w-9 items-center justify-center rounded-md transition-colors","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",he?"bg-secondary text-foreground shadow-sm":"text-muted-foreground"),"aria-pressed":he,"aria-label":Q,children:e.jsx(Ne,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(lt,{children:e.jsx("p",{children:Q})})]},L):e.jsxs("button",{onClick:()=>B(L),onMouseDown:he?Z:void 0,className:R("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",he?"app-region-drag bg-secondary text-foreground shadow-sm":"app-region-no-drag text-muted-foreground hover:bg-secondary/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-pressed":he,"aria-label":Q,children:[e.jsx(Ne,{className:"h-4 w-4",weight:"regular"}),O&&e.jsx("span",{children:Q})]},L)})})}),(t||oe)&&e.jsxs("div",{className:R("flex items-center gap-2",n?"":"pr-3"),children:[oe&&e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:G,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(Dr,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:G,className:R("flex h-9 max-w-[18rem] items-center gap-1.5 bg-transparent px-2 text-foreground outline-none hover:text-foreground/80 focus-visible:ring-2 focus-visible:ring-ring",!n&&"app-region-no-drag"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:G}),e.jsx(Wt,{className:"size-4 opacity-50"})]})}),e.jsx(rs,{align:"end",className:"w-auto",children:e.jsx(qa,{value:F?.id??"",onValueChange:L=>{L&&A(L)},children:P.map(L=>{const Q=L.label?.trim()?L.label.trim():L.path.split("/").filter(Boolean).pop()||L.path,ce=z(Q);return e.jsx(Ka,{value:L.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:ce})},L.id)})})})]}),t&&e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,"aria-label":"Close settings",className:R("inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",!n&&"app-region-no-drag"),children:e.jsx(es,{className:"h-5 w-5"})})}),e.jsx(lt,{children:e.jsxs("p",{children:["Close Settings (",me,"+,)"]})})]})]})]}),e.jsx("div",{className:"flex flex-1 overflow-hidden",children:n?m?e.jsx("div",{className:"flex-1 overflow-hidden bg-background","data-keyboard-avoid":"true",children:e.jsx(os,{children:ye()})}):e.jsx("div",{className:R("flex-1 overflow-hidden",w?"bg-background":"bg-sidebar"),children:e.jsx(os,{children:te()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:R("relative overflow-hidden border-r",D?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":w?"bg-background":"bg-sidebar",b?"transition-none":""),style:{width:`${p}px`,minWidth:`${p}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:R("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",b?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:q,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(os,{children:te()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(os,{children:ye()})})]})})]})},EC=()=>{const{isSidebarOpen:t,activeMainTab:r,setIsMobile:s,isSessionSwitcherOpen:n,isSettingsDialogOpen:o,setSettingsDialogOpen:a,isMultiRunLauncherOpen:c,setMultiRunLauncherOpen:l,multiRunLauncherPrefillPrompt:d}=Me(),{isMobile:u}=Gt();Bj({enabled:!0});const m=xi(g=>g.checkForUpdates);i.useEffect(()=>{const g=setTimeout(()=>{m()},3e3);return()=>clearTimeout(g)},[m]),i.useEffect(()=>{Me.getState().isMobile!==u&&s(u)},[u,s]),i.useEffect(()=>{if(typeof window>"u")return;let g;const x=()=>{g!==void 0&&window.clearTimeout(g),g=window.setTimeout(()=>{Me.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",x),()=>{window.removeEventListener("resize",x),g!==void 0&&window.clearTimeout(g)}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const g=document.documentElement;let x=0,b=!1,y=0,v=null;const S=Me.getState().setKeyboardOpen,C=()=>{v&&(v.style.setProperty("--oc-keyboard-avoid-offset","0px"),v.removeAttribute("data-keyboard-avoid-active"),v=null)},N=T=>{if(!T)return null;const E=T.closest("[data-keyboard-avoid]");if(E)return E;if(T.classList.contains("overlay-scrollbar-container")){const I=T.parentElement;if(I instanceof HTMLElement)return I}return T},j=()=>{x=0,b=!0,g.style.setProperty("--oc-keyboard-inset","0px"),S(!1)},D=()=>{const T=window.visualViewport,E=T?Math.round(T.height):window.innerHeight,I=T?Math.max(0,Math.round(T.offsetTop)):0;g.style.setProperty("--oc-visual-viewport-offset-top",`${I}px`);const A=document.activeElement,P=A?.tagName,z=P==="INPUT"||P==="TEXTAREA"||P==="SELECT"||!!A?.isContentEditable,G=Math.round(g.clientHeight||window.innerHeight),oe=E+I,O=Math.max(0,G-oe),Y=O>=(z?120:180)?O:0;if(b)Y===0&&(b=!1),x=0;else if(x===0)Y>0&&z&&(x=Y);else{const te=!z&&E>y+6;Y===0?(x=0,S(!1)):te?j():(Y>0&&z||Y>x)&&(x=Y,S(!0))}g.style.setProperty("--oc-keyboard-inset",`${x}px`),y=E;const B=/iPad|iPhone|iPod/.test(navigator.userAgent)&&x>0?34:0;g.style.setProperty("--oc-keyboard-home-indicator",`${B}px`);const W=z?N(A):null;if(!u||!W||!A)C();else{W!==v&&(C(),v=W);const te=I+E,me=A.getBoundingClientRect().bottom-te,K=8,L=Math.max(x,Y),Q=me>K&&L>0?Math.min(me,L):0,ce=v;ce&&(ce.style.setProperty("--oc-keyboard-avoid-offset",`${Q}px`),ce.setAttribute("data-keyboard-avoid-active","true"))}if(u&&z){const te=document.scrollingElement;te&&te.scrollTop!==0&&(te.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};D();const k=window.visualViewport;k?.addEventListener("resize",D),k?.addEventListener("scroll",D),window.addEventListener("resize",D),window.addEventListener("orientationchange",D);const M=T=>{const E=T.target;if(!E)return;const I=E.tagName;(I==="INPUT"||I==="TEXTAREA"||I==="SELECT"||E.isContentEditable)&&(b=!1),D()};document.addEventListener("focusin",M,!0);const w=T=>{const E=T.target;if(!E)return;const I=E.tagName;if(I==="INPUT"||I==="TEXTAREA"||I==="SELECT"||E.isContentEditable){const P=T.relatedTarget,F=P?.tagName;if(F==="INPUT"||F==="TEXTAREA"||F==="SELECT"||P?.isContentEditable)return;j()}};return document.addEventListener("focusout",w,!0),()=>{k?.removeEventListener("resize",D),k?.removeEventListener("scroll",D),window.removeEventListener("resize",D),window.removeEventListener("orientationchange",D),document.removeEventListener("focusin",M,!0),document.removeEventListener("focusout",w,!0),C()}},[u]);const f=i.useMemo(()=>{switch(r){case"plan":return e.jsx(rN,{});case"git":return e.jsx(JN,{});case"diff":return e.jsx(zv,{});case"terminal":return e.jsx(ik,{});case"files":return e.jsx(gk,{});default:return null}},[r]),p=r==="chat",h=o&&!u;return e.jsx(Ij,{children:e.jsxs("div",{className:R("main-content-safe-area h-[100dvh]",u?"flex flex-col":"flex","bg-background"),children:[e.jsx(oj,{}),e.jsx(cj,{}),e.jsx(kj,{}),u?e.jsxs(e.Fragment,{children:[!(o||c)&&e.jsx(Jd,{}),e.jsx("div",{className:R("flex flex-1 overflow-hidden",(o||c)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:n?e.jsx("div",{className:"flex-1 overflow-hidden bg-sidebar",children:e.jsx(os,{children:e.jsx(ni,{mobileVariant:!0})})}):e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:R("absolute inset-0",!p&&"invisible"),children:e.jsx(os,{children:e.jsx(Po,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(os,{children:f})})]})}),c&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(os,{children:e.jsx(mu,{initialPrompt:d,onCreated:()=>l(!1),onCancel:()=>l(!1)})})}),o&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(os,{children:e.jsx(rl,{onClose:()=>a(!1)})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:R("absolute inset-0 flex flex-col",(h||c)&&"invisible"),children:[e.jsx(Jd,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx(ej,{isOpen:t,isMobile:u,children:e.jsx(ni,{})}),e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:R("absolute inset-0",!p&&"invisible"),children:e.jsx(os,{children:e.jsx(Po,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(os,{children:f})})]})]})]}),c&&e.jsx("div",{className:R("absolute inset-0 z-10 bg-background"),children:e.jsx(os,{children:e.jsx(mu,{initialPrompt:d,onCreated:()=>l(!1),onCancel:()=>l(!1)})})})]}),h&&e.jsx("div",{className:R("absolute inset-0 z-10 bg-background"),children:e.jsx(os,{children:e.jsx(rl,{onClose:()=>a(!1)})})})]})]})})},IC=550,PC=1400,TC=280,FC=()=>{const t=Hs(),r=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),s=i.useMemo(()=>{const I=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof I=="string"&&I.trim().length>0?I.trim():null},[]),n=i.useRef(!1),[o,a]=i.useState("sessions"),[c,l]=i.useState(0),d=i.useRef(null),u=ve(I=>I.currentSessionId),m=ve(I=>I.sessions),f=i.useMemo(()=>u?m.find(I=>I.id===u)?.title||"Session":null,[u,m]),p=ve(I=>!!I.newSessionDraft?.open),h=ve(I=>I.openNewSessionDraft),[g,x]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),b=Je(I=>I.isInitialized),y=Je(I=>I.initializeApp),v=ve(I=>I.loadSessions),S=ve(I=>I.loadMessages),C=ve(I=>I.messages),[N,j]=i.useState(()=>b),[D,k]=i.useState(!1),M=i.useRef(0);i.useEffect(()=>{u&&a("chat")},[u]),i.useEffect(()=>{const I=t.vscode;I&&I.executeCommand("openchamber.setActiveSession",u,f)},[f,u,t.vscode]),i.useEffect(()=>{r!=="editor"&&!u&&!p&&o==="chat"&&a("sessions")},[u,p,o,r]);const w=i.useCallback(()=>{a("sessions")},[]);i.useEffect(()=>{const I=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(I==="connected"||I==="connecting"||I==="error"||I==="disconnected")&&x(I);const A=P=>{const z=P.detail?.status;(z==="connected"||z==="connecting"||z==="error"||z==="disconnected")&&x(z)};return window.addEventListener("openchamber:connection-status",A),()=>window.removeEventListener("openchamber:connection-status",A)},[]),i.useEffect(()=>{const I=A=>{const F=A.detail?.view;F==="settings"?a("settings"):F==="chat"?a("chat"):F==="sessions"&&a("sessions")};return window.addEventListener("openchamber:navigate",I),()=>window.removeEventListener("openchamber:navigate",I)},[]),i.useEffect(()=>{(async()=>{if(D||N||g!=="connected")return;const A=Date.now();if(!(A-M.current<750)){M.current=A,k(!0);try{const P=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();P&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:b}),b||await y();const F=Je.getState();if(!F.isInitialized||!F.isConnected||F.providers.length===0||F.agents.length===0)return;await v();const z=ve.getState().error;if(P&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:F.providers.length,agents:F.agents.length,sessions:ve.getState().sessions.length,sessionsError:z}),typeof z=="string"&&z.length>0)return;j(!0)}catch{}finally{k(!1)}}})()},[g,b,N,y,D,v]),i.useEffect(()=>{if(r==="editor"&&!n.current&&!(!N||g!=="connected")){if(!s){n.current=!0,h();return}m.some(I=>I.id===s)&&(n.current=!0,ve.getState().setCurrentSession(s))}},[g,N,s,h,m,r]),i.useEffect(()=>{(async()=>{if(!N||g!=="connected"||o!=="chat"||p||!u)return;if(!(C.has(u)&&(C.get(u)?.length||0)>0))try{await S(u)}catch{}})()},[g,u,o,N,S,C,p]),i.useEffect(()=>{const I=d.current;if(!I)return;const A=new ResizeObserver(P=>{for(const F of P)l(F.contentRect.width)});return A.observe(I),l(I.clientWidth),()=>A.disconnect()},[]);const T=c>0&&c<IC,E=c>=PC;return i.useEffect(()=>{E&&o==="sessions"&&r==="sidebar"&&a("chat")},[E,o,r]),e.jsx("div",{ref:d,className:"h-full w-full bg-background text-foreground flex flex-col",children:r==="editor"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(ja,{title:m.find(I=>I.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:e.jsx(Po,{})})})]}):o==="settings"?e.jsx(rl,{onClose:()=>a(E?"chat":"sessions"),forceMobile:T}):E?e.jsxs("div",{className:"flex h-full",children:[e.jsx("div",{className:"h-full border-r border-border overflow-hidden flex-shrink-0",style:{width:TC},children:e.jsx(ni,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(ja,{title:p&&!u?"New session":m.find(I=>I.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:e.jsx(Po,{})})})]})]}):o==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(ja,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ni,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>a("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(ja,{title:p&&!u?"New session":m.find(I=>I.id===u)?.title||"Chat",showBack:!0,onBack:w,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:e.jsx(Po,{})})})]})})},ja=({title:t,showBack:r,onBack:s,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:c,showContextUsage:l})=>{const{getCurrentModel:d}=Je(),u=ve(x=>x.getContextUsage),m=d(),f=m?.limit&&typeof m.limit=="object"?m.limit:null,p=typeof f?.context=="number"?f.context:0,h=typeof f?.output=="number"?f.output:0,g=u(p,h);return e.jsxs("div",{className:"flex items-center gap-1.5 pl-1 pr-2 py-1 border-b border-border bg-background shrink-0",children:[r&&s&&e.jsx("button",{onClick:s,className:"inline-flex h-7 w-7 items-center justify-center text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:e.jsx(af,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:t,children:t}),n&&e.jsx("button",{onClick:n,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"New session",children:e.jsx(ls,{className:"h-5 w-5"})}),a&&e.jsx("button",{onClick:a,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Agent Manager",children:e.jsx(Fo,{className:"h-5 w-5"})}),c&&e.jsx(Wc,{headerIconButtonClass:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"}),o&&e.jsx("button",{onClick:o,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Settings",children:e.jsx(vn,{className:"h-5 w-5"})}),l&&g&&g.totalTokens>0&&e.jsx(zc,{totalTokens:g.totalTokens,percentage:g.percentage,contextLimit:g.contextLimit,outputLimit:g.outputLimit??0,size:"compact"})]})},wm=".openchamber",Sa=t=>{const r=Lt.getState(),s=r.activeProjectId,n=s?r.projects.find(o=>o.id===s)?.path:void 0;return typeof n=="string"&&n.trim().length>0?n:t?$t(t):null},$t=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},vm=t=>{const r=$t(t);return!r||r==="/"?`/${wm}`:`${r}/${wm}`},RC=(t,r)=>{const s=$t(t);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const c=$t(o);if(c)return c}const a=typeof n.name=="string"?n.name.trim():"";return!a||!s?null:`${s}/${a}`}).filter(n=>!!n)},LC=async t=>{const r=$t(t);if(!r)return[];try{const n=(await Oe.listLocalDirectory(r)).filter(o=>o.isDirectory);return RC(r,n)}catch{return[]}},jm=(t,r)=>{const s=$t(t),n=$t(r);if(!s||!n)return!1;if(s===n)return!0;const o=n==="/"?"/":`${n}/`;return s.startsWith(o)},yh=async(t,r)=>{const s=$t(r);if(!s)return s;try{const n=await t.path.get({directory:s});return $t(n.data?.directory??"")||s}catch{return s}},bh=async(t,r)=>{const s=$t(r);if(!s)return[];const n=await yh(t,s),o=c=>c.filter(l=>{const d=$t(l.directory??"");return d?jm(d,s)||n!==s&&jm(d,n):!1}),a=async c=>{const l=await t.session.list({directory:c});return Array.isArray(l.data)?l.data:[]};try{const c=o(await a(s));if(c.length>0)return c}catch{}if(n&&n!==s)try{const c=o(await a(n));if(c.length>0)return c}catch{}try{const c=await t.session.list(void 0),l=Array.isArray(c.data)?c.data:[];return o(l)}catch{return[]}},OC=async(t,r)=>{const s=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&s.set($t(o.path),o.worktreeMetadata)});const n=Array.from(new Set(t.sessions.map(o=>$t(o.path)))).filter(Boolean).filter(o=>!s.has(o));if(n.length===0)return s;try{const o=await Si(r),a=new Map(o.map(c=>[$t(c.worktree),c]));n.forEach(c=>{const l=a.get(c);l&&s.set(c,Ni(r,l))})}catch{}return s},vc=async t=>{const{apiClient:r,group:s,projectDirectory:n,worktreePaths:o}=t,a=await OC(s,n),c=ve.getState(),l=Array.from(new Set(o.map(p=>$t(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<l.length;){const p=l[u];u+=1;const h=s.sessions.filter(v=>$t(v.path)===p).map(v=>v.id),g=c.getSessionsByDirectory(p),x=Array.isArray(g)?g.map(v=>v.id):[];let b=[];if(x.length===0)try{b=(await bh(r,p)).map(S=>S.id)}catch{b=[]}const y=Array.from(new Set([...x,...b,...h].filter(Boolean)));m.push({worktreePath:p,sessionIds:y,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,l.length)},f)),m};function _C(t){if(!t)return null;const r=t.split("/");if(r.length<3)return null;const s=r[0];if(!s||s.includes(" "))return null;const n=r[1];if(!n)return null;const o=r[r.length-1],a=parseInt(o,10),c=r.length>=4&&!isNaN(a)&&String(a)===o,l=c?r.slice(2,-1):r.slice(2);if(l.length===0)return null;const d=l.join("/");return{groupSlug:s,provider:n,model:d,index:c?a:1}}const Zr=ns()(fs((t,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const s=vt.getState().currentDirectory,n=Sa(s);if(!n){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=$t(n),l={id:Lt.getState().projects.find(u=>$t(u.path)===o)?.id??`path:${o}`,path:o},d=r().groups;t({isLoading:!0,error:null});try{const u=Oe.getApiClient(),m=await yh(u,o),f=m&&m!==o?{...l,path:m}:null,p=await $o(l).catch(()=>[]),h=f?await $o(f).catch(()=>[]):[],g=new Set;[...p,...h].forEach(k=>{k?.path&&g.add($t(k.path))});let x=new Map,b=[];try{b=await Si(o),x=new Map(b.map(k=>[$t(k.worktree),k]))}catch{console.debug("Failed to list git worktrees")}const y=async()=>{try{const M=await u.session.list({directory:o}),w=Array.isArray(M.data)?M.data:[];if(w.some(T=>{const E=$t(T.directory??"");return E?g.has(E):!1}))return w}catch{}const k=await u.session.list(void 0);return Array.isArray(k.data)?k.data:[]},v=async k=>{const M=new Map,w=5;let T=0;const E=async()=>{for(;T<k.length;){const I=k[T];T+=1;const A=$t(I);if(A)try{(await bh(u,A)).forEach(F=>M.set(F.id,F))}catch(P){console.debug("Failed to fetch sessions from worktree:",A,P)}}};return await Promise.all(Array.from({length:Math.min(w,k.length)},E)),Array.from(M.values())};let C=(await y()).filter(k=>{const M=$t(k.directory??"");return M?g.has(M):!1});if(C.length===0){const k=new Set;g.forEach(w=>k.add(w)),b.map(w=>$t(w.worktree)).filter(Boolean).forEach(w=>k.add(w));const M=[vm(o),vm(m)].map(w=>$t(w)).filter(Boolean);await Promise.all(Array.from(new Set(M)).map(async w=>{(await LC(w)).forEach(E=>k.add(E))})),k.size>0&&(C=await v(Array.from(k)))}const N=new Map;for(const k of C){const M=k.time?.updated??0;N.set(k.id,typeof M=="number"?M:0)}const j=new Map;for(const k of C){const M=_C(k.title);if(!M)continue;const w=$t(k.directory),T=x.get(w),E={id:k.id,path:w,providerId:M.provider,modelId:M.model,instanceNumber:M.index,branch:T?.branch??"",displayLabel:`${M.provider}/${M.model}`,worktreeMetadata:T?Ni(o,T):void 0},I=j.get(M.groupSlug);I?I.push(E):j.set(M.groupSlug,[E])}const D=Array.from(j.entries()).map(([k,M])=>{const w=M.reduce((T,E)=>{const I=N.get(E.id)??0;return Math.max(T,I)},0);return{name:k,sessions:M.sort((T,E)=>{const I=T.providerId.localeCompare(E.providerId);if(I!==0)return I;const A=T.modelId.localeCompare(E.modelId);return A!==0?A:T.instanceNumber-E.instanceNumber}),lastActive:w||Date.now(),sessionCount:M.length}});D.sort((k,M)=>k.name.localeCompare(M.name)),t({groups:D,isLoading:!1,error:null})}catch(u){console.error("Failed to load agent groups:",u),t({groups:d.length>0?d:[],isLoading:!1,error:u instanceof Error?u.message:"Failed to load agent groups"})}},selectGroup:s=>{const{groups:n}=r(),o=n.find(a=>a.name===s);t({selectedGroupName:s,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:s=>{t({selectedSessionId:s})},deleteGroup:async s=>{const n=r().groups.find(c=>c.name===s);if(!n)return!1;const o=vt.getState().currentDirectory,a=Sa(o);if(!a)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const c=Oe.getApiClient(),l=await vc({apiClient:c,group:n,projectDirectory:$t(a),worktreePaths:n.sessions.map(f=>f.path)}),d=ve.getState(),u=new Set;l.forEach(({worktreePath:f,sessionIds:p,metadata:h})=>{p.forEach(g=>{u.add(g),h&&(d.setWorktreeMetadata(g,h),d.setSessionDirectory(g,f))})});const{failedIds:m}=await d.deleteSessions(Array.from(u),{archiveWorktree:!0,silent:!0});return m.length>0&&t({error:"Failed to delete some sessions"}),r().selectedGroupName===s&&t({selectedGroupName:null,selectedSessionId:null}),await r().loadGroups(),m.length===0}catch(c){return t({error:c instanceof Error?c.message:"Failed to delete group"}),!1}finally{t({isLoading:!1})}},deleteGroupWorktree:async(s,n)=>{const o=r().groups.find(d=>d.name===s);if(!o)return!1;const a=$t(n);if(!a)return!1;const c=vt.getState().currentDirectory,l=Sa(c);if(!l)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const d=Oe.getApiClient(),u=await vc({apiClient:d,group:o,projectDirectory:$t(l),worktreePaths:[a]}),m=ve.getState(),f=new Set;u.forEach(({worktreePath:g,sessionIds:x,metadata:b})=>{x.forEach(y=>{f.add(y),b&&(m.setWorktreeMetadata(y,b),m.setSessionDirectory(y,g))})});const{failedIds:p}=await m.deleteSessions(Array.from(f),{archiveWorktree:!0,silent:!0});p.length>0&&t({error:"Failed to delete some sessions"}),await r().loadGroups();const h=r().groups.find(g=>g.name===s);if(!h)return r().selectedGroupName===s&&t({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===s){const g=r().selectedSessionId,x=new Set(h.sessions.map(b=>b.id));(!g||!x.has(g))&&t({selectedSessionId:h.sessions[0]?.id??null})}return p.length===0}catch(d){return t({error:d instanceof Error?d.message:"Failed to delete worktree"}),!1}finally{t({isLoading:!1})}},keepOnlyGroupWorktree:async(s,n)=>{const o=r().groups.find(m=>m.name===s);if(!o)return!1;const a=$t(n);if(!a)return!1;const l=Array.from(new Set(o.sessions.map(m=>$t(m.path)).filter(Boolean))).filter(m=>m!==a);if(l.length===0)return!0;const d=vt.getState().currentDirectory,u=Sa(d);if(!u)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const m=Oe.getApiClient(),f=await vc({apiClient:m,group:o,projectDirectory:$t(u),worktreePaths:l}),p=ve.getState(),h=new Set;f.forEach(({worktreePath:x,sessionIds:b,metadata:y})=>{b.forEach(v=>{h.add(v),y&&(p.setWorktreeMetadata(v,y),p.setSessionDirectory(v,x))})});const{failedIds:g}=await p.deleteSessions(Array.from(h),{archiveWorktree:!0,silent:!0});if(g.length>0&&t({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===s){const x=r().groups.find(y=>y.name===s),b=x?.sessions.find(y=>$t(y.path)===a)??x?.sessions[0]??null;t({selectedSessionId:b?.id??null})}return g.length===0}catch(m){return t({error:m instanceof Error?m.message:"Failed to remove other worktrees"}),!1}finally{t({isLoading:!1})}},getSelectedGroup:()=>{const{groups:s,selectedGroupName:n}=r();return n?s.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:s}=r(),n=r().getSelectedGroup();return!n||!s?null:n.sessions.find(o=>o.id===s)??null},clearError:()=>{t({error:null})}}),{name:"agent-groups-store"})),$C=t=>{const s=Date.now()-t,n=Math.floor(s/(60*1e3)),o=Math.floor(s/(3600*1e3)),a=Math.floor(s/(1440*60*1e3));return n<1?"now":n<60?`${n}m`:o<24?`${o}h`:`${a}d`},BC=({group:t,isSelected:r,onSelect:s})=>{const[n,o]=i.useState(!1),[a,c]=i.useState(!1),[l,d]=i.useState(!1),u=Zr(f=>f.deleteGroup),m=i.useCallback(async()=>{if(l)return;if(d(!0),V.info(`Deleting "${t.name}"...`),await u(t.name))V.success(`Deleted "${t.name}"`);else{const p=Zr.getState().error;V.error(p||`Failed to delete "${t.name}"`)}d(!1),c(!1)},[u,t.name,l]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1.5 cursor-pointer",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),onClick:s,children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col gap-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-micro text-muted-foreground/60 flex items-center gap-1",children:[e.jsx(Ut,{className:"h-3 w-3"}),t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:$C(t.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(ts,{open:n,onOpenChange:o,children:[e.jsx(ss,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","opacity-0 group-hover:opacity-100",n&&"opacity-100"),"aria-label":"Group menu",onClick:f=>f.stopPropagation(),children:e.jsx(nn,{className:"h-3.5 w-3.5"})})}),e.jsx(rs,{align:"end",className:"min-w-[140px]",children:e.jsx(kt,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),c(!0)},children:"Delete"})})]})})]})}),e.jsx(us,{open:a,onOpenChange:c,children:e.jsxs(ms,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Delete agent group"}),e.jsxs(Ss,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"outline",onClick:()=>c(!1),disabled:l,children:"Cancel"}),e.jsx(Se,{variant:"destructive",onClick:()=>{m()},disabled:l,children:l?"Deleting…":"Delete"})]})]})})]})},zC=({className:t,selectedGroupName:r,onGroupSelect:s,onNewAgent:n})=>{const[o,a]=i.useState(""),[c,l]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Zr(),f=vt(b=>b.currentDirectory);i.useEffect(()=>{f&&m()},[f,m]);const p=5,h=i.useMemo(()=>{if(!o.trim())return d;const b=o.toLowerCase();return d.filter(y=>y.name.toLowerCase().includes(b))},[o,d]),g=c?h:h.slice(0,p),x=h.length-p;return e.jsxs("div",{className:R("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",t),children:[e.jsx("div",{className:"px-2.5 pt-3 pb-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(St,{value:o,onChange:b=>a(b.target.value),placeholder:"Search Agent Groups...",className:"pl-8 h-8 rounded-lg border-border/40 bg-background/50 typography-meta"})]})}),e.jsx("div",{className:"px-2.5 pb-2",children:e.jsxs(Se,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label",children:"New Agent Group"})]})}),e.jsxs("div",{className:"px-2.5 py-1.5 flex items-center gap-1",children:[e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium text-muted-foreground uppercase tracking-wider",children:"Agent Groups"}),u&&e.jsx("span",{className:"typography-micro text-muted-foreground/50 ml-auto",children:"Loading..."})]}),e.jsxs(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[g.map(b=>e.jsx(BC,{group:b,isSelected:r===b.name,onSelect:()=>s?.(b.name)},b.name)),!c&&x>0&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",x,")"]}),c&&h.length>p&&e.jsx("button",{type:"button",onClick:()=>l(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&h.length===0&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:o.trim()?"No groups found":"No agent groups yet"}),!o.trim()&&e.jsx("p",{className:"typography-micro text-muted-foreground/60 mt-1",children:"Create a new agent group to get started"})]})]})]})},HC=10*1024*1024,WC=5,UC=({className:t,onCreateGroup:r,isCreating:s=!1})=>{const[n,o]=i.useState(""),[a,c]=i.useState(""),[l,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState("HEAD"),[h,g]=i.useState([]),[x,b]=i.useState(!1),[y,v]=i.useState([]),[S,C]=i.useState(!1),[N,j]=i.useState(!1),D=i.useRef(null),k=i.useRef(null),M=vt(te=>te.currentDirectory??null),{isGitRepository:w,isLoading:T}=Rl(M),E=i.useMemo(()=>{if(typeof window>"u")return null;const te=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof te=="string"&&te.trim().length>0?te.trim():null},[]),I=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),A=Lt(te=>te.activeProjectId),P=Lt(te=>te.projects),F=i.useMemo(()=>{if(I&&E)return{id:`vscode:${E}`,path:E};if(A){const te=P.find(ye=>ye.id===A);if(te?.path)return{id:te.id,path:te.path}}return M?{id:`path:${M}`,path:M}:null},[A,P,M,E,I]);i.useEffect(()=>{if(!F)return;let te=!1;return j(!0),(async()=>{try{const ye=await go(F);te||v(ye)}catch{}finally{te||j(!1)}})(),()=>{te=!0}},[F]);const z=i.useCallback(te=>{l.length>=WC||d(ye=>[...ye,te])},[l.length]),G=i.useCallback(te=>{d(ye=>ye.filter((me,K)=>K!==te))},[]),oe=i.useCallback((te,ye)=>{d(me=>me.map((K,L)=>L===te?ye:K))},[]),O=async te=>{const ye=te.target.files;if(!ye)return;let me=0;for(let K=0;K<ye.length;K++){const L=ye[K];if(L.size>HC){V.error(`File "${L.name}" is too large (max 10MB)`);continue}try{const Q=await new Promise((he,Ne)=>{const H=new FileReader;H.onload=()=>he(H.result),H.onerror=Ne,H.readAsDataURL(L)}),ce={id:ai(),filename:L.name,mimeType:L.type||"application/octet-stream",size:L.size,dataUrl:Q};g(he=>[...he,ce]),me++}catch(Q){console.error("File attach failed",Q),V.error(`Failed to attach "${L.name}"`)}}me>0&&V.success(`Attached ${me} file${me>1?"s":""}`),D.current&&(D.current.value="")},q=te=>{g(ye=>ye.filter(me=>me.id!==te))},Y=x||s,Z=!!(n.trim()&&a.trim()&&l.length>=1&&w&&!T),B=async te=>{if(te.preventDefault(),!(!Z||Y)){b(!0);try{const ye=l.map(({providerID:L,modelID:Q,displayName:ce,variant:he})=>({providerID:L,modelID:Q,displayName:ce,variant:he})),me=h.length>0?h.map(L=>({mime:L.mimeType,filename:L.filename,url:L.dataUrl})):void 0,K=y.filter(L=>L.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:ye,agent:u||void 0,worktreeBaseBranch:f,files:me,setupCommands:K.length>0?K:void 0}),o(""),c(""),d([]),m(""),g([]),p("HEAD")}catch(ye){console.error("Failed to create agent group:",ye),V.error("Failed to create agent group")}finally{b(!1)}}},W=te=>{Tl(te)||te.key==="Enter"&&!te.shiftKey&&(te.preventDefault(),Z&&!Y&&B(te))};return e.jsx("div",{className:R("flex flex-col items-center justify-center h-full w-full p-4",t),children:e.jsxs("form",{onSubmit:B,className:"w-full max-w-2xl space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:"Group Name"}),e.jsx(St,{id:"group-name",value:n,onChange:te=>o(te.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch naming"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-1.5",children:[e.jsx(Ut,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(Sp,{directory:M,value:f,onChange:p}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from ",e.jsx("code",{className:"font-mono text-xs",children:f})]})]}),e.jsxs(Pn,{open:S,onOpenChange:C,children:[e.jsxs(xo,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",y.filter(te=>te.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",y.filter(te=>te.trim()).length," configured)"]})]}),e.jsx(Wt,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",S&&"rotate-180")})]}),e.jsx(Tn,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_PROJECT_PATH"})," for project root."]}),N?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[y.map((te,ye)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(St,{value:te,onChange:me=>{const K=[...y];K[ye]=me.target.value,v(K)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const me=y.filter((K,L)=>L!==ye);v(me)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(es,{className:"h-4 w-4"})})]},ye)),e.jsxs("button",{type:"button",onClick:()=>v([...y,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(ls,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(Np,{value:u,onChange:m}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Models"}),e.jsx(jp,{selectedModels:l,onAdd:z,onRemove:G,onUpdate:oe,minModels:1,addButtonLabel:"Add model",maxModels:5})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:"Prompt"}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-input/10 dark:bg-input/30 overflow-hidden",children:[e.jsx(Fs,{ref:k,id:"prompt",value:a,onChange:te=>c(te.target.value),onKeyDown:W,placeholder:"Ask anything...",className:"min-h-[100px] max-h-[300px] resize-none border-0 bg-transparent px-4 py-3 typography-markdown focus-visible:ring-0 focus-visible:ring-offset-0"}),h.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:h.map(te=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[te.mimeType.startsWith("image/")?e.jsx(Ar,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(jr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:te.filename,children:te.filename}),e.jsx("button",{type:"button",onClick:()=>q(te.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(es,{className:"h-3.5 w-3.5"})})]},te.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:D,type:"file",multiple:!0,className:"hidden",onChange:O,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>D.current?.click(),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors","aria-label":"Add attachment",children:e.jsx(Vm,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length," model",l.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!Z||Y,className:R("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",Z?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:Y?e.jsx(Qx,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Vo,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},VC=({group:t,className:r})=>{const{selectedSessionId:s,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Zr(),{setCurrentSession:c,currentSessionId:l}=ve(),[d,u]=i.useState(null),[m,f]=i.useState(!1),p=i.useMemo(()=>s?t.sessions.find(S=>S.id===s)??t.sessions[0]??null:t.sessions[0]??null,[t.sessions,s]),h=i.useCallback(S=>{n(S.id),c(S.id)},[n,c]);i.useEffect(()=>{if(t.sessions.length>0){const S=s?t.sessions.find(C=>C.id===s)??t.sessions[0]:t.sessions[0];S&&(S.id!==l&&c(S.id),s||n(S.id))}},[t.name,t.sessions,s,l,n,c]);const g=p?.id===l,x=i.useCallback(()=>{if(!p?.path){V.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{V.success("Worktree path copied")}).catch(()=>{V.error("Failed to copy path")})},[p?.path]),b=i.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),y=i.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),v=i.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(V.info("Removing worktree..."),await o(t.name,d.path))V.success("Worktree removed");else{const C=Zr.getState().error;V.error(C||"Failed to remove worktree");return}else if(V.info("Removing other worktrees..."),await a(t.name,d.path))V.success("Removed other worktrees");else{const C=Zr.getState().error;V.error(C||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,t.name,m,a,d]);return e.jsxs("div",{className:R("flex h-full flex-col bg-background",r),children:[e.jsxs("div",{className:"flex-shrink-0 border-b border-border/30 px-4 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"typography-heading-lg text-foreground truncate",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{children:"·"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ut,{className:"h-3.5 w-3.5"}),p?.worktreeMetadata?.label||p?.branch||"No branch"]})]})]})}),t.sessions.length>0&&e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsxs(Se,{variant:"outline",className:"w-full justify-between h-10 px-3",children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:p&&e.jsxs(e.Fragment,{children:[e.jsx(gs,{providerId:p.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsx("span",{className:"truncate typography-body",children:p.modelId}),p.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",p.instanceNumber]})]})}),e.jsx(Wt,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(rs,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:t.sessions.map(S=>e.jsxs(kt,{onClick:()=>h(S),className:"flex items-center gap-2 py-2",children:[e.jsx(gs,{providerId:S.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate typography-body",children:S.modelId}),S.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",S.instanceNumber]})]}),S.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(Ut,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:S.worktreeMetadata?.label||S.branch})]})]}),p?.id===S.id&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},S.id))})]})}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(Se,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(nn,{className:"h-4 w-4"})})}),e.jsxs(rs,{align:"end",className:"min-w-[220px]",children:[e.jsx(kt,{onSelect:S=>{S.preventDefault(),b()},variant:"destructive",children:"Remove this worktree"}),e.jsx(kt,{onSelect:S=>{S.preventDefault(),y()},children:"Leave this one, remove others"}),e.jsxs(kt,{onClick:S=>{S.stopPropagation(),x()},disabled:!p?.path,children:[e.jsx(nr,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(us,{open:!!d,onOpenChange:S=>{S||u(null)},children:e.jsxs(ms,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(Ss,{children:d?.kind==="remove"?e.jsxs(e.Fragment,{children:["Remove ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label}),"? This deletes all sessions in that worktree and removes the worktree itself."]}):e.jsxs(e.Fragment,{children:["Keep ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label})," and remove the other worktrees in ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"."]})})]}),e.jsxs(Gs,{children:[e.jsx(Se,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Se,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{v()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?g?e.jsx(Xp,{sessionId:p.id,children:e.jsx(Yp,{})}):e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx("div",{className:"px-4 py-2 bg-muted/30 border-b border-border/30",children:e.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx(gs,{providerId:p.providerId,className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel}),e.jsx("span",{children:"·"}),e.jsx("span",{className:"font-mono text-xs truncate",children:p.path})]})}),e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center p-8",children:[e.jsxs("p",{className:"typography-body text-muted-foreground mb-2",children:["Loading session for ",e.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground/60",children:["Session ID: ",p.id]})]})})]}):e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx("p",{className:"typography-body text-muted-foreground",children:"No sessions in this group"})})})]})},GC=({className:t})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[s,n]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=Je(S=>S.isInitialized),a=Je(S=>S.initializeApp),c=ve(S=>S.loadSessions),l=vt(S=>S.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Zr(),{createMultiRun:h,isLoading:g}=Io();i.useEffect(()=>{if(!r)return;const S=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(S==="connected"||S==="connecting"||S==="error"||S==="disconnected")&&n(S);const C=N=>{const D=N.detail?.status;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&n(D)};return window.addEventListener("openchamber:connection-status",C),()=>window.removeEventListener("openchamber:connection-status",C)},[r]),i.useEffect(()=>{if(!r||s!=="connected")return;const S=Date.now();if(S-d.current<750)return;d.current=S;const C=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof C=="string"&&C.trim().length>0)try{l(C,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const j=Je.getState();if(!j.isInitialized||!j.isConnected||j.providers.length===0||j.agents.length===0)return;await c(),hs()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:j.providers.length,agents:j.agents.length,sessions:ve.getState().sessions.length})}catch{}})()},[s,o,a,r,c,l]);const x=i.useCallback(S=>{m(S)},[m]),b=i.useCallback(()=>{m(null)},[m]),y=i.useCallback(async S=>{V.info(`Creating agent group "${S.name}" with ${S.models.length} model(s)...`);const C=await h(S);if(C){V.success(`Agent group "${S.name}" created with ${C.sessionIds.length} session(s)`);const N=C.groupSlug,j=async(D=6)=>{for(let k=0;k<D;k+=1){if(await p(),Zr.getState().groups.some(w=>w.name===N))return!0;await new Promise(w=>setTimeout(w,500))}return!1};try{await ve.getState().loadSessions()}catch{}await j(),m(N)}else{const N=Io.getState().error;V.error(N||"Failed to create agent group")}},[h,p,m]),v=f();return e.jsxs("div",{className:R("flex h-full w-full bg-background",t),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(zC,{selectedGroupName:u,onGroupSelect:x,onNewAgent:b})}),e.jsx("div",{className:"flex-1 min-w-0",children:v?e.jsx(VC,{group:v}):e.jsx(UC,{onCreateGroup:y,isCreating:g})})]})},qC=(t=5e3)=>{const[r,s]=Ae.useState(null);return Ae.useEffect(()=>{if(!ds())return;let n=!1,o=null;const a=async()=>{const c=await yy();n||(s(c),o=setTimeout(a,t))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[t]),r},KC=({onClose:t})=>{const{sessions:r,messages:s,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:c}=ve(),l=qC(4e3),d=i.useMemo(()=>{let f=0;return s.forEach(p=>{f+=p.length}),f},[s]),u=i.useMemo(()=>r.map(f=>{const p=s.get(f.id)?.length||0,h=n.get(f.id);return{id:f.id,title:f.title||"Untitled",messageCount:p,isStreaming:h?.isStreaming||!1,isZombie:h?.isZombie||!1,backgroundCount:h?.backgroundMessageCount||0,lastAccessed:h?.lastAccessedAt||0,isCurrent:f.id===o}}).sort((f,p)=>p.lastAccessed-f.lastAccessed),[r,s,n,o]),m=s.size;return e.jsxs(Pl,{className:"fixed bottom-4 right-4 w-96 p-4 shadow-none z-50 bg-background/95 backdrop-blur bottom-safe-area",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yx,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),t&&e.jsx(Se,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:t,children:e.jsx(es,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Total Messages"}),e.jsx("div",{className:"typography-markdown font-semibold",children:d})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Cached Sessions"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[m," / ",Tr.MAX_SESSIONS]})]})]}),l&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:l.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[l.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:l.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[Tr.VIEWPORT_MESSAGES," messages"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Background Stream Limit:"}),e.jsxs("span",{children:[Tr.BACKGROUND_STREAMING_BUFFER," messages"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Zombie Timeout:"}),e.jsxs("span",{children:[Tr.ZOMBIE_TIMEOUT/1e3/60," minutes"]})]})]}),e.jsxs("div",{className:"border-t pt-2",children:[e.jsx("div",{className:"typography-meta font-semibold mb-1",children:"Sessions in Memory:"}),e.jsx(xt,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:u.map(f=>e.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${f.isCurrent?"bg-primary/10":"bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("span",{className:"truncate",children:f.title}),f.isStreaming&&e.jsx(Xx,{className:"h-3 w-3 text-primary animate-pulse"}),f.isZombie&&e.jsx("span",{className:"text-warning",children:"!"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-mono ${f.messageCount>Tr.VIEWPORT_MESSAGES?"text-warning":""}`,children:[f.messageCount," msgs"]}),f.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",f.backgroundCount]})]})]},f.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(Se,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(zs,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(lt,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{c()},children:"Evict LRU"})}),e.jsx(lt,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Se,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[MemoryDebug] Session store state:",{sessions:r.map(f=>({id:f.id,title:f.title})),currentSessionId:o,cachedSessions:Array.from(s.keys()),memoryStates:Object.fromEntries(n)})},children:"Log State"})}),e.jsx(lt,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},JC="openchamber-message-cursors",li="cursors",QC=1,wh="openchamber.messageCursors",Hl=()=>typeof window<"u",vh=()=>Hl()&&typeof indexedDB<"u",YC=()=>vh()?new Promise((t,r)=>{const s=indexedDB.open(JC,QC);s.onupgradeneeded=()=>{const n=s.result;n.objectStoreNames.contains(li)||n.createObjectStore(li)},s.onerror=()=>{r(s.error??new Error("Failed to open IndexedDB"))},s.onsuccess=()=>{t(s.result)}}):Promise.reject(new Error("IndexedDB not supported")),XC=()=>{if(!Hl())return{};try{const t=window.localStorage.getItem(wh);if(!t)return{};const r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},ZC=t=>{if(Hl())try{window.localStorage.setItem(wh,JSON.stringify(t))}catch{}},eM=async(t,r,s)=>{if(!t||!r)return;if(vh())try{const o=await YC();await new Promise((a,c)=>{const l=o.transaction(li,"readwrite");l.objectStore(li).put({messageId:r,completedAt:s},t),l.oncomplete=()=>a(),l.onerror=()=>c(l.error??new Error("Cursor write failed")),l.onabort=()=>c(l.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=XC();n[t]={messageId:r,completedAt:s},ZC(n)},wr=(t,r)=>{if(!t||typeof t!="object")return null;const s=t;for(let n=0;n<r.length;n++){const o=s[r[n]];if(typeof o=="string"&&o.length>0)return o}return null},tM=50,sM=750,Sm=new WeakMap,Nm=t=>{if(!t||!Array.isArray(t))return 0;const r=Sm.get(t);if(r!==void 0)return r;let s=0;for(let n=0;n<t.length;n++){const o=t[n];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(s+=a.length)}}return Sm.set(t,s),s},rM=10,km=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.indexOf("_"),n=s>=0?r.slice(s+1):r;return!n||n.length<rM?null:n},Cm=(t,r)=>{const s=km(t),n=km(r);return!s||!n||s.length!==n.length?!0:s>n},nl=new Map,jc=(t,r)=>{const s=`${t}:${r}`,n=nl.get(s);if(n&&n.sessionId===t)return n.message;const c=(ve.getState().messages.get(t)||[]).find(l=>l.info.id===r)||null;return nl.set(s,{sessionId:t,message:c}),c},nM=t=>{const r=t.split(/[-_]/),s=[];let n=0;for(;n<r.length;){const o=r[n];if(/^\d+$/.test(o)&&n+1<r.length&&/^\d+$/.test(r[n+1])){const a=`${o}.${r[n+1]}`;s.push(a),n+=2;continue}s.push(o),n+=1}return s.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")},oM=()=>{const{addStreamingPart:t,completeStreamingMessage:r,updateMessageInfo:s,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:c,currentSessionId:l,applySessionMetadata:d,getWorktreeMetadata:u,loadMessages:m,loadSessions:f,updateSession:p,removeSessionFromStore:h}=ve(),{checkConnection:g}=Je(),x=Me($e=>$e.nativeNotificationsEnabled),b=Me($e=>$e.notificationMode),y=vt($e=>$e.currentDirectory),v=i.useMemo(()=>{if(!l)return;try{const tt=u?.(l);if(tt?.path)return tt.path}catch(tt){console.warn("Failed to inspect worktree metadata for session directory:",tt)}const be=ve.getState().sessions.find(tt=>tt.id===l);if(be&&typeof be.directory=="string"&&be.directory.trim().length>0)return be.directory.trim()},[l,u]),S=i.useMemo(()=>{if(v&&v.length>0)return v;if(typeof y=="string"&&y.trim().length>0)return y.trim()},[v,y]);i.useEffect(()=>{let $e=!1;const be=async()=>{try{const Ce=await Oe.listPendingPermissions();if($e||Ce.length===0)return;for(const Ie of Ce)o(Ie)}catch{}},tt=async()=>{try{const Ie=Lt.getState().projects.map(Ve=>Ve.path),Te=ve.getState().sessions.map(Ve=>Ve.directory),Pe=[S,...Ie,...Te],Fe=await Oe.listPendingQuestions({directories:Pe});if($e||Fe.length===0)return;for(const Ve of Fe)a(Ve)}catch{}};return be(),tt(),()=>{$e=!0}},[o,a,S]);const C=i.useCallback($e=>{if(typeof $e!="string")return null;const be=$e.trim();if(!be)return null;const tt=be.replace(/\\/g,"/");return tt.length>1?tt.replace(/\/+$/,""):tt},[]),N=i.useCallback($e=>{if(!$e)return null;try{const Ce=u?.($e),Ie=C(Ce?.path??null);if(Ie)return Ie}catch{}const tt=ve.getState().sessions.find(Ce=>Ce.id===$e);return C(tt?.directory??null)},[u,C]),j=Me($e=>$e.setEventStreamStatus),D=i.useRef(null),k=i.useCallback(($e,be)=>{const tt=be??null,Ce=D.current;if(!(Ce&&Ce.status===$e&&Ce.hint===tt)){if(D.current={status:$e,hint:tt},hs()){const Qe={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[$e]??"[INFO]",Te=tt?`${Qe} SSE ${$e}: ${tt}`:`${Qe} SSE ${$e}`;console.info(Te)}j($e,tt)}},[j]),M=i.useCallback(($e,be,tt)=>{if(!$e)return Promise.resolve();const Ce=Date.now();if(q.current)return q.current;if(Ce-Y.current<sM)return Promise.resolve();const Ie=m($e,tt).catch(Qe=>{console.warn(`[useEventStream] Failed to resync messages (${be}):`,Qe)}).finally(()=>{q.current=null,Y.current=Date.now()});return q.current=Ie,Ie},[m]),w=i.useCallback(async $e=>{hs()&&console.info("[useEventStream] Bootstrapping state:",$e);try{const be=Gr();await Promise.all([f(),l?M(l,$e,be):Promise.resolve()])}catch(be){console.warn("[useEventStream] Bootstrap failed:",$e,be)}},[l,f,M]),T=i.useCallback(($e,be,tt=Gr())=>{if(!$e)return Promise.resolve();const Ie=ve.getState().sessionMemoryState.get($e)?.streamingCooldownUntil,Qe=Date.now();if(typeof Ie=="number"&&Ie>Qe){const Te=Math.min(3e3,Math.max(0,Ie-Qe));return new Promise(Pe=>{setTimeout(()=>{M($e,be,tt).finally(Pe)},Te)})}return M($e,be,tt)},[M]);i.useEffect(()=>{ge.current=T},[T]);const E=i.useCallback(($e,be,tt)=>{hs()&&console.debug(`[MessageTracker] ${$e}: ${be}`,tt)},[]),I=i.useCallback($e=>{hs()&&console.debug(`[MessageTracker] ${$e}: reported`)},[]),A=i.useRef(null),P=i.useRef(null),F=i.useRef(0);i.useRef(new Set);const z=i.useRef(new Set),G=i.useRef(new Map),oe=i.useRef(null),O=i.useRef(!1),q=i.useRef(null),Y=i.useRef(0),Z=i.useRef(new Set),B=i.useRef(new Set),W=i.useRef(new Set),te=i.useRef(new Set),ye=i.useRef(new Set),me=i.useRef(new Map),K=i.useCallback(()=>{if(typeof document>"u")return"visible";const $e=document.visibilityState;return $e==="hidden"&&document.hasFocus()?"visible":$e},[]),L=i.useRef(K()),Q=i.useRef(typeof navigator>"u"?!0:navigator.onLine),ce=i.useRef(!1),he=i.useRef(null),Ne=i.useRef(null),H=i.useRef(Date.now()),we=i.useRef(new Map),ee=i.useRef(new Map),ue=i.useRef(new Map),ge=i.useRef(()=>Promise.resolve()),X=i.useRef(()=>{}),de=i.useRef(!1),ae=i.useCallback($e=>{const be=Date.now();be-H.current>25e3&&(w($e),H.current=be)},[w]);i.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(de.current=!0)},[]);const fe=i.useRef(new Map),ie=i.useRef(new Map),se=i.useRef(0),re=i.useRef(null),ne=i.useRef(l),xe=i.useRef(null),Ue=i.useRef(null);i.useEffect(()=>{ne.current=l},[l]);const ze=i.useCallback(($e,be)=>{if(!$e)return;const tt=Date.now(),Ce=G.current,Ie=Ce.get($e);if(Ie&&tt-Ie<3e3)return;Ce.set($e,tt);const Qe=Te=>{if(typeof be=="string"&&be.trim().length>0)return be.trim();try{const Ve=u?.(Te);if(Ve?.path)return Ve.path}catch{}const Fe=ve.getState().sessions.find(Ve=>Ve.id===Te);return Fe&&typeof Fe.directory=="string"&&Fe.directory.trim().length>0?Fe.directory.trim():null};setTimeout(async()=>{try{const Te=Qe($e),Pe=Te?await Oe.withDirectory(Te,()=>Oe.getSession($e)):await Oe.getSession($e);if(Pe){const Fe={};typeof Pe.title=="string"&&Pe.title.length>0&&(Fe.title=Pe.title),Pe.summary!==void 0&&(Fe.summary=Pe.summary),Object.keys(Fe).length>0&&d($e,Fe)}}catch(Te){console.warn("Failed to refresh session metadata:",Te)}},100)},[d,u]),Ke=i.useCallback(($e,be)=>{const tt=ve.getState().sessionActivityPhase?.get($e);if(tt===be){ie.current=new Map(ve.getState().sessionActivityPhase??new Map);return}const Ce=tt==="idle"&&(be==="busy"||be==="cooldown");if(be==="idle"){const Pe=ee.current.get($e);Pe&&(clearTimeout(Pe),ee.current.delete($e))}if(Ce){const Pe=ee.current.get($e);Pe&&(clearTimeout(Pe),ee.current.delete($e));const Fe=Date.now(),Ve=setTimeout(()=>{const et=ve.getState().sessionActivityPhase?.get($e);if(et!=="busy"&&et!=="cooldown")return;const ot=ue.current.get($e)??0;Date.now()-ot<15e3||(we.current.get($e)??0)>=Fe||(ue.current.set($e,Date.now()),ge.current($e,"activity_started_no_message",Gr()).finally(()=>{X.current("No message events after activity start")}))},2e3);ee.current.set($e,Ve)}const Qe=fe.current.get($e);Qe&&(clearTimeout(Qe),fe.current.delete($e));const Te=new Map(ve.getState().sessionActivityPhase??new Map);if(Te.set($e,be),ie.current=Te,ve.setState({sessionActivityPhase:Te}),be==="cooldown"){const Pe=setTimeout(()=>{if(fe.current.delete($e),ve.getState().sessionActivityPhase?.get($e)==="cooldown"){const Ve=new Map(ve.getState().sessionActivityPhase??new Map);Ve.set($e,"idle"),ie.current=Ve,ve.setState({sessionActivityPhase:Ve})}},2e3);fe.current.set($e,Pe)}},[]),rt=i.useCallback(async()=>{const $e=Date.now();if(re.current)return re.current;if($e-se.current<1500)return;se.current=$e;const be=Ce=>{const Ie=new Set,Qe=ve.getState().sessions,Te=new Set(Qe.map(Fe=>Fe.id));for(const[Fe,Ve]of Object.entries(Ce)){if(!Fe||!Ve)continue;Ie.add(Fe);const et=Ve.type==="busy"||Ve.type==="retry"?"busy":"idle";Ke(Fe,et)}const Pe=ve.getState().sessionActivityPhase;if(Pe)for(const[Fe,Ve]of Pe.entries())Te.has(Fe)&&(Ve==="busy"||Ve==="cooldown")&&!Ie.has(Fe)&&Ke(Fe,"idle")},tt=(async()=>{try{if(mr()){const et=await Oe.getWebServerSessionActivity();if(et&&Object.keys(et).length>0){be(et);return}}const Ce=await Oe.getGlobalSessionStatus();if(Ce&&Object.keys(Ce).length>0){be(Ce);return}const Ie=new Set,Qe=ve.getState().sessions;for(const et of Qe){const ot=N(et.id);ot&&Ie.add(ot)}const Te=C(S??null);Te&&Ie.add(Te);const Pe=Array.from(Ie);if(Pe.length===0){const et=await Oe.getSessionStatus();et&&be(et);return}const Fe=await Promise.allSettled(Pe.map(et=>Oe.getSessionStatusForDirectory(et))),Ve={};for(const et of Fe)et.status!=="fulfilled"||!et.value||Object.assign(Ve,et.value);if(Object.keys(Ve).length===0&&Array.from(ve.getState().sessionActivityPhase?.values?.()??[]).some(ot=>ot==="busy"||ot==="cooldown")&&!await Oe.checkHealth().catch(()=>!1))return;be(Ve)}catch{}})().finally(()=>{re.current=null});return re.current=tt,tt},[S,C,N,Ke]);i.useEffect(()=>{const $e=l??null,be=xe.current,tt=N($e),Ce=Ue.current;be&&$e&&be!==$e&&Ce&&tt&&Ce!==tt&&rt(),xe.current=$e,Ue.current=tt},[l,rt,N]);const jt=i.useCallback($e=>{if(H.current=Date.now(),hs()&&console.debug("[useEventStream] Received event:",$e.type,$e.properties),!$e.properties)return;const be=$e.properties;if(!new Set(["session.abort","session.error"]).has($e.type)){const Ce=(typeof be.session=="object"&&be.session!==null?be.session:null)||(typeof be.sessionInfo=="object"&&be.sessionInfo!==null?be.sessionInfo:null);if(Ce){const Ie=Ce,Qe=typeof Ie.id=="string"&&Ie.id.length>0?Ie.id:typeof Ie.sessionID=="string"&&Ie.sessionID.length>0?Ie.sessionID:typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:typeof be.id=="string"&&be.id.length>0?be.id:void 0;if(Qe){const Te=typeof Ie.title=="string"?Ie.title:typeof be.title=="string"?be.title:void 0,Pe=typeof Ie.summary=="object"&&Ie.summary!==null?Ie.summary:typeof be.summary=="object"&&be.summary!==null?be.summary:void 0;if(Te!==void 0||Pe!==void 0){const Fe={};Te!==void 0&&(Fe.title=Te),Pe!==void 0&&(Fe.summary=Pe),d(Qe,Fe)}}}}switch($e.type){case"server.connected":g();break;case"global.disposed":case"server.instance.disposed":{w("server_disposed_event");break}case"openchamber:session-activity":{const Ce=typeof be.sessionId=="string"?be.sessionId:null,Ie=typeof be.phase=="string"?be.phase:null;Ce&&(Ie==="idle"||Ie==="busy"||Ie==="cooldown")&&(Ke(Ce,Ie),ze(Ce,typeof be.directory=="string"?be.directory:null));break}case"mcp.tools.changed":{const Ce=typeof be.directory=="string"?be.directory:S;Co.getState().refresh({directory:Ce??null,silent:!0});break}case"session.status":if(de.current)break;{const Ce=typeof be.sessionID=="string"?be.sessionID:null,Ie=typeof be.status=="object"&&be.status!==null?be.status:null,Qe=typeof Ie?.type=="string"?Ie.type:null;Ce&&Qe&&(Ke(Ce,Qe==="busy"||Qe==="retry"?"busy":"idle"),ze(Ce,typeof be.directory=="string"?be.directory:null))}break;case"message.part.updated":{const Ce=typeof be.part=="object"&&be.part!==null?be.part:null;if(!Ce)break;const Ie=Ce,Qe=typeof be.info=="object"&&be.info!==null?be.info:be,Te=wr(Qe,["sessionID","sessionId"]),Pe=wr(Ie,["sessionID","sessionId"])||Te||wr(be,["sessionID","sessionId"]),Fe=wr(Qe,["messageID","messageId","id"]),Ve=wr(Ie,["messageID","messageId"])||Fe||wr(be,["messageID","messageId"]);if(!Pe||!Ve){hs()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:Ie.sessionID??Te??be.sessionID,messageID:Ie.messageID??Fe??be.messageID});break}const et=Pe,ot=Ve;we.current.set(et,Date.now());const yt=ee.current.get(et);yt&&(clearTimeout(yt),ee.current.delete(et));const Dt=ve.getState().sessionMemoryState.get(et)?.trimmedHeadMaxId;if(Dt&&!Cm(ot,Dt)){hs()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:et,messageId:ot,trimmedHeadMaxId:Dt});break}let bt="assistant";if(Qe&&typeof Qe.role=="string")bt=Qe.role;else{const Vt=jc(et,ot);if(Vt){const Ft=Vt.info.role;typeof Ft=="string"&&(bt=Ft)}}if(E(ot,"part_received",{role:bt}),bt==="user"&&Ie.synthetic===!0){E(ot,"skipped_synthetic_user_part");break}const Qt={...Ce,type:Ce.type||"text"};E(ot,"addStreamingPart_called"),t(et,ot,Qt,bt);break}case"message.updated":{const Ce=typeof be.info=="object"&&be.info!==null?be.info:be,Ie=Ce,Qe=wr(Ie,["sessionID","sessionId"])||wr(be,["sessionID","sessionId"]),Te=wr(Ie,["messageID","messageId","id"])||wr(be,["messageID","messageId"]);if(!Qe||!Te){hs()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:Ie.sessionID??be.sessionID,messageID:Ie.id??be.messageID});break}const Pe=Qe,Fe=Te;we.current.set(Pe,Date.now());const Ve=ee.current.get(Pe);Ve&&(clearTimeout(Ve),ee.current.delete(Pe));const et=ve.getState().sessionMemoryState.get(Pe)?.trimmedHeadMaxId;if(et&&!Cm(Fe,et)){hs()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Pe,messageId:Fe,trimmedHeadMaxId:et});break}if(de.current&&hs())try{const $=be.parts||Ie.parts||[],J=(Array.isArray($)?$.filter(pe=>pe?.type==="text"):[]).map(pe=>{const Ee=pe;return typeof Ee?.text=="string"?Ee.text:typeof Ee?.content=="string"?Ee.content:""}).join(`
244
+ `);console.info("[STREAM-TRACE] message.updated",{messageId:Fe,role:Ie.role,status:Ie.status,textLen:J.length,textPreview:J.slice(0,120),partsCount:Array.isArray($)?$.length:0})}catch{}if(E(Fe,"message_updated",{role:Ie.role}),Ie.role==="user"){const $=be.parts||Ie.parts,U=Array.isArray($)?$:[],J=jc(Pe,Fe),pe=(()=>{const wt=Ie.agent;if(typeof wt=="string"&&wt.trim().length>0)return wt.trim();const at=Ie.mode;return typeof at=="string"&&at.trim().length>0?at.trim():""})(),Ee=(()=>{const at=Ie.time?.created;return typeof at=="number"?at:null})(),He=U.length>0&&U.every(wt=>wt?.synthetic===!0),ft=(()=>{if(!pe)return!1;if(He&&(pe==="plan"||pe==="build"))return!0;const wt=me.current.get(Pe);return wt?Ee===null?!1:Fe===wt.messageId?!0:Ee>=wt.created:!0})();if(pe&&ft)try{const wt=Je.getState().agents;if(Array.isArray(wt)&&wt.some(at=>at?.name===pe)){const at=Ye.getState();if(at.saveSessionAgentSelection(Pe,pe),me.current.set(Pe,{created:Ee??Date.now(),messageId:Fe}),ne.current===Pe)try{Je.getState().setAgent(pe)}catch{}const _t=Ie.model,qt=typeof _t?.providerID=="string"?_t.providerID:null,ht=typeof _t?.modelID=="string"?_t.modelID:null;if(qt&&ht){at.saveSessionModelSelection(Pe,qt,ht),at.saveAgentModelForSession(Pe,pe,qt,ht);const Et=typeof Ie.variant=="string"?Ie.variant:void 0;if(Et&&at.saveAgentModelVariantForSession(Pe,pe,qt,ht,Et),ne.current===Pe)try{Je.getState().setProvider(qt),Je.getState().setModel(ht)}catch{}}}}catch{}if(He&&(pe==="plan"||pe==="build")&&ne.current===Pe){const wt=`${Pe}:${Fe}:${pe}`;ye.current.has(wt)||(ye.current.add(wt),vs(async()=>{const{toast:at}=await import("./vendor-.bun-Bui932eM.js").then(_t=>_t.dj);return{toast:at}},__vite__mapDeps([0,1])).then(({toast:at})=>{at.info(pe==="plan"?"Plan mode active":"Build mode active",{description:pe==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const pt={...Ce,userMessageMarker:!0,clientRole:"user",...pe?{mode:pe}:{}};if(s(Pe,Fe,pt),!J&&U.length===0){const wt=`${Pe}:${Fe}`;z.current.has(wt)||(z.current.add(wt),Oe.getSessionMessages(Pe,50).then(at=>{ve.getState().syncMessages(Pe,at)}).catch(()=>{}))}if(U.length>0)for(let wt=0;wt<U.length;wt++){const at=U[wt];if(at.synthetic===!0){const ht=at.text,Et=typeof ht=="string"?ht.trim():"";if(!(Et.startsWith("User has requested to enter plan mode")||Et.startsWith("The plan at ")))continue}const qt={...at,type:at?.type||"text",sessionID:at?.sessionID||Pe,messageID:at?.messageID||Fe};t(Pe,Fe,qt,"user")}E(Fe,"user_message_created_from_event",{partsCount:U.length});break}const ot=jc(Pe,Fe),yt=Nm(ot?.parts||[]),Dt=ot?.info?.finish==="stop",bt=be.parts||Ie.parts,Qt=Array.isArray(bt)?bt:[],Vt=Qt.length>0,Kt=typeof(Ie.time||{})?.completed=="number";if(!Vt&&!Kt)break;const Rt=Ce.finish,cs=typeof Rt=="string"?Rt:null,Ns=cs==="stop";if(Ie.role==="assistant"&&Vt){const $=Nm(Qt);if(yt>0&&$+tM<yt&&!Ns){E(Fe,"skipped_shrinking_update",{incomingLen:$,existingLen:yt});break}if(de.current){const J=yt>0&&$<yt,pe=Qt.some(He=>{if(!He||He.type!=="text")return!1;const ft=He;return typeof ft.text=="string"&&ft.text.length>0});if(J&&!(Ns&&pe)){E(Fe,"desktop_shrinking_update_suppressed",{incomingLen:$,existingLen:yt});break}}}if(s(Pe,Fe,Ce),Vt&&Ie.role!=="user"){const J=(ve.getState().messages.get(Pe)||[]).find(He=>He.info.id===Fe),pe=!J||J.parts.length===0;E(Fe,pe?"server_parts_injected":"server_parts_refreshed",{count:Qt.length});const Ee=de.current&&Ie.role==="assistant"?Qt.filter(He=>He?.type!=="text"):Qt;for(let He=0;He<Ee.length;He++){const ft=Ee[He],pt={...ft,type:ft?.type||"text",sessionID:ft?.sessionID||Pe,messageID:ft?.messageID||Fe};t(Pe,Fe,pt,Ie.role),E(Fe,`server_part_${He}`)}}const bs=Ce.time,Cs=bs?.completed,Ms=typeof Cs=="number"&&Number.isFinite(Cs),ps=cs==="stop"||Dt;if(Ce.role==="assistant"&&(Ms||ps)&&Ce.role==="assistant"){const U=ve.getState().messages.get(Pe)||[];let J=null,pe="";for(let at=0;at<U.length;at++){const _t=U[at];_t.info.role==="assistant"&&_t.info.id>pe&&(pe=_t.info.id,J=_t.info.id)}if(l===Pe&&Fe!==J)break;if(!ps&&de.current){E(Fe,"desktop_completion_without_stop");break}const He=Ms?Cs:Date.now();if(Ms||s(Pe,Fe,{...Ce,time:{...bs??{},completed:He}}),E(Fe,"completed",{timeCompleted:He}),I(Fe),eM(Pe,Fe,He),r(Pe,Fe),cs==="stop"&&mr()&&x&&(b==="always"||L.current==="hidden")){const _t=W.current;if(!_t.has(Fe)){_t.add(Fe);const qt=Ps();if(qt?.notifications){const ht=Ie.mode||"agent",Et=Ie.modelID||"assistant",Jt=`${ht.charAt(0).toUpperCase()+ht.slice(1)} agent is ready`,Js=`${nM(Et)} completed the task`;qt.notifications.notifyAgentCompletion({title:Jt,body:Js,tag:Fe})}}}de.current||cs==="stop"&&ve.getState().sessionActivityPhase?.get(Pe)==="busy"&&Ke(Pe,"cooldown");const ft=Ce.sessionID,pt=typeof ft=="string"&&ft.length>0?ft:Pe;ze(pt,typeof be.directory=="string"?be.directory:null),Ce.summary&&typeof pt=="string"&&n(pt,null)}break}case"session.created":case"session.updated":{const Ce=typeof be.info=="object"&&be.info!==null?be.info:typeof be.sessionInfo=="object"&&be.sessionInfo!==null?be.sessionInfo:typeof be.session=="object"&&be.session!==null?be.session:be,Ie=typeof Ce.id=="string"&&Ce.id.length>0?Ce.id:typeof Ce.sessionID=="string"&&Ce.sessionID.length>0?Ce.sessionID:typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:typeof be.id=="string"&&be.id.length>0?be.id:void 0;if(Ie){const Qe=typeof Ce.time=="object"&&Ce.time!==null?Ce.time:typeof be.time=="object"&&be.time!==null?be.time:null,Te=Qe&&typeof Qe.compacting=="number"?Qe.compacting:null;n(Ie,Te);const Pe=typeof Ce.directory=="string"?Ce.directory:typeof be.directory=="string"?be.directory:null,Fe={...Ce,id:Ie,...Pe?{directory:Pe}:{}};p(Fe)}break}case"session.deleted":{const Ce=typeof be.sessionID=="string"?be.sessionID:typeof be.id=="string"?be.id:null;Ce&&h(Ce);break}case"session.abort":{const Ce=typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:null,Ie=typeof be.messageID=="string"&&be.messageID.length>0?be.messageID:null;Ce&&Ie&&r(Ce,Ie);break}case"permission.asked":{if(!("sessionID"in be)||typeof be.sessionID!="string")break;const Ce=be;o(Ce);const Ie=`${Ce.sessionID}:${Ce.id}`;Z.current.has(Ie)||setTimeout(()=>{if(ne.current===Ce.sessionID||!ve.getState().permissions.get(Ce.sessionID)?.some(Fe=>Fe.id===Ce.id))return;Z.current.add(Ie);const Pe=ve.getState().sessions.find(Fe=>Fe.id===Ce.sessionID)?.title||"Session";if(vs(async()=>{const{toast:Fe}=await import("./vendor-.bun-Bui932eM.js").then(Ve=>Ve.dj);return{toast:Fe}},__vite__mapDeps([0,1])).then(({toast:Fe})=>{Fe.warning("Permission required",{description:Pe,action:{label:"Open",onClick:()=>{Me.getState().setActiveMainTab("chat"),ve.getState().setCurrentSession(Ce.sessionID)}}})}),mr()&&x&&(b==="always"||L.current==="hidden")){const Ve=Ps();Ve?.notifications&&Ve.notifications.notifyAgentCompletion({title:"Permission required",body:Pe,tag:`permission-${Ie}`})}},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in be)||typeof be.sessionID!="string")break;const Ce=be;a(Ce);const Ie=`${Ce.sessionID}:${Ce.id}`;if(mr()&&x&&(b==="always"||L.current==="hidden")){const Te=te.current;if(!Te.has(Ie)){Te.add(Ie);const Pe=Ps();if(Pe?.notifications){const Fe=Array.isArray(Ce.questions)?Ce.questions[0]:void 0,Ve=typeof Fe?.header=="string"?Fe.header.trim():"",et=typeof Fe?.question=="string"?Fe.question.trim():"",ot=/plan\s*mode/i.test(Ve)?"Switch to plan mode":/build\s*agent/i.test(Ve)?"Switch to build mode":Ve||"Input needed",yt=et||"Agent is waiting for your response";Pe.notifications.notifyAgentCompletion({title:ot,body:yt,tag:Ie})}}}B.current.has(Ie)||setTimeout(()=>{if(ne.current===Ce.sessionID||!ve.getState().questions.get(Ce.sessionID)?.some(Fe=>Fe.id===Ce.id))return;B.current.add(Ie);const Pe=ve.getState().sessions.find(Fe=>Fe.id===Ce.sessionID)?.title||"Session";vs(async()=>{const{toast:Fe}=await import("./vendor-.bun-Bui932eM.js").then(Ve=>Ve.dj);return{toast:Fe}},__vite__mapDeps([0,1])).then(({toast:Fe})=>{Fe.info("Input needed",{description:Pe,action:{label:"Open",onClick:()=>{Me.getState().setActiveMainTab("chat"),ve.getState().setCurrentSession(Ce.sessionID)}}})})},0);break}case"question.replied":{const Ce=typeof be.sessionID=="string"?be.sessionID:null,Ie=typeof be.requestID=="string"?be.requestID:null;Ce&&Ie&&c(Ce,Ie);break}case"question.rejected":{const Ce=typeof be.sessionID=="string"?be.sessionID:null,Ie=typeof be.requestID=="string"?be.requestID:null;Ce&&Ie&&c(Ce,Ie);break}case"todo.updated":{const Ce=typeof be.sessionID=="string"?be.sessionID:null,Ie=Array.isArray(be.todos)?be.todos:null;Ce&&Ie&&s0(Ce,Ie);break}}},[l,x,b,t,r,s,o,a,c,g,ze,n,d,E,I,Ke,p,h,w,S]),Xe=i.useCallback(()=>{const $e=K();return L.current=$e,$e==="visible"&&Q.current},[K]),Ct=i.useCallback(()=>{hs()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:de.current,hasUnsubscribe:!!A.current,currentSessionId:ne.current,effectiveDirectory:S,onlineStatus:Q.current,visibilityState:L.current,lastEventTimestamp:H.current,reconnectAttempts:F.current})},[S]),st=i.useCallback(async()=>!0,[]),mt=i.useCallback(()=>{if(O.current){hs()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(O.current=!0,P.current&&(clearTimeout(P.current),P.current=null),A.current){const $e=A.current;A.current=null;try{$e()}catch(be){console.warn("[useEventStream] Error during unsubscribe:",be)}}O.current=!1},[]),Pt=i.useCallback(async $e=>{if(Ct(),!Xe()){ce.current=!0,Q.current?k("paused","Paused while hidden"):k("offline","Waiting for network");return}de.current&&(await st()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),$e?.resetAttempts&&(F.current=0),mt(),H.current=Date.now(),k("connecting",null),hs()&&console.info("[useEventStream] Starting event stream...");const be=Ce=>{console.warn("Event stream error:",Ce)},tt=()=>{const Ce=ce.current;if(F.current=0,ce.current=!1,H.current=Date.now(),k("connected",null),g(),rt(),Ce)w("sse_reconnected");else{const Ie=ne.current;Ie&&setTimeout(()=>{T(Ie,"sse_reconnected",Gr()).then(()=>ze(Ie)).catch(Qe=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Qe)})},0)}};if(hs()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:S,isCleaningUp:O.current}),O.current){hs()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Ce=Oe.subscribeToGlobalEvents(Qe=>{const Te=Qe.payload,Pe=Qe.payload,Fe=typeof Pe.properties=="object"&&Pe.properties!==null?Pe.properties:{},Ve=Qe.directory&&Qe.directory!=="global"?{...Fe,directory:Qe.directory}:Fe;jt({type:typeof Te.type=="string"?Te.type:"",properties:Ve})},be,tt),Ie=()=>{try{Ce()}catch(Qe){console.warn("[useEventStream] Error during unsubscribe:",Qe)}};O.current?Ie():A.current=Ie}catch(Ce){console.error("[useEventStream] Error during subscription:",Ce),be(Ce)}},[Xe,mt,k,g,T,ze,jt,S,rt,st,Ct,w]),Ot=i.useCallback($e=>{if(!Xe()){ce.current=!0,mt(),Q.current?k("paused","Paused while hidden"):k("offline","Waiting for network");return}const be=F.current+1;F.current=be;const tt=$e??`Retrying (${be})`;k("reconnecting",tt);const Ce=be<=3?Math.min(1e3*Math.pow(2,be-1),8e3):Math.min(2e3*Math.pow(2,be-3),32e3),Ie=Math.floor(Math.random()*250),Qe=Ce+Ie;P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{Pt({resetAttempts:!1})},Qe)},[Xe,mt,k,Pt]);i.useEffect(()=>{X.current=Ot},[Ot]),i.useEffect(()=>{const $e=fe.current;typeof window<"u"&&(window.__messageTracker=E);let be=null;de.current&&typeof window<"u"&&(be=ot=>{const yt=typeof ot.detail?.sessionId=="string"?ot.detail.sessionId:null,Dt=typeof ot.detail?.phase=="string"?ot.detail.phase:null;yt&&(Dt==="idle"||Dt==="busy"||Dt==="cooldown")&&(Ke(yt,Dt),ze(yt))},window.addEventListener("openchamber:session-activity",be));const tt=()=>{he.current&&(clearTimeout(he.current),he.current=null)},Ce=()=>{he.current||(he.current=setTimeout(()=>{const ot=K();L.current=ot,ot!=="visible"?(mt(),ce.current=!0,k("paused","Paused while hidden")):tt()},5e3))},Ie=()=>{if(L.current=K(),L.current==="visible"){if(tt(),ae("visibility_restore"),ce.current||!A.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const ot=ne.current;ot&&(T(ot,"visibility_restore",Gr()),ze(ot)),rt(),k("connecting","Resuming stream"),Pt({resetAttempts:!0})}}else k("paused","Paused while hidden"),Ce()},Qe=()=>{if(L.current=K(),L.current==="visible"&&(tt(),ae("window_focus"),ce.current||!A.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const ot=ne.current;ot&&(ze(ot),T(ot,"window_focus",Gr())),rt(),k("connecting","Resuming stream"),Pt({resetAttempts:!0})}},Te=()=>{Q.current=!0,ae("network_restored"),(ce.current||!A.current)&&(k("connecting","Network restored"),Pt({resetAttempts:!0}))},Pe=()=>{Q.current=!1,ce.current=!0,k("offline","Waiting for network"),mt()},Fe=()=>{ce.current=!0,mt(),k("paused","Paused while hidden")},Ve=ot=>{if(ce.current=ce.current||!!ot.persisted,L.current=K(),L.current==="visible"){const yt=ne.current;yt&&(T(yt,"page_show",Gr()),ze(yt)),rt(),Pt({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",Ie),typeof window<"u"&&(window.addEventListener("online",Te),window.addEventListener("offline",Pe),window.addEventListener("focus",Qe),window.addEventListener("pagehide",Fe),window.addEventListener("pageshow",Ve));const et=setTimeout(()=>{Pt({resetAttempts:!0})},100);return Ne.current&&clearInterval(Ne.current),Ne.current=setInterval(()=>{if(!Xe())return;const ot=Date.now();Array.from(ve.getState().sessionActivityPhase?.values?.()??[]).some(Dt=>Dt==="busy"||Dt==="cooldown")&&rt(),ot-H.current>45e3&&Promise.resolve().then(async()=>{try{await Oe.checkHealth()?H.current=Date.now():Ot("Refreshing stalled stream")}catch(Dt){console.warn("Health check after stale stream failed:",Dt),Ot("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(et),be&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",be),typeof document<"u"&&document.removeEventListener("visibilitychange",Ie),typeof window<"u"&&(window.removeEventListener("online",Te),window.removeEventListener("offline",Pe),window.removeEventListener("focus",Qe),window.removeEventListener("pagehide",Fe),window.removeEventListener("pageshow",Ve)),tt(),Ne.current&&(clearInterval(Ne.current),Ne.current=null),$e.forEach(ot=>clearTimeout(ot)),$e.clear(),nl.clear(),W.current.clear(),te.current.clear(),ce.current=!1,L.current=K(),Q.current=typeof navigator>"u"?!0:navigator.onLine,mt(),oe.current&&(clearTimeout(oe.current),oe.current=null),k("idle",null)}},[S,E,K,mt,k,Pt,Ot,m,ze,Ke,rt,Xe,f,ae,M,T])},aM=()=>{const{openNewSessionDraft:t,abortCurrentOperation:r,armAbortPrompt:s,clearAbortPrompt:n,currentSessionId:o}=ve(),{toggleCommandPalette:a,toggleHelpDialog:c,toggleSidebar:l,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=Me(),{themeMode:p,setThemeMode:h}=Wr(),{working:g}=Fp(),x=i.useRef(null),b=i.useRef(null),y=i.useRef(!1),v=i.useCallback(()=>{b.current&&(clearTimeout(b.current),b.current=null),x.current=null,n()},[n]);i.useEffect(()=>{const S=C=>{if($s(C)&&C.key==="k"&&(C.preventDefault(),a()),$s(C)&&C.shiftKey&&C.key.toLowerCase()==="l"){const j=Ps()?.diagnostics;if(!j||(C.preventDefault(),y.current))return;y.current=!0,j.downloadLogs().then(({fileName:D,content:k})=>{const M=D||"openchamber.log",w=new Blob([k],{type:"text/plain;charset=utf-8"}),T=URL.createObjectURL(w),E=document.createElement("a");E.href=T,E.download=M,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(T)}).finally(()=>{y.current=!1});return}if($s(C)&&C.key==="."&&(C.preventDefault(),c()),$s(C)&&C.key.toLowerCase()==="n"){C.preventDefault();const N=zt(),j=Je.getState().settingsAutoCreateWorktree;if(N?!1:j?!C.shiftKey:C.shiftKey){u("chat"),d(!1),Ii();return}u("chat"),d(!1),t()}if($s(C)&&C.key==="/"){C.preventDefault();const N=["light","dark","system"],D=(N.indexOf(p)+1)%N.length;h(N[D])}if($s(C)&&!C.shiftKey&&C.key.toLowerCase()==="t"){C.preventDefault();const{isTimelineDialogOpen:N,setTimelineDialogOpen:j}=Me.getState();j(!N);return}if($s(C)&&!C.shiftKey&&C.key===","){C.preventDefault();const{isSettingsDialogOpen:N}=Me.getState();m(!N);return}if($s(C)&&!C.shiftKey&&C.key.toLowerCase()==="l"){C.preventDefault();const{isMobile:N,isSessionSwitcherOpen:j}=Me.getState();N?d(!j):l();return}if($s(C)&&!C.shiftKey&&C.key.toLowerCase()==="i"){C.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if($s(C)&&C.shiftKey&&C.key.toLowerCase()==="m"){const{isSettingsDialogOpen:N,isCommandPaletteOpen:j,isHelpDialogOpen:D,isSessionSwitcherOpen:k,isAboutDialogOpen:M,activeMainTab:w,isModelSelectorOpen:T}=Me.getState();if(N||j||D||k||M||!(w==="chat"))return;C.preventDefault(),f(!T);return}if($s(C)&&C.shiftKey&&C.key.toLowerCase()==="t"){const{isSettingsDialogOpen:N,isCommandPaletteOpen:j,isHelpDialogOpen:D,isSessionSwitcherOpen:k,isAboutDialogOpen:M,activeMainTab:w}=Me.getState();if(N||j||D||k||M||!(w==="chat"))return;const I=Je.getState();if(I.getCurrentModelVariants().length===0)return;C.preventDefault(),I.cycleCurrentVariant();const P=Je.getState().currentVariant,F=ve.getState(),z=F.currentSessionId,G=Je.getState().currentAgentName,oe=Je.getState().currentProviderId,O=Je.getState().currentModelId;z&&G&&oe&&O&&F.saveAgentModelVariantForSession(z,G,oe,O,P);return}if(C.key==="Escape"){const{isSettingsDialogOpen:N,isCommandPaletteOpen:j,isHelpDialogOpen:D,isSessionSwitcherOpen:k,isAboutDialogOpen:M,activeMainTab:w}=Me.getState();if(N){C.preventDefault(),m(!1),v();return}if(j||D||k||M||!(w==="chat")){v();return}const I=o;if(!(g.canAbort&&!!I)){v();return}const P=Date.now(),F=x.current;if(F&&P<F){C.preventDefault(),v(),r();return}C.preventDefault();const z=s(3e3)??P+3e3;x.current=z,b.current&&clearTimeout(b.current);const G=Math.max(z-P,0);b.current=setTimeout(()=>{x.current&&Date.now()>=x.current&&v()},G||0);return}};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[t,r,a,c,l,d,u,m,f,h,p,g,s,v,o]),i.useEffect(()=>()=>{v()},[v])},Mm="openchamber:menu-action",iM=t=>{const{openNewSessionDraft:r}=ve(),{toggleCommandPalette:s,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:c,setSettingsDialogOpen:l,setAboutDialogOpen:d}=Me(),{addProject:u}=Lt(),{requestAccess:m,startAccessing:f}=Pi(),{setThemeMode:p}=Wr(),h=i.useRef(!1),g=i.useCallback(()=>{ds()?m("").then(async x=>{if(!x.success||!x.path){x.error&&x.error!=="Directory selection cancelled"&&V.error("Failed to select directory",{description:x.error});return}const b=await f(x.path);if(!b.success){V.error("Failed to open directory",{description:b.error||"Desktop could not grant file access."});return}u(x.path,{id:x.projectId})||V.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(x=>{console.error("Desktop: Error selecting directory:",x),V.error("Failed to select directory")}):io.requestDirectoryDialog()},[u,m,f]);i.useEffect(()=>{const x=b=>{switch(b.detail){case"about":d(!0);break;case"settings":l(!0);break;case"command-palette":s();break;case"new-session":c("chat"),a(!1),r();break;case"new-worktree-session":c("chat"),a(!1),Ii();break;case"change-workspace":g();break;case"open-git-tab":{const{activeMainTab:v}=Me.getState();c(v==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:v}=Me.getState();c(v==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:v}=Me.getState();c(v==="terminal"?"chat":"terminal");break}case"theme-light":p("light");break;case"theme-dark":p("dark");break;case"theme-system":p("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":t?.();break;case"help-dialog":n();break;case"download-logs":{const S=Ps()?.diagnostics;if(!S||h.current)break;h.current=!0,S.downloadLogs().then(({fileName:C,content:N})=>{const j=C||"openchamber.log",D=new Blob([N],{type:"text/plain;charset=utf-8"}),k=URL.createObjectURL(D),M=document.createElement("a");M.href=k,M.download=j,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(k),V.success("Logs saved",{description:`Downloaded to ~/Downloads/${j}`})}).catch(()=>{V.error("Failed to download logs")}).finally(()=>{h.current=!1});break}}};return window.addEventListener(Mm,x),()=>window.removeEventListener(Mm,x)},[r,s,n,o,a,c,l,d,p,t,g])},cM=()=>{i.useEffect(()=>{let t=!1;return(async()=>{try{const s=await Oe.getGlobalSessionStatus();if(t||!s)return;const n=new Map;Object.entries(s).forEach(([o,a])=>{if(!o||!a)return;const c=a,l=c.type==="busy"||c.type==="retry"?"busy":"idle";n.set(o,l)}),n.size>0&&ve.setState({sessionActivityPhase:n})}catch{}})(),()=>{t=!0}},[])},lM=["chat","git","diff","terminal","files"],dM=["settings","agents","commands","skills","providers","git-identities"],er={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function Dm(t){const r=uM();return{sessionId:mM(r),tab:fM(r),settingsSection:pM(r),diffFile:hM(r)}}function uM(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function mM(t){const r=t.get(er.SESSION);return!r||r.trim().length===0?null:r.trim()}function fM(t){const r=t.get(er.TAB);if(!r)return null;const s=r.toLowerCase().trim();return lM.includes(s)?s:null}function pM(t){const r=t.get(er.SETTINGS);if(!r)return null;const s=r.toLowerCase().trim();return dM.includes(s)?s:s==="openchamber"||s==="general"||s==="preferences"?"settings":null}function hM(t){const r=t.get(er.FILE);if(!r||r.trim().length===0)return null;try{return decodeURIComponent(r.trim())}catch{return r.trim()}}function Am(){if(typeof window>"u")return!1;try{const t=new URLSearchParams(window.location.search);return t.has(er.SESSION)||t.has(er.TAB)||t.has(er.SETTINGS)||t.has(er.FILE)}catch{return!1}}const gM="chat";function jh(t){const r=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&r.set(er.SESSION,t.sessionId),t.isSettingsOpen){const s=t.settingsSection==="sessions"?"settings":t.settingsSection;return r.set(er.SETTINGS,s),r}return t.tab!==gM&&r.set(er.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&r.set(er.FILE,t.diffFile),r}function xM(t,r){const s=typeof window<"u"?window.location.pathname:"/",n=t.toString();return n?`${s}?${n}`:s}function yM(t){if(typeof window>"u")return!0;try{const r=new URLSearchParams(window.location.search),s=jh(t),n=[...r.entries()].sort((a,c)=>a[0].localeCompare(c[0])),o=[...s.entries()].sort((a,c)=>a[0].localeCompare(c[0]));if(n.length!==o.length)return!1;for(let a=0;a<n.length;a++)if(n[a][0]!==o[a][0]||n[a][1]!==o[a][1])return!1;return!0}catch{return!0}}function bM(t,r={}){if(!(typeof window>"u")&&!wM()&&!(!r.force&&yM(t)))try{const s=jh(t),n=xM(s);r.replace?window.history.replaceState({...window.history.state,route:t},"",n):window.history.pushState({route:t},"",n)}catch{}}function wM(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function vM(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function jM(){const t=i.useMemo(()=>vM(),[]),r=i.useRef(!1),s=i.useRef(!1),n=ve(f=>f.setCurrentSession),o=Me(f=>f.setActiveMainTab),a=Me(f=>f.setSettingsDialogOpen),c=Me(f=>f.setSidebarSection),l=Me(f=>f.navigateToDiff),d=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=ve.getState().currentSessionId;f.sessionId!==p&&await n(f.sessionId)}if(f.settingsSection){c(f.settingsSection),a(!0);return}Me.getState().isSettingsDialogOpen&&a(!1),f.tab&&o(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{s.current=!1}}},[n,o,a,c,l]),u=i.useCallback(()=>{const f=ve.getState(),p=Me.getState();return{sessionId:f.currentSessionId,tab:p.activeMainTab,isSettingsOpen:p.isSettingsDialogOpen,settingsSection:p.sidebarSection,diffFile:p.pendingDiffFile}},[]),m=i.useCallback((f={})=>{if(t||s.current)return;const p=u();bM(p,f)},[t,u]);i.useEffect(()=>{if(r.current||(r.current=!0,!Am()))return;const f=Dm();(async()=>(await d(f),t||m({replace:!0})))()},[d,t,m]),i.useEffect(()=>{if(t)return;let f=ve.getState().currentSessionId;return ve.subscribe(h=>{const g=h.currentSessionId;g===f||s.current||(f=g,m())})},[t,m]),i.useEffect(()=>{if(t)return;let f=Me.getState().activeMainTab,p=Me.getState().isSettingsDialogOpen,h=Me.getState().sidebarSection,g=Me.getState().pendingDiffFile;return Me.subscribe(b=>{if(s.current)return;const y=b.activeMainTab!==f,v=b.isSettingsDialogOpen!==p,S=b.sidebarSection!==h,C=b.pendingDiffFile!==g&&b.activeMainTab==="diff";f=b.activeMainTab,p=b.isSettingsDialogOpen,h=b.sidebarSection,g=b.pendingDiffFile,(y||v||S||C)&&m()})},[t,m]),i.useEffect(()=>{if(typeof window>"u"||t)return;const f=()=>{const p=Dm();if(Am())d(p);else{const h=Me.getState();h.isSettingsDialogOpen&&a(!1),h.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[d,t,o,a])}const SM=1e4,Em=()=>{if(typeof document>"u")return"visible";const t=document.visibilityState;return t==="hidden"&&document.hasFocus()?"visible":t},Im=t=>{if(!mr())return;const r=Ps();r?.push?.setVisibility&&r.push.setVisibility({visible:t})},NM=()=>{i.useEffect(()=>{if(!mr()||typeof document>"u")return;const t=()=>{Im(Em()==="visible")},r=()=>{Em()==="visible"&&Im(!0)};t();const s=window.setInterval(r,SM);return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),window.addEventListener("blur",t),()=>{window.clearInterval(s),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t),window.removeEventListener("blur",t)}},[])};function kM(){const{git:t}=Hs(),r=vt(m=>m.currentDirectory),{currentSessionId:s,sessions:n,worktreeMetadata:o}=ve(),{setActiveDirectory:a,startPolling:c,stopPolling:l,fetchAll:d}=is(),u=i.useMemo(()=>{const m=s?o.get(s)??void 0:void 0,p=n.find(h=>h.id===s)?.directory??null;return m?.path??p??r??null},[s,n,o,r]);i.useEffect(()=>{if(!u||!t){l();return}return a(u),d(u,t),c(t),()=>{l()}},[u,t,a,c,l,d])}function CM({children:t}){return kM(),e.jsx(e.Fragment,{children:t})}const MM=()=>{const[{isUpdating:t,message:r},s]=i.useState(()=>$y());return i.useEffect(()=>_y(s),[]),t?e.jsxs("div",{className:"fixed inset-0 z-[9999] flex flex-col items-center justify-center gap-6 backdrop-blur-md",children:[e.jsx(Ol,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Sh={getLastAssistantMessage(){const t=ve.getState(),r=t.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const s=t.messages.get(r);if(!s||s.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=s.length-1;n>=0;n--){const o=s[n];if(o.info.role==="assistant"){const a=o.parts.map(p=>{const h={id:p.id,type:p.type};return p.type==="text"?(h.text=p.text,h.textLength=p.text?.length||0):p.type==="tool"?(h.tool=p.tool,h.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(h.isStepMarker=!0),h}),c=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),l=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!c&&!l&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:c,hasTools:l,hasStepMarkers:d,onlyStepMarkers:d&&!c&&!l}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!c&&!l&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(t,r=80){return!t||typeof t!="string"||t.length<=r?t:t.substring(0,r)+"…"},truncateMessages(t){return t.map(r=>({...r,parts:(r.parts||[]).map(s=>{const n={...s};return"text"in s&&(n.text=this.truncateString(s.text)),"textPreview"in s&&(n.textPreview=this.truncateString(s.textPreview)),s.state&&(n.state={...s.state},"output"in s.state&&(n.state.output=this.truncateString(s.state.output)),"error"in s.state&&(n.state.error=this.truncateString(s.state.error)),s.state.metadata&&"preview"in s.state.metadata&&(n.state.metadata={...s.state.metadata,preview:this.truncateString(s.state.metadata.preview)})),n})}))},getAllMessages(t=!1){const r=ve.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),[];const n=r.messages.get(s)||[];return console.log(`[MESSAGES] Total messages in session: ${n.length}`),n.forEach((o,a)=>{console.log(`[${a}] ${o.info.role} - ${o.info.id} - ${o.parts.length} parts`)}),t?this.truncateMessages(n):n},async getAppStatus(){const t=vt.getState(),r=ve.getState(),s=Lt.getState(),n=t.currentDirectory||null,o=Oe.getDirectory()??null,a=r.sessions||[],c=new Set,l={};a.forEach(k=>{const M=k.directory;typeof M=="string"&&M.trim().length>0?(c.add(M),l[M]=(l[M]??0)+1):l["(none)"]=(l["(none)"]??0)+1});const d=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(k){return{available:!1,error:k instanceof Error?k.message:String(k)}}})(),u=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,m=typeof window<"u"?window.__OPENCHAMBER_DESKTOP_SERVER__:null,f=!!(u?.runtime?.isDesktop||typeof window<"u"&&window.opencodeDesktop),p=async k=>{try{return await k.json()}catch{return null}},h=async k=>{try{return await k.text()}catch{return null}},g=async k=>{try{const M=await fetch(k);return M.ok?await p(M):{status:M.status}}catch(M){return{error:M instanceof Error?M.message:String(M)}}};let x=null,b=null,y=null,v=null;const S=n?`/api/path?directory=${encodeURIComponent(n)}`:"/api/path";x=await g(S);const C=n?`/api/project/current?directory=${encodeURIComponent(n)}`:"/api/project/current";b=await g(C),y=await g("/api/config/settings");try{const k=await fetch("/api/health"),M=k.headers.get("content-type")||"",w=await h(k);v={status:k.status,ok:k.ok,contentType:M,type:M.includes("application/json")?"json":"html",preview:w?w.slice(0,120):null}}catch(k){v={error:k instanceof Error?k.message:String(k)}}let N={isGitRepo:null};if(n)try{N.isGitRepo=await Hr(n)}catch(k){N={isGitRepo:null,error:k instanceof Error?k.message:String(k)}}const j=s.projects.map(k=>({id:k.id,path:k.path,label:k.label})),D={runtime:{platform:u?.runtime?.platform??null,isDesktop:f,isVSCode:!!u?.runtime?.isVSCode,hasRuntimeApis:!!u,desktopServerOrigin:m?.origin??null},location:typeof window<"u"?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:n,opencodeDirectory:x?.directory||x?.worktree||o,homeDirectory:t.homeDirectory||null,isHomeReady:t.isHomeReady,hasPersistedDirectory:t.hasPersistedDirectory,isSwitchingDirectory:t.isSwitchingDirectory},projects:{total:s.projects.length,activeProjectId:s.activeProjectId,samples:j},sessions:{total:a.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:c.size,directorySamples:Array.from(c).slice(0,5),directoryCounts:l},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:N,localStorage:d,opencode:{pathInfo:x,projectInfo:b,health:v},openchamber:{settingsInfo:y}};return console.log("[DEBUG] App status snapshot:",D),D},async buildDiagnosticsReport(){const t=await this.getAppStatus();return JSON.stringify(t,null,2)},async copyDiagnosticsReport(){const t=await this.buildDiagnosticsReport();return typeof navigator<"u"&&navigator.clipboard?(await navigator.clipboard.writeText(t),{ok:!0,report:t}):{ok:!1,report:t}},checkLastMessage(){const t=this.getLastAssistantMessage();if(!t)return!1;const r=t.isEmpty||t.isEmptyResponse;return r?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:t.messageId,isEmpty:t.isEmpty,isEmptyResponse:t.isEmptyResponse,partsCount:t.partsCount}),t.parts.length>0&&console.log("Parts:",t.parts)):console.log("[OK] Last message looks good!"),r},getStreamingState(){const t=ve.getState(),r=t.currentSessionId?t.streamingMessageIds.get(t.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:r,streamingMessageIds:Array.from(t.streamingMessageIds.entries()),messageStreamStates:Array.from(t.messageStreamStates.entries())}),{streamingMessageId:r,streamingMessageIds:t.streamingMessageIds,streamStates:t.messageStreamStates}},findEmptyMessages(){const t=ve.getState(),r=t.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=(t.messages.get(r)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],c=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),l=a.some(d=>d.type==="tool");return a.length===0||!c&&!l});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
245
+ `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
246
+ `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
247
+ `),console.log("3. To retry, you can:"),console.log(" - Edit your last user message and resend"),console.log(' - Send a follow-up message like "Please provide the response"'),console.log(` - Try a different model (OpenAI models tend to be more reliable)
248
+ `),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(t={}){const{includeNonAssistant:r=!1,verbose:s=!0,maxTableRows:n=25}=t,o=ve.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const c=o.messages.get(a)||[],l=r?c:c.filter(p=>p.info.role==="assistant"),d={totalMessages:c.length,analyzedMessages:l.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const h=p.filter(g=>typeof g=="number");return h.length>0?Math.max(...h):null},f=l.map((p,h)=>{const g=p.info??{},x=Array.isArray(p.parts)?p.parts:[],b=g.time??{},y=u(b.completed),v=y!==null,S=x.filter(E=>E.type==="tool"),C=x.filter(E=>E.type==="reasoning"),N=m(S.map(E=>u(E.state?.time?.end??E.state?.time?.start))),j=m(C.map(E=>u(E.time?.end??E.time?.start))),D=m([N,j].filter(E=>E!==null)),k=S.some(E=>["pending","running","started"].includes(E.state?.status)),M=C.some(E=>typeof E.time?.end!="number");S.length>0&&(d.withTools+=1),C.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const w=!!(v&&typeof N=="number"&&y<N);w&&(d.completedBeforeTool+=1);const T=!!(v&&typeof j=="number"&&y<j);return T&&(d.completedBeforeReasoning+=1),v&&k&&(d.runningToolsWhenCompleted+=1),v&&M&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:y,latestToolTimestamp:N,latestReasoningTimestamp:j,latestPartTimestamp:D,completed_missing:!v,completed_before_tool:w,completed_before_reasoning:T,running_tools_when_completed:!!(v&&k),reasoning_open_when_completed:!!(v&&M),has_tools:S.length>0,has_reasoning:C.length>0}});return s&&(console.table(f.slice(0,n)),f.length>n&&console.log(`Displayed first ${n} rows out of ${f.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:f}},checkCompletionStatus(){const t=ve.getState(),r=t.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const n=(t.messages.get(r)||[]).filter(b=>b.info.role==="assistant");if(n.length===0)return console.log("[ERROR] No assistant messages"),null;const o=n[n.length-1],a=o.parts.filter(b=>b.type==="step-finish"),c=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&c),p=t.messageStreamStates,h=o.info.sessionID?t.streamingMessageIds.get(o.info.sessionID)??null:null,g=p.get(o.info.id),x=o.info.id===h;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",m),console.log("hasStopReason:",c),console.log("messageIsComplete:",f),console.log("lifecycle phase:",g?.phase),console.log("isStreamingCandidate:",x),console.log("streamingMessageId:",h),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:m,hasStopReason:c,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Sh,hs()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",t=>{try{const r=t.message||"",s=t.filename||"";typeof r=="string"&&r.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(s))&&t.preventDefault()}catch{}}));const DM=({open:t,onOpenChange:r})=>{const[s,n]=i.useState(null),[o,a]=i.useState(!1),[c,l]=i.useState(!1),d=i.useCallback(async()=>{if(!o){a(!0),l(!1);try{(await Sh.copyDiagnosticsReport()).ok?(l(!0),V.success("Diagnostics copied")):V.error("Copy failed")}catch(m){V.error("Copy failed"),console.error("Failed to copy diagnostics:",m)}finally{a(!1)}}},[o]);i.useEffect(()=>{if(!t)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:p}=await vs(async()=>{const{getVersion:g}=await import("./vendor-.bun-Bui932eM.js").then(x=>x.dm);return{getVersion:g}},__vite__mapDeps([0,1])),h=await p();n(h)}catch{n("1.6.0")}})():n("1.6.0")},[t]);const u=s;return e.jsx(us,{open:t,onOpenChange:r,children:e.jsx(ms,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(Ol,{width:64,height:64}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),u&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",u]})]}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["A fan-made interface for"," ",e.jsx("a",{href:"https://opencode.ai/",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground transition-colors",children:"OpenCode"})," ","agent"]}),e.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[e.jsx("button",{onClick:d,disabled:o,className:R("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:c?"Diagnostics copied":"Copy diagnostics"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Includes OpenChamber state, OpenCode health, directories, and projects."})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[e.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Qr,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(uf,{className:"h-4 w-4"}),e.jsx("span",{children:"Discord"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Pc,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:"Made with love to comunity"})]})})})};function Sc({apis:t,children:r}){return e.jsx(Nl.Provider,{value:t,children:r})}const AM="curl -fsSL https://opencode.ai/install | bash",EM=3e3;function IM({onCopy:t}){return e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsxs("code",{children:[e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),e.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),e.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),e.jsx("span",{className:"text-muted-foreground",children:" | "}),e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e.jsx("button",{onClick:t,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(nr,{className:"h-4 w-4"})})]})}const PM=3e4;function TM({onCliAvailable:t}){const[r,s]=i.useState(!1),[n,o]=i.useState(!1),[a,c]=i.useState(!1);i.useEffect(()=>{const m=setTimeout(()=>o(!0),PM);return()=>clearTimeout(m)},[]),i.useEffect(()=>{c(typeof window.opencodeDesktop<"u")},[]);const l=i.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await vs(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-Bui932eM.js").then(g=>g.dl);return{getCurrentWindow:h}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=i.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=i.useCallback(async()=>{try{await navigator.clipboard.writeText(AM),s(!0),setTimeout(()=>s(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return i.useEffect(()=>{const m=async()=>{await d()&&t?.()},f=setInterval(m,EM);return m(),()=>clearInterval(f)},[d,t]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:l,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(Zs,{className:"h-4 w-4"})]})," ","is required to continue."]})]}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"bg-background/60 backdrop-blur-sm border border-border rounded-lg px-5 py-3 font-mono text-sm w-fit",children:r?e.jsxs("div",{className:"flex items-center justify-center gap-2",style:{color:"var(--status-success)"},children:[e.jsx(Tt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(IM,{onCopy:u})})}),e.jsxs("a",{href:"https://opencode.ai/docs",target:"_blank",rel:"noopener noreferrer",className:"text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-1 justify-center",children:["View documentation",e.jsx(Zs,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Waiting for OpenCode installation..."})]}),n&&e.jsxs("div",{className:"absolute bottom-8 left-0 right-0 text-center space-y-1",children:[e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["Already installed? Make sure ",e.jsx("code",{className:"text-foreground/70",children:"opencode"})," is in your PATH"]}),e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["or set ",e.jsx("code",{className:"text-foreground/70",children:"OPENCODE_BINARY"})," environment variable."]})]})]})}const FM=()=>{const{isAboutDialogOpen:t,setAboutDialogOpen:r}=Me();return e.jsx(DM,{open:t,onOpenChange:r})};function RM({apis:t}){const{initializeApp:r,isInitialized:s,isConnected:n}=Je(),{error:o,clearError:a,loadSessions:c}=ve(),l=vt(j=>j.currentDirectory),d=vt(j=>j.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=ch(),h=Bs(j=>j.refreshStatus),[g,x]=i.useState(()=>t.runtime.isDesktop),[b,y]=i.useState(()=>t.runtime.isVSCode),[v,S]=i.useState(()=>t.runtime.isDesktop?by():!0);i.useEffect(()=>{x(t.runtime.isDesktop),y(t.runtime.isVSCode)},[t.runtime.isDesktop,t.runtime.isVSCode]),i.useEffect(()=>(ld(t),()=>ld(null)),[t]),i.useEffect(()=>{h(t.github,{force:!0})},[t.github,h]),i.useEffect(()=>{if(typeof document>"u")return;const j=document.documentElement,D=Zu[f]?.stack??Zu[ZN].stack,k=mn[p]?.stack??mn[za].stack;j.style.setProperty("--font-sans",D),j.style.setProperty("--font-heading",D),j.style.setProperty("--font-family-sans",D),j.style.setProperty("--font-mono",k),j.style.setProperty("--font-family-mono",k),j.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=D)},[f,p]),i.useEffect(()=>{if(s){const D=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},150);return()=>clearTimeout(D)}},[s]),i.useEffect(()=>{const j=setTimeout(()=>{const D=document.getElementById("initial-loading");D&&!s&&(D.classList.add("fade-out"),setTimeout(()=>{D.remove()},300))},5e3);return()=>clearTimeout(j)},[s]),i.useEffect(()=>{(async()=>b||await r())()},[r,b]),i.useEffect(()=>{if(d)return;(async()=>b||n&&(Oe.setDirectory(l),await c()))()},[l,d,c,n,b]),oM(),NM(),jM(),aM();const C=i.useCallback(()=>{m(j=>!j)},[]);iM(C),cM(),hh(),i.useEffect(()=>{const j=D=>{$s(D)&&D.shiftKey&&D.key==="D"&&(D.preventDefault(),m(k=>!k))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=i.useCallback(()=>{S(!0),window.location.reload()},[]);return g&&!v?e.jsx(os,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(TM,{onCliAvailable:N})})}):b?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(os,{children:e.jsx(Sc,{apis:t,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(GC,{}),e.jsx(Qi,{})]})})}):e.jsx(os,{children:e.jsx(Sc,{apis:t,children:e.jsx(Uu,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(FC,{}),e.jsx(Qi,{})]})})})}):e.jsx(os,{children:e.jsx(Sc,{apis:t,children:e.jsx(CM,{children:e.jsx(Uu,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(EC,{}),e.jsx(Qi,{}),e.jsx(MM,{}),e.jsx(FM,{}),u&&e.jsx(KC,{onClose:()=>m(!1)})]})})})})})}const Nh=async()=>{if(typeof window>"u")return;let t=null,r=null;try{t=window.localStorage.getItem("homeDirectory"),r=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const s=vt.getState();t&&s.homeDirectory!==t&&s.synchronizeHomeDirectory(t),r&&!zt()&&s.setDirectory(r,{showOverlay:!1})},kh="/auth/session",LM=async()=>fetch(kh,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Pm=async t=>fetch(kh,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:t})}),Wl=({children:t})=>e.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:{fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-55",style:{background:"radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)"}}),e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),e.jsx("div",{className:"relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:t})]}),OM=({message:t="Preparing workspace…"})=>e.jsx(Wl,{children:e.jsx("div",{className:"w-full max-w-sm rounded-3xl border border-border/40 bg-card/90 px-6 py-5 text-center shadow-none backdrop-blur",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:t})})}),_M=({onRetry:t})=>e.jsx(Wl,{children:e.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:"Unable to reach server"}),e.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:"We couldn't verify the UI session. Check that the service is running and try again."})]}),e.jsx(Se,{type:"button",onClick:t,className:"w-full max-w-xs",children:"Retry"})]})}),$M=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},BM=()=>{try{const t=new URL(window.location.href);t.searchParams.delete("token"),window.history.replaceState({},"",t.toString())}catch{}},zM=({children:t})=>{const r=i.useMemo(()=>ds(),[]),s=i.useMemo(()=>zt(),[]),n=r||s,[o,a]=i.useState(()=>n?"authenticated":"pending"),[c,l]=i.useState(""),[d,u]=i.useState(!1),[m,f]=i.useState(""),p=i.useRef(null),h=i.useRef(n),g=i.useRef(!1),x=i.useCallback(async()=>{if(n){a("authenticated");return}a(y=>y==="authenticated"?y:"pending");try{const y=await LM();if(y.ok){a("authenticated"),f("");return}if(y.status===401){a("locked");return}a("error")}catch(y){console.warn("Failed to check session status:",y),a("error")}},[n]);i.useEffect(()=>{n||x()},[x,n]),i.useEffect(()=>{!n&&o==="locked"&&(h.current=!1)},[n,o]),i.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),i.useEffect(()=>{if(n||o!=="locked"||g.current||d)return;const y=$M();y&&(g.current=!0,BM(),u(!0),f(""),Pm(y).then(v=>{if(v.ok){l(""),a("authenticated");return}if(v.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(v=>{console.warn("Failed to submit URL token:",v),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),i.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await vf(),await jf(),await Nh()))())},[n,o]);const b=async y=>{if(y.preventDefault(),!(!c||d)){u(!0),f("");try{const v=await Pm(c);if(v.ok){l(""),a("authenticated");return}if(v.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(v){console.warn("Failed to submit UI password:",v),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(OM,{}):o==="error"?e.jsx(_M,{onRetry:()=>{x()}}):o==="locked"?e.jsx(Wl,{children:e.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold text-foreground",children:"Unlock OpenChamber"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"This session is password-protected."})]}),e.jsxs("form",{onSubmit:b,className:"w-full space-y-2","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zx,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(St,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:c,onChange:y=>{l(y.target.value),m&&f("")},className:"pl-10","aria-invalid":!!m||void 0,"aria-describedby":m?"oc-ui-auth-error":void 0,disabled:d})]}),e.jsx(Se,{type:"submit",size:"icon",disabled:!c||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Mt,{className:"h-4 w-4 animate-spin"}):e.jsx(ey,{className:"h-4 w-4"})})]}),m&&e.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:m})]})]})}):e.jsx(e.Fragment,{children:t})},Nc=t=>{if(!t||typeof t!="string")return null;const r=t.trim();if(!r.startsWith("#"))return null;let s=r.slice(1);if((s.length===3||s.length===4)&&(s=s.split("").map(l=>l+l).join("")),s.length===8&&(s=s.slice(0,6)),s.length!==6)return null;const n=Number.parseInt(s,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,c=n&255;return`${o} ${a} ${c}`};class HM{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(r){const s=[];return s.push(...this.generateTailwindVariables(r)),s.push(...this.generatePrimaryColors(r.colors.primary)),s.push(...this.generateSurfaceColors(r.colors.surface)),s.push(...this.generateInteractiveColors(r.colors.interactive)),s.push(...this.generateStatusColors(r.colors.status)),s.push(...this.generateSyntaxColors(r.colors.syntax)),s.push(...this.generateComponentColors(r.colors,r)),s.push(...this.generateTypographyVariables()),r.config&&s.push(...this.generateConfigVariables(r.config)),s.join(`
249
+ `)}generateTailwindVariables(r){const s=[];s.push(` --background: ${r.colors.surface.background} !important;`),s.push(` --foreground: ${r.colors.surface.foreground} !important;`),s.push(` --muted: ${r.colors.surface.muted} !important;`),s.push(` --muted-foreground: ${r.colors.surface.mutedForeground} !important;`),s.push(` --card: ${r.colors.surface.elevated} !important;`),s.push(` --card-foreground: ${r.colors.surface.elevatedForeground} !important;`),s.push(` --popover: ${r.colors.surface.elevated} !important;`),s.push(` --popover-foreground: ${r.colors.surface.elevatedForeground} !important;`),s.push(` --border: ${r.colors.interactive.border} !important;`),s.push(` --input: ${r.colors.interactive.border} !important;`),s.push(` --primary: ${r.colors.primary.base} !important;`),s.push(` --primary-foreground: ${r.colors.primary.foreground} !important;`),s.push(` --secondary: ${r.colors.surface.muted} !important;`),s.push(` --secondary-foreground: ${r.colors.surface.mutedForeground} !important;`),s.push(` --accent: ${r.colors.surface.subtle} !important;`),s.push(` --accent-foreground: ${r.colors.surface.foreground} !important;`),s.push(` --destructive: ${r.colors.status.error} !important;`),s.push(` --destructive-foreground: ${r.colors.status.errorForeground} !important;`),s.push(` --ring: ${r.colors.interactive.focusRing} !important;`),r.config?.radius?.md&&s.push(` --radius: ${r.config.radius.md} !important;`);const n=Nc(r.colors.surface.muted),o=Nc(r.colors.surface.subtle),a=Nc(r.colors.interactive.border);s.push(` --sidebar-base: ${r.colors.surface.muted} !important;`),n&&s.push(` --sidebar-base-rgb: ${n} !important;`),s.push(" --sidebar: var(--sidebar-base) !important;"),s.push(` --sidebar-foreground: ${r.colors.surface.mutedForeground} !important;`),s.push(` --sidebar-primary: ${r.colors.primary.base} !important;`),s.push(` --sidebar-primary-foreground: ${r.colors.primary.foreground} !important;`),s.push(` --sidebar-accent-base: ${r.colors.surface.subtle} !important;`),o&&s.push(` --sidebar-accent-base-rgb: ${o} !important;`),s.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),s.push(` --sidebar-accent-foreground: ${r.colors.surface.foreground} !important;`),s.push(` --sidebar-border: ${r.colors.interactive.border} !important;`),a&&s.push(` --sidebar-border-rgb: ${a} !important;`),s.push(` --sidebar-ring: ${r.colors.interactive.focusRing} !important;`);const c=r.metadata.variant==="dark",l=c?.8:.95,d=c?.7:.9;if(n)s.push(` --sidebar-overlay-strong: rgb(${n} / ${l}) !important;`),s.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=r.colors.surface.muted;s.push(` --sidebar-overlay-strong: ${this.opacity(u,l)} !important;`),s.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return r.colors.charts?.series&&Array.isArray(r.colors.charts.series)&&r.colors.charts.series.forEach((u,m)=>{s.push(` --chart-${m+1}: ${u};`)}),r.colors.loading?(s.push(` --loading-spinner: ${r.colors.loading.spinner||r.colors.primary.base};`),s.push(` --loading-spinner-track: ${r.colors.loading.spinnerTrack||r.colors.surface.muted};`)):(s.push(` --loading-spinner: ${r.colors.primary.base};`),s.push(` --loading-spinner-track: ${r.colors.surface.muted};`)),s}apply(r){const s=this.generate(r),n=document.createElement("style");n.id="opencode-theme-variables";let o="";r.metadata.variant==="dark"?(o=`:root {
250
+ ${s}
251
+ }
252
+
253
+ .dark {
254
+ ${s}
255
+ }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
256
+ ${s}
257
+ }
258
+
259
+ :root:not(.dark) {
260
+ ${s}
261
+ }`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),n.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(n),document.documentElement.setAttribute("data-theme",r.metadata.variant)}generatePrimaryColors(r){const s=[];return s.push(` --primary-base: ${r.base};`),s.push(` --primary-hover: ${r.hover||this.darken(r.base,10)};`),s.push(` --primary-active: ${r.active||this.darken(r.base,20)};`),s.push(` --primary-foreground: ${r.foreground||"#ffffff"};`),s.push(` --primary-muted: ${r.muted||this.opacity(r.base,.5)};`),s.push(` --primary-emphasis: ${r.emphasis||this.lighten(r.base,10)};`),s}generateSurfaceColors(r){const s=[];return s.push(` --surface-background: ${r.background};`),s.push(` --surface-foreground: ${r.foreground};`),s.push(` --surface-muted: ${r.muted};`),s.push(` --surface-muted-foreground: ${r.mutedForeground};`),s.push(` --surface-elevated: ${r.elevated};`),s.push(` --surface-elevated-foreground: ${r.elevatedForeground};`),s.push(` --surface-overlay: ${r.overlay};`),s.push(` --surface-subtle: ${r.subtle};`),s}generateInteractiveColors(r){const s=[];return s.push(` --interactive-border: ${r.border};`),s.push(` --interactive-border-hover: ${r.borderHover};`),s.push(` --interactive-border-focus: ${r.borderFocus};`),s.push(` --interactive-selection: ${r.selection};`),s.push(` --interactive-selection-foreground: ${r.selectionForeground};`),s.push(` --interactive-focus: ${r.focus};`),s.push(` --interactive-focus-ring: ${r.focusRing};`),s.push(` --interactive-cursor: ${r.cursor};`),s.push(` --interactive-hover: ${r.hover};`),s.push(` --interactive-active: ${r.active};`),s}generateStatusColors(r){const s=[];return s.push(` --status-error: ${r.error};`),s.push(` --status-error-foreground: ${r.errorForeground};`),s.push(` --status-error-background: ${r.errorBackground};`),s.push(` --status-error-border: ${r.errorBorder};`),s.push(` --status-warning: ${r.warning};`),s.push(` --status-warning-foreground: ${r.warningForeground};`),s.push(` --status-warning-background: ${r.warningBackground};`),s.push(` --status-warning-border: ${r.warningBorder};`),s.push(` --status-success: ${r.success};`),s.push(` --status-success-foreground: ${r.successForeground};`),s.push(` --status-success-background: ${r.successBackground};`),s.push(` --status-success-border: ${r.successBorder};`),s.push(` --status-info: ${r.info};`),s.push(` --status-info-foreground: ${r.infoForeground};`),s.push(` --status-info-background: ${r.infoBackground};`),s.push(` --status-info-border: ${r.infoBorder};`),s}generateSyntaxColors(r){const s=[];s.push(` --syntax-background: ${r.base.background};`),s.push(` --syntax-foreground: ${r.base.foreground};`),s.push(` --syntax-comment: ${r.base.comment};`),s.push(` --syntax-keyword: ${r.base.keyword};`),s.push(` --syntax-string: ${r.base.string};`),s.push(` --syntax-number: ${r.base.number};`),s.push(` --syntax-function: ${r.base.function};`),s.push(` --syntax-variable: ${r.base.variable};`),s.push(` --syntax-type: ${r.base.type};`),s.push(` --syntax-operator: ${r.base.operator};`);const n=this.generateSyntaxTokens(r);for(const[o,a]of Object.entries(n))s.push(` --syntax-${this.kebabCase(o)}: ${a};`);return s}generateSyntaxTokens(r){const s=r.base,n=r.tokens||{};return{commentDoc:n.commentDoc||this.lighten(s.comment,10),stringEscape:n.stringEscape||this.darken(s.string,20),stringInterpolation:n.stringInterpolation||s.variable,stringRegex:n.stringRegex||this.adjustHue(s.string,15),keywordControl:n.keywordControl||s.keyword,keywordOperator:n.keywordOperator||s.operator,keywordImport:n.keywordImport||this.lighten(s.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(s.keyword),functionCall:n.functionCall||this.lighten(s.function,5),functionBuiltin:n.functionBuiltin||this.darken(s.function,10),method:n.method||s.function,methodCall:n.methodCall||this.lighten(s.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(s.variable),variableProperty:n.variableProperty||this.lighten(s.variable,10),variableReadonly:n.variableReadonly||s.number,parameter:n.parameter||s.variable,typePrimitive:n.typePrimitive||this.darken(s.type,10),typeInterface:n.typeInterface||s.type,className:n.className||this.emphasize(s.type),enum:n.enum||s.type,boolean:n.boolean||s.number,null:n.null||this.opacity(s.number,.7),constant:n.constant||s.number,punctuation:n.punctuation||this.opacity(s.foreground,.7),delimiter:n.delimiter||this.opacity(s.foreground,.8),bracket:n.bracket||s.foreground,tag:n.tag||s.keyword,tagAttribute:n.tagAttribute||s.variable,tagAttributeValue:n.tagAttributeValue||s.string,tagBracket:n.tagBracket||this.opacity(s.foreground,.8),decorator:n.decorator||s.function,annotation:n.annotation||s.function,namespace:n.namespace||this.opacity(s.type,.8),module:n.module||this.opacity(s.type,.8),...n}}generateComponentColors(r,s){const n=[];return r.markdown?n.push(...this.generateMarkdownColors(r.markdown,s)):n.push(...this.generateDefaultMarkdownColors(s)),r.chat?n.push(...this.generateChatColors(r.chat,s)):n.push(...this.generateDefaultChatColors(s)),r.tools?n.push(...this.generateToolColors(r.tools,s)):n.push(...this.generateDefaultToolColors(s)),n}generateMarkdownColors(r,s){const n=[],o=s.colors.primary.base,a=s.colors.chat?.background||s.colors.surface.background;return n.push(` --markdown-heading1: ${r.heading1||o};`),n.push(` --markdown-heading2: ${r.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${r.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${r.heading4||s.colors.surface.foreground};`),n.push(` --markdown-link: ${r.link||o};`),n.push(` --markdown-link-hover: ${r.linkHover||s.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${r.inlineCode||s.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${r.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${r.blockquote||s.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${r.blockquoteBorder||s.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${r.bold||s.colors.surface.foreground};`),n.push(` --markdown-italic: ${r.italic||this.opacity(s.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${r.strikethrough||s.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${r.hr||s.colors.interactive.border};`),n}generateDefaultMarkdownColors(r){const s=[],n=r.colors.primary.base,o=r.colors.chat?.background||r.colors.surface.background;return s.push(` --markdown-heading1: ${n};`),s.push(` --markdown-heading2: ${this.opacity(n,.9)};`),s.push(` --markdown-heading3: ${this.opacity(n,.8)};`),s.push(` --markdown-heading4: ${r.colors.surface.foreground};`),s.push(` --markdown-link: ${n};`),s.push(` --markdown-link-hover: ${r.colors.primary.hover||this.darken(n,10)};`),s.push(` --markdown-inline-code: ${r.colors.syntax.base.string};`),s.push(` --markdown-inline-code-bg: ${o};`),s.push(` --markdown-blockquote: ${r.colors.surface.mutedForeground};`),s.push(` --markdown-blockquote-border: ${r.colors.interactive.border};`),s.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),s.push(` --markdown-bold: ${r.colors.surface.foreground};`),s.push(` --markdown-italic: ${this.opacity(r.colors.surface.foreground,.9)};`),s.push(` --markdown-strikethrough: ${r.colors.surface.mutedForeground};`),s.push(` --markdown-hr: ${r.colors.interactive.border};`),s}generateChatColors(r,s){const n=[],o=r.background||s.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${r.userMessage||s.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${r.userMessageBackground||s.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${r.assistantMessage||s.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${r.assistantMessageBackground||s.colors.surface.muted};`),n.push(` --chat-timestamp: ${r.timestamp||s.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${r.divider||s.colors.interactive.border};`),n.push(` --chat-typing: ${r.typing||s.colors.surface.mutedForeground};`),n}generateDefaultChatColors(r){const s=[];return s.push(` --chat-background: ${r.colors.surface.background};`),s.push(` --chat-user-message: ${r.colors.surface.foreground};`),s.push(` --chat-user-message-bg: ${r.colors.surface.elevated};`),s.push(` --chat-assistant-message: ${r.colors.surface.foreground};`),s.push(` --chat-assistant-message-bg: ${r.colors.surface.muted};`),s.push(` --chat-timestamp: ${r.colors.surface.mutedForeground};`),s.push(` --chat-divider: ${r.colors.interactive.border};`),s.push(` --chat-typing: ${r.colors.surface.mutedForeground};`),s}generateToolColors(r,s){const n=[];return n.push(` --tools-background: ${r?.background||this.opacity(s.colors.surface.muted,.2)};`),n.push(` --tools-border: ${r?.border||this.opacity(s.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${r?.headerHover||this.opacity(s.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${r?.icon||s.colors.surface.mutedForeground};`),n.push(` --tools-title: ${r?.title||s.colors.surface.foreground};`),n.push(` --tools-description: ${r?.description||this.opacity(s.colors.surface.mutedForeground,.6)};`),r?.edit?(n.push(` --tools-edit-added: ${r.edit.added||s.colors.status.success};`),n.push(` --tools-edit-added-bg: ${r.edit.addedBackground||s.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${r.edit.removed||s.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${r.edit.removedBackground||s.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${r.edit.modified||s.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${r.edit.modifiedBackground||s.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${r.edit.lineNumber||this.opacity(s.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${s.colors.status.success};`),n.push(` --tools-edit-added-bg: ${s.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${s.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${s.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${s.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${s.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(s.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(r){const s=[];return s.push(` --tools-background: ${this.opacity(r.colors.surface.muted,.2)};`),s.push(` --tools-border: ${this.opacity(r.colors.interactive.border,.3)};`),s.push(` --tools-header-hover: ${this.opacity(r.colors.surface.muted,.3)};`),s.push(` --tools-icon: ${r.colors.surface.mutedForeground};`),s.push(` --tools-title: ${r.colors.surface.foreground};`),s.push(` --tools-description: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),s.push(` --tools-edit-added: ${r.colors.status.success};`),s.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.successBackground),.15)};`),s.push(` --tools-edit-removed: ${r.colors.status.error};`),s.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.errorBackground),.15)};`),s.push(` --tools-edit-modified: ${r.colors.status.info};`),s.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.infoBackground),.15)};`),s.push(` --tools-edit-line-number: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),s}generateConfigVariables(r){const s=[];return r&&(r.fonts&&(r.fonts.sans&&(s.push(` --font-sans: ${r.fonts.sans};`),s.push(` --font-family-sans: ${r.fonts.sans};`)),r.fonts.mono&&(s.push(` --font-mono: ${r.fonts.mono};`),s.push(` --font-family-mono: ${r.fonts.mono};`)),r.fonts.heading&&s.push(` --font-heading: ${r.fonts.heading};`)),r.radius&&(r.radius.none&&s.push(` --radius-none: ${r.radius.none};`),r.radius.sm&&s.push(` --radius-sm: ${r.radius.sm};`),r.radius.md&&s.push(` --radius-md: ${r.radius.md};`),r.radius.lg&&s.push(` --radius-lg: ${r.radius.lg};`),r.radius.xl&&s.push(` --radius-xl: ${r.radius.xl};`),r.radius.full&&s.push(` --radius-full: ${r.radius.full};`)),r.transitions&&(r.transitions.fast&&s.push(` --transition-fast: ${r.transitions.fast};`),r.transitions.normal&&s.push(` --transition-normal: ${r.transitions.normal};`),r.transitions.slow&&s.push(` --transition-slow: ${r.transitions.slow};`))),s}generateTypographyVariables(){const r=[],s=zt()?Ay:pl;return r.push(" /* Semantic Typography Variables */"),r.push(" --ui-regular-font-weight: 400;"),r.push(" /* Markdown content - all markdown elements use same size */"),r.push(` --text-markdown: ${s.markdown};`),r.push(" /* Code content - all code elements use same size */"),r.push(` --text-code: ${s.code};`),r.push(" /* UI headers - dialog titles, panel headers */"),r.push(` --text-ui-header: ${s.uiHeader};`),r.push(" /* UI labels - buttons, menus, navigation */"),r.push(` --text-ui-label: ${s.uiLabel};`),r.push(" /* Metadata - timestamps, status, helper text */"),r.push(` --text-meta: ${s.meta};`),r.push(" /* Micro text - badges, shortcuts, indicators */"),r.push(` --text-micro: ${s.micro};`),r.push(" /* Heading line height and letter spacing */"),r.push(" --h1-line-height: 1.25rem;"),r.push(" --h2-line-height: 1.25rem;"),r.push(" --h3-line-height: 1.5rem;"),r.push(" --h4-line-height: 1.5rem;"),r.push(" --h5-line-height: 1.5rem;"),r.push(" --h6-line-height: 1.5rem;"),r.push(" --h1-letter-spacing: -0.025em;"),r.push(" --h2-letter-spacing: -0.02em;"),r.push(" --h3-letter-spacing: -0.015em;"),r.push(" --h4-letter-spacing: -0.01em;"),r.push(" --h5-letter-spacing: 0;"),r.push(" --h6-letter-spacing: 0.01em;"),r.push(" /* UI element line height and letter spacing */"),r.push(" --ui-button-line-height: 1.375rem;"),r.push(" --ui-button-letter-spacing: 0.02em;"),r.push(" --ui-button-font-weight: 500;"),r.push(" --ui-label-line-height: 1rem;"),r.push(" --ui-label-letter-spacing: 0.03em;"),r.push(" --ui-label-font-weight: 500;"),r.push(" --ui-caption-line-height: 1rem;"),r.push(" --ui-caption-letter-spacing: 0.025em;"),r.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Markdown line height and letter spacing */"),r.push(" --markdown-body-line-height: 1.5rem;"),r.push(" --markdown-body-letter-spacing: 0;"),r.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-h1-line-height: 1.25rem;"),r.push(" --markdown-h1-letter-spacing: -0.025em;"),r.push(" --markdown-h2-line-height: 1.25rem;"),r.push(" --markdown-h2-letter-spacing: -0.02em;"),r.push(" --markdown-h3-line-height: 1.5rem;"),r.push(" --markdown-h3-letter-spacing: -0.015em;"),r.push(" --markdown-h4-line-height: 1.5rem;"),r.push(" --markdown-h4-letter-spacing: -0.01em;"),r.push(" --markdown-h5-line-height: 1.5rem;"),r.push(" --markdown-h5-letter-spacing: 0;"),r.push(" --markdown-h6-line-height: 1.5rem;"),r.push(" --markdown-h6-letter-spacing: 0.01em;"),r.push(" --markdown-list-line-height: 1.375rem;"),r.push(" --markdown-code-block-line-height: 1rem;"),r.push(" --ui-button-small-line-height: 1.25rem;"),r.push(" --ui-button-small-letter-spacing: 0.02em;"),r.push(" --ui-button-small-font-weight: 500;"),r.push(" --markdown-body-small-line-height: 1.375rem;"),r.push(" --markdown-body-small-letter-spacing: 0;"),r.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-button-large-line-height: 1.5rem;"),r.push(" --ui-button-large-letter-spacing: 0.02em;"),r.push(" --ui-button-large-font-weight: 500;"),r.push(" --markdown-body-large-line-height: 1.625rem;"),r.push(" --markdown-body-large-letter-spacing: 0;"),r.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Code line height and letter spacing */"),r.push(" --code-inline-line-height: 1rem;"),r.push(" --code-inline-letter-spacing: 0;"),r.push(" --code-inline-font-weight: 400;"),r.push(" --code-block-line-height: 1.4rem;"),r.push(" --code-block-letter-spacing: 0;"),r.push(" --code-block-font-weight: 400;"),r.push(" --code-line-numbers-line-height: 1.25rem;"),r.push(" --code-line-numbers-letter-spacing: 0;"),r.push(" --code-line-numbers-font-weight: 400;"),r.push(" /* Additional UI element line height and letter spacing */"),r.push(" --ui-badge-line-height: 1rem;"),r.push(" --ui-badge-letter-spacing: 0.025em;"),r.push(" --ui-badge-font-weight: 500;"),r.push(" --ui-tooltip-line-height: 1rem;"),r.push(" --ui-tooltip-letter-spacing: 0.025em;"),r.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-input-line-height: 1.375rem;"),r.push(" --ui-input-letter-spacing: 0.02em;"),r.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-helper-text-line-height: 1rem;"),r.push(" --ui-helper-text-letter-spacing: 0.025em;"),r.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Additional markdown line height and letter spacing */"),r.push(" --markdown-blockquote-line-height: 1.5rem;"),r.push(" --markdown-blockquote-letter-spacing: 0;"),r.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-list-letter-spacing: 0;"),r.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-link-line-height: 1.5rem;"),r.push(" --markdown-link-letter-spacing: 0;"),r.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-code-line-height: 1.35;"),r.push(" --markdown-code-letter-spacing: 0;"),r.push(" --markdown-code-font-weight: 400;"),r.push(" --markdown-code-block-letter-spacing: 0;"),r.push(" --markdown-code-block-font-weight: 400;"),r}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(r,s){return r.startsWith("#")?`${r}${Math.round(s*255).toString(16).padStart(2,"0")}`:r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${s})`):r}removeTransparency(r){return r.startsWith("#")?r.length===9?r.slice(0,7):r.length===5?r.slice(0,4):r:r.startsWith("rgba")?r.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):r}addTransparency(r,s){if(r.startsWith("#")){const n=r.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),c=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${c}, ${s})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),c=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${c}, ${s})`}}return r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${s})`):r}darken(r,s){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*s),a=(n>>16)-o,c=(n>>8&255)-o,l=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(c<255?c<0?0:c:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}lighten(r,s){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*s),a=(n>>16)+o,c=(n>>8&255)+o,l=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(c<255?c<0?0:c:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}adjustHue(r,s){return this.lighten(r,s/10)}emphasize(r){return this.lighten(r,15)}kebabCase(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const Ul={metadata:{id:"flexoki-light",name:"Flexoki Light",description:"An inky color scheme for prose and code - light variant",author:"Steph Ango",version:"1.0.0",variant:"light",tags:["light","warm","natural","paper"]},colors:{primary:{base:"#EC8B49",hover:"#F9AE77",active:"#DA702C",foreground:"#FFFCF0",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#FFFCF0",foreground:"#100F0F",muted:"#F2F0E5",mutedForeground:"#6F6E69",elevated:"#E6E4D9",elevatedForeground:"#100F0F",overlay:"#100F0F20",subtle:"#DAD8CE"},interactive:{border:"#DAD8CE",borderHover:"#CECDC3",borderFocus:"#EC8B49",selection:"#100F0F44",selectionForeground:"#100F0F",focus:"#EC8B49",focusRing:"#EC8B4940",cursor:"#100F0F",hover:"#DAD8CE",active:"#CECDC3"},status:{error:"#AF3029",errorForeground:"#FFFCF0",errorBackground:"#D14D4120",errorBorder:"#D14D4150",warning:"#BC5215",warningForeground:"#FFFCF0",warningBackground:"#DA702C20",warningBorder:"#DA702C50",success:"#66800B",successForeground:"#FFFCF0",successBackground:"#879A3920",successBorder:"#879A3950",info:"#205EA6",infoForeground:"#FFFCF0",infoBackground:"#4385BE20",infoBorder:"#4385BE50"},syntax:{base:{background:"#F2F0E5",foreground:"#100F0F",comment:"#6F6E69",keyword:"#205EA6",string:"#24837B",number:"#5E409D",function:"#BC5215",variable:"#100F0F",type:"#AD8301",operator:"#AF3029"},tokens:{commentDoc:"#B7B5AC",stringEscape:"#100F0F",keywordImport:"#AF3029",storageModifier:"#205EA6",functionCall:"#BC5215",method:"#66800B",variableProperty:"#205EA6",variableOther:"#66800B",variableGlobal:"#A02F6F",variableLocal:"#E6E4D9",parameter:"#100F0F",constant:"#100F0F",class:"#BC5215",className:"#BC5215",interface:"#AD8301",struct:"#BC5215",enum:"#BC5215",typeParameter:"#BC5215",namespace:"#AD8301",module:"#AF3029",tag:"#205EA6",jsxTag:"#A02F6F",tagAttribute:"#AD8301",tagAttributeValue:"#24837B",boolean:"#AD8301",decorator:"#AD8301",label:"#A02F6F",punctuation:"#6F6E69",macro:"#205EA6",preprocessor:"#A02F6F",regex:"#24837B",url:"#205EA6",key:"#BC5215",exception:"#A02F6F"},highlights:{diffAdded:"#66800B",diffAddedBackground:"#879A3920",diffRemoved:"#AF3029",diffRemovedBackground:"#D14D4120",diffModified:"#205EA6",diffModifiedBackground:"#4385BE20",lineNumber:"#CECDC3",lineNumberActive:"#100F0F"}},markdown:{heading1:"#AD8301",heading2:"#BC5215",heading3:"#205EA6",heading4:"#100F0F",link:"#205EA6",linkHover:"#4385BE",inlineCode:"#24837B",inlineCodeBackground:"#F2F0E5",blockquote:"#6F6E69",blockquoteBorder:"#DAD8CE",listMarker:"#AD830199"},chat:{userMessage:"#100F0F",userMessageBackground:"#F2F0E5",assistantMessage:"#100F0F",assistantMessageBackground:"#FFFCF0",timestamp:"#6F6E69",divider:"#DAD8CE"},tools:{background:"#F2F0E550",border:"#DAD8CE80",headerHover:"#DAD8CE",icon:"#6F6E69",title:"#100F0F",description:"#6F6E69",edit:{added:"#66800B",addedBackground:"#66800B25",removed:"#AF3029",removedBackground:"#AF302925",lineNumber:"#CECDC3"}}},config:{fonts:{sans:'"IBM Plex Mono", monospace',mono:'"IBM Plex Mono", monospace',heading:'"IBM Plex Mono", monospace'},radius:{none:"0",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},transitions:{fast:"150ms ease",normal:"250ms ease",slow:"350ms ease"}}},Vl={metadata:{id:"flexoki-dark",name:"Flexoki Dark",description:"An inky color scheme for prose and code - dark variant",author:"Steph Ango",version:"1.0.0",variant:"dark",tags:["dark","warm","natural","ink"]},colors:{primary:{base:"#EC8B49",hover:"#DA702C",active:"#F9AE77",foreground:"#100F0F",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#100F0F",foreground:"#CECDC3",muted:"#1C1B1A",mutedForeground:"#878580",elevated:"#282726",elevatedForeground:"#CECDC3",overlay:"#00000080",subtle:"#343331"},interactive:{border:"#343331",borderHover:"#403E3C",borderFocus:"#EC8B49",selection:"#CECDC330",selectionForeground:"#CECDC3",focus:"#EC8B49",focusRing:"#EC8B4950",cursor:"#CECDC3",hover:"#343331",active:"#403E3C"},status:{error:"#D14D41",errorForeground:"#100F0F",errorBackground:"#AF302920",errorBorder:"#AF302950",warning:"#DA702C",warningForeground:"#100F0F",warningBackground:"#BC521520",warningBorder:"#BC521550",success:"#A0AF54",successForeground:"#100F0F",successBackground:"#66800B20",successBorder:"#66800B50",info:"#4385BE",infoForeground:"#100F0F",infoBackground:"#205EA620",infoBorder:"#205EA650"},syntax:{base:{background:"#1C1B1A",foreground:"#CECDC3",comment:"#878580",keyword:"#4385BE",string:"#3AA99F",number:"#8B7EC8",function:"#DA702C",variable:"#CECDC3",type:"#D0A215",operator:"#D14D41"},tokens:{commentDoc:"#575653",stringEscape:"#CECDC3",keywordImport:"#D14D41",storageModifier:"#4385BE",functionCall:"#DA702C",method:"#879A39",variableProperty:"#4385BE",variableOther:"#879A39",variableGlobal:"#CE5D97",variableLocal:"#282726",parameter:"#CECDC3",constant:"#CECDC3",class:"#DA702C",className:"#DA702C",interface:"#D0A215",struct:"#DA702C",enum:"#DA702C",typeParameter:"#DA702C",namespace:"#D0A215",module:"#D14D41",tag:"#4385BE",jsxTag:"#CE5D97",tagAttribute:"#D0A215",tagAttributeValue:"#3AA99F",boolean:"#D0A215",decorator:"#D0A215",label:"#CE5D97",punctuation:"#878580",macro:"#4385BE",preprocessor:"#CE5D97",regex:"#3AA99F",url:"#4385BE",key:"#DA702C",exception:"#CE5D97"},highlights:{diffAdded:"#879A39",diffAddedBackground:"#66800B20",diffRemoved:"#D14D41",diffRemovedBackground:"#AF302920",diffModified:"#4385BE",diffModifiedBackground:"#205EA620",lineNumber:"#403E3C",lineNumberActive:"#CECDC3"}},markdown:{heading1:"#D0A215",heading2:"#DA702C",heading3:"#4385BE",heading4:"#CECDC3",link:"#4385BE",linkHover:"#205EA6",inlineCode:"#A0AF54",inlineCodeBackground:"#1C1B1A",blockquote:"#878580",blockquoteBorder:"#343331",listMarker:"#D0A21599"},chat:{userMessage:"#CECDC3",userMessageBackground:"#282726",assistantMessage:"#CECDC3",assistantMessageBackground:"#100F0F",timestamp:"#878580",divider:"#343331"},tools:{background:"#1C1B1A50",border:"#34333180",headerHover:"#34333150",icon:"#878580",title:"#CECDC3",description:"#878580",edit:{added:"#879A39",addedBackground:"#66800B25",removed:"#D14D41",removedBackground:"#AF302925",lineNumber:"#403E3C"}}},config:{fonts:{sans:'"IBM Plex Mono", monospace',mono:'"IBM Plex Mono", monospace',heading:'"IBM Plex Mono", monospace'},radius:{none:"0",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},transitions:{fast:"150ms ease",normal:"250ms ease",slow:"350ms ease"}}},Uo=[Ul,Vl];function di(t){return Uo.find(r=>r.metadata.id===t)}const Ch=Ul.metadata.id,Mh=Vl.metadata.id,WM=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Dh=t=>t==="dark"?Vl:Ul,UM=t=>(Uo.find(s=>s.metadata.variant===t)??Dh(t)).metadata.id,Na=(t,r)=>{const s=di(t);return s&&s.metadata.variant===r?s:Uo.find(o=>o.metadata.variant===r)??Dh(r)},VM=typeof window<"u"?i.useLayoutEffect:i.useEffect,ui=(t,r)=>{if(!t)return r==="light"?Ch:Mh;const s=di(t);return s&&s.metadata.variant===r?s.metadata.id:UM(r)},GM=t=>{let r=Ch,s=Mh,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),c=localStorage.getItem("darkThemeId"),l=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(l!==null){if(l==="true")n="system";else if(d){const f=di(d);f&&(n=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?s=f.metadata.id:r=f.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);r=ui(a,"light"),s=ui(c,"dark")}if(t){const o=di(t);o&&(o.metadata.variant==="light"?r=o.metadata.id:s=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:s}};function qM({children:t,defaultThemeId:r}){const s=Ae.useMemo(()=>new HM,[]),[n,o]=Ae.useState(()=>GM(r)),[a,c]=Ae.useState(()=>WM()),[l,d]=Ae.useState(()=>typeof window>"u"||!zt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Ae.useMemo(()=>zt(),[]),m=Ae.useMemo(()=>u&&l?l:n.themeMode==="light"?Na(n.lightThemeId,"light"):n.themeMode==="dark"||a?Na(n.darkThemeId,"dark"):Na(n.lightThemeId,"light"),[u,n,a,l]),f=Ae.useMemo(()=>u&&l?[l,...Uo]:Uo,[u,l]);Ae.useEffect(()=>{if(!u)return;const C=D=>{d(D);const k=D.metadata.variant==="dark"?"dark":"light",M=Me.getState();M.theme!==k&&M.setTheme(k)},N=D=>{const k=D.detail;k?.theme&&C(k.theme)},j=window.__OPENCHAMBER_VSCODE_THEME__;return j&&C(j),window.addEventListener("openchamber:vscode-theme",N),()=>window.removeEventListener("openchamber:vscode-theme",N)},[u]);const p=Ae.useCallback(C=>{if(typeof document>"u")return;const N=C.colors.surface.background;document.body.style.backgroundColor=N;let j=document.querySelector('meta[name="theme-color"]');j||(j=document.createElement("meta"),j.setAttribute("name","theme-color"),document.head.appendChild(j)),j.setAttribute("content",N);const D=C.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let k=document.querySelector(`meta[name="theme-color"][media="${D}"]`);k||(k=document.createElement("meta"),k.setAttribute("name","theme-color"),k.setAttribute("media",D),document.head.appendChild(k)),k.setAttribute("content",N)},[]),h=Ae.useCallback(C=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",C)},[]);VM(()=>{if(typeof window>"u")return;s.apply(m),h(u),p(m);const C=document.documentElement;C.classList.remove("light","dark"),C.classList.add(m.metadata.variant)},[h,s,m,u,p]),Ae.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const C=window.matchMedia("(prefers-color-scheme: dark)"),N=j=>{c(j.matches)};return c(C.matches),C.addEventListener("change",N),()=>C.removeEventListener("change",N)},[n.themeMode]),Ae.useEffect(()=>{typeof window>"u"||(localStorage.setItem("themeMode",n.themeMode),localStorage.setItem("lightThemeId",n.lightThemeId),localStorage.setItem("darkThemeId",n.darkThemeId),localStorage.setItem("useSystemTheme",String(n.themeMode==="system")),localStorage.setItem("selectedThemeId",m.metadata.id),localStorage.setItem("selectedThemeVariant",m.metadata.variant==="light"?"light":"dark"))},[n,m]),Ae.useEffect(()=>{as({themeId:m.metadata.id,themeVariant:m.metadata.variant==="light"?"light":"dark",useSystemTheme:n.themeMode==="system",lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId})},[m.metadata.id,m.metadata.variant,n.themeMode,n.lightThemeId,n.darkThemeId]),Ae.useEffect(()=>{if(typeof window>"u")return;const C=N=>{const j=N.detail;j&&o(D=>{let k=D.themeMode;j.useSystemTheme===!0?k="system":j.useSystemTheme===!1&&(j.themeVariant==="dark"||j.themeVariant==="light")&&(k=j.themeVariant);let M=D.lightThemeId;typeof j.lightThemeId=="string"&&j.lightThemeId.length>0&&(M=ui(j.lightThemeId,"light"));let w=D.darkThemeId;return typeof j.darkThemeId=="string"&&j.darkThemeId.length>0&&(w=ui(j.darkThemeId,"dark")),k===D.themeMode&&M===D.lightThemeId&&w===D.darkThemeId?D:{themeMode:k,lightThemeId:M,darkThemeId:w}})};return window.addEventListener("openchamber:settings-synced",C),()=>window.removeEventListener("openchamber:settings-synced",C)},[]);const g=Ae.useCallback(C=>{const N=f.find(j=>j.metadata.id===C);N&&o(j=>N.metadata.variant==="dark"?j.darkThemeId===N.metadata.id&&j.themeMode==="dark"?j:{...j,darkThemeId:N.metadata.id,themeMode:"dark"}:j.lightThemeId===N.metadata.id&&j.themeMode==="light"?j:{...j,lightThemeId:N.metadata.id,themeMode:"light"})},[f]),x=Ae.useCallback(C=>{o(N=>N.themeMode===C?N:{...N,themeMode:C})},[]),b=Ae.useCallback(C=>{if(C){o(j=>j.themeMode==="system"?j:{...j,themeMode:"system"});return}const N=m.metadata.variant==="dark"?"dark":"light";o(j=>j.themeMode===N?j:{...j,themeMode:N})},[m.metadata.variant]),y=Ae.useCallback(C=>{const N=f.find(j=>j.metadata.id===C&&j.metadata.variant==="light");N&&o(j=>j.lightThemeId===N.metadata.id?j:{...j,lightThemeId:N.metadata.id})},[f]),v=Ae.useCallback(C=>{const N=f.find(j=>j.metadata.id===C&&j.metadata.variant==="dark");N&&o(j=>j.darkThemeId===N.metadata.id?j:{...j,darkThemeId:N.metadata.id})},[f]),S={currentTheme:m,availableThemes:f,setTheme:g,isSystemPreference:n.themeMode==="system",setSystemPreference:b,themeMode:n.themeMode,setThemeMode:x,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:y,setDarkThemePreference:v};return e.jsx(Ml.Provider,{value:S,children:t})}const KM=({children:t})=>{const{theme:r,applyTheme:s,fontSize:n,applyTypography:o,padding:a,applyPadding:c}=Me();return i.useLayoutEffect(()=>{s(),o(),c()},[r,s,n,o,a,c]),i.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&s()};return l.addEventListener("change",d),()=>{l.removeEventListener("change",d)}},[r,s]),e.jsx(e.Fragment,{children:t})};let Tm=!1;const JM=()=>{if(Tm||typeof window>"u")return;Tm=!0;let t={showReasoningTraces:Me.getState().showReasoningTraces,showTextJustificationActivity:Me.getState().showTextJustificationActivity,nativeNotificationsEnabled:Me.getState().nativeNotificationsEnabled,notificationMode:Me.getState().notificationMode,autoDeleteEnabled:Me.getState().autoDeleteEnabled,autoDeleteAfterDays:Me.getState().autoDeleteAfterDays,toolCallExpansion:Me.getState().toolCallExpansion,fontSize:Me.getState().fontSize,padding:Me.getState().padding,cornerRadius:Me.getState().cornerRadius,inputBarOffset:Me.getState().inputBarOffset,diffLayoutPreference:Me.getState().diffLayoutPreference,diffViewMode:Me.getState().diffViewMode},r=null,s=null;const n=()=>{const a=r;r=null,s=null,a&&Object.keys(a).length>0&&as(a)},o=a=>{r={...r??{},...a},!s&&(s=setTimeout(n,150))};Me.subscribe(a=>{const c={showReasoningTraces:a.showReasoningTraces,showTextJustificationActivity:a.showTextJustificationActivity,nativeNotificationsEnabled:a.nativeNotificationsEnabled,notificationMode:a.notificationMode,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays,toolCallExpansion:a.toolCallExpansion,fontSize:a.fontSize,padding:a.padding,cornerRadius:a.cornerRadius,inputBarOffset:a.inputBarOffset,diffLayoutPreference:a.diffLayoutPreference,diffViewMode:a.diffViewMode},l={};c.showReasoningTraces!==t.showReasoningTraces&&(l.showReasoningTraces=c.showReasoningTraces),c.showTextJustificationActivity!==t.showTextJustificationActivity&&(l.showTextJustificationActivity=c.showTextJustificationActivity),c.nativeNotificationsEnabled!==t.nativeNotificationsEnabled&&(l.nativeNotificationsEnabled=c.nativeNotificationsEnabled),c.notificationMode!==t.notificationMode&&(l.notificationMode=c.notificationMode),c.autoDeleteEnabled!==t.autoDeleteEnabled&&(l.autoDeleteEnabled=c.autoDeleteEnabled),c.autoDeleteAfterDays!==t.autoDeleteAfterDays&&(l.autoDeleteAfterDays=c.autoDeleteAfterDays),c.toolCallExpansion!==t.toolCallExpansion&&(l.toolCallExpansion=c.toolCallExpansion),c.fontSize!==t.fontSize&&(l.fontSize=c.fontSize),c.padding!==t.padding&&(l.padding=c.padding),c.cornerRadius!==t.cornerRadius&&(l.cornerRadius=c.cornerRadius),c.inputBarOffset!==t.inputBarOffset&&(l.inputBarOffset=c.inputBarOffset),c.diffLayoutPreference!==t.diffLayoutPreference&&(l.diffLayoutPreference=c.diffLayoutPreference),c.diffViewMode!==t.diffViewMode&&(l.diffViewMode=c.diffViewMode),t=c,Object.keys(l).length>0&&o(l)})};let Fm=!1;const Rm="openchamber-typography-base",QM=()=>{if(typeof document>"u")return;const r=`:root {
262
+ ${Object.entries(pl).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
263
+ `)}
264
+ }
265
+ `,s=document.getElementById(Rm);if(s){s.textContent=r;return}const n=document.createElement("style");n.id=Rm,n.textContent=r,document.head.appendChild(n)},YM=()=>{Fm||typeof window>"u"||(Fm=!0,QM())},XM=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await vf();await jf();JM();YM();await Nh();typeof window<"u"&&(window.debugContextTokens=()=>{const t=window.__zustand_session_store__;if(!t)return;const r=t.getState(),s=r.currentSessionId;if(!s)return;const o=(r.messages.get(s)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const c=o[o.length-1].info.tokens;c&&typeof c=="object"&&console.debug("Token breakdown:",{base:(c.input||0)+(c.output||0)+(c.reasoning||0),cache:c.cache?(c.cache.read||0)+(c.cache.write||0):0}),r.sessionContextUsage.get(s);const l=window.__zustand_config_store__;if(l){const d=l.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const Ah=document.getElementById("root");if(!Ah)throw new Error("Root element not found");ty.createRoot(Ah).render(e.jsx(Ae.StrictMode,{children:e.jsx(qM,{children:e.jsx(KM,{children:e.jsx(zM,{children:e.jsx(RM,{apis:XM})})})})}));if(typeof window<"u"){const t=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(r){console.warn("Failed to notify desktop runtime that renderer is ready:",r)}};t(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()})}const tD=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{us as D,kr as S,ms as a,tp as b,R as c,B0 as d,z0 as e,Eu as f,Er as g,H0 as h,U0 as i,tD as m,Op as p,W0 as r,Ma as t};