@openchamber/web 1.5.8 → 1.5.9

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.
@@ -1,254 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-koHRsLHN.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-DtvujDp_.js","assets/index-BsjSeUw1.js","assets/index-CDs3bEu_.css"])))=>i.map(i=>d[i]);
2
- import{t as ah,c as ih,F as lh,j as e,R as ch,T as dh,P as uh,C as mh,A as fh,a as ph,b as hh,d as gh,e as xh,f as yh,L as bh,g as wh,i as vh,I as jh,s as $t,S as Sh,k as Nh,l as rs,m as fs,p as Gs,n as qs,o as kh,_ as Ss,q as i,r as fm,u as os,v as Ch,w as pm,x as Mh,y as Dh,z as Ah,B as Eh,D as Ih,E as Ph,G as _e,H as Dc,J as Th,K as Fh,M as Ys,N as sl,O as Ac,Q as Fo,U as Gt,V as Hs,W as Tt,X as Rl,Y as hm,Z as gm,$ as Rh,a0 as Qr,a1 as Lh,a2 as Kn,a3 as er,a4 as ir,a5 as Xr,a6 as qt,a7 as Ll,a8 as Oh,a9 as wn,aa as Ol,ab as Dn,ac as vn,ad as qr,ae as rl,af as Ls,ag as xm,ah as $h,ai as _h,aj as Bh,ak as zh,al as Hh,am as Wh,an as Uh,ao as ma,ap as Vh,aq as $l,ar as Xs,as as Yr,at as Cs,au as An,av as Us,aw as Qn,ax as cs,ay as Sr,az as Gh,aA as qh,aB as ym,aC as _l,aD as jn,aE as Bl,aF as Nr,aG as bm,aH as Yn,aI as Kh,aJ as Qa,aK as pr,aL as wm,aM as Sn,aN as Nn,aO as Aa,aP as fi,aQ as Qh,aR as Zr,aS as Er,aT as sr,aU as Yh,aV as Ks,aW as Jh,aX as Ec,aY as nl,aZ as Xh,a_ as Zh,a$ as eg,b0 as tg,b1 as sg,b2 as rg,b3 as ng,b4 as og,b5 as ag,b6 as vm,b7 as pi,b8 as ig,b9 as lg,ba as cg,bb as dg,bc as ug,bd as mg,be as fg,bf as pg,bg as hg,bh as gg,bi as xg,bj as yg,bk as bg,bl as wg,bm as vg,bn as jg,bo as Sg,bp as Ir,bq as Ea,br as kr,bs as wr,bt as Ng,bu as kg,bv as Ya,bw as Cg,bx as _n,by as Mg,bz as Dg,bA as Ag,bB as Jn,bC as Eg,bD as Ig,bE as Pg,bF as Tg,bG as Fg,bH as fa,bI as Ja,bJ as Rg,bK as Lg,bL as Un,bM as $n,bN as jm,bO as Og,bP as $g,bQ as tr,bR as _g,bS as Fr,bT as Bg,bU as Sm,bV as zg,bW as Hg,bX as ol,bY as Nm,bZ as km,b_ as Wg,b$ as Ug,c0 as Vg,c1 as Xn,c2 as Gg,c3 as Ic,c4 as qg,c5 as al,c6 as ao,c7 as io,c8 as Kg,c9 as Qg,ca as Yg,cb as Xa,cc as Jg,cd as Xg,ce as Zg,cf as dn,cg as Pc,ch as ex,ci as tx,cj as sx,ck as rx,cl as nx,cm as ox,cn as Cm,co as Je,cp as Mm,cq as lo,cr as ax,cs as ix,ct as lx,cu as cx,cv as dx,cw as ux,cx as Dm,cy as Am,cz as Em,cA as Im,cB as Pm,cC as mx,cD as Tm,cE as Fm,cF as Rm,cG as Bn,cH as fx,cI as px,cJ as Lm,cK as Om,cL as zl,cM as Hl,cN as Wl,cO as hx,cP as gx,cQ as xx,cR as yx,cS as Tc,cT as $m,cU as bx,cV as wx,cW as vx,cX as jx,cY as Fc,cZ as Sx,c_ as Mo,c$ as _m,d0 as Bm,d1 as mo,d2 as Za,d3 as zm,d4 as Nx,d5 as kx,d6 as Hm,d7 as il,d8 as Cx,d9 as Mx,da as Dx,db as Ax,dc as Ex,dd as Ix}from"./vendor-.bun-koHRsLHN.js";import{c as Px,l as Tx,g as Fx,r as Rx,d as Lx,a as Ox,b as $x,e as _x,u as Bx,f as zx,h as Hx,i as Wx,j as Ux,k as Vx,m as Gx,n as qx,o as Kx}from"./index-BsjSeUw1.js";const ds=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Vt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,dr=()=>typeof window>"u"?!1:!ds()&&!Vt(),en=()=>ds()?window.opencodeDesktop??null:null,Wm=()=>{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},Um=async()=>{const t=en();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},Qx=async()=>{const t=en();if(!t)return null;try{return await t.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},Yx=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,$r=async()=>{const t=Wm();if(!t)return null;try{return await t.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},Jx=async t=>{const r=Wm();if(!r)return null;try{return await r.updateSettings(t)}catch(s){return console.warn("[desktop] Failed to update desktop settings",s),null}},Xx=async t=>{const r=en();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)}}},Zx=async t=>{const r=en();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)}}},ey=async t=>{const r=en();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)}}},ty=async()=>{const t=en();if(!t||!t.checkForUpdates)return null;try{return await t.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},sy=async t=>{const r=en();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(t),!0}catch(s){return console.warn("Failed to download update",s),!1}},ry=async()=>{const t=en();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 ah(ih(t))}const Vm=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),$s=t=>Vm()&&ds()?t.metaKey:t.ctrlKey,Zt=()=>Vm()&&ds()?"⌘":"Ctrl",Gm=(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 l=Math.max(0,n-(a.length+2));if(l<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const u=c?`${c}/${d}`:d;if(u.length>l)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,l):""}return c?`${c}…/${a}`:`…/${a}`},Ia=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function pn(t,r){if(!t)return"";const s=Ia(t);if(s==="/")return"/";const n=r?Ia(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 Rc(t,r){if(!t)return"/";const s=Ia(t);if(!s||s==="/")return"/";const n=r?Ia(r):void 0;return n&&n!=="/"&&s===n?"~":s.split("/").pop()||s||"/"}function Js(t,r){return r?t?t.toLowerCase().includes(r.toLowerCase())?!0:new lh([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function ny({delayDuration:t=0,...r}){return e.jsx(ph,{"data-slot":"tooltip-provider",delayDuration:t,...r})}function ht({delayDuration:t=0,...r}){return e.jsx(ny,{delayDuration:t,children:e.jsx(ch,{"data-slot":"tooltip",...r})})}function gt({...t}){return e.jsx(dh,{"data-slot":"tooltip-trigger",...t})}function ft({className:t,sideOffset:r=0,children:s,...n}){return e.jsx(uh,{children:e.jsxs(mh,{"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(fh,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}function es({...t}){return e.jsx(hh,{"data-slot":"dropdown-menu",...t})}function ts({...t}){return e.jsx(gh,{"data-slot":"dropdown-menu-trigger",...t})}function ss({className:t,sideOffset:r=4,...s}){return e.jsx(xh,{children:e.jsx(yh,{"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 Ct({className:t,inset:r,variant:s="default",...n}){return e.jsx(Nh,{"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 Pa({...t}){return e.jsx(wh,{"data-slot":"dropdown-menu-radio-group",...t})}function Ta({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(jh,{children:e.jsx($t,{className:"size-3"})})}),r]})}function Pr({className:t,inset:r,...s}){return e.jsx(bh,{"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(Sh,{"data-slot":"dropdown-menu-separator",className:R("bg-border -mx-1 my-0.5 h-px",t),...r})}let hi=null;const Lc=()=>{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}}},oy=()=>{if(typeof window>"u"||!window.localStorage)return Lc();const t=window.localStorage,r=Lc();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}}},ws=()=>(hi||(hi=oy()),hi),Ul={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 Oc(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Tr={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)"}}},pa={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Tr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:pa.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Tr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:pa.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Tr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:pa.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Tr.tool.inline})},je=rs()(fs(Gs((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(Ul);if(o===1){for(const[l]of a)n.style.removeProperty(Oc(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Oc(l),`${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 l=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*l).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*l).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*l).toFixed(3)),n.style.setProperty("--line-height-loose",(2*l).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(l=>l.providerID===s&&l.modelID===n)?{favoriteModels:o.favoriteModels.filter(l=>!(l.providerID===s&&l.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(l=>!(l.providerID===s&&l.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:qs(()=>ws()),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 iy(){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 ly(){return ds()?"desktop":dr()?"web":null}const $c={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},ei=rs()((t,r)=>({...$c,checkForUpdates:async()=>{const s=ly();if(s){t({checking:!0,error:null,runtimeType:s});try{let n=null;s==="desktop"?n=await ty():s==="web"&&(n=await iy()),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 sy(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 ry()}catch(o){t({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{t({available:!1,downloaded:!1,info:null})},reset:()=>{t($c)}})),cy="/api",dy=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,uy=t=>{const r=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(dy.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}},my=()=>{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},zo=t=>t.replace(/\\/g,"/"),gi=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class fy{client;baseUrl;sseAbortControllers=new Map;currentDirectory=void 0;globalSseAbortController=null;globalSseTask=null;globalSseLastEventId;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;constructor(r=cy){const n=my()||r;this.baseUrl=uy(n),this.client=kh({baseUrl:this.baseUrl})}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],c=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[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 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 l=new Image;l.onload=()=>{let c=l.width,d=l.height;(c>o||d>o)&&(c>d?(d=Math.round(d*(o/c)),c=o):(c=Math.round(c*(o/d)),d=o));const u=document.createElement("canvas");u.width=c,u.height=d;const m=u.getContext("2d");if(!m){a(r);return}m.drawImage(l,0,0,c,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)}},l.onerror=()=>a(r),l.src=r})}async convertHeicToJpeg(r){try{const s=(await Ss(async()=>{const{default:f}=await import("./vendor-.bun-koHRsLHN.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),l=new Uint8Array(a.length);for(let f=0;f<a.length;f++)l[f]=a.charCodeAt(f);const c=new Blob([l],{type:r.mime}),d=await s({blob:c,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 l=await this.normalizeFilePart(a),c={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(c)}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 l of a.files){const c=await this.normalizeFilePart(l),d={type:"file",mime:c.mime,filename:c.filename,url:c.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 l=await a.json().catch(()=>null);return!l||typeof l!="object"?{}:l}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),l=[],c=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||c.has(m)||(c.add(m),l.push(u))}return l}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 l of s)if(l.startsWith("data:"))n.push(l.slice(5).replace(/^\s/,""));else if(l.startsWith("id:")){const c=l.slice(3).trim();c&&(o=c)}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 l=a;if(typeof l.type=="string")return{directory:o&&o.length>0?o:"global",payload:l}}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 l=await fetch(s,{method:"GET",headers:a,signal:r.signal});if(!l.ok||!l.body)throw new Error(`Global SSE connect failed with status ${l.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const c=l.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await c.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 x of h){const g=this.parseSseBlock(x);if(!g)continue;g.id&&(this.globalSseLastEventId=g.id);const b=this.normalizeRoutedSsePayload(g.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),l=c=>{a&&c.directory!==a||r(c)};return this.globalSseListeners.add(l),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(c){console.warn("[OpencodeClient] Global SSE open handler error:",c)}},0)),s&&this.globalSseErrorListeners.add(s),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(l),n&&this.globalSseOpenListeners.delete(n),s&&this.globalSseErrorListeners.delete(s),this.maybeStopGlobalSse()}}subscribeToEvents(r,s,n,o,a){const l=a?.key??"default",c=a?.scope??"directory",d=this.sseAbortControllers.get(l);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(l,u);let m;if(c==="global"){let p=null;const h=g=>{if(g.directory==="global")return g.payload;const b=g.payload,y=typeof b.properties=="object"&&b.properties!==null?b.properties:{};return y.directory===g.directory?g.payload:{...b,properties:{...y,directory:g.directory}}},x=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)};return u.signal.addEventListener("abort",x,{once:!0}),p=this.subscribeToGlobalEvents(g=>{u.signal.aborted||r(h(g))},s?g=>{u.signal.aborted||s(g)}:void 0,n?()=>{u.signal.aborted||n()}:void 0),()=>{x(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const h=p;if(typeof h.type=="string")return h;const x=h.payload;if(x&&typeof x=="object"){const g=x;if(typeof g.type=="string"){if(typeof h.directory=="string"&&h.directory.length>0){const y={...(typeof g.properties=="object"&&g.properties!==null?g.properties:null)??{},directory:h.directory};return{...g,properties:y}}return g}}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 x=>{try{const g=p?{directory:p}:void 0,b={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:w=>{w instanceof Error&&w.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",w),s&&!u.signal.aborted&&s(w))},onSseEvent:w=>{if(u.signal.aborted)return;w.id&&typeof w.id=="string"&&(m=w.id);const S=w.data,C=f(S);C&&r(C)}};m&&(b.headers={...b.headers||{},"Last-Event-ID":m});const y=await this.client.event.subscribe(g,b);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const w of y.stream)if(u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(g){if(g?.name==="AbortError"||u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",g),s&&s(g);const b=Math.min(3e3*Math.pow(2,x),3e4);await new Promise(y=>setTimeout(y,b)),u.signal.aborted||await h(x+1);return}if(!u.signal.aborted){const g=Math.min(3e3*Math.pow(2,x),3e4);await new Promise(b=>setTimeout(b,g)),await h(x+1)}};try{await h(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)}})(),()=>{this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l),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=gi();if(s?.createDirectory)try{return await s.createDirectory(r)}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(l||"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=gi();if(n)try{const o=await n.listDirectory(r||"",s);return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:zo(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(),l=await fetch(`${this.baseUrl}/fs/list${a?`?${a}`:""}`);if(!l.ok){const d=await l.json().catch(()=>({})),u=typeof d.error=="string"?d.error:"Failed to list directory";throw new Error(u)}const c=await l.json();return!c||!Array.isArray(c.entries)?[]:c.entries}catch(o){throw console.error("Failed to list directory contents:",o),o}}async searchFiles(r,s){const n=gi(),o=typeof s?.directory=="string"&&s.directory.trim().length>0?s.directory.trim():this.currentDirectory,a=o?zo(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=zo(f.path),h=p.split("/").filter(Boolean).pop()||p,x=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?zo(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:x,extension:h.includes(".")?h.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const l=new URLSearchParams;o&&o.length>0&&l.set("directory",o),typeof r=="string"&&l.set("q",r),typeof s?.limit=="number"&&Number.isFinite(s.limit)&&l.set("limit",String(s.limit)),s?.includeHidden&&l.set("includeHidden","true"),s?.respectGitignore===!1&&l.set("respectGitignore","false");const c=`${this.baseUrl}/fs/search${l.toString()?`?${l.toString()}`:""}`,d=await fetch(c,{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 Um();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??{},l=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(l)}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 fy,py=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:Oe},Symbol.toStringTag,{value:"Module"})),ll=new Set;function ti(t){return ll.add(t),()=>{ll.delete(t)}}function vr(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 ll)try{const l=a(o);l instanceof Promise&&l.catch(c=>{console.error("[ConfigSync] Async listener failed:",c)})}catch(l){console.error("[ConfigSync] Listener threw:",l)}}function Do(t,r){return t.scopes.includes("all")||t.scopes.includes(r)}const Vl="Updating OpenCode configuration...";let jr=0,Jr=Vl;const cl=new Set;function Fa(){const t={isUpdating:jr>0,message:Jr};cl.forEach(r=>r(t))}function Ws(t){jr+=1,jr===1?(Jr=t||Vl,Fa()):t&&(Jr=t,Fa())}function Os(){jr!==0&&(jr-=1,jr===0&&(Jr=Vl,Fa()))}function Rr(t){Jr===t&&jr>0||(Jr=t,jr>0&&Fa())}function hy(t){return cl.add(t),t({isUpdating:jr>0,message:Jr}),()=>{cl.delete(t)}}function gy(){return{isUpdating:jr>0,message:Jr}}const br=rs()(fs(Gs((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(l=>{const c=l.queuedMessages[s]??[];return{queuedMessages:{...l.queuedMessages,[s]:[...c,a]}}})},removeFromQueue:(s,n)=>{t(o=>{const l=(o.queuedMessages[s]??[]).filter(c=>c.id!==n);if(l.length===0){const{[s]:c,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[s]:l}}})},popToInput:(s,n)=>{const l=(r().queuedMessages[s]??[]).find(c=>c.id===n);return l?(t(c=>{const u=(c.queuedMessages[s]??[]).filter(m=>m.id!==n);if(u.length===0){const{[s]:m,...f}=c.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...c.queuedMessages,[s]:u}}}),l):null},clearQueue:s=>{t(n=>{const{[s]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:s=>{t({queueModeEnabled:s}),is({queueModeEnabled:s})},getQueueForSession:s=>r().queuedMessages[s]??[]}),{name:"message-queue-store",storage:qs(()=>ws()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),qm="directoryTreeShowHidden",dl="directory-show-hidden-change",_c=()=>{if(typeof window>"u")return!0;try{const t=ws().getItem(qm);return t===null?!0:t==="true"}catch{return!0}},xy=()=>{typeof window>"u"||window.dispatchEvent(new Event(dl))},Gl=(t,r={})=>{if(!(typeof window>"u")){try{ws().setItem(qm,t?"true":"false"),xy()}catch{}r.persist!==!1&&is({directoryShowHidden:t})}},Ro=()=>{const[t,r]=i.useState(_c);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(_c())};return window.addEventListener("storage",s),window.addEventListener(dl,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(dl,s)}},[]),t},Km="filesViewShowGitignored",ul="files-view-show-gitignored-change",Bc=()=>{if(typeof window>"u")return!1;try{return ws().getItem(Km)==="true"}catch{return!1}},yy=()=>{typeof window>"u"||window.dispatchEvent(new Event(ul))},Qm=(t,r={})=>{if(!(typeof window>"u")){try{ws().setItem(Km,t?"true":"false"),yy()}catch{}r.persist!==!1&&is({filesViewShowGitignored:t})}},si=()=>{const[t,r]=i.useState(Bc);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(Bc())};return window.addEventListener("storage",s),window.addEventListener(ul,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(ul,s)}},[]),t},zc=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},by=t=>!t||typeof t!="object"?null:{showReasoningTraces:t.showReasoningTraces},wy=t=>{const r=je.getState();typeof t.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(t.showReasoningTraces)},vy=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 zc(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=by(r);return zc(s)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let Ym=null;const Hc=t=>{Ym=t},Ps=()=>Ym,ha=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"))},jy=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():"",l=typeof o.label=="string"?o.label.trim():"",c=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!l||!c||s.has(a)||(s.add(a),r.push({id:a,label:l,source:c,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},Sy=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,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=c==="/"?c:c.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||s.has(l)||n.has(d))continue;s.add(l),n.add(d);const u={id:l,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.branchPrefix=="string"&&m.branchPrefix.trim()&&(f.branchPrefix=m.branchPrefix.trim()),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},Jm=()=>{const t=je.persist;if(t&&typeof t=="object")return t},Xm=()=>Ps()?.settings??null,ga=t=>{const r=je.getState(),s=br.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"&&Qm(t.filesViewShowGitignored,{persist:!1})},Wc=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=Sy(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=jy(r.skillCatalogs);return o&&(s.skillCatalogs=o),s},Ny=async()=>{const t=Xm();if(t)try{const r=await t.load();return Wc(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 Wc(s)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},Zm=async()=>{if(typeof window>"u")return;const t=Jm(),r=s=>{ha(s);const n=()=>ga(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 $r():await Ny();s&&r(s)}catch(s){console.warn("Failed to synchronise settings:",s)}},is=async t=>{if(typeof window>"u")return;if(ds()){try{const s=await Jx(t);s&&(ha(s),ga(s))}catch(s){console.warn("Failed to update desktop settings:",s)}return}const r=Xm();if(r)try{const s=await r.save(t);s&&(ha(s),ga(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&&(ha(n),ga(n))}catch(s){console.warn("Failed to update shared settings via API:",s)}},ef=async()=>{if(typeof window>"u")return;const t=Jm();try{const r=await vy();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,Cy=40,My=60,Dy=(t,r,s,n,o)=>{const a=t.trim(),l=r.trim().toLowerCase();return`${a}::${l}::${s}::${n?"1":"0"}::${o?"1":"0"}`},ri=rs()(fs((t,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,n,o=My,a){if(!s||s.trim().length===0)return[];const l=s.trim(),c=typeof n=="string"?n.trim():"",d=!!a?.includeHidden,u=a?.respectGitignore??!0,m=Dy(l,c,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 x=Oe.searchFiles(c,{directory:l,limit:o,includeHidden:d,respectGitignore:u}).then(g=>(t(b=>{const y={...b.cache,[m]:{files:g,timestamp:Date.now()}},w=b.cacheKeys.filter(S=>S!==m);for(w.push(m);w.length>Cy;){const S=w.shift();S&&delete y[S]}return{cache:y,cacheKeys:w}}),g)).finally(()=>{t(g=>{const b={...g.inFlight};return delete b[m],{inFlight:b}})});return t(g=>({inFlight:{...g.inFlight,[m]:x}})),x},invalidateDirectory(s){if(!s||s.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${s.trim()}::`;t(a=>{const l={...a.cache},c=a.cacheKeys.filter(m=>m.startsWith(o)?(delete l[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:l,cacheKeys:c,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 Ay={};let cr=null;const lr=ws(),Uc=lr.getItem("lastDirectory"),Ey=typeof Uc=="string"&&Uc.length>0,Ho=t=>{try{ri.getState().invalidateDirectory(t)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},tf=t=>{const r=t.trim();if(!r)return r;const s=r.replace(/\\/g,"/");return s.length>1?s.replace(/\/+$/,""):s},Iy=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},xa=(t,r)=>{const s=Iy(t,r);return tf(s)},Ra=()=>{if(typeof window<"u"){const r=lr.getItem("homeDirectory")||cr||null,s=lr.getItem("lastDirectory");if(s&&!Vt())return xa(s,r);if(cr)return cr;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 cr=n,lr.setItem("homeDirectory",n),n;if(r&&!Vt())return cr=r,r}const t=typeof process<"u"&&Ay?.HOME;return t||process?.cwd?.()||"/"},Py=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},Ty=t=>(cr=t,typeof window<"u"&&lr.setItem("homeDirectory",t),is({homeDirectory:t}),t),sf=async()=>{const t=n=>{const o=Py(n);return o?Ty(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 Um(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=Ra(),s=t(r);return s||r},Fy=()=>{if(!Vt())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const r=tf(t);return r.length>0?r:null},hn=Fy()||Ra();hn&&Oe.setDirectory(hn);const Ry=!!(hn&&hn!=="/"),wt=rs()(fs((t,r)=>({currentDirectory:hn,directoryHistory:[hn],historyIndex:0,homeDirectory:hn,hasPersistedDirectory:Ey,isHomeReady:Ry,isSwitchingDirectory:!1,setDirectory:(s,n)=>{const o=cr||r().homeDirectory||lr.getItem("homeDirectory"),a=xa(s,o);hs()&&console.log("[DirectoryStore] setDirectory called with path:",a),Oe.setDirectory(a),Ho(),t(l=>{const c=[...l.directoryHistory.slice(0,l.historyIndex+1),a];return lr.setItem("lastDirectory",a),is({lastDirectory:a}),{currentDirectory:a,directoryHistory:c,historyIndex:c.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),Ho(),lr.setItem("lastDirectory",o),is({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),Ho(),lr.setItem("lastDirectory",o),is({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:s,setDirectory:n}=r(),o=cr||r().homeDirectory||Ra();if(s===o||s==="/")return;const a=s.endsWith("/")?s.slice(0,-1):s,l=a.lastIndexOf("/");if(l===-1){const c=cr||Ra();n(c)}else n(l===0?"/":a.substring(0,l))},goHome:async()=>{const s=cr||r().homeDirectory||await sf();r().setDirectory(s)},synchronizeHomeDirectory:s=>{const n=r(),o=s;cr=o;const a=n.homeDirectory!==o,l=lr.getItem("lastDirectory"),c=typeof l=="string"&&l.length>0,d=!c&&(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?xa(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(g=>xa(g,o)),p=f.some((g,b)=>g!==n.directoryHistory[b]),h=!!(m&&m!==n.currentDirectory),x={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d?(x.currentDirectory=o,x.directoryHistory=[o],x.historyIndex=0,x.isSwitchingDirectory=!1):(h||p)&&(x.currentDirectory=m,x.directoryHistory=f,x.historyIndex=Math.min(n.historyIndex,f.length-1),x.isSwitchingDirectory=!1),t(()=>x),(d||h)&&u){const g=d?o:m;Oe.setDirectory(g),Ho(),lr.setItem("lastDirectory",g),is({lastDirectory:g})}is({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&sf().then(t=>{wt.getState().synchronizeHomeDirectory(t)});const Vn=ws(),rf="projects",ml="activeProjectId",Ly=(t,r)=>{const s=t.trim();return!s.startsWith("~")||!r?s:s==="~"?r:s.startsWith("~/")||s.startsWith("~\\")?`${r}${s.slice(1)}`:s},ni=t=>{const r=t.trim();if(!r)return"";const s=Vn.getItem("homeDirectory")||wt.getState().homeDirectory||"",o=Ly(r,s).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},nf=t=>{const r=ni(t);if(!r||r==="/")return"Root";const s=r.split("/").filter(Boolean);return s[s.length-1]||r},Oy=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,of=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,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=ni(c);if(!d||s.has(l)||n.has(d))continue;s.add(l),n.add(d);const u={id:l,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.branchPrefix=="string"&&(f.branchPrefix=m.branchPrefix),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},$y=()=>{try{const t=Vn.getItem(rf);return t?of(JSON.parse(t)):[]}catch{return[]}},_y=()=>{try{const t=Vn.getItem(ml);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},ql=(t,r)=>{try{Vn.setItem(rf,JSON.stringify(t))}catch{}try{r?Vn.setItem(ml,r):Vn.removeItem(ml)}catch{}},In=(t,r)=>{ql(t,r),is({projects:t,activeProjectId:r??void 0})},By=$y(),zy=()=>{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=ni(r);if(!s)return null;const n=`vscode:${s}`,o={id:n,path:s,label:nf(s),addedAt:Date.now(),lastOpenedAt:Date.now()};return hs()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},ar=zy(),Kl=ar?.projects??By,af=ar?.activeProjectId??_y()??Kl[0]?.id??null;ar&&ql(Kl,af);const Wt=rs()(fs((t,r)=>({projects:Kl,activeProjectId:af,validateProjectPath:s=>{if(typeof s!="string"||s.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=ni(s);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(s,n)=>{if(ar)return null;const{validateProjectPath:o}=r(),a=o(s);if(!a.ok||!a.normalizedPath)return null;const l=a.normalizedPath,c=r().projects.find(x=>x.path===l);if(c)return r().setActiveProject(c.id),c;const d=Date.now(),u=n?.label?.trim()||nf(l),m=n?.id?.trim(),p={id:m&&!r().projects.some(x=>x.id===m)?m:Oy(),path:l,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(ar)return;const n=r(),o=n.projects.filter(l=>l.id!==s);let a=n.activeProjectId;if(n.activeProjectId===s&&(a=o[0]?.id??null),t({projects:o,activeProjectId:a}),In(o,a),a){const l=o.find(c=>c.id===a);l&&(Oe.setDirectory(l.path),wt.getState().setDirectory(l.path,{showOverlay:!1}))}else wt.getState().goHome()},setActiveProject:s=>{if(ar)return;const{projects:n,activeProjectId:o}=r();if(o===s)return;const a=n.find(d=>d.id===s);if(!a)return;const l=Date.now(),c=n.map(d=>d.id===s?{...d,lastOpenedAt:l}:d);t({projects:c,activeProjectId:s}),In(c,s),Oe.setDirectory(a.path),wt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:s=>{if(ar)return;const{projects:n,activeProjectId:o}=r();if(o===s||!n.find(d=>d.id===s))return;const l=Date.now(),c=n.map(d=>d.id===s?{...d,lastOpenedAt:l}:d);t({projects:c,activeProjectId:s}),In(c,s)},renameProject:(s,n)=>{if(ar)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:l}=r(),c=a.map(d=>d.id===s?{...d,label:o}:d);t({projects:c}),In(c,l)},reorderProjects:(s,n)=>{if(ar)return;const{projects:o,activeProjectId:a}=r();if(s<0||s>=o.length||n<0||n>=o.length||s===n)return;const l=[...o],[c]=l.splice(s,1);l.splice(n,0,c),t({projects:l}),In(l,a)},synchronizeFromSettings:s=>{if(ar)return;const n=of(s.projects??[]),o=typeof s.activeProjectId=="string"&&s.activeProjectId.trim()?s.activeProjectId.trim():null,a=r(),l=JSON.stringify(a.projects)!==JSON.stringify(n),c=a.activeProjectId!==o;if(!(!l&&!c)&&(t({projects:n,activeProjectId:o}),ql(n,o),o)){const d=n.find(u=>u.id===o);d&&(Oe.setDirectory(d.path),wt.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(ar)return;const{projects:o,activeProjectId:a}=r(),l=o.find(u=>u.id===s);if(!l)return;const c={...l.worktreeDefaults};n.branchPrefix!==void 0&&(n.branchPrefix.trim()?c.branchPrefix=n.branchPrefix.trim():delete c.branchPrefix),n.baseBranch!==void 0&&(n.baseBranch.trim()?c.baseBranch=n.baseBranch.trim():delete c.baseBranch),n.autoCreateWorktree!==void 0&&(c.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===s?{...u,worktreeDefaults:Object.keys(c).length>0?c:void 0}:u);t({projects:d}),In(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",t=>{const r=t.detail;r&&typeof r=="object"&&Wt.getState().synchronizeFromSettings(r)});const Hy=new Set(["init","review"]),zn=t=>Hy.has(t.name),wo="useCommandsStore",fl=t=>new Promise(r=>setTimeout(r,t)),Wo=()=>{try{const r=Wt.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},Wy=2e4,Vc=300,Gc=4,Uy=800,Vy=200,Gy=2e3,tn=rs()(fs(Gs((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=Wo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await Oe.withDirectory(a,()=>Oe.listCommandsWithDetails()),d=await Promise.all(c.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${l}`,{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 l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load commands:",n),t({commands:s,isLoading:!1}),!1},createCommand:async s=>{Ws("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=Wo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(s.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.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 xi({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&vr("commands",{source:wo}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Os()}},updateCommand:async(s,n)=>{Ws("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 l=Wo(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(s)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},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 xi({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&vr("commands",{source:wo}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Os()}},deleteCommand:async s=>{Ws("Deleting command configuration…");let n=!1;try{const o=Wo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),c?.requiresReload??!0)return n=!0,await xi({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&vr("commands",{source:wo}),r().selectedCommandName===s&&t({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||Os()}},getCommandByName:s=>{const{commands:n}=r();return n.find(o=>o.name===s)}}),{name:"commands-store",storage:qs(()=>ws()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=tn);async function qy(t){const r=typeof t=="number"&&t>0?Math.min(t,Vc):0;r>0&&await fl(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<Wy;){n+=1,Rr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Oe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-s,l=n<=Gc&&a<1200?Vc:Math.min(Uy+Math.max(0,n-Gc)*Vy,Gy);await fl(l)}throw o||new Error("OpenCode did not become ready in time")}async function xi(t={}){const{message:r,delayMs:s}=t;try{Rr(r||"Refreshing commands…")}catch{}try{await qy(s),Rr("Refreshing commands…"),await tn.getState().loadCommands(),vr("commands",{source:wo})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Rr("OpenCode refresh failed. Please retry refreshing configuration manually."),await fl(1500)}finally{Os()}}let qc=null;qc||(qc=ti(t=>{if(t.source!==wo&&Do(t,"commands")){const{loadCommands:r}=tn.getState();r()}}));const Hr=()=>{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},ya="useSkillsStore",ur=rs()(fs(Gs((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=Hr(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills${l}`);if(!c.ok)throw new Error(`Failed to list skills: ${c.status}`);const m=((await c.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 l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load skills:",n),t({skills:s,isLoading:!1}),!1},getSkillDetail:async s=>{try{const n=Hr(),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=>{Ws("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=Hr(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(s.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),c=await l.json().catch(()=>null);if(!l.ok){const u=c?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&vr("skills",{source:ya}),d}catch{return!1}finally{Os()}},updateSkill:async(s,n)=>{Ws("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=Hr(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(s)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&vr("skills",{source:ya}),u}catch{return!1}finally{Os()}},deleteSkill:async s=>{Ws("Deleting skill...");try{const n=Hr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(s)}${o}`,{method:"DELETE"}),l=await a.json().catch(()=>null);if(!a.ok){const d=l?.error||"Failed to delete skill";throw new Error(d)}const c=await r().loadSkills();return c&&vr("skills",{source:ya}),r().selectedSkillName===s&&t({selectedSkillName:null}),c}catch{return!1}finally{Os()}},getSkillByName:s=>{const{skills:n}=r();return n.find(o=>o.name===s)},readSupportingFile:async(s,n)=>{try{const o=Hr(),a=o?`&directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return l.ok?(await l.json()).content??null:null}catch{return null}},writeSupportingFile:async(s,n,o)=>{try{const a=Hr(),l=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}${l}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(s,n)=>{try{const o=Hr(),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:qs(()=>ws()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=ur);let Kc=null;Kc||(Kc=ti(t=>{if(t.source!==ya&&Do(t,"skills")){const{loadSkills:r}=ur.getState();r()}}));const Qc=[{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"}],Uo=()=>{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},Lo=rs()(fs((t,r)=>({sources:Qc,itemsBySource:{},selectedSourceId:Qc[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":"",l=new AbortController,c=window.setTimeout(()=>l.abort(),3e3);try{const d=await fetch(`/api/config/skills/catalog${a}`,{method:"GET",headers:{Accept:"application/json"},signal:l.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||{},x=s?.refresh?{}:r().clawdhubHasMoreBySource||{},g=r().selectedSourceId,b=g&&m.some(y=>y.id===g)?g:m[0]?.id??null;return t({sources:m,itemsBySource:f,pageInfoBySource:p,loadedSourceIds:h,clawdhubHasMoreBySource:x,selectedSourceId:b}),!0}finally{window.clearTimeout(c)}}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=Uo(),a=n?.refresh?"&refresh=true":"",l=o?`?directory=${encodeURIComponent(o)}&sourceId=${encodeURIComponent(s)}${a}`:`?sourceId=${encodeURIComponent(s)}${a}`,c=await fetch(`/api/config/skills/catalog/source${l}`,{method:"GET",headers:{Accept:"application/json"}}),d=await c.json().catch(()=>null),u=Array.isArray(d?.items);if(!c.ok||!d?.ok&&!u){const p=await fetch(`/api/config/skills/catalog${l}`,{method:"GET",headers:{Accept:"application/json"}}),h=await p.json().catch(()=>null),x=h?.itemsBySource?.[s];return p.ok&&h?.ok&&Array.isArray(x)?(t(g=>({itemsBySource:{...g.itemsBySource,[s]:x},pageInfoBySource:{...g.pageInfoBySource,[s]:{nextCursor:null}},loadedSourceIds:{...g.loadedSourceIds,[s]:!0},clawdhubHasMoreBySource:{...g.clawdhubHasMoreBySource,[s]:!1}})),!0):(t({lastCatalogError:d?.error||{kind:"unknown",message:`Failed to load source (${c.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=Uo(),l=[`sourceId=${encodeURIComponent(s)}`];a&&l.push(`directory=${encodeURIComponent(a)}`),o&&l.push(`cursor=${encodeURIComponent(o)}`);const c=`?${l.join("&")}`,d=await fetch(`/api/config/skills/catalog/source${c}`,{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 x=0;for(const b of p){const y=`${b.sourceId}:${b.skillDir}`;h.has(y)||(x+=1),h.set(y,b)}const g=p.length===0||x===0;return t(b=>({itemsBySource:{...b.itemsBySource,[s]:Array.from(h.values())},pageInfoBySource:{...b.pageInfoBySource,[s]:{nextCursor:m}},clawdhubHasMoreBySource:{...b.clawdhubHasMoreBySource,[s]:!g}})),!0}catch{return!1}finally{t({isLoadingMore:!1})}},scanRepo:async s=>{t({isScanning:!0,lastScanError:null,scanResults:null});try{const n=Uo(),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)}),l=await a.json().catch(()=>null);if(!a.ok||!l){const c=l?.error||{kind:"unknown",message:"Failed to scan repository"};return t({lastScanError:c}),{ok:!1,error:c}}return l.ok?(t({scanResults:l.items||[]}),l):(t({lastScanError:l.error||{kind:"unknown",message:"Failed to scan repository"}}),l)}finally{t({isScanning:!1})}},installSkills:async s=>{t({isInstalling:!0,lastInstallError:null});try{const n=Uo(),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)}),l=await a.json().catch(()=>null);if(!l){const c={kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:c}),{ok:!1,error:c}}if(!a.ok||!l.ok){const c=l.error||{kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:c}),{ok:!1,error:c}}return ur.getState().loadSkills(),l}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"})),Ky=()=>{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},Vo=()=>{try{const r=Wt.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},un=t=>{const r=t;return r.native===!0||r.builtIn===!0},lf=t=>{const r=t;return r.hidden===!0||r.options?.hidden===!0},cf=t=>t.filter(r=>!lf(r)),ba="useAgentsStore",La=t=>new Promise(r=>setTimeout(r,t)),Qy=2e4,Yc=300,Jc=4,Yy=800,Jy=200,Xy=2e3,sn=rs()(fs(Gs((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=Vo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await Oe.withDirectory(o,()=>Oe.listAgents()),c=await Promise.all(l.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(c)?t({agents:c,isLoading:!1}):t({isLoading:!1}),!0}catch{}return t({isLoading:!1}),!1},createAgent:async s=>{Ws("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=Vo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(s.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await vo({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&vr("agents",{source:ba}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||Os()}},updateAgent:async(s,n)=>{Ws("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 l=Vo(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(s)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},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 vo({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&vr("agents",{source:ba}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||Os()}},deleteAgent:async s=>{Ws("Deleting agent configuration…");let n=!1;try{const o=Vo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete agent";throw new Error(m)}if(c?.requiresReload??!0)return n=!0,await vo({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&vr("agents",{source:ba}),r().selectedAgentName===s&&t({selectedAgentName:null}),u}catch{return!1}finally{n||Os()}},getAgentByName:s=>{const{agents:n}=r();return n.find(o=>o.name===s)},getVisibleAgents:()=>{const{agents:s}=r();return cf(s)}}),{name:"agents-store",storage:qs(()=>ws()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=sn);async function Zy(t){const r=typeof t=="number"&&t>0?Math.min(t,Yc):0;r>0&&await La(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<Qy;){n+=1,Rr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Oe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-s,l=n<=Jc&&a<1200?Yc:Math.min(Yy+Math.max(0,n-Jc)*Jy,Xy);await La(l)}throw o||new Error("OpenCode did not become ready in time")}const eb=t=>{if(!t||t.length===0)return["all"];const r=Array.from(new Set(t));return r.includes("all")?["all"]:r};async function tb(t={}){const{message:r,delayMs:s}=t,n=eb(t.scopes),o=t.mode??(n.includes("all")?"projects":"active");try{Rr(r||"Refreshing configuration…")}catch{}try{await Zy(s);const a=et.getState(),l=sn.getState(),c=tn.getState(),d=ur.getState(),u=Lo.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"),x=n.includes("all")||n.includes("skills"),g=Ky(),b=o==="projects"?Wt.getState().projects:[],y=Array.from(new Set([...g?[g]:[],...b.map(C=>C.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&et.setState({directoryScoped:{}});const w=[];for(const C of y)m&&w.push(a.loadProviders({directory:C}).then(()=>{})),f&&w.push(a.loadAgents({directory:C}).then(()=>{}));const S=[];p&&S.push(l.loadAgents().then(()=>{})),h&&S.push(c.loadCommands().then(()=>{})),x&&(S.push(d.loadSkills().then(()=>{})),S.push(u.loadCatalog().then(()=>{}))),Rr("Refreshing configuration…"),await Promise.all([...w,...S])}catch{Rr("OpenCode refresh failed. Please retry."),await La(1500)}finally{Os()}}async function vo(t){await tb(t)}async function jo(t){Ws(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 vo({...n,message:s.message,delayMs:s.reloadDelayMs}):await vo(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),Rr("Failed to reload configuration. Please try again."),await La(2e3),Os(),r}}let Xc=null;Xc||(Xc=ti(t=>{if(t.source!==ba&&Do(t,"agents")){const{loadAgents:r}=sn.getState();r()}}));const sb="https://models.dev/api.json",rb="/api/openchamber/models-metadata",Zc="opencode",ed="big-pickle",nb=async()=>{try{if(ds()){const c=await $r();return{defaultModel:c?.defaultModel,defaultVariant:c?.defaultVariant,defaultAgent:c?.defaultAgent,autoCreateWorktree:c?.autoCreateWorktree,gitmojiEnabled:c?.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():"",l=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:l}}catch{return{}}},Go=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]}},ob=t=>t?.toLowerCase?.()??"",ab=t=>t==="primary"||t==="all"||t===void 0||t===null,Ao=t=>typeof t=="object"&&t!==null,Oa=t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),ib=t=>{if(!Ao(t))return!1;const r=t;if(r.modalities){const{input:s,output:n}=r.modalities;if(s&&!Oa(s)||n&&!Oa(n))return!1}return!0},lb=t=>{if(!Ao(t))return!1;const r=t;return r.models===void 0||Ao(r.models)},df=(t,r)=>{const s=ob(t);return!s||!r?"":`${s}/${r}`},cb=t=>{const r=new Map;if(!Ao(t))return r;for(const[s,n]of Object.entries(t)){if(!lb(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:s,a=n.models;if(!(!a||!Ao(a)))for(const[l,c]of Object.entries(a)){if(!ib(c))continue;const d=typeof l=="string"&&l.length>0?l:c.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof c.id=="string"&&c.id.length>0?c.id:d,providerId:o,name:typeof c.name=="string"?c.name:void 0,tool_call:typeof c.tool_call=="boolean"?c.tool_call:void 0,reasoning:typeof c.reasoning=="boolean"?c.reasoning:void 0,temperature:typeof c.temperature=="boolean"?c.temperature:void 0,attachment:typeof c.attachment=="boolean"?c.attachment:void 0,modalities:c.modalities?{input:Oa(c.modalities.input)?c.modalities.input:void 0,output:Oa(c.modalities.output)?c.modalities.output:void 0}:void 0,cost:c.cost,limit:c.limit,knowledge:typeof c.knowledge=="string"?c.knowledge:void 0,release_date:typeof c.release_date=="string"?c.release_date:void 0,last_updated:typeof c.last_updated=="string"?c.last_updated:void 0},m=df(o,d);m&&r.set(m,u)}}return r},db=async()=>{if(typeof fetch!="function")return new Map;const t=[rb,sb];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 l=await fetch(r,a);if(!l.ok)throw new Error(`Metadata request to ${r} returned status ${l.status}`);const c=await l.json();return cb(c)}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 yi=null;const ub=(t,r)=>{t().size>0||yi||(yi=db().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{yi=null}))},mb=t=>new Promise(r=>setTimeout(r,t)),Ql="__global__",Gn=t=>{const r=typeof t=="string"?t.trim():"";return r.length>0?r:Ql},Pn=t=>t===Ql?null:t,fb=()=>{if(typeof window>"u")return Ql;const t=Oe.getDirectory()??wt.getState().currentDirectory;return Gn(t)},et=rs()(fs(Gs((t,r)=>({activeDirectoryKey:fb(),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=Gn(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:Pn(n)}),await r().loadAgents({directory:Pn(n)}))},loadProviders:async s=>{const n=Gn(s?.directory??Pn(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),l=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let c=null;for(let d=0;d<3;d++)try{ub(()=>r().modelsMetadata,h=>t({modelsMetadata:h}));const u=await Oe.withDirectory(Pn(n),()=>Oe.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(h=>{const x=h.models??{},g=Object.keys(x).map(b=>x[b]);return{...h,models:g}});t(h=>{const g={...h.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:p,defaultProviders:f},b={directoryScoped:{...h.directoryScoped,[n]:g}};if(h.activeDirectoryKey===n&&(b.providers=p,b.defaultProviders=f,!h.currentProviderId&&!h.currentModelId&&h.settingsDefaultModel)){const y=Go(h.settingsDefaultModel);if(y){const w=p.find(S=>S.id===y.providerId);if(w?.models.some(S=>S.id===y.modelId)){const S=w.models.find(v=>v.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,g.currentProviderId=y.providerId,g.currentModelId=y.modelId,g.currentVariant=C,g.selectedProviderId=y.providerId}}}return b});return}catch(u){c=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",c),t(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:l},f={directoryScoped:{...d.directoryScoped,[n]:m}};if(d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=l,!d.currentProviderId&&!d.currentModelId&&d.settingsDefaultModel)){const p=Go(d.settingsDefaultModel);if(p){const h=a.find(x=>x.id===p.providerId);if(h?.models.some(x=>x.id===p.modelId)){const x=h.models.find(b=>b.id===p.modelId),g=d.settingsDefaultVariant&&x?.variants?.[d.settingsDefaultVariant]?d.settingsDefaultVariant:void 0;f.currentProviderId=p.providerId,f.currentModelId=p.modelId,f.currentVariant=g,f.selectedProviderId=p.providerId,m.currentProviderId=p.providerId,m.currentModelId=p.modelId,m.currentVariant=g,m.selectedProviderId=p.providerId}}}return f})},setProvider:s=>{const{providers:n}=r(),o=n.find(c=>c.id===s);if(!o)return;const l=o.models[0]?.id||"";t(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentVariant:c.currentVariant,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentProviderId:s,currentModelId:l,selectedProviderId:s};return{currentProviderId:s,currentModelId:l,selectedProviderId:s,directoryScoped:{...c.directoryScoped,[d]:m}}})},setModel:s=>{t(n=>{const o=n.activeDirectoryKey,l={...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]:l}}})},setCurrentVariant:s=>{t(n=>{if(n.currentVariant===s)return n;const o=n.activeDirectoryKey,l={...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]:l}}})},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,l={...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]:l}}})},saveAgentModelSelection:(s,n,o)=>{t(a=>{const l=a.activeDirectoryKey,c={...a.agentModelSelections,[s]:{providerId:n,modelId:o}},u={...a.directoryScoped[l]??{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:c};return{agentModelSelections:c,directoryScoped:{...a.directoryScoped,[l]:u}}})},getAgentModelSelection:s=>{const{agentModelSelections:n}=r();return n[s]||null},loadAgents:async s=>{const n=Gn(s?.directory??Pn(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let l=null;for(let c=0;c<3;c++)try{const[d,u]=await Promise.all([Oe.withDirectory(Pn(n),()=>Oe.listAgents()),nb()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(t(v=>{const M={...v.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:{...v.directoryScoped,[n]:M}};return v.activeDirectoryKey===n&&(k.agents=m),k}),m.length===0)return t(v=>{const M={...v.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},k={directoryScoped:{...v.directoryScoped,[n]:M}};return v.activeDirectoryKey===n&&(k.currentAgentName=void 0),k}),!0;const p=(v,j)=>{const M=f.find(k=>k.id===v);return M?M.models.some(k=>k.id===j):!1},h=m.filter(v=>ab(v.mode));let b=h.find(v=>v.name==="build")||h[0]||m[0];const y={};if(u.defaultAgent){const v=m.find(j=>j.name===u.defaultAgent);v?b=v:y.defaultAgent=""}let w,S,C;if(u.defaultModel){const v=Go(u.defaultModel);if(v&&p(v.providerId,v.modelId)){if(w=v.providerId,S=v.modelId,u.defaultVariant){const k=f.find(D=>D.id===v.providerId)?.models.find(D=>D.id===v.modelId)?.variants;k&&Object.prototype.hasOwnProperty.call(k,u.defaultVariant)?C=u.defaultVariant:y.defaultVariant=""}}else y.defaultModel=""}if(!w&&b?.model?.providerID&&b?.model?.modelID){const{providerID:v,modelID:j}=b.model;p(v,j)&&(w=v,S=j)}if(!w)if(p(Zc,ed))w=Zc,S=ed;else{const v=f[0],j=v?.models[0];v&&j&&(w=v.id,S=j.id)}return t(v=>{const j=v.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},M={...j,providers:f,agents:m,currentAgentName:b.name,currentProviderId:w??j.currentProviderId,currentModelId:S??j.currentModelId,currentVariant:C},k={directoryScoped:{...v.directoryScoped,[n]:M}};return v.activeDirectoryKey===n&&(k.currentAgentName=b.name,w&&S&&(k.currentProviderId=w,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}),is(y).catch(()=>{})),!0}catch(d){l=d;const u=200*(c+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",l),t(c=>{const d=c.activeDirectoryKey===n?c.providers:c.directoryScoped[n]?.providers??[],m={...c.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...c.directoryScoped,[n]:m}};return c.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:s=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:l}=r();if(t(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentAgentName:s};return{currentAgentName:s,directoryScoped:{...c.directoryScoped,[d]:m}}}),s&&typeof window<"u"){const c=window.__zustand_session_store__;if(c){const d=c.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&c.setState(h=>{const x=new Map(h.currentAgentContext);return x.set(u,s),{currentAgentContext:x}}),u&&m(u)&&(p(u,s)||f(u,n))}}if(s&&typeof window<"u"){const c=window.__zustand_session_store__;if(c?.getState){const{currentSessionId:m,getAgentModelForSession:f}=c.getState();if(m&&f(m,s))return}if(a){const m=Go(a);if(m&&o.find(p=>p.id===m.providerId)?.models.some(p=>p.id===m.modelId)){t(p=>{const h=p.activeDirectoryKey,x=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 g;if(l){const S=o.find(C=>C.id===m.providerId)?.models.find(C=>C.id===m.modelId)?.variants;S&&Object.prototype.hasOwnProperty.call(S,l)&&(g=l)}const b={...x,currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:g};return{currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:g,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(x=>x.id===m)?.models.find(x=>x.id===f)&&t(x=>{const g=x.activeDirectoryKey,y={...x.directoryScoped[g]??{providers:x.providers,agents:x.agents,currentProviderId:x.currentProviderId,currentModelId:x.currentModelId,currentAgentName:x.currentAgentName,selectedProviderId:x.selectedProviderId,agentModelSelections:x.agentModelSelections,defaultProviders:x.defaultProviders},currentProviderId:m,currentModelId:f,selectedProviderId:m};return{currentProviderId:m,currentModelId:f,selectedProviderId:m,directoryScoped:{...x.directoryScoped,[g]: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 l=400*n;await mb(l)}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=df(s,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:s}=r();return cf(s)}}),{name:"config-store",storage:qs(()=>ws()),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__=et);let td=null;td||(td=ti(async t=>{const r=[];if(Do(t,"agents")){const{loadAgents:s}=et.getState();r.push(s().then(()=>{}))}if(Do(t,"providers")){const{loadProviders:s}=et.getState();r.push(s())}r.length>0&&await Promise.all(r)}));let sd=null;typeof window<"u"&&!sd&&(sd=wt.subscribe((t,r)=>{const s=Gn(t.currentDirectory),n=Gn(r.currentDirectory);s!==n&&et.getState().activateDirectory(t.currentDirectory)}));const mn={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,HISTORICAL_MESSAGES:90,FETCH_BUFFER:20,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},pl=180,$a=()=>{const t=je.getState?.();return t?{...mn,HISTORICAL_MESSAGES:t.memoryLimitHistorical??mn.HISTORICAL_MESSAGES,VIEWPORT_MESSAGES:t.memoryLimitViewport??mn.VIEWPORT_MESSAGES}:mn},hl=()=>{const t=je.getState?.();return t?t.memoryLimitActiveSession??pl:pl},Ar=mn,Ts=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function _r(t){const r=Ts();return r?r.checkIsGitRepository(t):Px(t)}async function pb(t){const r=Ts();return r?r.getGitStatus(t):Fx(t)}async function oi(t){const r=Ts();return r?r.getGitBranches(t):Gx(t)}async function hb(t,r){const s=Ts();return s?s.deleteGitBranch(t,r):Lx(t,r)}async function gb(t,r){const s=Ts();return s?s.deleteRemoteBranch(t,r):Ox(t,r)}async function xb(t,r){const s=Ts();return s?.generatePullRequestDescription?s.generatePullRequestDescription(t,r):Kx(t,r)}async function uf(t){const r=Ts();return r?r.listGitWorktrees(t):Tx(t)}async function yb(t,r){const s=Ts();return s?s.addGitWorktree(t,r):$x(t,r)}async function mf(t,r){const s=Ts();return s?s.removeGitWorktree(t,r):Rx(t,r)}async function bb(t){const r=Ts();return r?r.ensureOpenChamberIgnored(t):Vx(t)}async function wb(t,r={}){const s=Ts();return s?s.gitFetch(t,r):qx(t,r)}async function vb(){const t=Ts();return t?t.getGitIdentities():Ux()}async function jb(t){const r=Ts();return r?r.createGitIdentity(t):zx(t)}async function Sb(t,r){const s=Ts();return s?s.updateGitIdentity(t,r):Bx(t,r)}async function Nb(t){const r=Ts();return r?r.deleteGitIdentity(t):_x(t)}async function kb(){const t=Ts();return t?.discoverGitCredentials?t.discoverGitCredentials():Hx()}async function Cb(){const t=Ts();return t?.getGlobalGitIdentity?t.getGlobalGitIdentity():Wx()}const Mb="openchamber.json",ff=".openchamber";function pf(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Db=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},gl=(t,r)=>{const s=Db(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},hf=t=>gl(gl(t,ff),Mb);async function gf(t){const r=hf(t);try{const s=pf();if(s?.readFile)try{const l=await s.readFile(r);if(!l.content.trim())return null;const c=JSON.parse(l.content);return!c||typeof c!="object"?null:c}catch{return null}const n=await fetch(`${yf()}/fs/read?path=${encodeURIComponent(r)}`);if(!n.ok)return n.status===404,null;const o=await n.text();if(!o.trim())return null;const a=JSON.parse(o);return!a||typeof a!="object"?null:a}catch{return null}}async function Ab(t,r){const s=hf(t),n=gl(t,ff);try{await Oe.createDirectory(n);const o=pf();if(o?.writeFile)try{return(await o.writeFile(s,JSON.stringify(r,null,2))).success}catch(l){return console.error("Failed to write openchamber config via runtime API:",l),!1}return(await fetch(`${yf()}/fs/write`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s,content:JSON.stringify(r,null,2)})})).ok}catch(o){return console.error("Failed to write openchamber config:",o),!1}}async function Eb(t,r){const n={...await gf(t)||{},...r};return Ab(t,n)}async function En(t){return(await gf(t))?.["setup-worktree"]??[]}async function xf(t,r){const s=r.filter(n=>n.trim().length>0);return Eb(t,{"setup-worktree":s})}function Ib(t,r){return t.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function yf(){const t="/api";return t.startsWith("/"),t}const Pb=".openchamber",rd="/api";function Tb(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Or=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},nd=(t,r)=>{const s=Or(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},bf=t=>t?t.startsWith("refs/heads/")?t.substring(11):t.startsWith("heads/")?t.substring(6):t.startsWith("refs/")?t.substring(5):t:"",Fb=async t=>{try{await Oe.createDirectory(t)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function Rb(t,r){const s=Or(t),n=nd(s,Pb);return await Fb(n),nd(n,r)}async function ai(t){const{projectDirectory:r,worktreeSlug:s,branch:n,createBranch:o,startPoint:a}=t,l=Or(r),c=await Rb(l,s),d={path:c,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await yb(l,d),{path:c,branch:n,label:bf(n),projectDirectory:l,relativePath:c.startsWith(`${l}/`)?c.slice(l.length+1):c}}async function Yl(t){const{projectDirectory:r,path:s,force:n}=t,o=Or(r);await mf(o,{path:s,force:n})}async function wf(t){const{projectDirectory:r,path:s,branch:n,force:o,deleteRemote:a,remote:l}=t,c=Or(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await mf(c,{path:s,force:o}),d&&(await hb(c,{branch:d,force:!0}),a))try{await gb(c,{branch:d,remote:l})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Zn(t){const r=Or(t);return uf(r)}async function Oo(t){const r=Or(t),s=await pb(r);return{isDirty:!s.isClean,ahead:s.ahead,behind:s.behind,upstream:s.tracking}}function eo(t,r){const s=Or(t),n=Or(r.worktree);return{path:n,branch:r.branch??"",label:bf(r.branch??""),projectDirectory:s,relativePath:n.startsWith(`${s}/`)?n.slice(s.length+1):n}}async function ii(t,r,s){const n=s??await En(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>Ib(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:t,projectDirectory:r,commands:o});try{const a=Tb();if(a?.execCommands){console.log("[worktreeService] Using runtime API for exec");try{const d=await a.execCommands(o,t);return console.log("[worktreeService] Runtime exec result:",d),d}catch(d){return console.error("[worktreeService] Runtime exec error:",d),{success:!1,results:o.map(u=>({command:u,success:!1,error:d instanceof Error?d.message:"Unknown error"}))}}}console.log("[worktreeService] Using web API for exec");const l=await fetch(`${rd}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:o,cwd:t,background:!0})}),c=await l.json().catch(()=>null);if(l.status===202&&c&&typeof c.jobId=="string"){const d=c.jobId,u=800,m=Math.max(5*6e4,o.length*6e4),f=Date.now();for(;Date.now()-f<m;){await new Promise(g=>setTimeout(g,u));const p=await fetch(`${rd}/fs/exec/${d}`,{method:"GET"}),h=await p.json().catch(()=>null);if(!p.ok)return{success:!1,results:o.map(g=>({command:g,success:!1,error:h&&h.error||"Failed to poll exec job"}))};if(h?.status==="done"){const g=Array.isArray(h?.results)?h.results:[];return{success:h?.success===!0,results:g}}}return{success:!1,results:o.map(p=>({command:p,success:!1,error:"Setup commands timed out"}))}}if(!l.ok){const d=c&&c.error||"Request failed";return console.error("[worktreeService] Web exec failed:",c),{success:!1,results:o.map(u=>({command:u,success:!1,error:d}))}}return console.log("[worktreeService] Web exec result:",c),c}catch(a){return console.error("[worktreeService] Exec exception:",a),{success:!1,results:o.map(l=>({command:l,success:!1,error:a instanceof Error?a.message:"Unknown error"}))}}}const vf=ws(),jf="oc.sessionSelectionByDirectory",bi=".openchamber",Lb=()=>{try{const t=vf.getItem(jf);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 wa=null;const Jl=()=>(wa||(wa=Lb()),wa),Sf=t=>{wa=t;try{vf.setItem(jf,JSON.stringify(t))}catch{}},Nf=t=>{if(!t)return null;const s=Jl()[t];return typeof s=="string"?s:null},Mr=(t,r)=>{if(!t)return;const s={...Jl()};r?s[t]=r:delete s[t],Sf(s)},Ob=(t,r)=>{if(!t)return;const s=Nf(t);if(!s)return;if(!new Set(r).has(s)){const o={...Jl()};delete o[t],Sf(o)}},od=async(t,r)=>{const s=t.status??await Oo(t.path).catch(()=>{});await wf({projectDirectory:t.projectDirectory,path:t.path,branch:t.branch,force:!!s?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},Pt=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},ad=()=>{if(typeof window>"u")return null;const t=window.__VSCODE_CONFIG__,r=typeof t?.workspaceFolder=="string"?t.workspaceFolder:null;return Pt(r)},$b=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,qo=(...t)=>{hs()&&$b()&&console.log("[OpenChamber][VSCode][sessions]",...t)},Wr=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())},rr=t=>{const r=new Map;t.forEach(s=>{const n=Pt(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,Wr(n));return r},Tn=(t,r)=>{const s=t.find(n=>n.id===r);return s?Pt(s.directory??null):null},_b=async(t,r,s)=>{const n=Pt(r);if(!n||t.length===0)return null;const o=t.map(u=>({id:u.id,directory:Pt(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Zn(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 l=new Map;a.forEach(u=>{const m=eo(n,u),f=Pt(m.path)??m.path;f!==n&&l.set(f,m)});let c=!1;const d=new Map(s);return o.forEach(({id:u,directory:m})=>{const f=l.get(m);if(!f){d.delete(u)&&(c=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),c=!0)}),c?d:null},bt=rs()(fs(Gs((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=wt.getState(),n=Wt.getState(),o=Oe.getApiClient(),a=ad(),l=!!a;qo("loadSessions:start",{workspace:a,currentDirectory:s.currentDirectory,clientDirectory:Oe.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const c=new Map,d=async F=>{const $=Pt(F)??F,Q=$,ie=c.get(Q);if(ie)return ie;try{const K=await o.path.get({directory:F}),V=Pt(K.data?.directory??null)??$;return c.set(Q,V),V}catch{return c.set(Q,$),$}},u=(F,$,Q)=>{const ie=Pt($);if(!ie)return F;const ee=Q?.includeDescendants===!0?`${ie}/`:null,V=Q?.includeMissingDirectory===!0;return F.filter(ae=>{const G=Pt(ae.directory??null);return G?!!(G===ie||ee&&G.startsWith(ee)):V})},m=(F,$,Q)=>{const ie=Pt($);if(!ie)return F;const K=Pt(Q??null);if(!K||K===ie)return F.map(ae=>Pt(ae.directory??null)?ae:{...ae,directory:ie});const ee=K==="/"?"/":`${K}/`,V=ie==="/"?"/":`${ie}/`;return F.map(ae=>{const G=Pt(ae.directory??null);if(!G)return{...ae,directory:ie};if(G===K)return{...ae,directory:ie};if(ee!=="/"&&G.startsWith(ee)){const q=G.slice(ee.length);return{...ae,directory:`${V}${q}`}}return ae})},f=async F=>{const $=Pt(F);if(!$)try{const G=await o.session.list(void 0);return Array.isArray(G.data)?G.data:[]}catch(G){throw console.debug("Failed to list sessions (global):",G),G}const Q=await d($),ie=async()=>{const G=await o.session.list({directory:$});return Array.isArray(G.data)?G.data:[]};let K=[],ee=null,V=!1;try{K=await ie()}catch(G){console.debug("Failed to list sessions for directory:",$,G),ee=G,K=[]}if(K.length===0){V=!0;try{const G=await o.session.list(void 0),q=Array.isArray(G.data)?G.data:[];K=u(q,Q,{includeDescendants:l,includeMissingDirectory:!1})}catch(G){throw console.debug("Failed to list sessions (global fallback):",G),ee||G}}const ae=u(K,Q,{includeDescendants:l,includeMissingDirectory:!V});return qo("fetchSessionsForDirectory",{requestedDirectory:$,canonicalDirectory:Q,fetched:K.length,filtered:ae.length}),m(ae,$,Q)},p=Pt(s.currentDirectory??Oe.getDirectory()??null),h=n.projects.find(F=>F.id===n.activeProjectId)??null,x=Pt(h?.path??null),g=x??p??null,b=n.projects.length>0?n.projects:g?[{id:"legacy",path:g}]:[];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 $=Pt(F.path);if(!$)return{projectId:F.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const Q=await _r($).catch(()=>!1),ie=await f($||null);qo("projectSessions",{projectId:F.id,projectPath:$,isGitRepo:Q,parentSessions:ie.length});const K=[];let ee=[];const V=new Set;if(V.add($),Q){const G=`${$}/${bi}`;try{const q=new Set;(await Oe.listLocalDirectory($)).some(B=>B.isDirectory&&B.name===bi)&&(await Oe.listLocalDirectory(G)).filter(O=>O.isDirectory).forEach(O=>{const we=/^([A-Za-z]:)?\//.test(O.path)?O.path:`${G}/${O.name}`,pe=Pt(we)??we;q.add(pe)});const L=await Zn($);Array.isArray(L)&&(ee=L.map(B=>eo($,B)).filter(B=>B.path.includes(`/${bi}/`)),ee.forEach(B=>q.add(B.path))),q.forEach(B=>{const O=Pt(B)??B;V.add(O)}),q.size>0&&(await Promise.allSettled(Array.from(q).map(O=>f(O)))).forEach(O=>{O.status==="fulfilled"&&Array.isArray(O.value)&&K.push(...O.value)})}catch{ee=[]}}const ae=Wr([...ie,...K]);return{projectId:F.id,projectPath:$,sessions:ae,discoveredWorktrees:ee,validPaths:V}})),w=new Map;y.forEach(F=>{F.projectPath&&F.validPaths.forEach($=>{const Q=Pt($)??$,ie=F.sessions.filter(K=>(Pt(K.directory??null)??Q)===Q);w.set(Q,Wr(ie))})});const S=Wr(Array.from(w.values()).flat()),C=r();let v=C.worktreeMetadata;for(const F of y)if(F.projectPath)try{const $=await _b(F.sessions,F.projectPath,v);$&&(v=$)}catch($){console.debug("Failed to refresh worktree metadata during session load:",$)}const j=new Map;y.forEach(F=>{F.projectPath&&j.set(F.projectPath,F.discoveredWorktrees)});const M=new Set;y.forEach(F=>{F.validPaths.forEach($=>{const Q=Pt($)??$;Q&&M.add(Q)})});const k=p??x??null,D=k&&M.has(k)?k:x??k,N=D?w.get(D)??[]:S,T=new Set(S.map(F=>F.id));for(const[F,$]of w.entries())Ob(F,$.map(Q=>Q.id));const A=(D??null)!==(C.lastLoadedDirectory??null);let E=C.currentSessionId;if((!E||!T.has(E)||A)&&(E=N[0]?.id??S[0]?.id??null),D){const F=Nf(D);F&&T.has(F)&&(E=F)}const I=(()=>{if(!E)return D??null;const F=v.get(E)?.path;if(F)return Pt(F)??F;const $=Tn(S,E);return $||(D??null)})();try{Oe.setDirectory(I??void 0)}catch(F){console.warn("Failed to sync OpenCode directory after session load:",F)}const P=x?y.find(F=>F.projectPath===x)?.discoveredWorktrees??[]:[];t({sessions:S,sessionsByDirectory:w,currentSessionId:E,lastLoadedDirectory:D??null,isLoading:!1,worktreeMetadata:v,availableWorktrees:P,availableWorktreesByProject:j}),D&&Mr(D,E),I&&I!==D&&Mr(I,E)}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=wt.getState(),l=Pt(a.currentDirectory),c=ad(),d=c??Pt(n??Oe.getDirectory()??l);qo("createSession:start",{title:s,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:c});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(g=>g.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(g=>{const b=[p,...g.sessions],y=new Map(g.sessionsByDirectory);if(d){const w=y.get(d)??[];y.set(d,Wr([p,...w]))}return{sessions:b,sessionsByDirectory:y,currentSessionId:u,webUICreatedSessions:new Set([...g.webUICreatedSessions,u]),isLoading:!1}}),d)try{Oe.setDirectory(d)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const h=g=>{const b=d??null,y=b?{...g,directory:b}:g;t(w=>{const S=w.sessions.map(v=>v.id===u?y:v),C=new Map(w.sessionsByDirectory);if(d){const j=(C.get(d)??[]).map(M=>M.id===u?y:M);C.set(d,Wr(j))}return{sessions:S,sessionsByDirectory:rr(S),currentSessionId:y.id,webUICreatedSessions:new Set([...Array.from(w.webUICreatedSessions).filter(v=>v!==u),y.id])}}),Mr(d??null,y.id)},x=async()=>{const g=Oe.getApiClient(),b=20;for(let y=0;y<b;y+=1){try{const w=await g.session.list(d?{directory:d}:void 0),C=(Array.isArray(w.data)?w.data:[]).find(v=>!(f.has(v.id)||s&&v.title&&v.title!==s));if(C)return C}catch(w){console.debug("Session poll attempt failed:",w)}await new Promise(w=>setTimeout(w,2e3))}return null};try{const g=()=>Oe.createSession({title:s,parentID:o??void 0});let b=null;try{b=d?await Oe.withDirectory(d,g):await g()}catch(y){console.warn("Direct session create failed or timed out, falling back to polling:",y)}return b||(b=await x()),b?(h(b),b):(t(y=>({sessions:y.sessions.filter(w=>w.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(w=>w!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){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:g instanceof Error?g.message:"Failed to create session"})),null}},deleteSession:async(s,n)=>{t({isLoading:!0,error:null});const o=r().worktreeMetadata.get(s),a=Tn(r().sessions,s),l=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await od(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Oe.deleteSession(s);if(!(l?await Oe.withDirectory(l,d):await d()))return t(p=>{const h={isLoading:!1,error:"Failed to delete session"};if(c){const x=new Map(p.worktreeMetadata);x.delete(s),h.worktreeMetadata=x}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 x=new Map(p.worktreeMetadata);x.delete(s);const g=n?.archiveWorktree&&o?p.availableWorktrees.filter(y=>Pt(y.path)!==Pt(o.path)):p.availableWorktrees,b=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const y=Pt(o.projectDirectory)??o.projectDirectory,w=b.get(y)??[];b.set(y,w.filter(S=>Pt(S.path)!==Pt(o.path)))}return{sessions:h,sessionsByDirectory:rr(h),currentSessionId:m,isLoading:!1,worktreeMetadata:x,availableWorktrees:g,availableWorktreesByProject:b}});const f=l??Oe.getDirectory()??null;return Mr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return t(c?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 l=[],c=[],d=new Set,u=[],m=new Set;for(const b of o)try{const y=r().worktreeMetadata.get(b),w=Tn(r().sessions,b),S=y?.path??w;y&&n?.archiveWorktree&&!m.has(y.path)&&(await od(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())?(l.push(b),y?.path&&!u.some(j=>j.path===y.path)&&u.push({path:y.path,projectDirectory:y.projectDirectory})):c.push(b)}catch{c.push(b)}const f=wt.getState();u.forEach(({path:b,projectDirectory:y})=>{f.currentDirectory===b&&f.setDirectory(y,{showOverlay:!1})});const p=new Set(l),h=c.length>0?c.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let x=null;t(b=>{const y=b.sessions.filter(j=>!p.has(j.id));b.currentSessionId&&p.has(b.currentSessionId)?x=null:x=b.currentSessionId;const w=new Map(b.worktreeMetadata);for(const j of p)w.delete(j);for(const j of d)w.delete(j);const S=new Set(u.map(j=>Pt(j.path)).filter(j=>!!j)),C=S.size>0?b.availableWorktrees.filter(j=>!S.has(Pt(j.path)??j.path)):b.availableWorktrees,v=new Map(b.availableWorktreesByProject);return u.length>0&&u.reduce((M,k)=>{const D=Pt(k.projectDirectory)??k.projectDirectory,N=Pt(k.path)??k.path;return M.has(D)||M.set(D,new Set),M.get(D)?.add(N),M},new Map).forEach((M,k)=>{const N=(v.get(k)??[]).filter(T=>!M.has(Pt(T.path)??T.path));v.set(k,N)}),{sessions:y,sessionsByDirectory:rr(y),currentSessionId:x,...a?{}:{isLoading:!1,error:h},worktreeMetadata:w,availableWorktrees:C,availableWorktreesByProject:v}});const g=Oe.getDirectory()??null;return Mr(g,x),{deletedIds:l,failedIds:c}},updateSessionTitle:async(s,n)=>{try{const o=Tn(r().sessions,s),a=r().worktreeMetadata.get(s),l=()=>Oe.updateSession(s,n),c=a?.path??o,d=c?await Oe.withDirectory(c,l):await l();t(u=>{const m=u.sessions.map(f=>f.id===s?d:f);return{sessions:m,sessionsByDirectory:rr(m)}})}catch(o){t({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async s=>{try{const n=Tn(r().sessions,s),o=Oe.getApiClient(),l=r().worktreeMetadata.get(s)?.path??n,c=async()=>{const u=n??Oe.getDirectory();return o.session.share({sessionID:s,...u?{directory:u}:{}})},d=l?await Oe.withDirectory(l,c):await c();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:rr(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=Tn(r().sessions,s),o=Oe.getApiClient(),l=r().worktreeMetadata.get(s)?.path??n,c=async()=>{const u=n??Oe.getDirectory();return o.session.unshare({sessionID:s,...u?{directory:u}:{}})},d=l?await Oe.withDirectory(l,c):await c();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:rr(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;Mr(n,s)},clearError:()=>{t({error:null})},getSessionsByDirectory:s=>{const n=Pt(s)??s,{sessionsByDirectory:o,sessions:a}=r(),l=o.get(n);return l||a.filter(c=>(Pt(c.directory??null)??n)===n)},getDirectoryForSession:s=>{if(!s)return null;const n=r().worktreeMetadata.get(s);if(n?.path)return Pt(n.path)??n.path;const o=r().sessions.find(l=>l.id===s);return Pt(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 l=o.sessions[a],c=n.time?{...l.time,...n.time}:l.time,d=n.summary===void 0?l.summary:n.summary||void 0,u=n.share===void 0?l.share:n.share||void 0,m={...l,...n,time:c,summary:d,share:u},f=m.title!==l.title||m.parentID!==l.parentID||m.directory!==l.directory||m.version!==l.version||m.projectID!==l.projectID||JSON.stringify(m.time)!==JSON.stringify(l.time)||JSON.stringify(m.summary??null)!==JSON.stringify(l.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(l.share??null),p=[...o.sessions];return p[a]=f?m:l,{sessions:p,sessionsByDirectory:rr(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 c=o[a].directory??null,d=n??void 0;c!==(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:rr(m)}}),c&&Mr(c,null),n&&Mr(n,s))},updateSession:s=>{t(n=>{const a=n.sessions.findIndex(c=>c.id===s.id)===-1?[s,...n.sessions]:n.sessions.map(c=>c.id===s.id?s:c),l=Wr(a);return{sessions:l,sessionsByDirectory:rr(l)}})},removeSessionFromStore:s=>{s&&t(n=>{const o=n.sessions.find(u=>u.id===s),a=Pt(o?.directory??null),l=n.sessions.filter(u=>u.id!==s);if(l.length===n.sessions.length)return n;const c=new Map(n.worktreeMetadata);c.delete(s);const d=n.currentSessionId===s?null:n.currentSessionId;return a&&Mr(a,null),{sessions:l,sessionsByDirectory:rr(l),currentSessionId:d,worktreeMetadata:c}})}}),{name:"session-store",storage:qs(()=>ws()),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:[],l=Array.isArray(t.worktreeMetadata)?t.worktreeMetadata:[],c=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=Wr(n);return{...r,...t,sessions:f,sessionsByDirectory:rr(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(l),availableWorktrees:c,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),kf="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.",Bb="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: ",wi=t=>typeof t=="string"&&t.trim()===kf.trim(),vi=(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},fo=(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},id=new Map,Cf=t=>{const r=id.get(t);r&&(clearTimeout(r),id.delete(t))},rn=t=>{for(const r of t)Cf(r)},Eo=t=>{if(!t)return"";if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>Eo(r)).join("");if(typeof t=="object"){if(typeof t.text=="string")return t.text;if(Array.isArray(t.content))return t.content.map(r=>Eo(r)).join("")}return""},an=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:an(n)).join("");const s=Eo(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||Eo(o.delta)||""}return""}).join(""):"")},po=(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=Eo(t.delta);o?s.text=o:a?s.text=n?`${n}${a}`:a:n?s.text=n:s.text="",delete s.delta}return s},ld=50*1024*1024,zb=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"}},Hb=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"}},Wb=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},Ub=t=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let s="";for(let n=0;n<t.length;n+=3){const o=t[n]??0,a=t[n+1],l=t[n+2],c=o<<16|(a??0)<<8|(l??0);s+=r[c>>18&63],s+=r[c>>12&63],s+=typeof a=="number"?r[c>>6&63]:"=",s+=typeof l=="number"?r[c&63]:"="}return s},mr=rs()(fs(Gs((t,r)=>({attachedFiles:[],addAttachedFile:async s=>{const{attachedFiles:n}=r();if(n.some(x=>x.filename===s.name&&x.size===s.size)){console.log(`File "${s.name}" is already attached`);return}const a=ld;if(s.size>a)throw new Error(`File "${s.name}" is too large. Maximum size is 50MB.`);const l=["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"],c=Hb(s);!l.some(x=>c.startsWith(x)||c===x||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const u=new FileReader,m=await new Promise((x,g)=>{u.onload=()=>x(u.result),u.onerror=g,u.readAsDataURL(s)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${c}`):m,p=x=>{const g=x.replace(/\\/g,"/").split("/");return g[g.length-1]||x},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:s,dataUrl:f,mimeType:c,filename:p(s.name),size:s.size,source:"local"};t(x=>({attachedFiles:[...x.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 c=o,d,u;if(!c)try{const y=Oe.getApiClient(),w=s.lastIndexOf("/"),S=w>0?s.substring(0,w):"/",C=w>0?s.substring(w+1):s,v=await y.file.read({path:C,directory:S});v.data&&"content"in v.data?(c=v.data.content,d=v.data.encoding??void 0,u=v.data.mimeType??void 0):c=""}catch(y){console.error("Failed to read server file:",y),c=`[File: ${n}]`}const m=u||zb(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const w=new TextEncoder().encode(c||"");return Ub(w)})(),h=d==="base64"?Wb(p):new TextEncoder().encode(c||"").length;if(h>ld)throw new Error(`File "${n}" is too large. Maximum size is 50MB.`);const x=new File([],n,{type:f}),g=`data:${f};base64,${p}`,b={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:x,dataUrl:g,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:qs(()=>ws()),partialize:t=>({attachedFiles:t.attachedFiles})}),{name:"file-store"})),Vb=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Gb=t=>t?Vb.has(t.toLowerCase()):!1,qb=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Kb=t=>{if(t)try{const r=qb();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===t)}catch{}},Qb=(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"},va=t=>{const r=Kb(t);return r?Qb(r.permission,"edit"):"ask"},cd=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},ji=t=>{const r=t.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return cd(r);const s=t.parts.find(n=>typeof n.tokens<"u");return!s||typeof s.tokens>"u"?0:typeof s.tokens=="number"?s.tokens:cd(s.tokens)},Si=(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,l=Math.min(o?a:32e3,32e3),c=Math.min(l,n),d=n>0?Math.max(n-c,1):0,u=d>0?t/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},ho=["ask","allow","full"],dd="__global__",nt=rs()(fs(Gs((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 l=new Map(a.sessionModelSelections);return l.set(s,{providerId:n,modelId:o}),{sessionModelSelections:l}})},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 l=new Map(o.currentAgentContext);return l.set(s,n),{sessionAgentSelections:a,currentAgentContext:l}})},getSessionAgentSelection:s=>{const{sessionAgentSelections:n}=r();return n.get(s)||null},saveAgentModelForSession:(s,n,o,a)=>{t(l=>{const c=new Map(l.sessionAgentModelSelections);let d=c.get(s);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(s,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(s,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(s);return a&&a.get(n)||null},saveAgentModelVariantForSession:(s,n,o,a,l)=>{t(c=>{const d=new Map(c.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 l===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,l),u.set(n,m),d.set(s,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(s,n,o,a)=>{const{sessionAgentModelVariantSelections:l}=r(),c=l.get(s);if(!c)return;const d=c.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(s,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:l}=r(),c=new Map,d=(x,g)=>{if("mode"in x&&x.mode&&typeof x.mode=="string"&&n.find(S=>S.name===x.mode))return x.mode;if("agent"in x&&x.agent&&typeof x.agent=="string"&&n.find(S=>S.name===x.agent))return x.agent;if(x.providerID&&x.modelID){const w=n.find(S=>S.model?.providerID===x.providerID&&S.model?.modelID===x.modelID);if(w)return w.name}const{currentAgentContext:b}=r(),y=b.get(s);if(y&&n.find(w=>w.name===y))return y;if(g>0&&x.providerID&&x.modelID){const S=(o.get(s)||[]).filter(C=>C.info.role==="assistant").sort((C,v)=>C.info.time.created-v.info.time.created);for(let C=g-1;C>=0;C--){const j=S[C].info;if(j.providerID===x.providerID&&j.modelID===x.modelID){if(j.mode&&typeof j.mode=="string"&&n.find(D=>D.name===j.mode))return j.mode;const M=n.find(k=>k.model?.providerID===j.providerID&&k.model?.modelID===j.modelID);if(M)return M.name}}}return x.providerID&&x.modelID&&n.find(S=>S.name==="build")?"build":null},u=o.get(s)||[],m=u.filter(x=>x.info.role==="assistant"||x.info.role==="user").sort((x,g)=>x.info.time.created-g.info.time.created),f=u.filter(x=>x.info.role==="assistant").sort((x,g)=>x.info.time.created-g.info.time.created);let p,h;for(let x=0;x<m.length;x++){const g=m[x],{info:b}=g,y=b;if(y.role==="user"){const w=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(w&&S&&C&&n.find(v=>v.name===w)){const v={providerId:S,modelId:C,timestamp:b.time.created},j=c.get(w);(!j||v.timestamp>j.timestamp)&&c.set(w,v),typeof y.variant=="string"&&y.variant.trim().length>0&&l(s,w,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 w=d(y,f.indexOf(g));if(w&&n.find(S=>S.name===w)){p&&h&&h.providerID===y.providerID&&h.modelID===y.modelID&&l(s,w,y.providerID,y.modelID,p);const S={providerId:y.providerID,modelId:y.modelID,timestamp:b.time.created},C=c.get(w);(!C||S.timestamp>C.timestamp)&&c.set(w,S)}}p=void 0,h=void 0}for(const[x,g]of c)a(s,x,g.providerId,g.modelId);return c},getContextUsage:(s,n,o,a)=>{if(!s)return null;const l=Si(0,n,o),c=l.contextLimit,d=l.normalizedOutput??0,u=l.thresholdLimit;if(c===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,x=S=>{const C=()=>{t(v=>{const j=v.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 v;const M=new Map(v.sessionContextUsage);return M.set(s,S),{sessionContextUsage:M}})};typeof queueMicrotask=="function"?queueMicrotask(C):typeof window<"u"?window.setTimeout(C,0):setTimeout(C,0)},g=r().sessionContextUsage.get(s);if(g&&g.lastMessageId===h){const S=g.normalizedOutput??g.outputLimit??0,C=g.contextLimit!==c||S!==d||g.thresholdLimit!==u;if(C&&g.totalTokens>0){const v=g.totalTokens/u*100,j={totalTokens:g.totalTokens,percentage:Math.min(v,100),contextLimit:c,outputLimit:l.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return x(j),j}if(!C&&g.totalTokens>0)return g}const b=ji(p);if(b===0)return g||null;const y=Si(b,n,o),w={totalTokens:b,percentage:y.percentage,contextLimit:y.contextLimit,outputLimit:y.outputLimit,normalizedOutput:y.normalizedOutput,thresholdLimit:y.thresholdLimit,lastMessageId:h};return x(w),w},updateSessionContextUsage:(s,n,o,a)=>{const c=(a.get(s)||[]).filter(f=>f.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=ji(d);if(u===0)return;const m=Si(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 c=r().sessionContextUsage.get(s);(!c||c.totalTokens===0)&&r().updateSessionContextUsage(s,n,o,a)},pollForTokenUpdates:(s,n,o,a=10)=>{let l=0;const c=()=>{l++;const u=(o.get(s)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&ji(u)>0){r().updateSessionContextUsage(s,0,0,o);return}l<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:s=>{const{currentAgentContext:n}=r();return n.get(s)},getSessionAgentEditMode:(s,n,o=va(n))=>{if(!s||!n)return o;const l=r().sessionAgentEditModes.get(s)?.get(n);if(l!==void 0)return l;if(s!==dd){const d=r().sessionAgentEditModes.get(dd)?.get(n);if(d!==void 0)return d}return o},setSessionAgentEditMode:(s,n,o,a=va(n))=>{if(!s||!n)return;const l=a??"ask";l==="deny"||o==="deny"||ho.includes(o)&&t(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(s)??new Map);return o===l?(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=va(n))=>{if(!s||!n)return;const a=o??"ask";if(a==="deny")return;const l=r().getSessionAgentEditMode(s,n,a),c=ho.indexOf(l),d=ho.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%ho.length,f=ho[m];r().setSessionAgentEditMode(s,n,f,a)}}),{name:"context-store",storage:qs(()=>ws()),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,l])=>{s.set(a,new Map(l))});const n=new Map;t?.sessionAgentModelVariantSelections&&t.sessionAgentModelVariantSelections.forEach(([a,l])=>{const c=new Map;l.forEach(([d,u])=>{c.set(d,new Map(u))}),n.set(a,c)});const o=new Map;return t?.sessionAgentEditModes&&t.sessionAgentEditModes.forEach(([a,l])=>{o.set(a,new Map(l))}),{...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"})),ud=(t,r)=>{const s=new Map(t);return s.delete(r),s};let Ni=[],ki=null;const Yb=50,Jb=3e4,nn=new Map,Ko=new Map,Fn=new Map,Xb=10,_a=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<Xb?null:n},Qo=(t,r)=>{const s=_a(t),n=_a(r);return!s||!n||s.length!==n.length?!0:s>n},Zb=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Hn=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),Ba=t=>t?.finish==="stop",md=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??""}`}}},fd=new Set,za=(t=[],r=[])=>{if(!r.length)return[...t];const s=[...t],n=new Set(t.map(md).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=md(o);a&&n.has(a)||(s.push(o),a&&n.add(a))}),s},ew=(t,r)=>{const s=Array.isArray(t.parts)?t.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=Hn(s),a=Hn(n),l=Ba(t.info),c=Ba(r.info);let d=n;return l&&o>=a?d=za(s,n):c&&a>=o?d=za(n,s):o>=a&&(d=s),{...r,info:{...t.info,...r.info},parts:d}},Yo=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]=ew(r[a],n)}return r},tw=(t,r)=>{let s=r,n=r?_a(r):null;for(const o of t){const a=o?.info?.id,l=_a(a);!a||!l||(!n||l>n)&&(n=l,s=a)}return s},gr=(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},Rn=(t,r,s)=>{if(t.get(r)===s)return t;const o=new Map(t);return o.set(r,s),o},Jo=(t,r)=>{const s=new Map(t);let n=!1;for(const o of r)s.delete(o)&&(n=!0);return n?s:t},sw=(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},pd=(t,r,s)=>t.streamingMessageIds.get(r)===s?!0:t.messageSessionIndex.get(s)===r&&t.messageStreamStates.has(s),rw=async t=>{if(t)try{return bt.getState().getDirectoryForSession(t)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},hd=t=>{if(!t)return null;try{return bt.getState().sessions.find(n=>n.id===t)?.revert?.messageID??null}catch{return null}},gd=(t,r)=>{if(!r)return t;const s=t.findIndex(n=>n.info.id===r);return s===-1?t:t.slice(0,s)},Ci=async(t,r)=>{const s=await rw(t);return s?Oe.withDirectory(s,r):r()},Dt=rs()(fs(Gs((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=$a(),a=n===1/0,l=a?1/0:n??o.HISTORICAL_MESSAGES,c=r().sessionMemoryState.get(s)?.isStreaming,d=c?o.VIEWPORT_MESSAGES:l,u=c||a?void 0:d+o.FETCH_BUFFER,m=await Ci(s,()=>Oe.getSessionMessages(s,u)),f=hd(s),p=gd(m,f),h=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,g=(h?p.filter(b=>{const y=b?.info?.id;return y?Qo(y,h):!0}):p).slice(-d);t(b=>{const y=new Map(b.messages),w=b.messages.get(s)||[],S=new Map(w.filter(P=>typeof P.info?.id=="string").map(P=>[P.info.id,P])),C=g.map(P=>{const F={...P.info,clientRole:P.info?.clientRole??P.info.role,userMessageMarker:P.info.role==="user"?!0:P.info?.userMessageMarker},$=(Array.isArray(P.parts)?P.parts:[]).map(ie=>{if(ie?.type==="text"){const K=ie.text??ie.content??"";if(wi(K))return{...ie,synthetic:!0}}return ie}),Q=F?.id?S.get(F.id):void 0;if(Q&&Q.info.role==="assistant"){const ie=Array.isArray(Q.parts)?Q.parts:[],K=Hn(ie),ee=Hn($);if(Ba(Q.info)&&K>ee){const ae=za(ie,$);return{...P,info:F,parts:ae}}}return{...P,info:F,parts:$}}),v=Yo(C),j=new Set(w.map(P=>P.info.id)),M=new Set(v.map(P=>P.info.id)),k=[];j.forEach(P=>{M.has(P)||k.push(P)}),y.set(s,v);const D=new Map(b.sessionMemoryState),N=b.sessionMemoryState.get(s);D.set(s,{...N,viewportAnchor:v.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:m.length,hasMoreAbove:m.length>g.length,trimmedHeadMaxId:N?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const T={messages:y,sessionMemoryState:D};rn(k);const A=fo(b.messageStreamStates,k);if(A!==b.messageStreamStates&&(T.messageStreamStates=A),k.length>0){const P=b.streamingMessageIds.get(s);P&&k.includes(P)&&(T.streamingMessageIds=gr(T.streamingMessageIds??b.streamingMessageIds,s,null))}if(k.length>0){const P=Jo(T.messageSessionIndex??b.messageSessionIndex,k);P!==(T.messageSessionIndex??b.messageSessionIndex)&&(T.messageSessionIndex=P)}if(k.length>0){const P=new Map(b.pendingAssistantParts);let F=!1;k.forEach($=>{P.delete($)&&(F=!0)}),F&&(T.pendingAssistantParts=P)}const E=T.messageSessionIndex??b.messageSessionIndex;let I=E;return v.forEach(P=>{const F=P?.info?.id;typeof F=="string"&&F.length>0&&(I=Rn(I,F,s))}),I!==E&&(T.messageSessionIndex=I),T})},sendMessage:async(s,n,o,a,l,c,d,u,m)=>{if(!l)throw new Error("No session selected");const f=l;r().sessionAbortFlags.has(f)&&t(p=>{const h=new Map(p.sessionAbortFlags);return h.delete(f),{sessionAbortFlags:h}}),await Ci(f,async()=>{try{let p=s;if(s.startsWith("/")){const x=s.indexOf(" "),g=x===-1?s.substring(1):s.substring(1,x),b=x===-1?"":s.substring(x+1).trim(),y=Oe.getApiClient(),w=Oe.getDirectory();if(g==="init"){const S=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await y.session.init({sessionID:f,...w?{directory:w}:{},messageID:S,providerID:n,modelID:o});return}if(g==="summarize"){await y.session.summarize({sessionID:f,...w?{directory:w}:{},providerID:n,modelID:o});return}try{const S=await Oe.getCommandDetails(g);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(x=>{const g=x.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},b=Fn.get(f);b&&(clearTimeout(b),Fn.delete(f));const y=new Map(x.sessionMemoryState);return y.set(f,{...g,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:y}});try{const x=new AbortController;t(y=>{const w=new Map(y.abortControllers);return w.set(f,x),{abortControllers:w}});const g=(c??[]).map(y=>({type:"file",mime:y.mimeType,filename:y.filename,url:y.dataUrl}));t(y=>{const w=new Set(y.pendingAssistantHeaderSessions);w.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:w,pendingUserMessageMetaBySession:S}});const b=u?.map(y=>({text:y.text,synthetic:y.synthetic,files:y.attachments?.map(w=>({type:"file",mime:w.mimeType,filename:w.filename,url:w.dataUrl}))}));if(await Oe.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:g.length>0?g:void 0,additionalParts:b&&b.length>0?b:void 0,agentMentions:d?[{name:d}]:void 0}),g.length>0)try{mr.getState().clearAttachedFiles()}catch(y){console.error("Failed to clear attached files after send",y)}t(y=>{const w=new Map(y.abortControllers);return w.delete(f),{abortControllers:w}})}catch(x){let g="Network error while sending message. The message may still be processing.";if(x.name==="AbortError")g="Request timed out. The message may still be processing.";else if(x.message?.includes("504")||x.message?.includes("Gateway")){g="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 x.message&&(g=x.message);throw t(b=>{const y=new Map(b.abortControllers);y.delete(f);const w=new Set(b.pendingAssistantHeaderSessions);w.delete(f);const S=new Map(b.pendingUserMessageMetaBySession);return S.delete(f),{abortControllers:y,pendingAssistantHeaderSessions:w,pendingUserMessageMetaBySession:S}}),new Error(g)}}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(x=>{const g=new Map(x.abortControllers);g.delete(f);const b=new Set(x.pendingAssistantHeaderSessions);b.delete(f);const y=new Map(x.pendingUserMessageMetaBySession);return y.delete(f),{abortControllers:g,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 c=sw(n,s);if(c.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(x=>x.type==="reasoning"||x.type==="tool"||x.type==="step-start")){c.add(p.info.id);break}}c.size===0&&m&&c.add(m)}for(const u of c){const m=nn.get(u);m&&(clearTimeout(m),nn.delete(u),Ko.delete(u))}c.size>0&&rn(c);const d=Date.now();t(u=>{const m=fo(u.messageStreamStates,c),f=u.messages.get(s)??[];let p=!1,h=u.messages;if(f.length>0&&c.size>0){const y=f.map(w=>{if(!c.has(w.info.id)&&c.size>0)return w;const S=(w.parts??[]).map(C=>{if(C.type==="reasoning"){const v=C,j={...v.time??{}};return typeof j.end!="number"&&(j.end=d),{...v,time:j}}if(C.type==="tool"){const v=C,j={...v.state??{}};return(j.status==="running"||j.status==="pending")&&(j.status="aborted"),{...v,state:j}}return C.type==="step-start"?{...C,type:"step-finish",aborted:!0}:C});return p=!0,{...w,info:{...w.info,abortedAt:d,streaming:!1,status:"aborted"},parts:S}});p&&(h=new Map(u.messages),h.set(s,y))}const x=u.sessionMemoryState.get(s);let g=u.sessionMemoryState;if(x){const y=new Map(u.sessionMemoryState);y.set(s,{...x,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),g=y}const b=new Map(u.sessionAbortFlags);return b.set(s,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:g,sessionAbortFlags:b,abortControllers:(()=>{const y=new Map(u.abortControllers);return y.delete(s),y})(),streamingMessageIds:gr(u.streamingMessageIds,s,null),...p?{messages:h}:{}}}),Oe.abortSession(s).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(s,n,o,a,l)=>{const c=r();if(fd.has(n))return;const d=c.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!Qo(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=c.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>Ar.ZOMBIE_TIMEOUT){p.isZombie||t(x=>{const g=new Map(x.sessionMemoryState);return g.set(s,{...p,isZombie:!0}),{sessionMemoryState:g}}),setTimeout(()=>{r().completeStreamingMessage(s,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}t(h=>{const g=[...h.messages.get(s)||[]],b={},y=Rn(h.messageSessionIndex,n,s);y!==h.messageSessionIndex&&(b.messageSessionIndex=y);const w=D=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(s)))return D;const T=new Map(h.sessionAbortFlags);return T.delete(s),{...D,sessionAbortFlags:T}},S=D=>{const N=D||"",T=Ko.get(n);if(N&&T===N){const I=r();if(pd(I,s,n)){const P=nn.get(n);P&&(clearTimeout(P),nn.delete(n)),setTimeout(()=>{const F=r();typeof F.forceCompleteMessage=="function"&&F.forceCompleteMessage(s,n,"timeout"),F.completeStreamingMessage(s,n)},100)}}Ko.set(n,N);const A=nn.get(n);A&&clearTimeout(A);const E=setTimeout(()=>{const I=r();typeof I.forceCompleteMessage=="function"&&I.forceCompleteMessage(s,n,"timeout"),pd(I,s,n)&&I.completeStreamingMessage(s,n),nn.delete(n),Ko.delete(n)},8e3);nn.set(n,E)},C=s!==l,v=h.sessionMemoryState.get(s);if(C&&v?.isStreaming){g.length>=Ar.BACKGROUND_STREAMING_BUFFER&&g.shift();const D=new Map(h.sessionMemoryState);D.set(s,{...v,backgroundMessageCount:(v.backgroundMessageCount||0)+1}),h.sessionMemoryState=D}if(f==="assistant"){const D=h.sessionMemoryState.get(s);if(D){const N=Date.now(),T=new Map(h.sessionMemoryState);T.set(s,{...D,isStreaming:!0,streamStartTime:D.streamStartTime??N,lastAccessedAt:N,isZombie:!1}),h.sessionMemoryState=T}}const j=an(o);if(wi(j)&&(o.synthetic=!0),Zb()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:j.length,snapshotParts:u.length})}catch{}const M=b.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const D=gr(M,s,n);D!==M&&(b.streamingMessageIds=D,window.__messageTracker?.(n,"streamingId_set_latest"))}const k=g.findIndex(D=>D.info.id===n);if(k!==-1&&f==="user"){const D=g[k],N=D.parts.findIndex(P=>P.id===o.id);if(o.synthetic===!0){const P=an(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=po(o,N!==-1?D.parts[N]:void 0);window.__messageTracker?.(n,`user_part_type:${T.type||"unknown"}`);const A={...D};N!==-1?A.parts=A.parts.map((P,F)=>F===N?T:P):A.parts=[...A.parts,T];const E=[...g];E[k]=A;const I=new Map(h.messages);return I.set(s,E),w({messages:I})}if(f==="assistant"&&k!==-1){const D=g[k],N=D.parts.findIndex(F=>F.id===o.id),T=po(o,N!==-1?D.parts[N]:void 0);window.__messageTracker?.(n,`part_type:${T.type||"unknown"}`);const A={...D};N!==-1?A.parts=A.parts.map((F,$)=>$===N?T:F):A.parts=[...A.parts,T];const E=[...g];E[k]=A;const I=new Map(h.messages);I.set(s,E),b.messageStreamStates=vi(h.messageStreamStates,n);const P=gr(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(""),w({messages:I,...b})}if(k===-1){if(f==="user"){if(o.synthetic===!0){const he=an(o).trim();if(!(he.startsWith("User has requested to enter plan mode")||he.startsWith("The plan at ")))return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h}const _=po(o);window.__messageTracker?.(n,`new_user_part_type:${_.type||"unknown"}`);const H=h.pendingUserMessageMetaBySession.get(s),L=nt.getState(),B=H?.mode??L.getSessionAgentSelection(s)??L.getCurrentAgent(s),O=typeof B=="string"&&B.trim().length>0?B.trim():void 0,le=H?.providerID??(h.lastUsedProvider?.providerID||void 0),we=H?.modelID??(h.lastUsedProvider?.modelID||void 0);H&&(b.pendingUserMessageMetaBySession=ud(h.pendingUserMessageMetaBySession,s));const pe={info:{id:n,sessionID:s,role:"user",clientRole:"user",userMessageMarker:!0,...O?{mode:O}:{},...le?{providerID:le}:{},...we?{modelID:we}:{},time:{created:Date.now()}},parts:[_]},De=[...g,pe];De.sort((he,Z)=>{const de=he.info?.time?.created||0,Ee=Z.info?.time?.created||0;return de-Ee});const z=new Map(h.messages);return z.set(s,De),w({messages:z})}if(o?.type==="text"){const _=an(o).trim();if(_.length>0){const H=[...g].reverse().find(L=>L.info.role==="user");if(H){const L=H.parts.map(B=>an(B)).join("").trim();if(L.length>0&&L===_)return fd.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const D=po(o);window.__messageTracker?.(n,`part_type:${D.type||"unknown"}`),D.type==="text"?S(D.text||""):S("");const N=h.pendingAssistantParts.get(n),T=N?[...N.parts]:[],A=T.findIndex(_=>_.id===D.id);A!==-1?T[A]=D:T.push(D);const E=new Map(h.pendingAssistantParts);E.set(n,{sessionId:s,parts:T});const I=h.lastUsedProvider?.providerID||"",P=h.lastUsedProvider?.modelID||"",F=Date.now(),$=Oe.getDirectory()??"/",Q=nt.getState(),ie=Q.getSessionAgentSelection(s)??Q.getCurrentAgent(s),K=typeof ie=="string"&&ie.trim().length>0?ie.trim():void 0,ee=h.pendingAssistantHeaderSessions.has(s);if(ee){const _=new Set(h.pendingAssistantHeaderSessions);_.delete(s),b.pendingAssistantHeaderSessions=_}const ae={info:f==="user"?{id:n,sessionID:s,role:"user",time:{created:F},agent:K||"default",model:{providerID:I,modelID:P},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:s,role:"assistant",time:{created:F},parentID:n,modelID:P,providerID:I,mode:K||"default",...ee?{openchamberHeaderAnchor:!0}:{},path:{cwd:$,root:$},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:T},G=[...g,ae],q=new Map(h.messages);if(q.set(s,G),f==="assistant"){b.messageStreamStates=vi(h.messageStreamStates,n);const _=gr(b.streamingMessageIds??h.streamingMessageIds,s,n);_!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=_,window.__messageTracker?.(n,"streamingId_set"))}return w({messages:q,pendingAssistantParts:E,...b})}else{const D=g[k],N=D.parts.findIndex(P=>P.id===o.id),T=po(o,N!==-1?D.parts[N]:void 0);window.__messageTracker?.(n,`part_type:${T.type||"unknown"}`);const A={...D};N!==-1?A.parts=A.parts.map((P,F)=>F===N?T:P):A.parts=[...A.parts,T];const E=[...g];E[k]=A;const I=new Map(h.messages);if(I.set(s,E),A.info.role==="assistant"){b.messageStreamStates=vi(h.messageStreamStates,n);const P=gr(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(""),w({messages:I,...b})}})},addStreamingPart:(s,n,o,a,l)=>{if(a!=="user"){r()._addStreamingPartImmediate(s,n,o,a,l);return}Ni.push({sessionId:s,messageId:n,part:o,role:a,currentSessionId:l}),ki||(ki=setTimeout(()=>{const c=[...Ni];Ni=[],ki=null;const d=r();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Yb))},forceCompleteMessage:(s,n,o="timeout")=>{const a=l=>{if(s)return s;for(const[c,d]of l.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};t(l=>{const c=a(l);if(!c)return l;const d=l.messages.get(c)??[],u=d.findIndex(v=>v.info.id===n);if(u===-1)return l;const m=d[u];if(!m)return l;const f=Date.now(),p=m.info,h=typeof p?.time?.completed=="number"&&p.time.completed>0;let x=!1;const g={...p};h||(g.time={...p.time??{},completed:f},x=!0),g.status!=="completed"&&(g.status="completed",x=!0),g.streaming&&(g.streaming=!1,x=!0);let b=!1;const y=m.parts.map(v=>{if(!v)return v;if(v.type==="tool"){const j=v.state;if(!j)return v;const M=j.status,k=M==="running"||M==="pending"||M==="started",D=!j.time||typeof j.time?.end!="number";if(k||D){const N={...j};return k&&(N.status="completed"),D&&(N.time={...j.time??{},end:f}),b=!0,{...v,state:N}}return v}if(v.type==="reasoning"){const j=v.time;return!j||typeof j.end!="number"?(b=!0,{...v,time:{...j??{},end:f}}):v}if(v.type==="text"){const j=v.time;return j&&typeof j.end!="number"?(b=!0,{...v,time:{...j,end:f}}):v}return v});if(!x&&!b)return l;window.__messageTracker?.(n,`force_complete:${o}`);const w={...m,info:g,parts:b?y:m.parts},S=[...d];S[u]=w;const C=new Map(l.messages);return C.set(c,S),{messages:C}})},markMessageStreamSettled:s=>{t(n=>{Cf(s);const o=new Map(n.messageStreamStates);o.delete(s);let a=n.messages,l=!1;return n.messages.forEach((d,u)=>{if(l)return;const m=d.findIndex(g=>g.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 x=new Map(n.messages);x.set(u,h),a=x,l=!0}),{messageStreamStates:o,...l?{messages:a}:{}}}),rn([s])},updateMessageInfo:(s,n,o)=>{t(c=>{const d=c.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!Qo(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(s)??[]],f=m.findIndex(k=>k.info.id===n),p=c.pendingAssistantParts.get(n),h=(k=[],D=[])=>{if(!D.length)return k;const N=[...k];return D.forEach(T=>{const A=N.findIndex(E=>E.id===T.id);A===-1?N.push(T):N[A]=T}),N},x=k=>{if(!k)return k;const D=k.clientRole??k.role,N=D==="user"?!0:k.userMessageMarker;return{...k,clientRole:D,...N?{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 $=m[0]?.info,Q=typeof $?.time?.created=="number"?$.time.created:null,ie=typeof $?.id=="string"?$.id:null,K=o,ee=typeof K?.time?.created=="number"?K.time.created:null,V=typeof K?.id=="string"?K.id:n;let ae=!1;if(ee!==null&&Q!==null&&(ae=ee<Q),!ae&&V&&ie&&(ae=V.localeCompare(ie)<0),ae)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const k=x(o);if(k&&k.role==="user"){const F=p?.parts??[],$=c.pendingUserMessageMetaBySession.get(s),Q={info:{...k,userMessageMarker:!0,clientRole:"user",...$?.mode?{mode:$.mode}:{},...$?.providerID?{providerID:$.providerID}:{},...$?.modelID?{modelID:$.modelID}:{}},parts:F.length>0?[...F]:[]},ie=new Map(c.messages),K=[...m,Q];K.sort((ae,G)=>{const q=ae.info?.time?.created||0,_=G.info?.time?.created||0;return q-_}),ie.set(s,K);const ee={messages:ie,...$?{pendingUserMessageMetaBySession:ud(c.pendingUserMessageMetaBySession,s)}:{}},V=Rn(ee.messageSessionIndex??c.messageSessionIndex,n,s);if(V!==(ee.messageSessionIndex??c.messageSessionIndex)&&(ee.messageSessionIndex=V),p){const ae=new Map(c.pendingAssistantParts);ae.delete(n),ee.pendingAssistantParts=ae}return ee}if(!k||k.role!=="assistant")return c;const D=p?.parts??[],N=c.pendingAssistantHeaderSessions.has(s),T={info:{...k,animationSettled:k?.animationSettled??!1,...N?{openchamberHeaderAnchor:!0}:{}},parts:D.length>0?[...D]:[]},A=new Map(c.messages),E=[...m,T];A.set(s,E);const I={messages:A,...N?{pendingAssistantHeaderSessions:(()=>{const F=new Set(c.pendingAssistantHeaderSessions);return F.delete(s),F})()}:{}},P=Rn(I.messageSessionIndex??c.messageSessionIndex,n,s);if(P!==(I.messageSessionIndex??c.messageSessionIndex)&&(I.messageSessionIndex=P),p){const F=new Map(c.pendingAssistantParts);F.delete(n),I.pendingAssistantParts=F}return I}const g=m[f],b=g.info;if(b.userMessageMarker===!0||b.clientRole==="user"||b.role==="user"){const k={...g.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:b.providerID||void 0,modelID:b.modelID||void 0},D=c.pendingUserMessageMetaBySession.get(s);D&&!k.mode&&D.mode&&(k.mode=D.mode);const N={...g,info:k},T=new Map(c.messages),A=[...m];if(A[f]=N,T.set(s,A),D){const E=new Map(c.pendingUserMessageMetaBySession);return E.delete(s),{messages:T,pendingUserMessageMetaBySession:E}}return{messages:T}}const w={...g.info,...o};o.role&&o.role!==g.info.role&&(w.role=g.info.role),w.clientRole=w.clientRole??g.info.clientRole??g.info.role,w.clientRole==="user"&&(w.userMessageMarker=!0);const S=p?.parts?h(g.parts,p.parts):g.parts,C={...g,info:w,parts:S},v=new Map(c.messages),j=[...m];j[f]=C,v.set(s,j);const M={messages:v};if(p){const k=new Map(c.pendingAssistantParts);k.delete(n),M.pendingAssistantParts=k}return M});const a=o?.finish,l=o?.role;typeof a=="string"&&l!=="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 l={};if(a&&(l.streamingMessageIds=gr(o.streamingMessageIds,s,null),l.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),l.messageStreamStates=d}Object.keys(l).length>0&&t(l),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}}),rn([n]);let c=!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),c=!0,{sessionMemoryState:m}}),c){const d=Fn.get(s);d&&(clearTimeout(d),Fn.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,...x}=f;return p.set(s,x),{sessionMemoryState:p}}),Fn.delete(s)},2e3);Fn.set(s,u)}},syncMessages:(s,n)=>{const o=hd(s),a=gd(n,o),l=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,c=l?a.filter(d=>{const u=d?.info?.id;return u?Qo(u,l):!0}):a;t(d=>{const u=new Map(d.messages),m=d.messages.get(s)||[],f=new Map(m.filter(v=>typeof v.info?.id=="string").map(v=>[v.info.id,v])),p=c.map(v=>{const j={...v.info,clientRole:v.info?.clientRole??v.info.role,userMessageMarker:v.info.role==="user"?!0:v.info?.userMessageMarker,animationSettled:v.info.role==="assistant"?v.info?.animationSettled??!0:v.info?.animationSettled},M=(Array.isArray(v.parts)?v.parts:[]).map(N=>{if(N?.type==="text"){const T=N.text??N.content??"";if(wi(T))return{...N,synthetic:!0}}return N}),k=typeof j?.id=="string"?j.id:void 0,D=k?f.get(k):void 0;if(D&&D.info.role==="assistant"){const N=Array.isArray(D.parts)?D.parts:[],T=Hn(N),A=Hn(M);if(Ba(D.info)&&T>A){const I=za(N,M);return{...v,info:j,parts:I}}}return{...v,info:j,parts:M}}),h=Yo(p),x=new Set(m.map(v=>v.info.id)),g=new Set(h.map(v=>v.info.id)),b=[];x.forEach(v=>{g.has(v)||b.push(v)}),u.set(s,h);const y={messages:u,isSyncing:!0};rn(b);const w=fo(d.messageStreamStates,b);if(w!==d.messageStreamStates&&(y.messageStreamStates=w),b.length>0){const v=d.streamingMessageIds.get(s);v&&b.includes(v)&&(y.streamingMessageIds=gr(y.streamingMessageIds??d.streamingMessageIds,s,null))}if(b.length>0){const v=Jo(y.messageSessionIndex??d.messageSessionIndex,b);v!==(y.messageSessionIndex??d.messageSessionIndex)&&(y.messageSessionIndex=v)}if(b.length>0){const v=new Map(d.pendingAssistantParts);let j=!1;b.forEach(M=>{v.delete(M)&&(j=!0)}),j&&(y.pendingAssistantParts=v)}const S=y.messageSessionIndex??d.messageSessionIndex;let C=S;return h.forEach(v=>{const j=v?.info?.id;typeof j=="string"&&j.length>0&&(C=Rn(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 l=n+Jb;return a.get(s)===l?o:(a.set(s,l),{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},l=new Map(o.sessionMemoryState);return l.set(s,{...a,viewportAnchor:n}),{sessionMemoryState:l}})},trimToViewportWindow:(s,n,o)=>{const a=n??$a().VIEWPORT_MESSAGES,l=r(),c=l.messages.get(s);if(!c||c.length<=a)return;const d=l.sessionMemoryState.get(s)||{viewportAnchor:c.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(d.isStreaming&&s===o)return;const u=d.viewportAnchor||c.length-1;let m=Math.max(0,u-Math.floor(a/2));const f=Math.min(c.length,m+a);f===c.length&&f-m<a&&(m=Math.max(0,f-a));const p=c.slice(m,f),h=c.slice(0,m),x=new Set(p.map(b=>b.info.id)),g=c.filter(b=>!x.has(b.info.id)).map(b=>b.info.id);t(b=>{const y=new Map(b.messages);y.set(s,p);const w=new Map(b.sessionMemoryState),S={...d,viewportAnchor:u-m,trimmedHeadMaxId:tw(h,d.trimmedHeadMaxId)};w.set(s,S);const C={messages:y,sessionMemoryState:w};rn(g);const v=fo(b.messageStreamStates,g);if(v!==b.messageStreamStates&&(C.messageStreamStates=v),g.length>0){const k=b.streamingMessageIds.get(s);k&&g.includes(k)&&(C.streamingMessageIds=gr(C.streamingMessageIds??b.streamingMessageIds,s,null))}if(g.length>0){const k=Jo(C.messageSessionIndex??b.messageSessionIndex,g);k!==(C.messageSessionIndex??b.messageSessionIndex)&&(C.messageSessionIndex=k)}const j=C.messageSessionIndex??b.messageSessionIndex;let M=j;return p.forEach(k=>{const D=k?.info?.id;typeof D=="string"&&D.length>0&&(M=Rn(M,D,s))}),M!==j&&(C.messageSessionIndex=M),C})},evictLeastRecentlyUsed:s=>{const n=r();if(n.messages.size<=Ar.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 l=a.filter(([d,u])=>d!==s&&!u.isStreaming);if(l.length===0)return;l.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const c=l[0][0];t(d=>{const m=(d.messages.get(c)||[]).map(C=>C.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(c);const h={messages:f,sessionMemoryState:p},x=new Map(d.pendingAssistantParts);let g=!1;x.forEach((C,v)=>{C.sessionId===c&&(x.delete(v),g=!0)}),g&&(h.pendingAssistantParts=x);const b=new Map(d.sessionCompactionUntil);b.delete(c)&&(h.sessionCompactionUntil=b),rn(m);const y=fo(d.messageStreamStates,m);y!==d.messageStreamStates&&(h.messageStreamStates=y);const w=Jo(h.messageSessionIndex??d.messageSessionIndex,m);w!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=w);const S=gr(d.streamingMessageIds,c,null);if(S!==d.streamingMessageIds&&(h.streamingMessageIds=S),d.abortControllers.has(c)){const C=new Map(d.abortControllers);C.delete(c),h.abortControllers=C}return h})},loadMoreMessages:async(s,n="up")=>{const o=r(),a=o.messages.get(s),l=o.sessionMemoryState.get(s);if(!a||!l||l.totalAvailableMessages&&a.length>=l.totalAvailableMessages)return;const c=await Ci(s,()=>Oe.getSessionMessages(s));if(n==="up"&&a.length>0){const d=Yo(c),u=a[0],m=d.findIndex(f=>f.info.id===u.info.id);if(m>0){const f=Math.min(Ar.VIEWPORT_MESSAGES,m),p=d.slice(m-f,m);t(h=>{const x=[...p,...a],g=Yo(x),b=Math.max(0,g.length-a.length),y=new Map(h.messages);y.set(s,g);const w=new Map(h.sessionMemoryState);return w.set(s,{...l,viewportAnchor:l.viewportAnchor+b,hasMoreAbove:m-f>0,totalAvailableMessages:d.length}),{messages:y,sessionMemoryState:w}})}else m===0&&t(f=>{const p=new Map(f.sessionMemoryState);return p.set(s,{...l,hasMoreAbove:!1,totalAvailableMessages:d.length}),{sessionMemoryState:p}})}},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 l=o[a];if(l.info.role==="assistant"&&"providerID"in l.info&&"modelID"in l.info)return{providerID:l.info.providerID,modelID:l.info.modelID}}return null}}),{name:"message-store",storage:qs(()=>ws()),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"})),nw=t=>typeof t=="object"&&t!==null,ow=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},aw=async(t,r)=>{try{const n=bt.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()},Io=rs()(fs(Gs((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 l=s.permission?.toLowerCase?.()??null;let c=n?.currentAgentContext?.get(o);if(c||(c=n?.sessionAgentSelections?.get(o)??void 0),!c&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(c=f.getState().currentAgentName??void 0)}const d=va(c),u=n?.getSessionAgentEditMode?.(o,c)??d;if((u==="allow"||u==="full")&&Gb(l)){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 aw(s,()=>Oe.replyToPermission(n,o)),o==="reject"&&await Dt.getState().abortCurrentOperation(s),t(a=>{const c=(a.permissions.get(s)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(s,c),{permissions:d}})}}),{name:"permission-store",storage:qs(()=>ws()),partialize:t=>({permissions:Array.from(t.permissions.entries())}),merge:(t,r)=>{if(!nw(t))return r;const s=ow(t.permissions);return{...r,permissions:new Map(s)}}}),{name:"permission-store"})),iw=t=>typeof t=="object"&&t!==null,lw=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},xd=async(t,r)=>{try{const n=bt.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()},Wn=rs()(fs(Gs((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 l=a.questions.get(n)||[],c=new Map(a.questions);return c.set(n,[...l,s]),{questions:c}})},dismissQuestion:(s,n)=>{!s||!n||t(o=>{const l=(o.questions.get(s)||[]).filter(d=>d.id!==n),c=new Map(o.questions);return c.set(s,l),{questions:c}})},respondToQuestion:async(s,n,o)=>{await xd(s,()=>Oe.replyToQuestion(n,o)),r().dismissQuestion(s,n)},rejectQuestion:async(s,n)=>{await xd(s,()=>Oe.rejectQuestion(n)),r().dismissQuestion(s,n)}}),{name:"question-store",storage:qs(()=>ws()),partialize:t=>({questions:Array.from(t.questions.entries())}),merge:(t,r)=>{if(!iw(t))return r;const s=lw(t.questions);return{...r,questions:new Map(s)}}}),{name:"question-store"})),Xl=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
- `),So=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},yd=(t,r,s)=>{if(!r)return null;const n=s(r)?.path;if(typeof n=="string"&&n.trim().length>0)return So(n);const o=t.find(a=>a.id===r);return o?So(o.directory??null):null},ge=rs()(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)=>nt.getState().getSessionAgentEditMode(s,n,o),toggleSessionAgentEditMode:(s,n,o)=>nt.getState().toggleSessionAgentEditMode(s,n,o),setSessionAgentEditMode:(s,n,o,a)=>nt.getState().setSessionAgentEditMode(s,n,o,a),loadSessions:()=>bt.getState().loadSessions(),openNewSessionDraft:s=>{let n=null;s?.directoryOverride!==void 0?n=s.directoryOverride:n=Wt.getState().getActiveProject()?.path??null,t({newSessionDraft:{open:!0,directoryOverride:n,parentID:s?.parentID??null,title:s?.title},currentSessionId:null,error:null});try{const o=et.getState(),a=o.getVisibleAgents();let l;if(o.settingsDefaultAgent){const c=a.find(d=>d.name===o.settingsDefaultAgent);c&&(l=c.name)}l||(l=a.find(c=>c.name==="build")?.name||a[0]?.name),l&&o.setAgent(l)}catch{}},closeNewSessionDraft:()=>{const s=bt.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 bt.getState().createSession(s,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async s=>{if(!s)return;const n=Dt.getState(),{messages:o,lastUsedProvider:a}=n;let l,c;if(o.forEach((y,w)=>{const S=y.find(C=>C.info?.id===s);S&&!l&&(l=S,c=w)}),!l||l.info.role!=="assistant")return;const d=Xl(l.parts);if(!d.trim())return;const u=bt.getState(),m=yd(u.sessions,c??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:x}=et.getState(),g=p||a?.providerID,b=h||a?.modelID;!g||!b||await Oe.sendMessage({id:f.id,providerID:g,modelID:b,text:d,prefaceText:kf,agent:x??void 0})},deleteSession:(s,n)=>bt.getState().deleteSession(s,n),deleteSessions:(s,n)=>bt.getState().deleteSessions(s,n),updateSessionTitle:(s,n)=>bt.getState().updateSessionTitle(s,n),shareSession:s=>bt.getState().shareSession(s),unshareSession:s=>bt.getState().unshareSession(s),setCurrentSession:async s=>{s&&r().closeNewSessionDraft();const n=bt.getState().currentSessionId,o=yd(bt.getState().sessions,s,bt.getState().getWorktreeMetadata),a=Oe.getDirectory()??wt.getState().currentDirectory??null,l=o??a;try{Oe.setDirectory(l??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}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,$a().VIEWPORT_MESSAGES)}if(bt.getState().setCurrentSession(s),s){r().messages.get(s)||await r().loadMessages(s),r().trimToViewportWindow(s,hl());const d=r().messages.get(s);if(d&&d.length>0){const u=et.getState().agents;if(u.length>0)try{await nt.getState().analyzeAndSaveExternalSessionChoices(s,u,r().messages)}catch(m){console.warn("Failed to analyze session choices:",m)}}}r().evictLeastRecentlyUsed()},loadMessages:(s,n)=>Dt.getState().loadMessages(s,n),sendMessage:async(s,n,o,a,l,c,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=w=>{t(S=>{const C=new Map(S.sessionActivityPhase??new Map);return C.set(w,"busy"),{sessionActivityPhase:C}})},h=w=>{t(S=>{const C=new Map(S.sessionActivityPhase??new Map);return C.set(w,"idle"),{sessionActivityPhase:C}})};if(m?.open){const w=await bt.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!w?.id)throw new Error("Failed to create session");const S=et.getState(),C=S.currentAgentName,v=f??C,j=S.currentProviderId,M=S.currentModelId;if(j&&M)try{nt.getState().saveSessionModelSelection(w.id,j,M)}catch{}if(v){try{nt.getState().saveSessionAgentSelection(w.id,v)}catch{}if(j&&M){try{nt.getState().saveAgentModelForSession(w.id,v,j,M)}catch{}if(u!==void 0)try{nt.getState().saveAgentModelVariantForSession(w.id,v,j,M,u)}catch{}}}try{bt.getState().initializeNewOpenChamberSession(w.id,S.agents)}catch{}r().closeNewSessionDraft(),p(w.id);try{return await Dt.getState().sendMessage(s,n,o,v,w.id,l,c,d,u)}catch(k){throw h(w.id),k}}const x=bt.getState().currentSessionId,g=x?nt.getState().getSessionAgentSelection(x):null,b=et.getState().currentAgentName,y=f||g||b||void 0;if(x&&y){try{nt.getState().saveSessionAgentSelection(x,y)}catch{}if(u!==void 0)try{nt.getState().saveAgentModelVariantForSession(x,y,n,o,u)}catch{}}x&&p(x);try{return await Dt.getState().sendMessage(s,n,o,y,x||void 0,l,c,d,u)}catch(w){throw x&&h(x),w}},abortCurrentOperation:()=>{const s=bt.getState().currentSessionId;return Dt.getState().abortCurrentOperation(s||void 0)},armAbortPrompt:(s=3e3)=>{const n=bt.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&&Dt.getState().acknowledgeSessionAbort(s)},addStreamingPart:(s,n,o,a)=>{const c=bt.getState().currentSessionId||s;return Dt.getState().addStreamingPart(s,n,o,a,c)},completeStreamingMessage:(s,n)=>Dt.getState().completeStreamingMessage(s,n),markMessageStreamSettled:s=>Dt.getState().markMessageStreamSettled(s),updateMessageInfo:(s,n,o)=>Dt.getState().updateMessageInfo(s,n,o),updateSessionCompaction:(s,n)=>Dt.getState().updateSessionCompaction(s,n??null),addPermission:s=>{const n={currentAgentContext:nt.getState().currentAgentContext,sessionAgentSelections:nt.getState().sessionAgentSelections,getSessionAgentEditMode:nt.getState().getSessionAgentEditMode};return Io.getState().addPermission(s,n)},respondToPermission:(s,n,o)=>Io.getState().respondToPermission(s,n,o),addQuestion:s=>Wn.getState().addQuestion(s),dismissQuestion:(s,n)=>Wn.getState().dismissQuestion(s,n),respondToQuestion:(s,n,o)=>Wn.getState().respondToQuestion(s,n,o),rejectQuestion:(s,n)=>Wn.getState().rejectQuestion(s,n),clearError:()=>bt.getState().clearError(),getSessionsByDirectory:s=>bt.getState().getSessionsByDirectory(s),getDirectoryForSession:s=>bt.getState().getDirectoryForSession(s),getLastMessageModel:s=>Dt.getState().getLastMessageModel(s),getCurrentAgent:s=>nt.getState().getCurrentAgent(s),syncMessages:(s,n)=>Dt.getState().syncMessages(s,n),applySessionMetadata:(s,n)=>bt.getState().applySessionMetadata(s,n),addAttachedFile:s=>mr.getState().addAttachedFile(s),addServerFile:(s,n,o)=>mr.getState().addServerFile(s,n,o),removeAttachedFile:s=>mr.getState().removeAttachedFile(s),clearAttachedFiles:()=>mr.getState().clearAttachedFiles(),updateViewportAnchor:(s,n)=>Dt.getState().updateViewportAnchor(s,n),trimToViewportWindow:(s,n)=>{const o=bt.getState().currentSessionId,a=r().sessionActivityPhase?.get(s);if(!(a==="busy"||a==="cooldown"))return Dt.getState().trimToViewportWindow(s,n,o||void 0)},evictLeastRecentlyUsed:()=>{const s=bt.getState().currentSessionId;return Dt.getState().evictLeastRecentlyUsed(s||void 0)},loadMoreMessages:(s,n)=>Dt.getState().loadMoreMessages(s,n),saveSessionModelSelection:(s,n,o)=>nt.getState().saveSessionModelSelection(s,n,o),getSessionModelSelection:s=>nt.getState().getSessionModelSelection(s),saveSessionAgentSelection:(s,n)=>nt.getState().saveSessionAgentSelection(s,n),getSessionAgentSelection:s=>nt.getState().getSessionAgentSelection(s),saveAgentModelForSession:(s,n,o,a)=>nt.getState().saveAgentModelForSession(s,n,o,a),getAgentModelForSession:(s,n)=>nt.getState().getAgentModelForSession(s,n),saveAgentModelVariantForSession:(s,n,o,a,l)=>nt.getState().saveAgentModelVariantForSession(s,n,o,a,l),getAgentModelVariantForSession:(s,n,o,a)=>nt.getState().getAgentModelVariantForSession(s,n,o,a),analyzeAndSaveExternalSessionChoices:(s,n)=>{const o=Dt.getState().messages;return nt.getState().analyzeAndSaveExternalSessionChoices(s,n,o)},isOpenChamberCreatedSession:s=>bt.getState().isOpenChamberCreatedSession(s),markSessionAsOpenChamberCreated:s=>bt.getState().markSessionAsOpenChamberCreated(s),initializeNewOpenChamberSession:(s,n)=>bt.getState().initializeNewOpenChamberSession(s,n),setWorktreeMetadata:(s,n)=>bt.getState().setWorktreeMetadata(s,n),setSessionDirectory:(s,n)=>bt.getState().setSessionDirectory(s,n),getWorktreeMetadata:s=>bt.getState().getWorktreeMetadata(s),getContextUsage:(s,n)=>{if(r().newSessionDraft?.open)return null;const o=bt.getState().currentSessionId;if(!o)return null;const a=Dt.getState().messages;return nt.getState().getContextUsage(o,s,n,a)},updateSessionContextUsage:(s,n,o)=>{const a=Dt.getState().messages;return nt.getState().updateSessionContextUsage(s,n,o,a)},initializeSessionContextUsage:(s,n,o)=>{const a=Dt.getState().messages;return nt.getState().initializeSessionContextUsage(s,n,o,a)},debugSessionMessages:async s=>{const n=Dt.getState().messages.get(s)||[],o=bt.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=Dt.getState().messages;return nt.getState().pollForTokenUpdates(s,n,a,o)},updateSession:s=>bt.getState().updateSession(s),removeSessionFromStore:s=>bt.getState().removeSessionFromStore(s),revertToMessage:async(s,n)=>{const a=(Dt.getState().messages.get(s)||[]).find(m=>m.info.id===n);let l="";a&&a.info.role==="user"&&(l=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
11
- `).trim());const c=await Oe.revertSession(s,n);bt.getState().updateSession(c);const d=Dt.getState().messages.get(s)||[],u=c.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);Dt.getState().syncMessages(s,f)}}l&&t({pendingInputText:l})},handleSlashUndo:async s=>{const o=(r().messages.get(s)||[]).filter(p=>p.info.role==="user"),l=r().sessions.find(p=>p.id===s);if(o.length===0)return;const c=l?.revert?.messageID;let d;if(c){const p=o.findIndex(h=>h.info.id===c);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 Ss(async()=>{const{toast:p}=await import("./vendor-.bun-koHRsLHN.js").then(h=>h.df);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 c=(r().messages.get(s)||[]).filter(m=>m.info.role==="user"),d=c.findIndex(m=>m.info.id===a),u=c[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 Ss(async()=>{const{toast:h}=await import("./vendor-.bun-koHRsLHN.js").then(x=>x.df);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await Oe.unrevertSession(s);await bt.getState().updateSession(m),await r().loadMessages(s);const{toast:f}=await Ss(async()=>{const{toast:p}=await import("./vendor-.bun-koHRsLHN.js").then(h=>h.df);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(s,n)=>{const a=r().sessions.find(l=>l.id===s);if(a)try{const l=await Oe.forkSession(s,n);if(!l||!l.id){const{toast:f}=await Ss(async()=>{const{toast:p}=await import("./vendor-.bun-koHRsLHN.js").then(h=>h.df);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 Ss(async()=>{const{toast:p}=await import("./vendor-.bun-koHRsLHN.js").then(h=>h.df);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(l.id),u&&t({pendingInputText:u}),await r().loadMessages(l.id);const{toast:m}=await Ss(async()=>{const{toast:f}=await import("./vendor-.bun-koHRsLHN.js").then(p=>p.df);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(l){console.error("Failed to fork session:",l);const{toast:c}=await Ss(async()=>{const{toast:d}=await import("./vendor-.bun-koHRsLHN.js").then(u=>u.df);return{toast:d}},__vite__mapDeps([0,1]));c.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"}));bt.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=ge.getState().newSessionDraft?.open;ge.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})});Dt.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 l=n[a];if(!l||!l.info)continue;const c=l.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=c.time&&typeof c.time.created=="number"?c.time.created:null;s.set(o,{title:u,createdAt:m});break}}}}}),ge.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})});mr.subscribe((t,r)=>{t.attachedFiles!==r.attachedFiles&&ge.setState({attachedFiles:t.attachedFiles})});nt.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||ge.setState({sessionModelSelections:t.sessionModelSelections,sessionAgentSelections:t.sessionAgentSelections,sessionAgentModelSelections:t.sessionAgentModelSelections,currentAgentContext:t.currentAgentContext,sessionContextUsage:t.sessionContextUsage,sessionAgentEditModes:t.sessionAgentEditModes})});Io.subscribe((t,r)=>{t.permissions!==r.permissions&&ge.setState({permissions:t.permissions})});Wn.subscribe((t,r)=>{t.questions!==r.questions&&ge.setState({questions:t.questions})});wt.subscribe((t,r)=>{const s=So(t.currentDirectory??null),n=So(r.currentDirectory??null);if(s===n)return;const o=ge.getState().newSessionDraft;if(!o?.open)return;const a=So(o.directoryOverride);a&&a!==n||ge.setState(l=>({newSessionDraft:{...l.newSessionDraft,directoryOverride:s,parentID:null}}))});const cw=ge.getState().newSessionDraft?.open;ge.setState({sessions:bt.getState().sessions,currentSessionId:cw?null:bt.getState().currentSessionId,lastLoadedDirectory:bt.getState().lastLoadedDirectory,isLoading:bt.getState().isLoading,error:bt.getState().error,webUICreatedSessions:bt.getState().webUICreatedSessions,worktreeMetadata:bt.getState().worktreeMetadata,availableWorktrees:bt.getState().availableWorktrees,availableWorktreesByProject:bt.getState().availableWorktreesByProject,messages:Dt.getState().messages,sessionMemoryState:Dt.getState().sessionMemoryState,messageStreamStates:Dt.getState().messageStreamStates,sessionCompactionUntil:Dt.getState().sessionCompactionUntil,sessionAbortFlags:Dt.getState().sessionAbortFlags,streamingMessageIds:Dt.getState().streamingMessageIds,abortControllers:Dt.getState().abortControllers,lastUsedProvider:Dt.getState().lastUsedProvider,isSyncing:Dt.getState().isSyncing,permissions:Io.getState().permissions,questions:Wn.getState().questions,attachedFiles:mr.getState().attachedFiles,sessionModelSelections:nt.getState().sessionModelSelections,sessionAgentSelections:nt.getState().sessionAgentSelections,sessionAgentModelSelections:nt.getState().sessionAgentModelSelections,currentAgentContext:nt.getState().currentAgentContext,sessionContextUsage:nt.getState().sessionContextUsage,sessionAgentEditModes:nt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=ge);const dw=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},_s=rs((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 l=await dw(s);return t({status:l,isLoading:!1,hasChecked:!0}),l}catch(l){const c=l instanceof Error?l.message:String(l);return t({status:{connected:!1,error:c},isLoading:!1,hasChecked:!0}),null}}})),Zl=i.createContext(null),Bs=()=>{const t=i.useContext(Zl);if(!t)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return t},Mf=t=>{const r=Bs();return t(r)},uw=()=>Mf(t=>t.runtime.isDesktop),Df=()=>Mf(t=>t.runtime.isVSCode),ec=({containerRef:t,minThumbSize:r=32,hideDelayMs:s=1e3,className:n,disableHorizontal:o=!1})=>{const[a,l]=i.useState(!1),[c,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),x=i.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),g=i.useRef(null),b=i.useCallback(()=>{const D=t.current;if(!D)return;const{scrollHeight:N,clientHeight:T,scrollTop:A,scrollWidth:E,clientWidth:I,scrollLeft:P}=D,F=8;if(N>T){const $=Math.max(T-F*2,0),Q=T/N*$,ie=Math.max(r,Math.min($,Q)),K=Math.max($-ie,0),ee=Math.max(N-T,1),V=A/ee*K;d({length:ie,offset:V})}else d({length:0,offset:0});if(!o&&E>I){const $=Math.max(I-F*2,0),Q=I/E*$,ie=Math.max(r,Math.min($,Q)),K=Math.max($-ie,0),ee=Math.max(E-I,1),V=P/ee*K;m({length:ie,offset:V})}else m({length:0,offset:0})},[t,r,o]),y=i.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),s)},[s]),w=i.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{b(),l(!0),y()})},[y,b]);i.useEffect(()=>{const D=t.current;if(!D)return;b(),l(!0),y(),D.addEventListener("scroll",w,{passive:!0});const N=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null;N?.observe(D);const T=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return T?.observe(D,{childList:!0,subtree:!0,characterData:!0}),()=>{D.removeEventListener("scroll",w),N?.disconnect(),T?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[t,w,y,b]);const S=(D,N)=>{const T=t.current;T&&(h.current=!0,x.current={pointerX:D.clientX,pointerY:D.clientY,scrollTop:T.scrollTop,scrollLeft:T.scrollLeft},g.current=N,l(!0),f.current&&clearTimeout(f.current),D.currentTarget.setPointerCapture(D.pointerId))},C=D=>{if(!h.current)return;const N=t.current;if(!N)return;const T=g.current;if(T==="vertical"){const{pointerY:A,scrollTop:E}=x.current,I=D.clientY-A,P=N.clientHeight,F=Math.max(P-c.length,1),$=Math.max(N.scrollHeight-N.clientHeight,1),Q=I/F*$;N.scrollTop=E+Q}else if(T==="horizontal"){const{pointerX:A,scrollLeft:E}=x.current,I=D.clientX-A,P=N.clientWidth,F=Math.max(P-u.length,1),$=Math.max(N.scrollWidth-N.clientWidth,1),Q=I/F*$;N.scrollLeft=E+Q}},v=D=>{h.current&&(h.current=!1,D.currentTarget.releasePointerCapture(D.pointerId),y())},j=c.length>0,M=u.length>0;if(!j&&!M)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:`${c.length}px`,top:`${k+c.offset}px`,right:`${k/2}px`},onPointerDown:D=>S(D,"vertical"),onPointerMove:C,onPointerUp:v,onPointerCancel:v}),M&&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:D=>S(D,"horizontal"),onPointerMove:C,onPointerUp:v,onPointerCancel:v})]})},jt=i.forwardRef(({className:t,outerClassName:r,children:s,style:n,minThumbSize:o,hideDelayMs:a,as:l="div",scrollbarClassName:c,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(l,{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(ec,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});jt.displayName="ScrollableOverlay";const bd="mobile-overlay-root",mw=()=>{if(typeof document>"u")return null;let t=document.getElementById(bd);return t||(t=document.createElement("div"),t.id=bd,document.body.appendChild(t)),t},zs=({open:t,title:r,onClose:s,children:n,footer:o,className:a,contentMaxHeightClassName:l,renderHeader:c})=>{const d=i.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=mw()),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=l??"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(os,{className:"h-4 w-4"})});return c?c(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(jt,{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 fm.createPortal(m,d.current)},xl=({totalTokens:t,percentage:r,contextLimit:s,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[l,c]=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(()=>{c(!0)},500)},[]),x=i.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);i.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=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?x:void 0,children:[!a&&e.jsx(Ch,{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:[g,e.jsx(zs,{open:l,onClose:()=>c(!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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:g}),e.jsx(ft,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(b=>e.jsx("p",{className:"typography-micro leading-tight",children:b},b))})})]})},go={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Af=(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 Mi(){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,l=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||l>0,u=t>go.md&&t<=go.lg,m=t<=go.md;let f=d&&m,p=d&&!f&&u,h=!d||t>go.lg,x="desktop";c?(f=!1,p=!1,h=!0,x="desktop"):f?x="mobile":p?x="tablet":(h=!0,x="desktop"),Af(c,x,d);let g="xs";for(const[b,y]of Object.entries(go))t>=y&&(g=b);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:x,screenWidth:t,breakpoint:g,hasTouchInput:d}}function Kt(){const[t,r]=i.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Mi());return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(Mi())};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(Mi())},a=[],l=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return l(s),l(n),()=>{a.forEach(c=>c())}},[]),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,l=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=l||c||d>0;Af(s,t.deviceType,u)},[t.deviceType,t.hasTouchInput]),t}const Xo=5e3,fw=1e4,pw=5e3,hw=1e4,gw=25,xw=4,wd=15e3,xr=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),yw=(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},bw=(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!!yw(t.diffStats,r.diffStats)},ww=(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])),l=new Map(o.map(f=>[f.path,f])),c=new Set([...a.keys(),...l.keys()]);for(const f of c){const p=a.get(f),h=l.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},ls=rs()(fs((t,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:Xo,setActiveDirectory:s=>{const{activeDirectory:n,directories:o}=r();if(n!==s)if(s&&!o.has(s)){const a=new Map(o);a.set(s,xr()),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:l}=r();let c=l.get(s);c||(c=xr()),a||t({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(s)){const f=new Map(l);return f.set(s,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),t({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(s);if(bw(c.status,m)){d=!0;const f=new Map(r().directories),p=f.get(s)??xr(),h=ww(p.status,m),x=new Set((p.status?.files??[]).map(w=>w.path)),g=new Set((m.files??[]).map(w=>w.path)),b=new Map(p.diffCache);for(const w of x)g.has(w)||b.delete(w);for(const w of h)b.delete(w);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)??xr();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),l=a.get(s)??xr();a.set(s,{...l,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(),l=a.get(s),c=o??l?.logMaxCount??25;t({isLoadingLog:!0});try{const d=await n.getGitLog(s,{maxCount:c}),u=new Map(r().directories),m=u.get(s)??xr();u.set(s,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:c}),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),l=a.get(s)??xr();a.set(s,{...l,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 l=a.get(s);if(!l){l=xr();const f=new Map(a);f.set(s,l),t({directories:f})}const{force:c=!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);(c||m>hw||!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),l=a.get(s)??xr(),c=new Map(l.diffCache);c.set(n,{...o,fetchedAt:Date.now()}),a.set(s,{...l,diffCache:c}),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 c=o.status.files.filter(w=>!o.diffCache.has(w.path)).slice(0,gw);if(c.length===0)return;let d=0;const u=[],m=()=>{const w=d;return d+=1,w<c.length?c[w]:null},f=async w=>{const S=n.getGitFileDiff(s,{path:w}),C=new Promise((j,M)=>{setTimeout(()=>M(new Error(`Timed out after ${wd}ms`)),wd)}),v=await Promise.race([S,C]);return{path:w,diff:{original:v.original??"",modified:v.modified??""}}},p=async()=>{for(;;){const w=m();if(!w)return;try{u.push(await f(w.path))}catch{}}},h=Math.min(xw,c.length);await Promise.allSettled(Array.from({length:h},()=>p()));const x=new Map(r().directories),g=x.get(s);if(!g)return;const b=new Map(g.diffCache),y=Date.now();u.forEach(w=>{b.set(w.path,{...w.diff,fetchedAt:y})}),x.set(s,{...g,diffCache:b}),t({directories:x})},setLogMaxCount:(s,n)=>{const o=new Map(r().directories),a=o.get(s)??xr();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:c}=r();if(!c){t({pollIntervalId:o()});return}if(await r().fetchStatus(c,s,{silent:!0}))await r().fetchLog(c,s),r().fetchAllDiffs(c,s),t({currentPollInterval:Xo});else{const m=Math.min(a+pw,fw);t({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&t({pollIntervalId:o()})},a)};t({pollIntervalId:o(),currentPollInterval:Xo})},stopPolling:()=>{const{pollIntervalId:s}=r();s&&(clearTimeout(s),t({pollIntervalId:null,currentPollInterval:Xo}))},refresh:async(s,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,s,n)}}),{name:"git-store"})),Ef=t=>ls(r=>t?r.directories.get(t)?.status??null:null),If=t=>ls(r=>t?r.directories.get(t)?.branches??null:null),vw=t=>ls(r=>t?r.directories.get(t)?.log??null:null),jw=t=>ls(r=>t?r.directories.get(t)?.identity??null:null),tc=t=>ls(r=>t?r.directories.get(t)?.isGitRepo??null:null),Sw=t=>ls(r=>t?r.directories.get(t)?.status?.files?.length??0:0),Nw=Mh("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?pm:"button";return e.jsx(a,{"data-slot":"button",className:R(Nw({variant:r,size:s,className:t})),...o})}const co=Dh,$o=({className:t,...r})=>e.jsx(Ah,{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}),uo=({className:t,...r})=>e.jsx(Eh,{className:R("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",t),...r}),kw={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 sc(t){return kw[t]||{displayName:t.charAt(0).toUpperCase()+t.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Cw(t,r,s){const n=sc(t);if(n.outputLanguage==="auto"){if(s?.filePath||s?.file_path||s?.sourcePath){const o=s.filePath||s.file_path||s.sourcePath,a=Cr(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 Cr(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 Mw=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function Po(t){const r=t.split(".").pop()?.toLowerCase();return Mw.includes(r||"")}function yl(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 Dw(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 l=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${l}: ${c}`}).join(`
12
- `):String(t)}const Pf=({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(Ih,{className:"h-3 w-3"}):e.jsx(Ph,{className:"h-3 w-3"})})},rc=_e.createContext(void 0);function Br(){const t=_e.useContext(rc);if(!t)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return t}function li(){return _e.useContext(rc)}const Aw="Flexoki",Ew="dark",Iw={"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"},Pw=[{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"}}],Tw={name:Aw,type:Ew,colors:Iw,tokenColors:Pw},Fw="Flexoki",Rw="light",Lw={"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"},Ow=[{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"}}],$w={name:Fw,type:Rw,colors:Lw,tokenColors:Ow},nc="flexoki-dark",oc="flexoki-light",_w=Tw,Bw=$w;function Tf(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 Ff(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 ac=Ff(_w,nc,"dark"),ic=Ff(Bw,oc,"light");Tf(ac,nc);Tf(ic,oc);const to={dark:nc,light:oc},vd=[ic,ac];let jd=!1;function Rf(){jd||(Dc(to.dark,async()=>ac),Dc(to.light,async()=>ic),jd=!0)}const Di=({...t})=>{const{theme:r="system"}=Th();return e.jsx(Fh,{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})},Sd=async t=>{try{await navigator.clipboard.writeText(t)}catch(r){console.error("Failed to copy to clipboard:",r)}},W={...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:()=>Sd(String(t))}}),warning:(t,r)=>Ys.warning(t,{...r,action:r?.action||{label:"Copy",onClick:()=>Sd(String(t))}})},Rs=_e.forwardRef(({className:t,...r},s)=>e.jsx(jt,{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}));Rs.displayName="Textarea";const zw=`
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 Hw(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 Ww=(t,r,s)=>{const a=(s.side==="deletions"?t:r).split(`
75
- `),l=Math.max(1,s.start),c=Math.min(a.length,s.end);return l>c?"":a.slice(l-1,c).join(`
76
- `)},bl=({original:t,modified:r,language:s,fileName:n="file",renderSideBySide:o,wrapLines:a=!1,layout:l="fill"})=>{const{isMobile:c}=Kt(),{inputBarOffset:d,isKeyboardOpen:u}=je(),f=li()?.currentTheme?.metadata?.variant==="dark",p=je(ee=>ee.setActiveMainTab),[h,x]=_e.useState(null),[g,b]=_e.useState(""),y=_e.useRef(null),w=_e.useCallback(()=>{if(c)return"50%";const ee=document.querySelector("main.flex-1");if(ee){const V=ee.getBoundingClientRect();return`${V.left+V.width/2}px`}return"50%"},[c]),[S,C]=_e.useState(w),v=ge(ee=>ee.sendMessage),j=ge(ee=>ee.currentSessionId),{currentProviderId:M,currentModelId:k,currentAgentName:D,currentVariant:N}=et(),T=nt(ee=>ee.getSessionAgentSelection),A=nt(ee=>ee.getAgentModelForSession),E=nt(ee=>ee.getAgentModelVariantForSession);_e.useEffect(()=>{if(c)return;const ee=()=>{C(w())};return window.addEventListener("resize",ee),()=>window.removeEventListener("resize",ee)},[c,w]);const I=_e.useCallback(ee=>{if(c&&ee&&h&&ee.start===ee.end){const V=ee.start,ae=h.start,G=h.end,q=Math.min(ae,G,V),_=Math.max(ae,G,V);if(V<ae||V>G){x({...ee,start:q,end:_});return}}x(ee),ee||b("")},[c,h]);_e.useEffect(()=>{if(!h)return;const ee=ae=>{const G=ae.target;if(y.current?.contains(G)||G.closest("[data-sonner-toast]")||G.closest("[data-sonner-toaster]"))return;ae.composedPath().some(H=>H instanceof HTMLElement?H.hasAttribute("data-line-number")||H.closest?.("[data-line-number]"):!1)||(x(null),b(""))},V=setTimeout(()=>{document.addEventListener("click",ee)},100);return()=>{clearTimeout(V),document.removeEventListener("click",ee)}},[h]);const P=_e.useCallback(async()=>{if(!h||!g.trim())return;if(!j){W.error("Select a session to send comment");return}const ee=T(j)||D,V=ee?A(j,ee):null,ae=V?.providerId||M,G=V?.modelId||k;if(!ae||!G){W.error("Select a model to send comment");return}const q=ee&&ae&&G?E(j,ee,ae,G)??N:N,_=Ww(t,r,h),H=h.start,L=h.end,B=h.side==="deletions"?"original":"modified",O=`Comment on \`${n}\` lines ${H}-${L} (${B}):
77
- \`\`\`${s}
78
- ${_}
79
- \`\`\`
80
-
81
- ${g}`;b(""),x(null),p("chat"),v(O,ae,G,ee,void 0,void 0,void 0,q).catch(le=>{console.error("Failed to send comment",le)})},[h,g,t,r,n,s,v,j,M,k,D,N,p,T,A,E]);Rf();const F=_e.useRef(null),$=_e.useMemo(()=>{const ee=Hw(n,t,r);if(F.current?.key===ee)return F.current.fileDiff;const V={name:n,contents:t,cacheKey:`old-${ee}`},ae={name:n,contents:r,cacheKey:`new-${ee}`},G=sl(V,ae);return F.current={key:ee,fileDiff:G},G},[n,t,r,s]),Q=_e.useMemo(()=>({theme:{dark:to.dark,light:to.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:I,unsafeCSS:zw}),[f,o,a,I]);if(typeof window>"u")return null;const K=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(Rs,{value:g,onChange:ee=>{b(ee.target.value);const V=ee.target;V.style.height="auto";const G=20*5+8;V.style.height=`${Math.min(V.scrollHeight,G)}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:!c,rows:1,onKeyDown:ee=>{ee.key==="Enter"&&(ee.metaKey||ee.ctrlKey)&&(ee.preventDefault(),P()),ee.key==="Escape"&&(ee.preventDefault(),x(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:[!c&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Zt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:ee=>{g.trim()&&(ee.preventDefault(),P())},onClick:()=>{c||P()},disabled:!g.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",g.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Fo,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return l==="fill"?e.jsxs("div",{className:R("flex flex-col relative","size-full"),style:{paddingBottom:c?"var(--oc-keyboard-inset, 0px)":void 0},children:[e.jsx("div",{className:"flex-1 relative min-h-0",children:e.jsx(jt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,children:e.jsx(Ac,{fileDiff:$,options:Q,selectedLines:h})})}),h&&e.jsx("div",{className:R("pointer-events-auto relative pb-2 transition-none z-50 flex justify-center",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:K})]}):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(Ac,{fileDiff:$,options:Q,selectedLines:h})}),h&&fm.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:c?"var(--oc-keyboard-inset, 0px)":"0px",isolation:"isolate"},children:e.jsx("div",{className:R("pointer-events-auto relative pb-2 transition-none",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginLeft:S,transform:"translateX(-50%)",marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:K})}),document.body)]})},Uw=1100,Lf=15e3,Of={"?":{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"}},Vw=Of.M,ja=[{value:"single",label:"Single file",description:"Show one file at a time"},{value:"stacked",label:"All files",description:"Stack all modified files together"}],Gw=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"},$f=t=>{const r=Gw(t);return Of[r]??Vw},qw=t=>{const{index:r,working_dir:s}=t;return r==="A"||s==="A"||r==="?"||s==="?"},Ha=(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]})},Kw=i.memo(({changedFiles:t,selectedFile:r,selectedFileEntry:s,onSelectFile:n,isMobile:o,showModeSelector:a=!1,mode:l,onModeChange:c})=>{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(es,{children:[e.jsx(ts,{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)}),Ha(s.insertions,s.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Gt,{className:"size-4 opacity-50"})]})}),e.jsxs(ss,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:[a&&l&&c?e.jsxs(e.Fragment,{children:[e.jsx(Pr,{className:"typography-meta text-muted-foreground",children:"View mode"}),e.jsx(Pa,{value:l,onValueChange:u=>c(u),children:ja.map(u=>e.jsx(Ta,{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(Pa,{value:r??"",onValueChange:n,children:t.map(u=>e.jsx(Ta,{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:Ha(u.insertions,u.deletions)})]})},u.path))})]})]})}),Qw=i.memo(({mode:t,onModeChange:r})=>{const s=ja.find(n=>n.value===t)??ja[0];return e.jsxs(es,{children:[e.jsx(ts,{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(Gt,{className:"size-4 opacity-50"})]})}),e.jsx(ss,{className:"min-w-[220px]",children:e.jsx(Pa,{value:t,onValueChange:n=>r(n),children:ja.map(n=>e.jsx(Ta,{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))})})]})}),Yw=i.memo(({changedFiles:t,selectedFile:r,onSelectFile:s})=>t.length===0?null:e.jsx(jt,{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=$f(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}),Ha(n.insertions,n.deletions)]})},n.path)})})})),Jw=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 l=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",c=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:l,children:[o&&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:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:c,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"}})]})]})})}),Xw=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",l=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: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:s?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),o&&e.jsxs("div",{className:l,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"}})]})]})})}),Zw=i.memo(({filePath:t,diff:r,renderSideBySide:s,wrapLines:n})=>{const o=i.useMemo(()=>Cr(t)||"text",[t]);return Po(t)?e.jsx(Xw,{filePath:t,diff:r,renderSideBySide:s}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(bl,{original:r.original,modified:r.modified,language:o,fileName:t,renderSideBySide:s,wrapLines:n,layout:"inline"})})}),ev=i.memo(({filePath:t,diff:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=i.useMemo(()=>Cr(t)||"text",[t]);return Po(t)?e.jsx(Jw,{filePath:t,diff:r,isVisible:s,renderSideBySide:n}):s?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(bl,{original:r.original,modified:r.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})}):e.jsx("div",{className:"absolute inset-0 hidden",children:e.jsx(bl,{original:r.original,modified:r.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})})}),tv=i.memo(({directory:t,filePath:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=ls(i.useCallback(c=>c.directories.get(t)?.diffCache.get(r)??null,[t,r])),l=i.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return l?e.jsx(ev,{filePath:r,diff:l,isVisible:s,renderSideBySide:n,wrapLines:o}):null}),sv=i.memo(({directory:t,file:r,layout:s,wrapLines:n,scrollRootRef:o,isSelected:a,onSelect:l,registerSectionRef:c})=>{const{git:d}=Bs(),u=ls(i.useCallback(I=>I.directories.get(t)?.diffCache.get(r.path)??null,[t,r.path])),m=ls(I=>I.setDiff),f=je(I=>I.setDiffFileLayout),[p,h]=i.useState(!0),[x,g]=i.useState(!1),[b,y]=i.useState(0),[w,S]=i.useState(null),[C,v]=i.useState(!1),j=i.useRef(null),M=i.useRef(null),k=i.useMemo(()=>$f(r),[r]),D=s==="side-by-side",N=i.useMemo(()=>u?{original:u.original,modified:u.modified}:null,[u]),T=i.useCallback(I=>{M.current=I,c(r.path,I)},[r.path,c]),A=i.useCallback(I=>{h(I),I&&g(!0)},[]),E=i.useCallback(()=>{l(r.path)},[r.path,l]);return i.useEffect(()=>{if(!p||x)return;const I=M.current;if(!I)return;if(!o.current||typeof IntersectionObserver>"u"){g(!0);return}const P=new IntersectionObserver(F=>{F.some($=>$.isIntersecting)&&(g(!0),P.disconnect())},{root:o.current,rootMargin:"200px 0px",threshold:.1});return P.observe(I),()=>P.disconnect()},[x,p,o]),i.useEffect(()=>{if(!p||!x)return;if(!t||N){j.current=null,v(!1);return}const I=`${t}::${r.path}::${b}`;if(j.current===I)return;j.current=I,S(null),v(!0);let P=!1;return(async()=>{try{const F=d.getGitFileDiff(t,{path:r.path}),$=Lf,Q=new Promise((K,ee)=>{setTimeout(()=>ee(new Error(`Timed out after ${$}ms`)),$)}),ie=await Promise.race([F,Q]);if(P)return;m(t,r.path,{original:ie.original??"",modified:ie.modified??""}),v(!1)}catch(F){if(P)return;const $=F instanceof Error?F.message:String(F);S($),v(!1)}})(),()=>{P=!0,j.current===I&&(j.current=null)}},[t,N,b,r.path,d,x,p,m]),e.jsx("div",{ref:T,className:"scroll-mt-4",children:e.jsxs(co,{open:p,onOpenChange:A,className:"group/collapsible",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background",children:e.jsxs($o,{onClick:E,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",p?"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:p?e.jsx(Gt,{className:"size-4"}):e.jsx(Hs,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:k.color},title:k.description,"aria-label":k.description,children:k.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:[Ha(r.insertions,r.deletions),e.jsx(Pf,{mode:D?"side-by-side":"unified",onModeChange:I=>{const P=I==="side-by-side"?"side-by-side":"inline";f(r.path,P)},className:"opacity-70"})]})]})}),e.jsx(uo,{children:e.jsxs("div",{className:"relative border border-t-0 border-border/60 bg-background rounded-b-xl overflow-hidden",children:[w?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:w}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>y(I=>I+1),children:"Retry"})]}):null,C&&!N&&!w?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(Tt,{size:16,className:"animate-spin"}),"Loading diff…"]}):null,N?e.jsx(Zw,{filePath:r.path,diff:N,renderSideBySide:D,wrapLines:n}):null]})})]})})}),rv=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=ge(),{currentDirectory:n}=wt(),o=t?s.get(t)??void 0:void 0,l=r.find(c=>c.id===t)?.directory;return o?.path??l??n??void 0},nv=()=>{const{git:t}=Bs(),r=rv(),{screenWidth:s,isMobile:n}=Kt(),o=tc(r??null),a=Ef(r??null),l=ls(z=>z.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=ls(),[m,f]=i.useState(null),[p,h]=i.useState(0),[x,g]=i.useState(null),b=i.useRef(null),y=je(z=>z.pendingDiffFile),w=je(z=>z.setPendingDiffFile),S=je(z=>z.diffLayoutPreference),C=je(z=>z.diffFileLayout),v=je(z=>z.setDiffFileLayout),j=je(z=>z.diffWrapLines),M=je(z=>z.setDiffWrapLines),k=je(z=>z.diffViewMode),D=je(z=>z.setDiffViewMode),N=n||j,T=k==="stacked",A=n||s<=768,E=!A&&s>=1024,I=i.useRef(null),P=i.useRef(new Map),F=i.useRef(null),$=i.useMemo(()=>{if(!a?.files)return[];const z=a.diffStats??{};return a.files.map(he=>({...he,insertions:z[he.path]?.insertions??0,deletions:z[he.path]?.deletions??0,isNew:qw(he)})).sort((he,Z)=>he.path.localeCompare(Z.path))},[a]),Q=i.useMemo(()=>m?$.find(z=>z.path===m)??null:null,[$,m]),ie=i.useCallback(z=>{const he=C[z.path];if(he)return he;if(S==="inline")return"inline";if(S==="side-by-side")return"side-by-side";const Z=s<Uw;return z.isNew||Z?"inline":"side-by-side"},[C,S,s]),K=i.useMemo(()=>Q?ie(Q):null,[ie,Q]);i.useEffect(()=>{r&&(c(r),ls.getState().directories.get(r)?.status||d(r,t))},[r,c,d,t]),i.useEffect(()=>{y&&(f(y),w(null),T&&(F.current=y))},[T,y,w]),i.useEffect(()=>{!m&&!y&&$.length>0&&f($[0].path)},[$,m,y]),i.useEffect(()=>{if(!T){F.current=null;return}const z=F.current;if(!z)return;const he=P.current.get(z);he&&(he.scrollIntoView({behavior:"smooth",block:"start"}),F.current=null)},[$,T]),i.useEffect(()=>{m&&$.length>0&&($.some(he=>he.path===m)||f($[0]?.path??null))},[$,m]);const ee=i.useCallback((z,he)=>{const Z=P.current;he?Z.set(z,he):Z.delete(z)},[]),V=i.useCallback((z,he="smooth")=>{const Z=P.current.get(z);return Z?(Z.scrollIntoView({behavior:he,block:"start"}),!0):!1},[]),ae=i.useCallback(z=>{f(z)},[]),G=i.useCallback(z=>{f(z),T&&!V(z)&&(F.current=z)},[T,V]),q=i.useCallback(z=>{D(z),z==="stacked"&&m&&!V(m,"auto")&&(F.current=m)},[V,m,D]),_=i.useCallback(z=>{const he=z==="side-by-side"?"side-by-side":"inline";if(T){$.forEach(Z=>{v(Z.path,he)});return}Q&&v(Q.path,he)},[$,T,Q,v]),H=(K??"side-by-side")==="side-by-side",L=!T||!E,B=ls(i.useCallback(z=>!r||!m?null:z.directories.get(r)?.diffCache.get(m)??null,[r,m])),O=!!B,le=!T&&!!m&&!O;i.useEffect(()=>{if(T)return;if(g(null),!r||!m){b.current=null;return}if(B){b.current=null;return}const z=`${r}::${m}::${p}`;if(b.current===z)return;b.current=z;let he=!1;return(async()=>{try{const Z=t.getGitFileDiff(r,{path:m}),de=Lf,Ee=new Promise((ye,te)=>{setTimeout(()=>te(new Error(`Timed out after ${de}ms`)),de)}),ne=await Promise.race([Z,Ee]);if(he)return;u(r,m,{original:ne.original??"",modified:ne.modified??""})}catch(Z){if(he)return;const de=Z instanceof Error?Z.message:String(Z);g(de)}})(),()=>{he=!0,b.current===z&&(b.current=null)}},[r,T,m,B,t,u,p]);const we=()=>!r||$.length===0?null:$.map(z=>e.jsx(tv,{directory:r,filePath:z.path,isVisible:z.path===m,renderSideBySide:H,wrapLines:N},z.path)),pe=()=>r?e.jsxs("div",{className:"flex flex-1 min-h-0 h-full gap-3 px-3 pb-3 pt-2",children:[E&&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:$.length})]}),e.jsx(Yw,{changedFiles:$,selectedFile:m,onSelectFile:G})]}),e.jsx(jt,{ref:I,outerClassName:"flex-1 min-h-0 h-full",className:"pr-2",disableHorizontal:!0,children:e.jsx("div",{className:"flex flex-col gap-3",children:$.map(z=>e.jsx(sv,{directory:r,file:z,layout:ie(z),wrapLines:N,scrollRootRef:I,isSelected:z.path===m,onSelect:ae,registerSectionRef:ee},z.path))})})]}):null,De=()=>r?l&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Tt,{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."}):$.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?pe():e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[we(),le&&!O&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:x?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:x}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{g(null),h(z=>z+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Tt,{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(Rl,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:l&&!a?"Loading changes…":`${$.length} ${$.length===1?"file":"files"} changed`})]}),!A&&e.jsx(Qw,{mode:k,onModeChange:q}),L&&e.jsx(Kw,{changedFiles:$,selectedFile:m,selectedFileEntry:Q,onSelectFile:G,isMobile:A,showModeSelector:A,mode:k,onModeChange:q}),e.jsx("div",{className:"flex-1"}),Q&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>M(!j),className:R("h-5 w-5 p-0 transition-opacity",N?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:N?"Disable line wrap":"Enable line wrap",children:e.jsx(hm,{className:"size-4"})}),Q&&K&&e.jsx(Pf,{mode:K==="side-by-side"?"side-by-side":"unified",onModeChange:_})]}),De()]})},ov=()=>{const{git:t}=Bs(),{currentSessionId:r,sessions:s,worktreeMetadata:n}=ge(),{currentDirectory:o}=wt(),a=r?n.get(r)??void 0:void 0,c=s.find(p=>p.id===r)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:u,fetchStatus:m}=ls(),f=Sw(d??null);return i.useEffect(()=>{d&&(u(d),ls.getState().directories.get(d)?.status||m(d,t))},[d,u,m,t]),f},gn=_e.forwardRef(({className:t,...r},s)=>e.jsx(gm,{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(Rh,{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"}})}));gn.displayName=gm.displayName;const av={},Sa=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},Nd=t=>Sa(t)??"__global__",iv=t=>{const r=Object.entries(t??{}),s=r.filter(([,l])=>l?.status==="connected").length,n=r.length,o=r.some(([,l])=>l?.status==="failed"),a=r.some(([,l])=>l?.status==="needs_auth"||l?.status==="needs_client_registration");return{connected:s,total:n,hasFailed:o,hasAuthRequired:a}},bo=rs()(fs((t,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:s=>{const n=Nd(s??wt.getState().currentDirectory);return r().byDirectory[n]??av},refresh:async s=>{const n=Sa(s?.directory??wt.getState().currentDirectory),o=Nd(n);s?.silent||t(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const c=(await Oe.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};t(d=>({byDirectory:{...d.byDirectory,[o]:c},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const l=a instanceof Error?a.message:"Failed to load MCP status";t(c=>({loadingKeys:{...c.loadingKeys,[o]:!1},lastErrorKeys:{...c.lastErrorKeys,[o]:l}}))}},connect:async(s,n)=>{const o=Sa(n??wt.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=Sa(n??wt.getState().currentDirectory);await Oe.getApiClient().mcp.disconnect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function lv(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 cv=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}},dv=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},wl=({headerIconButtonClass:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(!1),{isMobile:l}=Kt(),d=wt(k=>k.currentDirectory)??null,u=bo(k=>k.getStatusForDirectory(d)),m=bo(k=>k.refresh),f=bo(k=>k.connect),p=bo(k=>k.disconnect),h=i.useCallback(k=>{k||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),s(k)},[]),x=i.useCallback(k=>{a.current||o(k)},[]),[g,b]=i.useState(!1),[y,w]=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(()=>iv(u),[u]),C=i.useMemo(()=>Object.keys(u).sort((k,D)=>k.localeCompare(D)),[u]),v=i.useCallback(k=>{if(k?.preventDefault(),g)return;b(!0);const D=new Promise(N=>setTimeout(N,500));Promise.all([m({directory:d}),D]).finally(()=>{b(!1)})},[g,m,d]),j=()=>e.jsxs(e.Fragment,{children:[C.map(k=>{const D=u[k],N=dv(D),T=D?.status==="connected",A=y===k,E=cv(D);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:[l?e.jsx("span",{className:R("h-2 w-2 rounded-full flex-shrink-0",N==="success"&&"bg-status-success",N==="error"&&"bg-status-error",N==="warning"&&"bg-status-warning",N==="default"&&"bg-muted-foreground/40"),"aria-label":E}):e.jsxs(ht,{delayDuration:300,children:[e.jsx(gt,{asChild:!0,children:e.jsx("span",{className:R("h-2 w-2 rounded-full flex-shrink-0",N==="success"&&"bg-status-success",N==="error"&&"bg-status-error",N==="warning"&&"bg-status-warning",N==="default"&&"bg-muted-foreground/40"),"aria-label":E})}),e.jsx(ft,{side:"left",children:e.jsx("p",{children:E})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:k})]})}),e.jsx(gn,{checked:T,disabled:A,className:"data-[state=checked]:bg-status-info",onCheckedChange:async I=>{w(k);try{I?await f(k,d):await p(k,d)}finally{w(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."})]}),M=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:R(t,"relative"),onClick:l?()=>s(!0):void 0,children:[e.jsx(lv,{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 l?e.jsxs(e.Fragment,{children:[M,e.jsxs(zs,{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:g,onClick:v,"aria-label":"Refresh",children:e.jsx(Qr,{className:R("h-4 w-4",g&&"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(es,{open:r,onOpenChange:h,children:[e.jsxs(ht,{delayDuration:1e3,open:r?!1:n,onOpenChange:x,children:[e.jsx(gt,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:M})}),e.jsx(ft,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsxs(ss,{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:g,onClick:v,"aria-label":"Refresh",children:e.jsx(Qr,{className:R("h-4 w-4",g&&"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})})]})]})]})},_f=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},kd=(t,r)=>{const s=_f(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},uv=t=>kd(kd(t,".opencode"),"plans"),mv=()=>"~/.opencode/plans",fv=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},Cd=()=>{const t=je(Z=>Z.setSessionSwitcherOpen),r=je(Z=>Z.toggleSidebar),s=je(Z=>Z.setSettingsDialogOpen),n=je(Z=>Z.toggleCommandPalette),o=je(Z=>Z.toggleHelpDialog),a=je(Z=>Z.activeMainTab),l=je(Z=>Z.setActiveMainTab),{getCurrentModel:c}=et(),d=Bs(),u=ge(Z=>Z.getContextUsage),m=ge(Z=>Z.currentSessionId),f=ge(Z=>Z.sessions),p=wt(Z=>Z.homeDirectory),{isMobile:h}=Kt(),x=ov(),g=ei(Z=>Z.available),b=_s(Z=>Z.status),y=_s(Z=>Z.setStatus),w=i.useRef(null),[S,C]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),v=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);_e.useEffect(()=>{if(typeof window>"u")return;const Z=typeof window.opencodeDesktop<"u";C(Z)},[]);const j=c(),M=j&&typeof j.limit=="object"&&j.limit!==null?j.limit:null,k=M&&typeof M.context=="number"?M.context:0,D=M&&typeof M.output=="number"?M.output:0,N=u(k,D),T=je(Z=>Z.isSessionSwitcherOpen),A=b?.connected?b.user?.avatarUrl:null,E=b?.connected?b.user?.login:null,I=b?.accounts??[],[P,F]=i.useState(!1),$=i.useMemo(()=>m?f.find(Z=>Z.id===m)??null:null,[m,f]),Q=i.useMemo(()=>{const Z=typeof $?.directory=="string"?$.directory:"";return _f(Z||"")},[$?.directory]),[ie,K]=i.useState(!1),ee=ie,V=i.useRef(""),ae=i.useCallback(async Z=>{if(!(!Z||P)){F(!0);try{const de=d.github?await d.github.authActivate(Z):await(async()=>{const Ee=await fetch("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:Z})}),ne=await Ee.json().catch(()=>null);if(!Ee.ok||!ne)throw new Error(ne?.error||Ee.statusText);return ne})();y(de)}catch(de){console.error("Failed to switch GitHub account:",de)}finally{F(!1)}}},[P,d.github,y]);i.useEffect(()=>{let Z=!1;const de=async(te,ce)=>{if(!te||!ce||!d.files?.listDirectory)return!1;try{const X=await d.files.listDirectory(te);return(Array.isArray(X?.entries)?X.entries:[]).some(Y=>Y?.name===ce&&!Y?.isDirectory)}catch{return!1}},Ee=async()=>{if(Z)return;if(!$?.slug||!$?.time?.created||!Q){K(!1),je.getState().activeMainTab==="plan"&&je.getState().setActiveMainTab("chat");return}const te=`${$.time.created}-${$.slug}.md`,ce=uv(Q),X=fv(mv(),p||null),[U,Y]=await Promise.all([de(ce,te),de(X,te)]);if(Z)return;const se=U||Y;K(se),!se&&je.getState().activeMainTab==="plan"&&je.getState().setActiveMainTab("chat")},ne=`${m||"none"}:${Q||"none"}:${$?.time?.created||0}:${$?.slug||"none"}`;V.current!==ne&&(V.current=ne,K(!1)),Ee();const ye=window.setInterval(()=>{Ee()},3e3);return()=>{Z=!0,window.clearInterval(ye)}},[Q,$?.slug,$?.time?.created,m,p,d.files]);const G=i.useCallback(()=>{if(typeof document>"u")return;const Z=document.activeElement;if(!Z)return;const de=Z.tagName;(de==="INPUT"||de==="TEXTAREA"||de==="SELECT"||Z.isContentEditable)&&Z.blur()},[]),q=i.useCallback(()=>{if(h){G(),t(!T);return}r()},[G,h,T,t,r]),_=i.useCallback(()=>{h&&G(),t(!1),s(!0)},[G,h,t,s]),H="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",L=i.useMemo(()=>S&&v?"pl-[5.75rem]":"pl-3",[S,v]),B=i.useCallback(()=>{if(typeof document>"u")return;const Z=w.current?.getBoundingClientRect().height;Z&&document.documentElement.style.setProperty("--oc-header-height",`${Z}px`)},[]);_e.useEffect(()=>{if(typeof window>"u")return;B();const Z=w.current;if(!Z||typeof ResizeObserver>"u")return()=>{};const de=new ResizeObserver(()=>{B()});return de.observe(Z),window.addEventListener("resize",B),window.addEventListener("orientationchange",B),()=>{de.disconnect(),window.removeEventListener("resize",B),window.removeEventListener("orientationchange",B)}},[B]),_e.useEffect(()=>{B()},[B,h]);const O=i.useCallback(async Z=>{if(!Z.target.closest("button, a, input, select, textarea")&&Z.button===0&&S)try{const{getCurrentWindow:de}=await Ss(async()=>{const{getCurrentWindow:ne}=await import("./vendor-.bun-koHRsLHN.js").then(ye=>ye.dh);return{getCurrentWindow:ne}},__vite__mapDeps([0,1]));await de().startDragging()}catch(de){console.error("Failed to start window dragging:",de)}},[S]),le=i.useCallback(async Z=>{if(Z.button===0&&S)try{const{getCurrentWindow:de}=await Ss(async()=>{const{getCurrentWindow:ne}=await import("./vendor-.bun-koHRsLHN.js").then(ye=>ye.dh);return{getCurrentWindow:ne}},__vite__mapDeps([0,1]));await de().startDragging()}catch(de){console.error("Failed to start window dragging:",de)}},[S]),we=i.useMemo(()=>{const Z=[{id:"chat",label:"Chat",icon:Lh}];return ee&&Z.push({id:"plan",label:"Plan",icon:Kn}),Z.push({id:"diff",label:"Diff",icon:er,badge:!h&&x>0?x:void 0},{id:"files",label:"Files",icon:ir},{id:"terminal",label:"Terminal",icon:Xr},{id:"git",label:"Git",icon:qt,showDot:h&&x>0}),Z},[x,h,ee]);_e.useEffect(()=>{const Z=de=>{if($s(de)&&!de.shiftKey&&!de.altKey){const Ee=parseInt(de.key,10);Ee>=1&&Ee<=we.length&&(de.preventDefault(),l(we[Ee-1].id))}};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[we,l]);const pe=Z=>{const de=a===Z.id,Ee=Z.icon,ne=Z.id==="chat";return e.jsxs("button",{type:"button",onClick:()=>l(Z.id),onMouseDown:de?le:void 0,className:R("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",de?"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",ne&&!h&&"min-w-[100px] justify-center"),"aria-label":Z.label,"aria-selected":de,role:"tab",children:[h?e.jsx(Ee,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{size:16}),e.jsx("span",{className:"header-tab-label",children:Z.label})]}),ne&&!h&&N&&N.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(xl,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact"})}),Z.badge!==void 0&&Z.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:Z.badge})]},Z.id)},De=()=>e.jsxs("div",{onMouseDown:O,className:R("app-region-drag relative flex h-12 select-none items-center",L),role:"tablist","aria-label":"Main navigation",children:[e.jsx("button",{type:"button",onClick:q,"aria-label":"Open sessions",className:`${H} mr-2`,children:e.jsx(Ol,{className:"h-5 w-5"})}),e.jsx("div",{className:"flex items-center gap-1 p-1 bg-background/50 rounded-lg",children:we.map(Z=>pe(Z))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(ht,{delayDuration:500,children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:H,children:e.jsx(Dn,{className:"h-5 w-5"})})}),e.jsx(ft,{children:e.jsxs("p",{children:["Command Palette (",Zt(),"+K)"]})})]}),e.jsx(wl,{headerIconButtonClass:H}),e.jsxs(ht,{delayDuration:500,children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:H,children:e.jsx(vn,{className:"h-5 w-5"})})}),e.jsx(ft,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Zt(),"+.)"]})})]}),b?.connected&&!h?I.length>1?e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsx("button",{type:"button",className:R(H,"h-8 w-8 p-0 overflow-hidden rounded-full border border-border/60 bg-muted/80"),title:E?`GitHub: ${E}`:"GitHub connected",disabled:P,children:A?e.jsx("img",{src:A,alt:E?`${E} 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(ss,{align:"end",className:"w-64",children:[e.jsx(Pr,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),e.jsx(Ds,{}),I.map(Z=>{const de=Z.user,Ee=!!Z.current;return e.jsxs(Ct,{className:"gap-2",disabled:Ee||P,onSelect:()=>{Ee||ae(Z.id)},children:[de?.avatarUrl?e.jsx("img",{src:de.avatarUrl,alt:de.login?`${de.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:de?.name?.trim()||de?.login||"GitHub"}),de?.login?e.jsx("span",{className:"typography-micro text-muted-foreground truncate font-mono",children:de.login}):null]}),Ee?e.jsx($t,{className:"h-4 w-4 text-primary"}):null]},Z.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:E?`GitHub: ${E}`:"GitHub connected",children:A?e.jsx("img",{src:A,alt:E?`${E} 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]})]}),z=()=>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(Ll,{className:"h-5 w-5"})}):e.jsx("button",{onClick:q,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(Oh,{className:"h-5 w-5"})}),!T&&N&&N.totalTokens>0&&a==="chat"&&e.jsx(xl,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.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:we.map(Z=>{const de=a===Z.id,Ee=Z.icon;return e.jsxs(ht,{delayDuration:500,children:[e.jsx(gt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{h&&G(),l(Z.id)},"aria-label":Z.label,"aria-selected":de,role:"tab",className:R(H,"relative",de&&"text-foreground bg-secondary"),children:[e.jsx(Ee,{className:"h-5 w-5"}),Z.badge!==void 0&&Z.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:Z.badge}),Z.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(ft,{children:e.jsx("p",{children:Z.label})})]},Z.id)})}),e.jsx(wl,{headerIconButtonClass:H}),e.jsxs(ht,{delayDuration:500,children:[e.jsx(gt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:_,"aria-label":"Open settings",className:R(H,"relative"),children:[e.jsx(wn,{className:"h-5 w-5"}),g&&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(ft,{children:e.jsx("p",{children:g?"Settings (Update available)":"Settings"})})]})]})]}),he=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:w,className:he,style:{"--padding-scale":"1"},children:h?z():De()})};function lc({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 Bf({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 zf({className:t,...r}){return e.jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",t),...r})}function Hf({className:t,...r}){return e.jsx("div",{"data-slot":"card-content",className:R("px-6",t),...r})}class bs 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(lc,{className:"w-full max-w-md",children:[e.jsx(Bf,{className:"text-center",children:e.jsxs(zf,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(rl,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(Hf,{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 Zo=0;function us({...t}){return e.jsx($h,{"data-slot":"dialog",...t})}function pv({...t}){return e.jsx(zh,{"data-slot":"dialog-portal",...t})}const Wf=_e.forwardRef(({className:t,...r},s)=>(_e.useEffect(()=>(Zo+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Zo=Math.max(0,Zo-1),Zo===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(xm,{ref:s,"data-slot":"dialog-overlay",className:R("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",t),...r})));Wf.displayName=xm.displayName;function ms({className:t,children:r,showCloseButton:s=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(pv,{"data-slot":"dialog-portal",children:[e.jsx(Wf,{className:"rounded-none"}),e.jsxs(_h,{"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(Bh,{"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(os,{}),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 Vs({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(Hh,{"data-slot":"dialog-title",className:R("typography-markdown leading-none font-semibold text-foreground",t),...r})}function Ns({className:t,...r}){return e.jsx(Wh,{"data-slot":"dialog-description",className:R("text-muted-foreground typography-ui-label",t),...r})}const Md="https://github.com/btriapitsyn/openchamber/releases";async function hv(){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 gv(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 vl=({open:t,onOpenChange:r,info:s,downloading:n,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=_e.useState(!1),[p,h]=_e.useState("idle"),[x,g]=_e.useState(null),b=s?.version?`${Md}/tag/v${s.version}`:Md,y=a?.total?Math.round(a.downloaded/a.total*100):0,w=u==="web",S=s?.updateCommand||"openchamber update";_e.useEffect(()=>{t||(h("idle"),g(null))},[t]);const C=async()=>{try{await navigator.clipboard.writeText(S),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},v=_e.useCallback(async()=>{h("updating"),g(null);const M=await hv();if(!M.success){h("error"),g(M.error||"Update failed");return}h("restarting"),await new Promise(D=>setTimeout(D,2e3)),h("reconnecting"),await gv()?window.location.reload():(h("error"),g("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(Uh,{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})]}),w&&j&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ma,{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(jt,{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((M,k)=>/^\d+\.\d+\.\d+$/.test(M.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",M.trim(),`
82
- `]},k):M.replace(/^- /gm,"• ").trim()+`
83
-
84
- `)})}),w&&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(Vh,{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($t,{className:"h-4 w-4"}):e.jsx($l,{className:"h-4 w-4"})})]})]}),!w&&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}%`}})})]}),(l||x)&&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:l||x})}),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(Xs,{className:"h-4 w-4"}),"GitHub"]}),!w&&!o&&!n&&e.jsxs("button",{onClick:c,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(Yr,{className:"h-4 w-4"}),"Download Update"]}),!w&&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(ma,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!w&&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"]}),w&&!j&&e.jsxs("button",{onClick:v,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(Yr,{className:"h-4 w-4"}),"Update Now"]}),w&&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(ma,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Dd=264,Ad=200,Ed=500,Id="openchamber:check-for-updates",xv=({isOpen:t,isMobile:r,children:s})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:l}=je(),[c,d]=i.useState(!1),u=i.useRef(0),m=i.useRef(n||Dd),[f,p]=i.useState(!1),h=ei(),x=i.useRef(!1),g=h.checkForUpdates,{available:b,downloaded:y,checking:w}=h,[S,C]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");if(i.useEffect(()=>{if(typeof window>"u")return;const M=typeof window.opencodeDesktop<"u";C(M)},[]),i.useEffect(()=>{if(typeof window>"u")return;const M=()=>{typeof window.opencodeDesktop<"u"&&(x.current=!0,g())};return window.addEventListener(Id,M),()=>{window.removeEventListener(Id,M)}},[g]),i.useEffect(()=>{x.current&&(w||(b||y?p(!0):W.success("No updates available",{description:"You are running the latest version."}),x.current=!1))},[b,y,w]),i.useEffect(()=>{if(r||!c)return;const M=D=>{const N=D.clientX-u.current,T=Math.min(Ed,Math.max(Ad,m.current+N));o(T)},k=()=>{d(!1)};return window.addEventListener("pointermove",M),window.addEventListener("pointerup",k,{once:!0}),()=>{window.removeEventListener("pointermove",M),window.removeEventListener("pointerup",k)}},[r,c,o]),i.useEffect(()=>{r&&c&&d(!1)},[r,c]),r)return null;const v=t?Math.min(Ed,Math.max(Ad,n||Dd)):0,j=M=>{t&&(d(!0),u.current=M.clientX,m.current=v,M.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",c?"transition-none":"transition-[width] duration-300 ease-in-out",!t&&"border-r-0"),style:{width:`${v}px`,minWidth:`${v}px`,maxWidth:`${v}px`,overflowX:"clip"},"aria-hidden":!t||v===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",c&&"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:`${v}px`,overflowX:"hidden"},"aria-hidden":!t,children:[e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(bs,{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(wn,{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(Yr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!S&&e.jsxs(ht,{children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{onClick:()=>l(!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(Cs,{className:"h-4 w-4"})})}),e.jsx(ft,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(vl,{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 cc({className:t,...r}){return e.jsx(An,{"data-slot":"command",className:R("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",t),...r})}function yv({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(Ns,{children:r})]}),e.jsx(ms,{className:R("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(cc,{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 dc({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(Us,{className:"size-4 shrink-0 opacity-50"}),e.jsx(An.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 uc({className:t,children:r,scrollbarClassName:s,disableHorizontal:n,...o}){return e.jsx(jt,{as:An.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 mc({...t}){return e.jsx(An.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...t})}function xn({className:t,...r}){return e.jsx(An.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 Wa({className:t,...r}){return e.jsx(An.Separator,{"data-slot":"command-separator",className:R("bg-border -mx-1 h-px",t),...r})}function js({className:t,...r}){return e.jsx(An.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 Dr({className:t,...r}){const s=a=>{const l=a.trim().toLowerCase();return l==="ctrl"||l==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):l==="cmd"||l==="⌘"||l==="command"||l==="meta"?e.jsx(Dn,{className:"size-3.5"}):l==="shift"||l==="⇧"?e.jsx(Qn,{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,l)=>e.jsxs(_e.Fragment,{children:[l>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),s(a)]},`${a}-${l}`)):r.children})}const Pd=["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"],Td=["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 Uf(){const t=Pd[Math.floor(Math.random()*Pd.length)],r=Td[Math.floor(Math.random()*Td.length)];return`${t}-${r}`}function Fd(t){const r=Uf();return t&&t.trim()?`${t.trim().replace(/\/+$/,"")}/${r}`:r}async function bv(t,r,s=10){let n;try{const o=await oi(t);n=new Set(o?.all??[])}catch{return Fd(r)}for(let o=0;o<s;o++){const a=Fd(r);if(!n.has(a))return a}return null}const fc=t=>t.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let Lr=!1;async function ci(){if(Lr)return null;const t=Wt.getState().getActiveProject();if(!t?.path)return W.error("No active project",{description:"Please select a project first."}),null;const r=t.path;let s=!1;try{s=await _r(r)}catch{}if(!s)return W.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Lr=!0,Ws("Creating new worktree session...");try{const n=t.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,l=await bv(r,o);if(!l)return W.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const c=fc(l),u=await ai({projectDirectory:r,worktreeSlug:c,branch:l,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await Oo(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=ge.getState(),h=await p.createSession(void 0,u.path);if(!h)return await Yl({projectDirectory:r,path:u.path,force:!0}).catch(()=>{}),W.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const x=et.getState(),g=x.agents;p.initializeNewOpenChamberSession(h.id,g),p.setSessionDirectory(h.id,u.path),p.setWorktreeMetadata(h.id,f);try{const w=x.getVisibleAgents();let S;if(x.settingsDefaultAgent){const C=w.find(v=>v.name===x.settingsDefaultAgent);C&&(S=C.name)}if(S||(S=w.find(C=>C.name==="build")?.name||w[0]?.name),S){x.setAgent(S),nt.getState().saveSessionAgentSelection(h.id,S);const C=x.settingsDefaultModel;if(C){const v=C.split("/");if(v.length===2){const[j,M]=v;if(x.getModelMetadata(j,M)){nt.getState().saveSessionModelSelection(h.id,j,M),nt.getState().saveAgentModelForSession(h.id,S,j,M);const D=x.settingsDefaultVariant;if(D){const A=x.providers.find(E=>E.id===j)?.models.find(E=>E.id===M)?.variants;A&&Object.prototype.hasOwnProperty.call(A,D)&&(x.setCurrentVariant(D),nt.getState().saveAgentModelVariantForSession(h.id,S,j,M,D))}}}}}}catch{}wt.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const y=(await En(r)).filter(w=>w.trim().length>0);return y.length>0?(W.success("Worktree created",{description:`Branch: ${l}. Running ${y.length} setup command${y.length===1?"":"s"}...`}),ii(u.path,r,y).then(w=>{if(w.success)W.success("Setup commands completed",{description:`All ${w.results.length} command${w.results.length===1?"":"s"} succeeded.`});else{const S=w.results.filter(v=>!v.success),C=w.results.filter(v=>v.success);W.error("Setup commands failed",{description:`${S.length} of ${w.results.length} command${w.results.length===1?"":"s"} failed.`+(C.length>0?` ${C.length} succeeded.`:"")})}}).catch(()=>{W.error("Setup commands failed",{description:"Could not execute setup commands."})})):W.success("Worktree created",{description:`Branch: ${l}`}),h}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return W.error("Failed to create worktree",{description:o}),null}finally{Os(),Lr=!1}}async function wv(t,r){if(Lr)return null;let s=!1;try{s=await _r(t)}catch{}if(!s)return W.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Lr=!0,Ws("Creating worktree session...");try{const n=fc(r),o=await ai({projectDirectory:t,worktreeSlug:n,branch:r,createBranch:!1}),a=await Oo(o.path).catch(()=>{}),l=a?{...o,status:a}:o,c=ge.getState(),d=await c.createSession(void 0,o.path);if(!d)return await Yl({projectDirectory:t,path:o.path,force:!0}).catch(()=>{}),W.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const u=et.getState(),m=u.agents;c.initializeNewOpenChamberSession(d.id,m),c.setSessionDirectory(d.id,o.path),c.setWorktreeMetadata(d.id,l);try{const h=u.getVisibleAgents();let x;if(u.settingsDefaultAgent){const g=h.find(b=>b.name===u.settingsDefaultAgent);g&&(x=g.name)}if(x||(x=h.find(g=>g.name==="build")?.name||h[0]?.name),x){u.setAgent(x),nt.getState().saveSessionAgentSelection(d.id,x);const g=u.settingsDefaultModel;if(g){const b=g.split("/");if(b.length===2){const[y,w]=b;if(u.getModelMetadata(y,w)){nt.getState().saveSessionModelSelection(d.id,y,w),nt.getState().saveAgentModelForSession(d.id,x,y,w);const C=u.settingsDefaultVariant;if(C){const M=u.providers.find(k=>k.id===y)?.models.find(k=>k.id===w)?.variants;M&&Object.prototype.hasOwnProperty.call(M,C)&&(u.setCurrentVariant(C),nt.getState().saveAgentModelVariantForSession(d.id,x,y,w,C))}}}}}}catch{}wt.getState().setDirectory(o.path,{showOverlay:!1});try{await c.loadSessions()}catch{}const p=(await En(t)).filter(h=>h.trim().length>0);return p.length>0?(W.success("Worktree created",{description:`Branch: ${r}. Running ${p.length} setup command${p.length===1?"":"s"}...`}),ii(o.path,t,p).then(h=>{if(h.success)W.success("Setup commands completed",{description:`All ${h.results.length} command${h.results.length===1?"":"s"} succeeded.`});else{const x=h.results.filter(b=>!b.success),g=h.results.filter(b=>b.success);W.error("Setup commands failed",{description:`${x.length} of ${h.results.length} command${h.results.length===1?"":"s"} failed.`+(g.length>0?` ${g.length} succeeded.`:"")})}}).catch(()=>{W.error("Setup commands failed",{description:"Could not execute setup commands."})})):W.success("Worktree created",{description:`Branch: ${r}`}),d}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return W.error("Failed to create worktree",{description:o}),null}finally{Os(),Lr=!1}}async function Vf(t,r,s,n){if(Lr)return null;let o=!1;try{o=await _r(t)}catch{}if(!o)return W.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Lr=!0,Ws("Creating worktree session...");try{const a=s?.trim()||"HEAD",l=r?.trim();if(!l)throw new Error("Branch name is required");let c=null;const u=n?.allowSuffix!==!1?6:1;for(let f=0;f<u;f+=1){const p=f===0?l:`${l}-${f+1}`;try{const h=fc(p),x=await ai({projectDirectory:t,worktreeSlug:h,branch:p,createBranch:!0,startPoint:a}),g=await Oo(x.path).catch(()=>{}),b=g?{...x,status:g}:x,y=ge.getState(),w=await y.createSession(void 0,x.path);if(!w)throw await Yl({projectDirectory:t,path:x.path,force:!0}).catch(()=>{}),new Error("Could not create a session for the worktree.");const S=et.getState();y.initializeNewOpenChamberSession(w.id,S.agents),y.setSessionDirectory(w.id,x.path),y.setWorktreeMetadata(w.id,b);try{const j=S.getVisibleAgents();let M;if(S.settingsDefaultAgent){const k=j.find(D=>D.name===S.settingsDefaultAgent);k&&(M=k.name)}if(M||(M=j.find(k=>k.name==="build")?.name||j[0]?.name),M){S.setAgent(M),nt.getState().saveSessionAgentSelection(w.id,M);const k=S.settingsDefaultModel;if(k){const D=k.split("/");if(D.length===2){const[N,T]=D;if(S.getModelMetadata(N,T)){nt.getState().saveSessionModelSelection(w.id,N,T),nt.getState().saveAgentModelForSession(w.id,M,N,T);const E=S.settingsDefaultVariant;if(E){const F=S.providers.find($=>$.id===N)?.models.find($=>$.id===T)?.variants;F&&Object.prototype.hasOwnProperty.call(F,E)&&(S.setCurrentVariant(E),nt.getState().saveAgentModelVariantForSession(w.id,M,N,T,E))}}}}}}catch{}wt.getState().setDirectory(x.path,{showOverlay:!1});try{await y.loadSessions()}catch{}const v=(await En(t)).filter(j=>j.trim().length>0);return v.length>0?(W.success("Worktree created",{description:`Branch: ${p}. Running ${v.length} setup command${v.length===1?"":"s"}...`}),ii(x.path,t,v).then(j=>{if(j.success)W.success("Setup commands completed",{description:`All ${j.results.length} command${j.results.length===1?"":"s"} succeeded.`});else{const M=j.results.filter(D=>!D.success),k=j.results.filter(D=>D.success);W.error("Setup commands failed",{description:`${M.length} of ${j.results.length} command${j.results.length===1?"":"s"} failed.`+(k.length>0?` ${k.length} succeeded.`:"")})}}).catch(()=>{W.error("Setup commands failed",{description:"Could not execute setup commands."})})):W.success("Worktree created",{description:`Branch: ${p}`}),{id:w.id,branch:p}}catch(h){c=h}}const m=c instanceof Error?c.message:"Failed to create worktree session";return W.error("Failed to create worktree",{description:m}),null}finally{Os(),Lr=!1}}async function vv(t,r,s){return Vf(t,r,s,{allowSuffix:!1})}const jv=()=>{const{isCommandPaletteOpen:t,setCommandPaletteOpen:r,setHelpDialogOpen:s,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:l,toggleSidebar:c}=je(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=ge(),f=et(P=>P.settingsAutoCreateWorktree),{currentDirectory:p}=wt(),{themeMode:h,setThemeMode:x}=Br(),g=()=>{r(!1)},b=async()=>{n("chat"),a(!1),d(),g()},y=P=>{u(P),g()},w=P=>{x(P),g()},S=()=>{s(!0),g()},C=()=>{g(),ci()},{isMobile:v}=Kt(),j=()=>{if(v){const{isSessionSwitcherOpen:P}=je.getState();a(!P)}else c();g()},M=()=>{n("diff"),g()},k=()=>{n("git"),g()},D=()=>{n("terminal"),g()},N=()=>{o(!0),g()},T=()=>{jo(),g()},A=()=>{l(!0),g()},E=m(p??""),I=i.useMemo(()=>E.slice(0,5),[E]);return e.jsxs(yv,{open:t,onOpenChange:r,children:[e.jsx(dc,{placeholder:"Type a command or search..."}),e.jsxs(uc,{children:[e.jsx(mc,{children:"No results found."}),e.jsxs(xn,{heading:"Actions",children:[e.jsxs(js,{onSelect:j,children:[e.jsx(Ol,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(Dr,{children:[Zt()," + L"]})]}),e.jsxs(js,{onSelect:b,children:[e.jsx(cs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Dr,{children:f?`Shift + ${Zt()} + N`:`${Zt()} + N`})]}),e.jsxs(js,{onSelect:C,children:[e.jsx(qt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Dr,{children:f?`${Zt()} + N`:`Shift + ${Zt()} + N`})]}),e.jsxs(js,{onSelect:S,children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(Dr,{children:[Zt()," + ."]})]}),e.jsxs(js,{onSelect:M,children:[e.jsx(er,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(Dr,{children:[Zt()," + 2"]})]}),e.jsxs(js,{onSelect:D,children:[e.jsx(Xr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(Dr,{children:[Zt()," + 3"]})]}),e.jsxs(js,{onSelect:k,children:[e.jsx(qt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(Dr,{children:[Zt()," + 4"]})]}),e.jsxs(js,{onSelect:A,children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(Dr,{children:[Zt()," + T"]})]}),e.jsxs(js,{onSelect:N,children:[e.jsx(wn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(Dr,{children:[Zt()," + ,"]})]}),e.jsxs(js,{onSelect:T,children:[e.jsx(Ls,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Wa,{}),e.jsxs(xn,{heading:"Theme",children:[e.jsxs(js,{onSelect:()=>w("light"),children:[e.jsx(Gh,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx($t,{className:"ml-auto h-4 w-4"})]}),e.jsxs(js,{onSelect:()=>w("dark"),children:[e.jsx(qh,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx($t,{className:"ml-auto h-4 w-4"})]}),e.jsxs(js,{onSelect:()=>w("system"),children:[e.jsx(ym,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx($t,{className:"ml-auto h-4 w-4"})]})]}),I.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Wa,{}),e.jsx(xn,{heading:"Recent Sessions",children:I.map(P=>e.jsxs(js,{onSelect:()=>y(P.id),children:[e.jsx(_l,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:P.title||"Untitled Session"})]},P.id))})]})]})]})},Sv=(t,r)=>{const s=t.trim().toLowerCase();return s==="ctrl"||s==="control"?e.jsx(Qa,{className:"h-3.5 w-3.5"},`ctrl-${r}`):s==="⌘"||s==="cmd"||s==="command"||s==="meta"?e.jsx(Dn,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:t.trim()},`key-${r}`)},Nv=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:"+"}),Sv(s,n)]},`${s}-${n}`))},kv=()=>{const{isHelpDialogOpen:t,setHelpDialogOpen:r}=je(),s=et(a=>a.settingsAutoCreateWorktree),n=Zt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:Dn},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:vn},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:Ol},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:jn},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:Bl},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:Nr}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:s?"Create New Session in Worktree":"Create New Session",icon:s?qt:cs},{keys:[`Shift + ${n} + N`],description:s?"Create New Session":"Create New Session in Worktree",icon:s?cs:qt},{keys:[`${n} + I`],description:"Focus Chat Input",icon:bm},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Yn}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:Kh},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:er},{keys:[`${n} + 3`],description:"Open Files",icon:ir},{keys:[`${n} + 4`],description:"Open Terminal",icon:Xr},{keys:[`${n} + 5`],description:"Open Git Panel",icon:qt},{keys:[`${n} + T`],description:"Open Timeline",icon:Sr},{keys:[`${n} + ,`],description:"Open Settings",icon:wn}]}];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(wn,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Ns,{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((l,c)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l.icon&&e.jsx(l.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:l.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(l.keys)?l.keys:l.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:Nv(d)})]},`${d}-${u}`))})]},c))})]},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(vn,{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"})]})]})]})})]})]})})},Cv={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"}},Gf=({className:t,size:r="md"})=>{const s=Cv[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))})},Ai=new Set,Ei=new Set,Ii=new Set,so={onDeleteRequest(t){return Ai.add(t),()=>{Ai.delete(t)}},requestDelete(t){!t.sessions.length&&t.mode!=="worktree"||Ai.forEach(r=>r(t))},onCreateRequest(t){return Ei.add(t),()=>{Ei.delete(t)}},requestCreate(t){const r=t??{};Ei.forEach(s=>s(r))},onDirectoryRequest(t){return Ii.add(t),()=>{Ii.delete(t)}},requestDirectoryDialog(){Ii.forEach(t=>t())}};function qf(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})}function Mv({open:t,onOpenChange:r,projects:s,activeProjectId:n}){const[o,a]=i.useState(""),[l,c]=i.useState(new Map),[d,u]=i.useState(new Set),[m,f]=i.useState(null);i.useEffect(()=>{if(!t){a("");return}const b=s.find(y=>y.id===n);b&&u(new Set([b.id])),s.forEach(async y=>{c(w=>{const S=new Map(w);return S.set(y.id,{branches:null,worktrees:[],loading:!0,error:null}),S});try{const[w,S]=await Promise.all([oi(y.path),uf(y.path)]);c(C=>{const v=new Map(C);return v.set(y.id,{branches:w,worktrees:S,loading:!1,error:null}),v})}catch(w){c(S=>{const C=new Map(S);return C.set(y.id,{branches:null,worktrees:[],loading:!1,error:w instanceof Error?w.message:"Failed to load"}),C})}})},[t,s,n]);const p=b=>{u(y=>{const w=new Set(y);return w.has(b)?w.delete(b):w.add(b),w})},h=async(b,y)=>{const w=`${b.id}:${y}`;f(w);try{await wv(b.path,y),r(!1)}catch(S){console.error("Failed to create worktree:",S)}finally{f(null)}},x=(b,y)=>{if(!y.trim())return b;const w=y.toLowerCase();return b.filter(S=>S.toLowerCase().includes(w))},g=s.filter(b=>{const y=l.get(b.id);return y&&!y.error&&(y.loading||y.branches)});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(qt,{className:"h-5 w-5"}),"Branches & Worktrees"]}),e.jsx(Ns,{children:"Start a new worktree session from any local branch"})]}),e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Us,{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:o,onChange:b=>a(b.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:g.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No git repositories found"}):g.map(b=>{const y=l.get(b.id),w=d.has(b.id),S=y?.branches,C=y?.worktrees||[],v=new Set(C.map(D=>D.branch).filter(Boolean)),j=S?.all||[],k=x(j,o).filter(D=>!D.startsWith("remotes/")).filter(D=>!v.has(D));return e.jsxs("div",{className:"rounded-md",children:[e.jsxs("button",{type:"button",onClick:()=>p(b.id),className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-muted/30 transition-colors rounded-md",children:[e.jsx(Hs,{className:R("h-4 w-4 text-muted-foreground transition-transform",w&&"rotate-90")}),e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm truncate flex-1 text-left",children:b.label||b.normalizedPath.split("/").pop()||b.normalizedPath}),y?.loading&&e.jsx(Tt,{className:"h-4 w-4 text-muted-foreground animate-spin"}),S&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[k.length," branches"]})]}),w&&e.jsx("div",{className:"mt-1 space-y-1 pl-6",children:y?.loading?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading branches..."}):y?.error?e.jsx("div",{className:"px-2 py-2 text-destructive text-sm",children:y.error}):k.length===0?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:o?"No matching branches":"No branches found"}):k.map(D=>{const N=S?.branches[D],T=N?.current,A=m===`${b.id}:${D}`;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(qt,{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:[e.jsx("span",{className:R("text-sm truncate",T&&"font-medium text-primary"),children:D}),T&&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"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[N?.commit&&e.jsx("span",{className:"font-mono",children:N.commit.slice(0,7)}),N?.ahead!==void 0&&N.ahead>0&&e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["↑",N.ahead]}),N?.behind!==void 0&&N.behind>0&&e.jsxs("span",{className:"text-[color:var(--status-warning)]",children:["↓",N.behind]})]})]}),e.jsxs(ht,{children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>h(b,D),disabled:A,className:"inline-flex h-7 px-2 items-center justify-center text-xs rounded-md bg-primary/10 hover:bg-primary/20 text-primary transition-colors disabled:opacity-50 flex-shrink-0",children:A?e.jsx(Tt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"h-3.5 w-3.5 mr-1"}),"Worktree"]})})}),e.jsx(ft,{side:"left",children:"Create worktree for this branch"})]})]},D)})})]},b.id)})})})]})})}const Dv=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},Av=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 Ev({open:t,onOpenChange:r}){const{github:s}=Bs(),n=_s(q=>q.status),o=_s(q=>q.hasChecked),a=je(q=>q.setSettingsDialogOpen),l=je(q=>q.setSidebarSection),c=Wt(q=>q.getActiveProject()),d=c?.path??null,u=c?.worktreeDefaults?.baseBranch||"main",[m,f]=i.useState(""),[p,h]=i.useState(!1),[x,g]=i.useState(null),[b,y]=i.useState([]),[w,S]=i.useState(1),[C,v]=i.useState(!1),[j,M]=i.useState(null),[k,D]=i.useState(!1),[N,T]=i.useState(!1),[A,E]=i.useState(null),I=i.useCallback(async()=>{if(!d){g(null),E("No active project");return}if(o&&n?.connected===!1){g({connected:!1}),y([]),v(!1),S(1),E(null);return}if(!s?.issuesList){g(null),E("GitHub runtime API unavailable");return}D(!0),E(null);try{const q=await s.issuesList(d,{page:1});g(q),y(q.issues??[]),S(q.page??1),v(!!q.hasMore),q.connected===!1&&E(null)}catch(q){E(q instanceof Error?q.message:String(q))}finally{D(!1)}},[s,o,n,d]),P=i.useCallback(async()=>{if(d&&s?.issuesList&&!(N||k)&&C){T(!0);try{const q=w+1,_=await s.issuesList(d,{page:q});g(_),y(H=>[...H,..._.issues??[]]),S(_.page??q),v(!!_.hasMore)}catch(q){const _=q instanceof Error?q.message:String(q);W.error("Failed to load more issues",{description:_})}finally{T(!1)}}},[s,C,k,N,w,d]);i.useEffect(()=>{if(!t){f(""),h(!1),M(null),E(null),g(null),y([]),S(1),v(!1),D(!1);return}I()},[t,I]),i.useEffect(()=>{t&&o&&n?.connected===!1&&(g({connected:!1}),y([]),v(!1),S(1),E(null))},[o,n,t]);const F=o?x?.connected!==!1:!0,$=x?.repo?.url??null,Q=i.useCallback(()=>{l("settings"),a(!0)},[a,l]),ie=i.useMemo(()=>{const q=m.trim().toLowerCase();return q?b.filter(_=>String(_.number)===q.replace(/^#/,"")?!0:_.title.toLowerCase().includes(q)):b},[b,m]),K=i.useMemo(()=>Dv(m),[m]),ee=i.useCallback(()=>{const q=et.getState(),_=q.getVisibleAgents();if(q.settingsDefaultAgent){const H=_.find(L=>L.name===q.settingsDefaultAgent);if(H)return H.name}return _.find(H=>H.name==="build")?.name||_[0]?.name},[]),V=i.useCallback(()=>{const q=et.getState(),_=q.settingsDefaultModel;if(!_)return null;const H=_.split("/");if(H.length!==2)return null;const[L,B]=H;return!L||!B||!q.getModelMetadata(L,B)?null:{providerID:L,modelID:B}},[]),ae=i.useCallback((q,_)=>{const H=et.getState(),L=H.settingsDefaultVariant;if(!L)return;const le=H.providers.find(we=>we.id===q)?.models.find(we=>we.id===_)?.variants;if(le&&Object.prototype.hasOwnProperty.call(le,L))return L},[]),G=i.useCallback(async q=>{if(!d){W.error("No active project");return}if(!s?.issueGet||!s?.issueComments){W.error("GitHub runtime API unavailable");return}if(!j){M(q);try{const _=await s.issueGet(d,q);if(_.connected===!1){W.error("GitHub not connected");return}if(!_.repo){W.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}const H=_.issue;if(!H){W.error("Issue not found");return}const L=await s.issueComments(d,q);if(L.connected===!1){W.error("GitHub not connected");return}const B=L.comments??[],O=`#${H.number} ${H.title}`.trim(),le=await(async()=>{if(p){const ce=`issue-${H.number}-${Uf()}`,X=await Vf(d,ce,u||"main");if(!X?.id)throw new Error("Failed to create worktree session");return X.id}const te=await ge.getState().createSession(O,d,null);if(!te?.id)throw new Error("Failed to create session");return te.id})();ge.getState().updateSessionTitle(le,O).catch(()=>{});try{ge.getState().initializeNewOpenChamberSession(le,et.getState().agents)}catch{}r(!1);const we=et.getState(),pe=Dt.getState().lastUsedProvider,De=V(),z=De?.providerID||we.currentProviderId||pe?.providerID,he=De?.modelID||we.currentModelId||pe?.modelID,Z=ee()||we.currentAgentName||void 0;if(!z||!he){W.error("No model selected");return}const de=ae(z,he);try{nt.getState().saveSessionModelSelection(le,z,he)}catch{}if(Z){try{we.setAgent(Z)}catch{}try{nt.getState().saveSessionAgentSelection(le,Z)}catch{}try{nt.getState().saveAgentModelForSession(le,Z,z,he)}catch{}if(de!==void 0){try{we.setCurrentVariant(de)}catch{}try{nt.getState().saveAgentModelVariantForSession(le,Z,z,he,de)}catch{}}}const Ee="Review this issue using the provided issue context: title, body, labels, assignees, comments, metadata.",ne=`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>”.`,ye=Av({repo:_.repo,issue:H,comments:B});Oe.sendMessage({id:le,providerID:z,modelID:he,agent:Z,variant:de,text:Ee,additionalParts:[{text:ne,synthetic:!0},{text:ye,synthetic:!0}]}).catch(te=>{const ce=te instanceof Error?te.message:String(te);W.error("Failed to send issue context",{description:ce})}),W.success("Session created from issue")}catch(_){const H=_ instanceof Error?_.message:String(_);W.error("Failed to start session",{description:H})}finally{M(null)}}},[p,s,r,d,u,ee,V,ae,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(Ns,{children:"Seeds a new session with hidden issue context (title/body/labels/comments)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Us,{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:q=>f(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."}),k?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Tt,{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:Q,children:"Open settings"})})]}):null,A?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:A}):null,K&&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===K&&"bg-muted/30"),onClick:()=>{G(K)},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 #",K]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:j===K?e.jsx(Tt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,ie.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,ie.map(q=>e.jsxs("div",{className:R("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",j===q.number&&"bg-muted/30"),onClick:()=>{G(q.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0",children:["#",q.number]}),e.jsx("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:q.title}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:j===q.number?e.jsx(Tt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:q.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:_=>_.stopPropagation(),"aria-label":"Open in GitHub",children:e.jsx(Xs,{className:"h-4 w-4"})})})]},q.number)),C&&F&&d&&s?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{P()},disabled:N||!!j,className:R("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(N||!!j)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:N?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Tt,{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(q=>!q),onKeyDown:q=>{(q.key===" "||q.key==="Enter")&&(q.preventDefault(),h(_=>!_))},children:[e.jsx("button",{type:"button",onClick:q=>{q.preventDefault(),q.stopPropagation(),h(_=>!_)},"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(Sn,{className:"h-4 w-4 text-primary"}):e.jsx(Nn,{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"}),$?e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:$,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(Se,{variant:"outline",size:"sm",onClick:I,disabled:k||!!j,children:"Refresh"})]})]})]})})}const Iv=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},Pv=t=>`GitHub pull request context (JSON)
120
- ${JSON.stringify(t,null,2)}`;function Tv({open:t,onOpenChange:r}){const{github:s}=Bs(),n=_s(H=>H.status),o=_s(H=>H.hasChecked),a=je(H=>H.setSettingsDialogOpen),l=je(H=>H.setSidebarSection),d=Wt(H=>H.getActiveProject())?.path??null,[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,x]=i.useState(!1),[g,b]=i.useState(null),[y,w]=i.useState([]),[S,C]=i.useState(1),[v,j]=i.useState(!1),[M,k]=i.useState(null),[D,N]=i.useState(!1),[T,A]=i.useState(!1),[E,I]=i.useState(null),P=i.useCallback(async()=>{if(!d){b(null),I("No active project");return}if(o&&n?.connected===!1){b({connected:!1}),w([]),j(!1),C(1),I(null);return}if(!s?.prsList){b(null),I("GitHub runtime API unavailable");return}N(!0),I(null);try{const H=await s.prsList(d,{page:1});b(H),w(H.prs??[]),C(H.page??1),j(!!H.hasMore),H.connected===!1&&I(null)}catch(H){I(H instanceof Error?H.message:String(H))}finally{N(!1)}},[s,o,n,d]),F=i.useCallback(async()=>{if(d&&s?.prsList&&!(T||D)&&v){A(!0);try{const H=S+1,L=await s.prsList(d,{page:H});b(L),w(B=>[...B,...L.prs??[]]),C(L.page??H),j(!!L.hasMore)}catch(H){const L=H instanceof Error?H.message:String(H);W.error("Failed to load more PRs",{description:L})}finally{A(!1)}}},[s,v,D,T,S,d]);i.useEffect(()=>{if(!t){m(""),p(!1),x(!1),b(null),w([]),C(1),j(!1),k(null),N(!1),I(null);return}P()},[t,P]),i.useEffect(()=>{t&&o&&n?.connected===!1&&(b({connected:!1}),w([]),j(!1),C(1),I(null))},[o,n,t]);const $=o?g?.connected!==!1:!0,Q=g?.repo?.url??null,ie=i.useCallback(()=>{l("settings"),a(!0)},[a,l]),K=i.useMemo(()=>{const H=u.trim().toLowerCase();return H?y.filter(L=>String(L.number)===H.replace(/^#/,"")?!0:L.title.toLowerCase().includes(H)):y},[y,u]),ee=i.useMemo(()=>Iv(u),[u]),V=i.useCallback(()=>{const H=et.getState(),L=H.getVisibleAgents();if(H.settingsDefaultAgent){const B=L.find(O=>O.name===H.settingsDefaultAgent);if(B)return B.name}return L.find(B=>B.name==="build")?.name||L[0]?.name},[]),ae=i.useCallback(()=>{const H=et.getState(),L=H.settingsDefaultModel;if(!L)return null;const B=L.split("/");if(B.length!==2)return null;const[O,le]=B;return!O||!le||!H.getModelMetadata(O,le)?null:{providerID:O,modelID:le}},[]),G=i.useCallback((H,L)=>{const B=et.getState(),O=B.settingsDefaultVariant;if(!O)return;const pe=B.providers.find(De=>De.id===H)?.models.find(De=>De.id===L)?.variants;if(pe&&Object.prototype.hasOwnProperty.call(pe,O))return O},[]),q=i.useCallback(async(H,L)=>{if(!d)return null;const B=L.head,O=L.headRepo;if(!B)throw new Error("PR head ref missing");const we=!!(O?.owner&&O?.repo&&H?.owner&&H?.repo&&(O.owner!==H.owner||O.repo!==H.repo))?O?.cloneUrl||O?.url||"":"origin";if(!we)throw new Error("PR head remote URL missing");const pe=`refs/heads/${B}`;if(!(await wb(d,{remote:we,branch:pe}))?.success)throw new Error("Failed to fetch PR head");const z=L.head,he=await vv(d,z,"FETCH_HEAD");if(!he?.id)throw new Error("Failed to create PR worktree session");return{id:he.id}},[d]),_=i.useCallback(async H=>{if(!d){W.error("No active project");return}if(!s?.prContext){W.error("GitHub runtime API unavailable");return}if(!M){k(H);try{const L=await s.prContext(d,H,{includeDiff:h,includeCheckDetails:!1});if(L.connected===!1){W.error("GitHub not connected");return}if(!L.repo){W.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}if(!L.pr){W.error("PR not found");return}const B=L.pr,O=`#${B.number} ${B.title}`.trim(),le=await(async()=>{if(f)try{return(await q(L.repo,B))?.id||null}catch(ce){const X=ce instanceof Error?ce.message:String(ce);W.error("PR worktree failed",{description:X})}return(await ge.getState().createSession(O,d,null))?.id||null})();if(!le)throw new Error("Failed to create session");ge.getState().updateSessionTitle(le,O).catch(()=>{});try{ge.getState().initializeNewOpenChamberSession(le,et.getState().agents)}catch{}r(!1);const we=et.getState(),pe=Dt.getState().lastUsedProvider,De=ae(),z=De?.providerID||we.currentProviderId||pe?.providerID,he=De?.modelID||we.currentModelId||pe?.modelID,Z=V()||we.currentAgentName||void 0;if(!z||!he){W.error("No model selected");return}const de=G(z,he);try{nt.getState().saveSessionModelSelection(le,z,he)}catch{}if(Z){try{we.setAgent(Z)}catch{}try{nt.getState().saveSessionAgentSelection(le,Z)}catch{}try{nt.getState().saveAgentModelForSession(le,Z,z,he)}catch{}if(de!==void 0){try{we.setCurrentVariant(de)}catch{}try{nt.getState().saveAgentModelVariantForSession(le,Z,z,he,de)}catch{}}}const Ee="Review this pull request using the provided PR context: description, comments, files, diff, checks.",ne=`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`,ye=Pv(L);Oe.sendMessage({id:le,providerID:z,modelID:he,agent:Z,variant:de,text:Ee,additionalParts:[{text:ne,synthetic:!0},{text:ye,synthetic:!0}]}).catch(te=>{const ce=te instanceof Error?te.message:String(te);W.error("Failed to send PR context",{description:ce})}),W.success("Session created from PR")}catch(L){const B=L instanceof Error?L.message:String(L);W.error("Failed to start session",{description:B})}finally{k(null)}}},[f,q,s,h,r,d,V,ae,G,M]);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(Aa,{className:"h-5 w-5"}),"New Session From GitHub PR"]}),e.jsx(Ns,{children:"Seeds a new session with hidden PR context (title/body/comments/files/checks)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Us,{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:H=>m(H.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."}),D?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Tt,{className:"h-4 w-4 animate-spin"}),"Loading pull requests..."]}):null,$===!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:ie,children:"Open settings"})})]}):null,E?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:E}):null,ee&&d&&s&&$?e.jsxs("div",{className:R("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",M===ee&&"bg-muted/30"),onClick:()=>{_(ee)},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 #",ee]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:M===ee?e.jsx(Tt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,K.length===0&&!D&&$&&s&&d?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:u?"No PRs found":"No open PRs found"}):null,K.map(H=>e.jsxs("div",{className:R("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",M===H.number&&"bg-muted/30"),onClick:()=>{_(H.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0",children:["#",H.number]}),e.jsx("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:H.title}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:M===H.number?e.jsx(Tt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:H.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:L=>L.stopPropagation(),"aria-label":"Open in GitHub",children:e.jsx(Xs,{className:"h-4 w-4"})})})]},H.number)),v&&$&&d&&s?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{F()},disabled:T||!!M,className:R("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(T||!!M)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:T?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Tt,{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(H=>!H),onKeyDown:H=>{(H.key===" "||H.key==="Enter")&&(H.preventDefault(),p(L=>!L))},children:[e.jsx("button",{type:"button",onClick:H=>{H.preventDefault(),H.stopPropagation(),p(L=>!L)},"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(Sn,{className:"h-4 w-4 text-primary"}):e.jsx(Nn,{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:()=>x(H=>!H),onKeyDown:H=>{(H.key===" "||H.key==="Enter")&&(H.preventDefault(),x(L=>!L))},children:[e.jsx("button",{type:"button",onClick:H=>{H.preventDefault(),H.stopPropagation(),x(L=>!L)},"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(Sn,{className:"h-4 w-4 text-primary"}):e.jsx(Nn,{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(Xs,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(Se,{variant:"outline",size:"sm",onClick:P,disabled:D||!!M,children:"Refresh"})]})]})]})})}const Rd="oc.sessions.projectCollapse",Ld="oc.sessions.expandedParents",Od=t=>{const r=new Date(t),s=new Date,n=(l,c)=>l.getFullYear()===c.getFullYear()&&l.getMonth()===c.getMonth()&&l.getDate()===c.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(",","")},yr=t=>{if(!t)return null;const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},$d=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),Fv=({id:t,projectLabel:r,projectDescription:s,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:l,isDesktopRuntime:c,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:h,onNewWorktreeSession:x,onOpenBranchPicker:g,onNewSessionFromGitHubIssue:b,onNewSessionFromGitHubPR:y,onOpenMultiRunLauncher:w,onClose:S,sentinelRef:C,children:v,settingsAutoCreateWorktree:j})=>{const{attributes:M,listeners:k,setNodeRef:D,isDragging:N}=ag({id:t}),[T,A]=i.useState(!1);return e.jsxs("div",{ref:D,className:R("relative",N&&"opacity-40"),children:[c&&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",!c&&"bg-sidebar"),style:{backgroundColor:c?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:l?"var(--color-border)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onContextMenu:E=>{E.preventDefault(),A(!0)},children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...M,children:[e.jsxs(ht,{delayDuration:1500,children:[e.jsx(gt,{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(ft,{side:"right",sideOffset:8,children:s})]}),e.jsxs(es,{open:T,onOpenChange:A,children:[e.jsx(ts,{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:E=>E.stopPropagation(),children:e.jsx(Zr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"min-w-[180px]",children:[a&&!u&&j&&h&&e.jsxs(Ct,{onClick:h,children:[e.jsx(cs,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),a&&!u&&!j&&x&&e.jsxs(Ct,{onClick:x,children:[e.jsx(qt,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),a&&!u&&g&&e.jsxs(Ct,{onClick:g,children:[e.jsx(vm,{className:"mr-1.5 h-4 w-4"}),"Browse Branches"]}),a&&!u&&b&&e.jsxs(Ct,{onClick:b,children:[e.jsx(wm,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub issue"]}),a&&!u&&y&&e.jsxs(Ct,{onClick:y,children:[e.jsx(Aa,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub PR"]}),a&&!u&&e.jsxs(Ct,{onClick:w,children:[e.jsx(qf,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(Ct,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(os,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),a&&!u&&x&&j&&e.jsxs(ht,{children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:E=>{E.stopPropagation(),x()},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(qt,{className:"h-4 w-4"})})}),e.jsx(ft,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session in worktree"})})]}),(!j||!a)&&e.jsxs(ht,{children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:E=>{E.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(cs,{className:"h-4 w-4"})})}),e.jsx(ft,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session"})})]})]})}),v]})},Rv=({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})})}),Ua=({mobileVariant:t=!1,onSessionSelected:r,allowReselect:s=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,l]=i.useState(null),[c,d]=i.useState(""),[u,m]=i.useState(null),f=i.useRef(null),[p,h]=i.useState(new Set),[x,g]=i.useState(()=>new Map),b=i.useRef(new Set),y=i.useMemo(()=>ws(),[]),[w,S]=i.useState(new Set),[C,v]=i.useState(new Map),[j,M]=i.useState(new Set),[k,D]=i.useState(null),[N,T]=i.useState(!1),[A,E]=i.useState(!1),[I,P]=i.useState(!1),[F,$]=i.useState(null),[Q,ie]=i.useState(new Set),[K,ee]=i.useState(null),V=i.useRef(new Map),ae=i.useRef(0),G=wt(oe=>oe.homeDirectory),q=wt(oe=>oe.currentDirectory),_=wt(oe=>oe.setDirectory),H=Wt(oe=>oe.projects),L=Wt(oe=>oe.activeProjectId),B=Wt(oe=>oe.addProject),O=Wt(oe=>oe.removeProject),le=Wt(oe=>oe.setActiveProject),we=Wt(oe=>oe.setActiveProjectIdOnly),pe=Wt(oe=>oe.reorderProjects),De=je(oe=>oe.setActiveMainTab),z=je(oe=>oe.setSessionSwitcherOpen),he=je(oe=>oe.openMultiRunLauncher),Z=et(oe=>oe.settingsAutoCreateWorktree),de=ge(oe=>oe.sessions),Ee=ge(oe=>oe.sessionsByDirectory),ne=ge(oe=>oe.currentSessionId),ye=ge(oe=>oe.setCurrentSession),te=ge(oe=>oe.updateSessionTitle),ce=ge(oe=>oe.shareSession),X=ge(oe=>oe.unshareSession),U=ge(oe=>oe.sessionMemoryState),Y=ge(oe=>oe.sessionActivityPhase),se=ge(oe=>oe.permissions),me=ge(oe=>oe.worktreeMetadata),ze=ge(oe=>oe.availableWorktreesByProject),qe=ge(oe=>oe.getSessionsByDirectory),tt=ge(oe=>oe.openNewSessionDraft),[Xe,Nt]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),Ne=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{try{const oe=y.getItem(Ld);if(oe){const Ie=JSON.parse(oe);Array.isArray(Ie)&&h(new Set(Ie.filter(fe=>typeof fe=="string")))}const Te=y.getItem(Rd);if(Te){const Ie=JSON.parse(Te);Array.isArray(Ie)&&S(new Set(Ie.filter(fe=>typeof fe=="string")))}}catch{}},[y]),i.useEffect(()=>{typeof window>"u"||Nt(typeof window.opencodeDesktop<"u")},[]);const ue=i.useMemo(()=>[...de].sort((oe,Te)=>(Te.time?.updated||0)-(oe.time?.updated||0)),[de]);i.useEffect(()=>{let oe=!1;const Te=H.map(Ie=>({id:Ie.id,path:yr(Ie.path)})).filter(Ie=>!!Ie.path);return v(new Map),Te.length===0?()=>{oe=!0}:(Te.forEach(Ie=>{_r(Ie.path).then(fe=>{oe||v(xe=>{const Re=new Map(xe);return Re.set(Ie.id,fe),Re})}).catch(()=>{oe||v(fe=>{const xe=new Map(fe);return xe.set(Ie.id,null),xe})})}),()=>{oe=!0})},[H]);const We=i.useMemo(()=>{const oe=new Map;return ue.forEach(Te=>{const Ie=Te.parentID;Ie&&oe.set(Te.id,Ie)}),oe},[ue]),ve=i.useMemo(()=>{const oe=new Map;return ue.forEach(Te=>{const Ie=Te.parentID;if(!Ie)return;const fe=oe.get(Ie)??[];fe.push(Te),oe.set(Ie,fe)}),oe.forEach(Te=>Te.sort((Ie,fe)=>(fe.time?.updated||0)-(Ie.time?.updated||0))),oe},[ue]);i.useEffect(()=>{ne&&h(oe=>{const Te=new Set(oe);let Ie=We.get(ne)||null,fe=!1;for(;Ie;)Te.has(Ie)||(Te.add(Ie),fe=!0),Ie=We.get(Ie)||null;return fe?Te:oe})},[ne,We]),i.useEffect(()=>{const oe=new Set;ue.forEach(Te=>{const Ie=yr(Te.directory??null);Ie&&oe.add(Ie)}),H.forEach(Te=>{const Ie=yr(Te.path);Ie&&oe.add(Ie)}),oe.forEach(Te=>{const Ie=x.get(Te);Ie&&Ie!=="unknown"||b.current.has(Te)||(b.current.add(Te),Oe.listLocalDirectory(Te).then(()=>{g(fe=>{const xe=new Map(fe);return xe.get(Te)==="exists"?fe:(xe.set(Te,"exists"),xe)})}).catch(()=>{g(fe=>{const xe=new Map(fe);return xe.get(Te)==="missing"?fe:(xe.set(Te,"missing"),xe)})}).finally(()=>{b.current.delete(Te)}))})},[ue,H,x]),i.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const ke=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."})]}),Ze=i.useCallback((oe,Te,Ie,fe)=>{if(!Ie){if(fe&&fe!==L&&we(fe),Te&&Te!==q&&_(Te,{showOverlay:!1}),t&&(De("chat"),z(!1)),!s&&oe===ne){r?.(oe);return}ye(oe),r?.(oe)}},[L,s,q,ne,t,r,De,we,ye,_,z]),ct=i.useCallback(async()=>{a&&c.trim()&&(await te(a,c.trim()),l(null),d(""))},[a,c,te]),Ue=i.useCallback(()=>{l(null),d("")},[]),Be=i.useCallback(async oe=>{const Te=await ce(oe.id);Te&&Te.share?.url?W.success("Session shared",{description:"You can copy the link from the menu."}):W.error("Unable to share session")},[ce]),Ve=i.useCallback((oe,Te)=>{navigator.clipboard.writeText(oe).then(()=>{m(Te),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{W.error("Failed to copy URL")})},[]),dt=i.useCallback(async oe=>{await X(oe)?W.success("Session unshared"):W.error("Unable to unshare session")},[X]),pt=i.useCallback(oe=>{const Te=[],Ie=fe=>{(ve.get(fe)??[]).forEach(Re=>{Te.push(Re),Ie(Re.id)})};return Ie(oe),Te},[ve]),Ge=ge(oe=>oe.deleteSession),ut=ge(oe=>oe.deleteSessions),xt=i.useCallback(async oe=>{const Te=pt(oe.id),Ie=me.get(oe.id);if(Ie){const fe=Ie.path,xe=[],Re=new Set;de.forEach(st=>{const mt=me.get(st.id);mt&&mt.path===fe&&!Re.has(st.id)&&(xe.push(st),Re.add(st.id),pt(st.id).forEach(Bt=>{Re.has(Bt.id)||(xe.push(Bt),Re.add(Bt.id))}))}),so.requestDelete({sessions:xe,mode:"worktree",worktree:Ie});return}if(Te.length===0)await Ge(oe.id)?W.success("Session deleted",{action:{label:"OK",onClick:()=>{}}}):W.error("Failed to delete session");else{const fe=[oe.id,...Te.map(st=>st.id)],{deletedIds:xe,failedIds:Re}=await ut(fe);xe.length>0&&W.success(`Deleted ${xe.length} session${xe.length===1?"":"s"}`,{action:{label:"OK",onClick:()=>{}}}),Re.length>0&&W.error(`Failed to delete ${Re.length} session${Re.length===1?"":"s"}`)}},[pt,Ge,ut,me,de]),kt=i.useCallback(()=>{Xe&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(oe=>{oe.success&&oe.path?B(oe.path,{id:oe.projectId})||W.error("Failed to add project",{description:"Please select a valid directory."}):oe.error&&oe.error!=="Directory selection cancelled"&&W.error("Failed to select directory",{description:oe.error})}).catch(oe=>{console.error("Desktop: Error selecting directory:",oe),W.error("Failed to select directory")}):so.requestDirectoryDialog()},[B,Xe]),At=i.useCallback(oe=>{h(Te=>{const Ie=new Set(Te);Ie.has(oe)?Ie.delete(oe):Ie.add(oe);try{y.setItem(Ld,JSON.stringify(Array.from(Ie)))}catch{}return Ie})},[y]),Xt=i.useCallback(oe=>{const Te=ve.get(oe.id)??[];return{session:oe,children:Te.map(Ie=>Xt(Ie)),worktree:me.get(oe.id)??null}},[ve,me]),as=i.useCallback((oe,Te,Ie)=>{const fe=yr(Te??null),xe=[...oe].sort((It,zt)=>(zt.time?.updated||0)-(It.time?.updated||0)),Re=new Map(xe.map(It=>[It.id,It])),st=new Map;xe.forEach(It=>{const zt=It.parentID;if(!zt)return;const ns=st.get(zt)??[];ns.push(It),st.set(zt,ns)}),st.forEach(It=>It.sort((zt,ns)=>(ns.time?.updated||0)-(zt.time?.updated||0)));const mt=new Map;Ie.forEach(It=>{if(It.path){const zt=yr(It.path)??It.path;mt.set(zt,It)}});const Ot=It=>{const zt=yr(It.directory??null),ns=me.get(It.id)??null;if(ns)return ns;if(zt){const Pe=mt.get(zt)??null;if(Pe&&zt!==fe)return Pe}return null},Bt=It=>{const zt=st.get(It.id)??[];return{session:It,children:zt.map(ns=>Bt(ns)),worktree:Ot(It)}},vs=xe.filter(It=>{const zt=It.parentID;return zt?!Re.has(zt):!0}).map(It=>Bt(It));return[{id:"all",label:"All sessions",description:fe?pn(fe,G):null,isMain:!0,worktree:null,directory:fe,sessions:vs}]},[G,me]),_t=i.useCallback(oe=>{M(Te=>{const Ie=new Set(Te);return Ie.has(oe)?Ie.delete(oe):Ie.add(oe),Ie})},[]),Mt=i.useCallback(oe=>{ae.current=Date.now()+150,S(Te=>{const Ie=new Set(Te);Ie.has(oe)?Ie.delete(oe):Ie.add(oe);try{y.setItem(Rd,JSON.stringify(Array.from(Ie)))}catch{}return Ie})},[y]),Rt=i.useMemo(()=>H.map(oe=>({...oe,normalizedPath:yr(oe.path)})).filter(oe=>!!oe.normalizedPath),[H]),Jt=i.useCallback(oe=>{const Te=Ne?[]:ze.get(oe.normalizedPath)??[],Ie=[oe.normalizedPath,...Te.map(Re=>yr(Re.path)??Re.path).filter(Re=>!!Re)],fe=new Set,xe=[];return Ie.forEach(Re=>{(Ee.get(Re)??qe(Re)).forEach(mt=>{fe.has(mt.id)||(fe.add(mt.id),xe.push(mt))})}),xe},[ze,qe,Ee,Ne]),Ft=i.useMemo(()=>Rt.map(oe=>{const Te=Jt(oe),Ie=ze.get(oe.normalizedPath)??[],fe=as(Te,oe.normalizedPath,Ie);return{project:oe,groups:fe}}),[Rt,Jt,as,ze]);i.useEffect(()=>{if(!Xe)return;const oe=new IntersectionObserver(Te=>{Te.forEach(Ie=>{const fe=Ie.target.dataset.projectId;fe&&ie(xe=>{const Re=new Set(xe);return Ie.isIntersecting?Re.delete(fe):Re.add(fe),Re})})},{threshold:0});return V.current.forEach(Te=>{Te&&oe.observe(Te)}),()=>oe.disconnect()},[Xe,Ft]);const Qt=i.useCallback((oe,Te=0,Ie,fe)=>{const xe=oe.session,Re=yr(xe.directory??null)??yr(Ie??null),mt=(Re?x.get(Re):null)==="missing",Ot=U.get(xe.id),Bt=ne===xe.id,Ms=xe.title||"Untitled Session",vs=oe.children.length>0,It=p.has(xe.id),zt=xe.summary?.additions,ns=xe.summary?.deletions,Pe=typeof zt=="number"||typeof ns=="number";if(a===xe.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",Te>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:be=>{be.preventDefault(),ct()},children:[e.jsx("input",{value:c,onChange:be=>d(be.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:be=>{be.key==="Escape"&&Ue()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx($t,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:Ue,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(os,{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:[vs?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:It?e.jsx(Gt,{className:"h-3 w-3"}):e.jsx(Hs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Od(xe.time?.created||Date.now())}),xe.share?e.jsx(fi,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Pe&&((zt??0)!==0||(ns??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,zt??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,ns??0)]})]}):null,vs?e.jsxs("span",{className:"truncate",children:[oe.children.length," ",oe.children.length===1?"task":"tasks"]}):null]})]})},xe.id);const He=Y?.get(xe.id)??"idle",it=He==="busy"||He==="cooldown",re=se.get(xe.id)?.length??0,Ae=Ot&&Ot.isZombie?e.jsx(rl,{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",Bt?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",mt?"opacity-75":"",Te>0&&"pl-[20px]"),onContextMenu:be=>{be.preventDefault(),ee(xe.id)},children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:mt,onClick:()=>Ze(xe.id,Re,mt,fe),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:[it?e.jsx(Gf,{size:"xs",className:"text-primary flex-shrink-0"}):null,e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:Ms}),re>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(Qh,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:re})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[vs?e.jsx("span",{role:"button",tabIndex:0,onClick:be=>{be.stopPropagation(),At(xe.id)},onKeyDown:be=>{(be.key==="Enter"||be.key===" ")&&(be.preventDefault(),be.stopPropagation(),At(xe.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":It?"Collapse subsessions":"Expand subsessions",children:It?e.jsx(Gt,{className:"h-3 w-3"}):e.jsx(Hs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Od(xe.time?.created||Date.now())}),xe.share?e.jsx(fi,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,oe.worktree?e.jsxs(ht,{delayDuration:700,children:[e.jsx(gt,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(qt,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(ft,{side:"top",className:"text-xs",children:oe.worktree.branch||oe.worktree.label||"Worktree"})]}):null,Pe&&((zt??0)!==0||(ns??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,zt??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,ns??0)]})]}):null,vs?e.jsxs("span",{className:"truncate",children:[oe.children.length," ",oe.children.length===1?"task":"tasks"]}):null,mt?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(rl,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Ae,e.jsxs(es,{open:K===xe.id,onOpenChange:be=>ee(be?xe.id:null),children:[e.jsx(ts,{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:be=>be.stopPropagation(),onKeyDown:be=>be.stopPropagation(),children:e.jsx(Zr,{className:t?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"min-w-[180px]",children:[e.jsxs(Ct,{onClick:()=>{l(xe.id),d(Ms)},className:"[&>svg]:mr-1",children:[e.jsx(Er,{className:"mr-1 h-4 w-4"}),"Rename"]}),xe.share?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{onClick:()=>{xe.share?.url&&Ve(xe.share.url,xe.id)},className:"[&>svg]:mr-1",children:u===xe.id?e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(sr,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(Ct,{onClick:()=>dt(xe.id),className:"[&>svg]:mr-1",children:[e.jsx(Yh,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(Ct,{onClick:()=>Be(xe),className:"[&>svg]:mr-1",children:[e.jsx(fi,{className:"mr-1 h-4 w-4"}),"Share"]}),oe.worktree?e.jsxs(Ct,{onClick:()=>{fe&&fe!==L&&le(fe),De("chat"),t&&z(!1),tt({directoryOverride:oe.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(qt,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(Ct,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>xt(xe),children:[e.jsx(Ks,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),vs&&It?oe.children.map(be=>Qt(be,Te+1,Re??Ie,fe)):null]},xe.id)},[x,U,Y,se,ne,p,a,c,ct,Ue,At,Ze,Be,Ve,dt,xt,u,t,L,le,De,z,tt,K]),ps=i.useCallback((oe,Te,Ie)=>{const fe=j.has(Te),xe=n?10:5,Re=oe.sessions.length,st=fe?oe.sessions:oe.sessions.slice(0,xe),mt=Re-st.length;return e.jsxs(e.Fragment,{children:[st.map(Ot=>Qt(Ot,0,oe.directory,Ie)),Re===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,mt>0&&!fe?e.jsxs("button",{type:"button",onClick:()=>_t(Te),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 ",mt," more ",mt===1?"session":"sessions"]}):null,fe&&Re>xe?e.jsx("button",{type:"button",onClick:()=>_t(Te),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,Qt,_t]),Lt=Jh(Ec(og,{activationConstraint:{distance:8}}),Ec(ng,{coordinateGetter:rg})),Me=i.useCallback(oe=>{$(oe.active.id)},[]),$e=i.useCallback(oe=>{const{active:Te,over:Ie}=oe;if($(null),!Ie||Te.id===Ie.id)return;const fe=Rt.findIndex(Re=>Re.id===Te.id),xe=Rt.findIndex(Re=>Re.id===Ie.id);fe!==-1&&xe!==-1&&pe(fe,xe)},[Rt,pe]),Le=i.useCallback(()=>{$(null)},[]),ot=i.useMemo(()=>{if(!F)return null;const oe=Ft.find(Ie=>Ie.project.id===F);if(!oe)return null;const Te=oe.project;return{id:Te.id,label:$d(Te.label?.trim()||Rc(Te.normalizedPath,G)||Te.normalizedPath),isActive:Te.id===L}},[F,Ft,G,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:H.length})]}),e.jsx("button",{type:"button",onClick:kt,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(nl,{className:"h-4.5 w-4.5"})})]})}),e.jsx(jt,{outerClassName:"flex-1 min-h-0",className:R("space-y-1 pb-1 pl-2.5 pr-1",""),children:Ft.length===0?ke:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const oe=Ft.find(fe=>fe.project.id===L)??Ft[0];if(!oe)return ke;const Te=oe.groups.find(fe=>fe.isMain&&fe.sessions.length>0)??oe.groups.find(fe=>fe.sessions.length>0)??oe.groups.find(fe=>fe.isMain)??oe.groups[0];if(!Te)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const Ie=`${oe.project.id}:${Te.id}`;return ps(Te,Ie,oe.project.id)})()}):e.jsxs(Xh,{sensors:Lt,collisionDetection:Zh,onDragStart:Me,onDragEnd:$e,onDragCancel:Le,children:[e.jsx(eg,{items:Rt.map(oe=>oe.id),strategy:tg,children:Ft.map(oe=>{const Te=oe.project,Ie=Te.id,fe=$d(Te.label?.trim()||Rc(Te.normalizedPath,G)||Te.normalizedPath),xe=pn(Te.normalizedPath,G),Re=w.has(Ie),st=Ie===L,mt=C.get(Ie),Ot=k===Ie;return e.jsx(Fv,{id:Ie,projectLabel:fe,projectDescription:xe,isCollapsed:Re,isActiveProject:st,isRepo:!!mt,isHovered:Ot,isDesktopRuntime:Xe,isStuck:Q.has(Ie),hideDirectoryControls:n,mobileVariant:t,onToggle:()=>Mt(Ie),onHoverChange:Bt=>D(Bt?Ie:null),onNewSession:()=>{Ie!==L&&le(Ie),De("chat"),t&&z(!1),tt({directoryOverride:Te.normalizedPath})},onNewWorktreeSession:()=>{Ie!==L&&le(Ie),De("chat"),t&&z(!1),ci()},onOpenBranchPicker:()=>T(!0),onNewSessionFromGitHubIssue:()=>{Ie!==L&&le(Ie),De("chat"),t&&z(!1),E(!0)},onNewSessionFromGitHubPR:()=>{Ie!==L&&le(Ie),De("chat"),t&&z(!1),P(!0)},onOpenMultiRunLauncher:()=>{Ie!==L&&le(Ie),he()},onClose:()=>O(Ie),sentinelRef:Bt=>{V.current.set(Ie,Bt)},settingsAutoCreateWorktree:Z,children:Re?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:oe.groups[0]?ps(oe.groups[0],`${Ie}:all`,Ie):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},Ie)})}),e.jsx(sg,{children:ot?e.jsx(Rv,{projectLabel:ot.label,isActiveProject:ot.isActive}):null})]})}),e.jsx(Mv,{open:N,onOpenChange:T,projects:Rt,activeProjectId:L}),e.jsx(Ev,{open:A,onOpenChange:E}),e.jsx(Tv,{open:I,onOpenChange:P})]})},di=()=>{const[t,r]=_e.useState(!1);_e.useEffect(()=>{r(ds())},[]);const s=_e.useCallback(async a=>t?await Xx(a):{success:!0,path:a},[t]),n=_e.useCallback(async a=>t?await Zx(a):{success:!0},[t]),o=_e.useCallback(async a=>t?await ey(a):{success:!0},[t]);return{isDesktop:t,requestAccess:s,startAccessing:n,stopAccessing:o}},_d=({currentPath:t,onSelectPath:r,triggerClassName:s,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:l,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=i.useMemo(()=>ds(),[]),{isMobile:p}=Kt(),[h,x]=i.useState([]),[g,b]=i.useState(new Set),[y,w]=i.useState(!0),[S,C]=i.useState(!1),[v,j]=i.useState(""),[M,k]=i.useState(new Set),[D,N]=i.useState(null),[T,A]=i.useState(""),[E,I]=i.useState(!0),P=i.useRef(null),{requestAccess:F,startAccessing:$,isDesktop:Q}=di(),ie=i.useRef(c),K=i.useCallback(ne=>{if(!ne)return ne;if(ne==="/"||ne.length===0)return"/";let ye=ne;for(;ye.length>1&&ye.endsWith("/");)ye=ye.slice(0,-1);return ye.length===0?"/":ye},[]),ee=i.useMemo(()=>{if(!v)return null;const ne=v.replace(/\\/g,"/");return K(ne)},[v,K]),V=i.useMemo(()=>{if(typeof d=="string"&&d.length>0){const ne=d.replace(/\\/g,"/"),ye=K(ne);if(ye&&ye!=="/")return ye}return ee&&ee!=="/"?ee:null},[d,ee,K]),ae=i.useMemo(()=>typeof u=="boolean"?!!(u&&V):!!V,[u,V]);i.useEffect(()=>{ae||(w(!0),x([]))},[ae]);const G=i.useCallback(ne=>{if(!ne||!ae||!V)return!1;const ye=ne.replace(/\\/g,"/"),te=K(ye)??ye;if(te===V)return!0;const ce=`${V}/`;return te.startsWith(ce)},[ae,V,K]),q=async ne=>{if(ae){if(a==="deferred"){r(ne);return}if(Q){const ye=await F(ne);ye.success&&ye.path?(await $(ye.path),r(ye.path)):(console.error("Failed to get directory access:",ye.error),r(ne))}else r(ne)}};i.useEffect(()=>{let ne=!1;const ye=X=>{if(!X)return!1;const U=K(X.replace(/\\/g,"/"));return!U||U==="/"?!1:(j(typeof U=="string"?U:X.replace(/\\/g,"/")),!0)};return d&&ye(d)||(async()=>{try{const X=await Oe.getFilesystemHome();if(!ne&&ye(X))return}catch(X){console.warn("Failed to resolve filesystem home directory:",X)}try{const X=await Oe.getSystemInfo();if(!ne&&ye(X?.homeDirectory))return}catch(X){console.warn("Failed to resolve home directory from system info:",X)}})(),()=>{ne=!0}},[d,K]),i.useEffect(()=>{let ne=!1;const ye=U=>{if(ne)return;const Y=U.filter(se=>typeof se=="string"&&se.length>0).map(se=>{const me=se.replace(/\\/g,"/");return K(me)??me});k(new Set(Y))},te=()=>{try{const U=localStorage.getItem("pinnedDirectories");if(!U)return;const Y=JSON.parse(U);Array.isArray(Y)&&ye(Y)}catch(U){console.warn("Failed to load pinned directories from local storage:",U)}},ce=async()=>{try{let U=[];if(f){const Y=await $r();U=Array.isArray(Y?.pinnedDirectories)?Y.pinnedDirectories:[]}else{const Y=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(Y.ok){const se=await Y.json();U=Array.isArray(se?.pinnedDirectories)?se.pinnedDirectories:[]}}if(ne)return;ye(U)}catch(U){console.warn("Failed to load pinned directories:",U)}};te();const X=U=>{const Y=U.detail;Y&&Array.isArray(Y.pinnedDirectories)&&ye(Y.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",X),ce(),()=>{ne=!0,window.removeEventListener("openchamber:settings-synced",X)}},[f,K]);const _=i.useRef(!0);i.useEffect(()=>{if(_.current){_.current=!1;return}const ne={pinnedDirectories:Array.from(M)};is(ne)},[M]),i.useEffect(()=>{V&&k(ne=>{const ye=Array.from(ne).map(te=>K(te.replace(/\\/g,"/"))??te).filter(te=>G(te));return new Set(ye)})},[V,G,K]),i.useEffect(()=>{ie.current!==c&&(ie.current=c)},[c]);const H=ne=>{k(ye=>{if(!G(ne))return ye;const te=K(ne.replace(/\\/g,"/"))??ne.replace(/\\/g,"/"),ce=new Set(ye);return ce.has(te)?ce.delete(te):ce.add(te),ce})},L=i.useMemo(()=>Array.from(M).map(ne=>K(ne.replace(/\\/g,"/"))??ne).filter(ne=>G(ne)).map(ne=>({path:ne,name:ne.split("/").pop()||ne})).sort((ne,ye)=>ne.name.localeCompare(ye.name)),[M,G,K]),B=i.useCallback(async ne=>{const ye=Y=>c||!Y.startsWith("."),te=V;if(!ae||!te)return[];const ce=ne&&ne.length>0?ne:te,X=ce?ce.replace(/\\/g,"/"):null,U=X?K(X)??X:null;if(U){const Y=`${te}/`;if(!(U===te||U.startsWith(Y)))return[]}try{return(await Oe.listLocalDirectory(ne)).filter(se=>{if(!se.isDirectory||!ye(se.name))return!1;const me=se.path.replace(/\\/g,"/"),ze=K(me)??me,qe=ze===te?te:`${te}/`;return ze===te||ze.startsWith(qe)}).map(se=>({name:se.name,path:se.path.replace(/\\/g,"/"),isDirectory:!0})).sort((se,me)=>se.name.localeCompare(me.name))}catch{try{const se=await Oe.getApiClient().file.list({path:".",directory:ne});return se.data?se.data.filter(me=>{if(me.type!=="directory"||!me.name||!ye(me.name))return!1;const ze=String(me.absolute||me.path||me.name).replace(/\\/g,"/"),qe=K(ze)??ze,tt=qe===te?te:`${te}/`;return qe===te||qe.startsWith(tt)}).map(me=>({name:me.name||"",path:String(me.absolute||me.path||me.name).replace(/\\/g,"/"),isDirectory:!0})).filter(me=>me.name!=="").sort((me,ze)=>me.name.localeCompare(ze.name)):[]}catch{return[]}}},[c,V,K,ae]),O=i.useRef(!1),le=i.useCallback(async()=>{if(!ae||!V){w(!0),x([]);return}O.current||w(!0);try{const ne=await B(V);x(ne),O.current=!0}catch{}finally{w(!1)}},[ae,V,B]);i.useEffect(()=>{ae&&(n==="inline"||S)&&le()},[n,S,ae,le]);const we=async ne=>{if(!ae)return;const ye=g.has(ne.path),te=new Set(g);if(ye){te.delete(ne.path),b(te);return}te.add(ne.path),b(te);const ce=await B(ne.path),X=U=>U.map(Y=>Y.path===ne.path?{...Y,children:ce}:Y.children?{...Y,children:X(Y.children)}:Y);x(U=>X(U))};i.useEffect(()=>{D&&P.current&&(P.current.focus(),P.current.select())},[D]);const pe=(ne,ye=[])=>{const te="new_directory",ce=ye.map(se=>se.name);if(!ce.includes(te))return te;let X=1;const U=new RegExp(`^${te}(\\d+)$`);for(const se of ce){const me=se.match(U);if(me){const ze=parseInt(me[1],10);ze>X&&(X=ze)}}let Y=2;for(;ce.includes(`${te}${Y}`);)Y++;return`${te}${Math.max(Y,X+1)}`},De=async ne=>{if(ae){if(g.has(ne.path)){const ye=pe(ne.path,ne.children);A(ye)}else{const ye=new Set(g);if(ye.add(ne.path),b(ye),ne.children){const te=pe(ne.path,ne.children);A(te)}else{const te=await B(ne.path),ce=U=>U.map(Y=>Y.path===ne.path?{...Y,children:te}:Y.children?{...Y,children:ce(Y.children)}:Y);x(U=>ce(U));const X=pe(ne.path,te);A(X)}}N(ne.path)}},z=async()=>{if(!D||!ae)return;const ne=T.trim()||"new_directory",ye=`${D}/${ne}`;try{await Oe.createDirectory(ye);const te=await B(D),ce=X=>X.map(U=>U.path===D?{...U,children:te}:U.children?{...U,children:ce(U.children)}:U);x(X=>ce(X)),N(null),A("")}catch(te){console.error("Failed to create directory:",te)}},he=()=>{N(null),A("")},Z=(ne,ye=0)=>{const te=g.has(ne.path),ce=ne.isDirectory,X=M.has(ne.path),U=t===ne.path,Y=n==="inline",se=e.jsxs(e.Fragment,{children:[ce&&e.jsx("button",{onClick:me=>{me.stopPropagation(),we(ne)},className:R("hover:bg-accent rounded","p-0.5"),children:te?e.jsx(Gt,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Hs,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!ce&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:me=>{me.stopPropagation(),q(ne.path),n==="dropdown"&&a==="immediate"&&C(!1)},onDoubleClick:me=>{me.stopPropagation(),l&&l(ne.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",Y&&U?"text-primary":"text-foreground"),children:[e.jsx(ir,{className:R("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",Y&&U&&"text-primary")}),e.jsx("span",{className:R("font-medium truncate","typography-ui-label",Y&&U?"text-primary":"text-foreground"),children:ne.name})]}),e.jsx("button",{onClick:me=>{me.stopPropagation(),De(ne)},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(cs,{className:R("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:me=>{me.stopPropagation(),H(ne.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:X?"Unpin directory":"Pin directory",children:X?e.jsx(pi,{className:R("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(ig,{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",U?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${ye*(p?12:14)+(p?4:6)}px`},children:se}),te&&e.jsxs(e.Fragment,{children:[D===ne.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(ye+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ir,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{ref:P,value:T,onChange:me=>A(me.target.value),onKeyDown:me=>{me.key==="Enter"?(me.preventDefault(),me.stopPropagation(),z()):me.key==="Escape"&&(me.preventDefault(),me.stopPropagation(),he())},onBlur:z,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:me=>{me.preventDefault(),me.stopPropagation(),z()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx($t,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:me=>{me.preventDefault(),me.stopPropagation(),he()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(os,{className:"h-3 w-3 text-muted-foreground"})})]}),ne.children&&ne.children.map(me=>Z(me,ye+1))]})]},ne.path):e.jsxs("div",{children:[e.jsxs(Ct,{className:R("flex items-center gap-1 cursor-pointer group",t===ne.path&&"bg-accent"),style:{paddingLeft:`${ye*12+8}px`},onSelect:me=>{me.preventDefault()},children:[ce&&e.jsx("button",{onClick:me=>{me.stopPropagation(),we(ne)},className:"p-0.5 hover:bg-accent rounded",children:te?e.jsx(Gt,{className:"h-3 w-3"}):e.jsx(Hs,{className:"h-3 w-3"})}),!ce&&e.jsx("div",{className:"w-4"}),se]}),te&&e.jsxs("div",{children:[D===ne.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(ye+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ir,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{ref:P,value:T,onChange:me=>A(me.target.value),onKeyDown:me=>{me.key==="Enter"?(me.preventDefault(),me.stopPropagation(),z()):me.key==="Escape"&&(me.preventDefault(),me.stopPropagation(),he())},onBlur:z,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:me=>{me.preventDefault(),me.stopPropagation(),z()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx($t,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:me=>{me.preventDefault(),me.stopPropagation(),he()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(os,{className:"h-3 w-3 text-muted-foreground"})})]}),ne.children&&ne.children.map(me=>Z(me,ye+1))]})]},ne.path)},de=(ne,ye)=>{if(n==="inline"){const te=t===ye;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",te?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>q(ye),onDoubleClick:ce=>{ce.stopPropagation(),l&&l(ye)},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",te?"text-primary":"text-foreground"),children:[e.jsx(ir,{className:R("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",te?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:R("typography-ui-label font-medium truncate flex-shrink-0",te?"text-primary":"text-foreground"),children:ne}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:pn(ye,v)})]}),e.jsx("button",{onClick:()=>H(ye),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(pi,{className:R("text-primary","h-3.5 w-3.5")})})]},ye)}return e.jsxs(Ct,{onSelect:te=>{te.preventDefault(),q(ye),a==="immediate"&&C(!1)},className:R("flex items-start gap-2 cursor-pointer group py-2",t===ye&&"bg-accent"),children:[e.jsx(ir,{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:ne}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:pn(ye,v)})]}),e.jsx("button",{onClick:te=>{te.stopPropagation(),te.preventDefault(),H(ye)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(pi,{className:"h-3 w-3 text-primary"})})]},ye)},Ee=e.jsx(e.Fragment,{children:ae?e.jsxs(e.Fragment,{children:[L.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>I(ne=>!ne),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:[E?e.jsx(Gt,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Hs,{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:L.length})]}),E&&L.map(({name:ne,path:ye})=>de(ne,ye)),n==="dropdown"&&e.jsx(Ds,{}),n==="inline"&&E&&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(ne=>Z(ne)),!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(jt,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:Ee})}):e.jsxs(es,{open:S,onOpenChange:C,children:[e.jsx(ts,{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(ir,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:t,children:pn(t,v)})]}),e.jsx(Gt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(ss,{align:"start",className:"w-[350px]",children:e.jsx(jt,{outerClassName:"h-full",className:"w-full",children:Ee})})]})},ui=(t,r=200)=>{const[s,n]=_e.useState(t);return _e.useEffect(()=>{const o=window.setTimeout(()=>{n(t)},r);return()=>{window.clearTimeout(o)}},[t,r]),s},Kf=i.forwardRef(({inputValue:t,homeDirectory:r,onSelectSuggestion:s,visible:n,onClose:o,showHidden:a},l)=>{const[c,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(0),h=i.useRef(null),x=i.useRef([]),g=i.useCallback((v,j)=>{const M=v.trim().toLowerCase();if(!M)return 0;const k=j.toLowerCase();let D=0,N=-1,T=0;for(let A=0;A<M.length;A+=1){const E=M[A];if(!E||E===" ")continue;const I=k.indexOf(E,N+1);if(I===-1)return null;const P=I-N-1;if(P===0?T+=1:T=0,D+=10,D+=Math.max(0,18-I),D-=Math.max(0,P),I===0)D+=12;else{const F=k[I-1];(F==="/"||F==="_"||F==="-"||F==="."||F===" ")&&(D+=10)}D+=T>0?12:0,N=I}return D+=Math.max(0,24-Math.round(k.length/3)),D},[]),b=i.useCallback(v=>v.startsWith("~")&&r?v.replace(/^~/,r):v,[r]),y=i.useCallback(v=>{const j=b(v);if(j.endsWith("/"))return j;const M=j.lastIndexOf("/");return M===-1?"":M===0?"/":j.substring(0,M+1)},[b]),w=i.useCallback(v=>{const j=b(v);if(j.endsWith("/"))return"";const M=j.lastIndexOf("/");return M===-1?j:j.substring(M+1)},[b]),S=ui(t,150);i.useEffect(()=>{if(!n||!S){d([]);return}const v=y(S),j=w(S).toLowerCase();if(!v){d([]);return}let M=!1;return m(!0),Oe.listLocalDirectory(v).then(k=>{if(M)return;const D=k.filter(T=>!(!T.isDirectory||!a&&T.name.startsWith("."))),N=j?D.map(T=>{const A=g(j,T.name);return A!==null?{entry:T,score:A}:null}).filter(T=>T!==null).sort((T,A)=>A.score-T.score||T.entry.name.localeCompare(A.entry.name)).map(T=>T.entry):D.sort((T,A)=>T.name.localeCompare(A.name));d(N.slice(0,10)),p(0)}).catch(()=>{M||d([])}).finally(()=>{M||m(!1)}),()=>{M=!0}},[n,S,y,w,a,g]),i.useEffect(()=>{x.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),i.useEffect(()=>{if(!n)return;const v=j=>{const M=j.target;!M||!h.current||h.current.contains(M)||o()};return document.addEventListener("pointerdown",v,!0),()=>{document.removeEventListener("pointerdown",v,!0)}},[n,o]);const C=i.useCallback(v=>{const j=v.path.endsWith("/")?v.path:v.path+"/";s(j)},[s]);return i.useImperativeHandle(l,()=>({handleKeyDown:v=>{if(!n||c.length===0)return!1;const j=c.length;if(v.key==="Tab"){if(v.preventDefault(),v.shiftKey)p(M=>(M-1+j)%j);else if(j===1){const M=c[0];M&&C(M)}else p(M=>(M+1)%j);return!0}if(v.key==="ArrowDown")return v.preventDefault(),p(M=>(M+1)%j),!0;if(v.key==="ArrowUp")return v.preventDefault(),p(M=>(M-1+j)%j),!0;if(v.key==="Enter"){v.preventDefault();const M=(f%j+j)%j,k=c[M];return k&&C(k),o(),!0}return v.key==="Escape"?(v.preventDefault(),o(),!0):!1}}),[n,c,f,C,o]),!n||c.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(Qr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:c.map((v,j)=>{const M=f===j;return e.jsxs("div",{ref:k=>{x.current[j]=k},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",M&&"bg-muted"),onClick:()=>{C(v),o()},onMouseEnter:()=>p(j),children:[e.jsx(pr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:v.name})]},v.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"})]})});Kf.displayName="DirectoryAutocomplete";const Lv=({open:t,onOpenChange:r})=>{const{currentDirectory:s,homeDirectory:n,isHomeReady:o}=wt(),{addProject:a,getActiveProject:l}=Wt(),[c,d]=i.useState(null),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,x]=i.useState(!1),g=Ro(),{isDesktop:b,requestAccess:y,startAccessing:w}=di(),{isMobile:S}=Kt(),[C,v]=i.useState(!1),j=i.useRef(null),M=i.useCallback(q=>q?pn(q,n):"",[n]);i.useEffect(()=>{if(t){p(!1),x(!1),v(!1);const _=l()?.path||s||n||"";d(_),m(M(_))}},[t,s,n,M,l]),i.useEffect(()=>{!t||f||c||n&&o&&(d(n),p(!0),m("~"))},[t,f,c,n,o]);const k=i.useCallback(()=>{r(!1)},[r]),D=i.useCallback(async q=>{if(!(!q||h)){x(!0);try{let _=q,H;if(b){const B=await y(q);if(!B.success){W.error("Unable to access directory",{description:B.error||"Desktop denied directory access."});return}_=B.path??q,H=B.projectId;const O=await w(_);if(!O.success){W.error("Failed to open directory",{description:O.error||"Desktop could not grant file access."});return}}if(!a(_,{id:H})){W.error("Failed to add project",{description:"Please select a valid directory path."});return}k()}catch(_){W.error("Failed to select directory",{description:_ instanceof Error?_.message:"Unknown error occurred."})}finally{x(!1)}}},[a,k,b,y,w,h]),N=i.useCallback(async()=>{const q=u.trim()||c;q&&await D(q)},[D,u,c]),T=i.useCallback(q=>{d(q),p(!0),m(M(q))},[M]),A=i.useCallback(async q=>{d(q),p(!0),m(M(q)),await D(q)},[D,M]),E=i.useCallback(q=>{const _=q.target.value;if(m(_),p(!0),v(_.startsWith("/")||_.startsWith("~")),_.startsWith("/")||_.startsWith("~")){const H=_.startsWith("~")&&n?_.replace(/^~/,n):_;d(H)}},[n]),I=i.useCallback(q=>{j.current?.handleKeyDown(q)||q.key==="Enter"&&(q.preventDefault(),N())},[N]),P=i.useCallback(q=>{d(q),p(!0),m(M(q))},[M]),F=i.useCallback(()=>{v(!1)},[]),$=i.useCallback(()=>{Gl(!g)},[g]),Q=e.jsxs("button",{type:"button",onClick:$,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:[g?e.jsx(Sn,{className:"h-4 w-4 text-primary"}):e.jsx(Nn,{className:"h-4 w-4"}),"Show hidden"]}),ie=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(Ns,{className:"flex-1",children:"Choose a folder to add as a project."}),Q]})]}),K=e.jsxs("div",{className:"relative",children:[e.jsx(St,{value:u,onChange:E,onKeyDown:I,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(Kf,{ref:j,inputValue:u,homeDirectory:n,onSelectSuggestion:P,visible:C,onClose:F,showHidden:g})]}),ee=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(_d,{variant:"inline",currentPath:c??s,onSelectPath:T,onDoubleClickPath:A,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o})}),V=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:K}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children: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(_d,{variant:"inline",currentPath:c??s,onSelectPath:T,onDoubleClickPath:A,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),ae=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[K,ee]}),G=()=>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:N,disabled:h||!f||!c&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:h?"Adding...":"Add Project"})]});return S?e.jsx(zs,{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:G()}),children:V}):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:q=>{q.preventDefault()},children:[ie,ae,e.jsx(Vs,{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:G()})]})})},ea=t=>t?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,Ov=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},$v=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),o=i.useRef(new Set),[a,l]=i.useState(null),[c,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(!1),{deleteSession:h,deleteSessions:x,loadSessions:g,getWorktreeMetadata:b}=ge(),{currentDirectory:y,homeDirectory:w,isHomeReady:S}=wt(),{projects:C,addProject:v,activeProjectId:j}=Wt(),{requestAccess:M,startAccessing:k}=di(),{isMobile:D,isTablet:N,hasTouchInput:T}=Kt(),A=D||N||T,E=i.useMemo(()=>{const le=(j?C.find(we=>we.id===j)??null:null)?.path??y;return Ov(le)},[j,y,C]),I=i.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||c.some(O=>O.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,c]),P=i.useMemo(()=>{const O=a?.worktree;return O&&typeof O.branch=="string"&&O.branch.trim().length>0?!0:c.length>0&&c.every(({metadata:le})=>typeof le.branch=="string"&&le.branch.trim().length>0)},[a?.worktree,c]),F=a?.mode==="worktree",$=F,Q=f||!F||!P;i.useEffect(()=>{E&&(o.current.has(E)||bb(E).then(()=>o.current.add(E)).catch(O=>{console.warn("Failed to ensure .openchamber directory is ignored:",O),o.current.delete(E)}))},[E]),i.useEffect(()=>{g()},[g,y]);const ie=i.useMemo(()=>C.map(O=>`${O.id}:${O.path}`).join("|"),[C]),K=i.useRef(ie);i.useEffect(()=>{ie!==K.current&&(K.current=ie,g())},[g,ie]),i.useEffect(()=>{if(!(s||!S||C.length>0)){if(n(!0),ds()){M("").then(async O=>{if(!O.success||!O.path){O.error&&O.error!=="Directory selection cancelled"&&W.error("Failed to select directory",{description:O.error});return}const le=await k(O.path);if(!le.success){W.error("Failed to open directory",{description:le.error||"Desktop could not grant file access."});return}v(O.path,{id:O.projectId})||W.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(O=>{console.error("Desktop: Error selecting directory:",O),W.error("Failed to select directory")});return}r(!0)}},[v,s,S,C.length,M,k]);const ee=i.useCallback(O=>{l({sessions:O.sessions,dateLabel:O.dateLabel,mode:O.mode??"session",worktree:O.worktree??null})},[]),V=i.useCallback(()=>{l(null),d([]),m(!1),p(!1)},[]);i.useEffect(()=>so.onDeleteRequest(O=>{ee(O)}),[ee]),i.useEffect(()=>so.onDirectoryRequest(()=>{r(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1);return}const O=a.sessions.map(we=>{const pe=b(we.id);return pe?{session:we,metadata:pe}:null}).filter(we=>!!we);if(d(O),m(!1),O.length===0)return;let le=!1;return(async()=>{const we=await Promise.all(O.map(async({metadata:pe})=>{if(pe.status&&typeof pe.status.isDirty=="boolean")return pe.status;try{return await Oo(pe.path)}catch{return pe.status}})).catch(pe=>(console.warn("Failed to inspect worktree status before deletion:",pe),O.map(({metadata:De})=>De.status)));le||!Array.isArray(we)||d(pe=>pe.map((De,z)=>({session:De.session,metadata:{...De.metadata,status:we[z]??De.metadata.status}})))})(),()=>{le=!0}},[a,b]),i.useEffect(()=>{P||m(!1)},[P]);const ae=i.useCallback(async()=>{if(a){p(!0);try{const O=$,le=O&&u;if(a.sessions.length===0&&F&&a.worktree){const we=u&&P;await wf({projectDirectory:E,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:we});const pe=we?"Worktree and remote branch removed.":"Worktree removed.";W.success("Worktree removed",{description:ea(pe)}),V(),g();return}if(a.sessions.length===1){const we=a.sessions[0];if(!await h(we.id,{archiveWorktree:O,deleteRemoteBranch:le})){W.error("Failed to delete session"),p(!1);return}const De=O?le?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;W.success("Session deleted",{description:ea(De),action:{label:"OK",onClick:()=>{}}})}else{const we=a.sessions.map(z=>z.id),{deletedIds:pe,failedIds:De}=await x(we,{archiveWorktree:O,deleteRemoteBranch:le});if(pe.length>0){const z=O?le?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,Z=[De.length>0?`${De.length} session${De.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,z].filter(Boolean).join(" ");W.success(`Deleted ${pe.length} session${pe.length===1?"":"s"}`,{description:ea(Z||void 0),action:{label:"OK",onClick:()=>{}}})}if(De.length>0&&(W.error(`Failed to delete ${De.length} session${De.length===1?"":"s"}`,{description:ea("Please try again in a moment.")}),pe.length===0)){p(!1);return}}V()}finally{p(!1)}}},[a,u,h,x,V,$,F,P,E,g]),G=a?.worktree??c[0]?.metadata??null,q=a?a.mode==="worktree"?a.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and ${a.sessions.length===1?"1 linked session":`${a.sessions.length} linked sessions`}.`:`This action permanently removes ${a.sessions.length===1?"1 session":`${a.sessions.length} sessions`}${a.dateLabel?` from ${a.dateLabel}`:""}.`:"",_=a?e.jsxs("div",{className:R(F?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&e.jsxs("div",{className:R(F?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[F&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:a.sessions.length===1?"Linked session":"Linked sessions"}),e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:a.sessions.length})]}),e.jsxs("ul",{className:R(F?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(O=>e.jsxs("li",{className:R(F?"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(!F&&"hidden"),children:"•"}),e.jsx("span",{className:"truncate",children:O.title||"Untitled Session"})]},O.id)),a.sessions.length>5&&e.jsxs("li",{className:R(F?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",a.sessions.length-5," more"]})]})]}),F?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(qt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),G?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:G.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:G?pn(G.path,w):"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,H=F?P?e.jsxs("button",{type:"button",onClick:()=>{Q||m(O=>!O)},disabled:Q,className:R("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",Q?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?e.jsx(Sn,{className:"size-4 text-primary"}):e.jsx(Nn,{className:"size-4"}),"Delete remote branch"]}):e.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,L=F?e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[H,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{variant:"ghost",onClick:V,disabled:f,children:"Cancel"}),e.jsx(Se,{variant:"destructive",onClick:ae,disabled:f,children:f?"Deleting…":"Delete worktree"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Se,{variant:"ghost",onClick:V,disabled:f,children:"Cancel"}),e.jsx(Se,{variant:"destructive",onClick:ae,disabled:f,children:f?"Deleting…":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),B=F?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[A?e.jsx(zs,{open:!!a,onClose:()=>{f||V()},title:B,footer:e.jsx("div",{className:"flex justify-end gap-2",children:L}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[q&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:q}),_]})}):e.jsx(us,{open:!!a,onOpenChange:O=>{if(!O){if(f)return;V()}},children:e.jsxs(ms,{className:R(F?"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(F&&"flex items-center gap-2"),children:[F&&e.jsx(Ks,{className:"h-5 w-5"}),B]}),q&&e.jsx(Ns,{children:q})]}),e.jsx("div",{className:R(F&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:_}),e.jsx(Vs,{className:"mt-2 gap-2 pt-1 pb-1",children:L})]})}),e.jsx(Lv,{open:t,onOpenChange:r})]})};function _v(){return new Worker(lg,{type:"module"})}const Bv=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function zv(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 Bd(t){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>t(void 0),0);return()=>window.clearTimeout(r)}const Hv=({children:t})=>{const r=dg(),s=ls(c=>c.activeDirectory),n=ls(c=>s?c.directories.get(s)?.lastStatusChange??0:0),o=ls(c=>s?c.directories.get(s)?.diffCache.size??0:0),a=_e.useRef(!1),l=_e.useRef(new Map);return _e.useEffect(()=>{if(!r||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=sl(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),_e.useEffect(()=>{if(!r||!s||!n||o===0)return;const c=ls.getState().directories.get(s);if(!c||c.diffCache.size===0||(l.current.get(s)??0)>=c.lastStatusChange)return;l.current.set(s,c.lastStatusChange);let u=!1,m=null;const f=Array.from(c.diffCache.entries());let p=0;const h=x=>{if(u)return;const g=Date.now();for(;p<f.length&&!(x&&x.timeRemaining()<8||!x&&Date.now()-g>8);){const[b,y]=f[p];p+=1,Cr(b);const w=zv(b,y.original,y.modified),S={name:b,contents:y.original,cacheKey:`old-${w}`},C={name:b,contents:y.modified,cacheKey:`new-${w}`},v=sl(S,C),j={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(j,v)}p<f.length&&(m=Bd(h))};return h(void 0),p<f.length&&(m=Bd(h)),()=>{u=!0,m?.()}},[r,s,n,o]),e.jsx(e.Fragment,{children:t})},Wv=({children:t})=>{const s=li()?.currentTheme?.metadata?.variant==="dark";Rf();const n=_e.useMemo(()=>({theme:{dark:to.dark,light:to.light},themeType:s?"dark":"light",langs:Bv}),[s]);return e.jsx(cg,{poolOptions:{workerFactory:_v,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(Hv,{children:t})})},jl=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),Uv=(t,r)=>{const s=jl(t),n=jl(r);return`${s}-${n}`.substring(0,60)},zd=(t,r)=>`${t}/${r}`,Vv=t=>t.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),Gv=()=>{const t=Wt.getState(),r=t.activeProjectId,s=r?t.projects.find(c=>c.id===r)?.path:void 0;if(typeof s=="string"&&s.trim().length>0)return s;const n=wt.getState().currentDirectory??null;if(!n)return null;const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n,l=o.indexOf("/.openchamber/");return l>0?o.slice(0,l):o.endsWith("/.openchamber")?o.slice(0,o.length-13):o},No=rs()(fs(t=>({isLoading:!1,error:null,createMultiRun:async r=>{const s=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:l,setupCommands:c}=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=Gv();if(!d)return t({error:"No directory selected",isLoading:!1}),null;if(!await _r(d))return t({error:"Not in a git repository",isLoading:!1}),null;const m=jl(s),f=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",p=f!=="HEAD"?f:void 0,h=[],x=c?.filter(v=>v.trim().length>0)??[],g=new Map;for(const v of o){const j=`${v.providerID}:${v.modelID}`;g.set(j,(g.get(j)||0)+1)}const b=new Map;for(const v of o){const j=`${v.providerID}:${v.modelID}`,M=g.get(j)||1,k=(b.get(j)||0)+1;b.set(j,k);const D=Uv(v.providerID,v.modelID),N=M>1?zd(m,`${D}/${k}`):zd(m,D);if(!N)return t({error:"Branch name is required for worktree creation",isLoading:!1}),null;const T=Vv(N);if(!T)return t({error:`Invalid branch name: ${N}`,isLoading:!1}),null;try{const A=await ai({projectDirectory:d,worktreeSlug:T,branch:N,createBranch:!0,startPoint:p}),E=M>1?`${m}/${v.providerID}/${v.modelID}/${k}`:`${m}/${v.providerID}/${v.modelID}`,I=await Oe.withDirectory(A.path,()=>Oe.createSession({title:E}));bt.getState().setWorktreeMetadata(I.id,A),h.push({sessionId:I.id,worktreePath:A.path,providerID:v.providerID,modelID:v.modelID,variant:v.variant})}catch(A){console.warn("[MultiRun] Failed to create session:",A)}}const y=c?.filter(v=>v.trim().length>0)??[];y.length>0&&xf(d,y).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const w=h.map(v=>v.sessionId),S=h[0]?.sessionId??null;if(w.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const C=l?.map(v=>({type:"file",mime:v.mime,filename:v.filename,url:v.url}));try{await bt.getState().loadSessions()}catch{}if(x.length>0)for(const v of h)ii(v.worktreePath,d,x).then(j=>{if(!j.success){const M=j.results.filter(k=>!k.success);console.warn(`[MultiRun] Setup commands failed for ${v.worktreePath}:`,M)}}).catch(j=>{console.warn(`[MultiRun] Setup commands error for ${v.worktreePath}:`,j)});return(async()=>{try{await Promise.allSettled(h.map(async v=>{try{await Oe.withDirectory(v.worktreePath,()=>Oe.sendMessage({id:v.sessionId,providerID:v.providerID,modelID:v.modelID,variant:v.variant,text:n,agent:a,files:C}))}catch(j){console.warn("[MultiRun] Failed to start run:",j)}}))}catch(v){console.warn("[MultiRun] Failed to start runs:",v)}})(),t({isLoading:!1}),{groupSlug:m,sessionIds:w,firstSessionId:S}}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(ug,{"data-slot":"select",...t})}function yn({...t}){return e.jsx(yg,{"data-slot":"select-group",...t})}function kn({...t}){return e.jsx(pg,{"data-slot":"select-value",...t})}function Es({className:t,size:r="default",children:s,...n}){return e.jsxs(mg,{"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(fg,{asChild:!0,children:e.jsx(Gt,{className:"size-4 opacity-50"})})]})}function Is({className:t,children:r,position:s="popper",fitContent:n=!1,...o}){return e.jsx(hg,{children:e.jsx(gg,{"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(jt,{as:xg,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 qn({className:t,...r}){return e.jsx(bg,{"data-slot":"select-label",className:R("text-muted-foreground px-2 py-1.5 typography-meta",t),...r})}function Ht({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(vg,{children:e.jsx($t,{className:"size-4"})})}),e.jsx(jg,{children:r})]})}function Va({className:t,...r}){return e.jsx(Sg,{"data-slot":"select-separator",className:R("bg-border pointer-events-none -mx-1 my-1 h-px",t),...r})}const qv="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",Kv=Object.assign({"../assets/provider-logos/gocode.svg":qv}),Sl=new Map;for(const[t,r]of Object.entries(Kv)){const s=t.match(/provider-logos\/([^/]+)\.svg$/i);s?.[1]&&r&&Sl.set(s[1].toLowerCase(),r)}function Qf(t){const r=t?.toLowerCase()??null,s=r?Sl.has(r):!1,n=r?Sl.get(r)??null:null,[o,a]=_e.useState(s?"local":"remote");_e.useEffect(()=>{a(s?"local":"remote")},[s,r]);const l=_e.useCallback(()=>{a(c=>c==="local"&&s?"remote":"none")},[s]);return r?o==="local"&&n?{src:n,onError:l,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:l,hasLogo:!0}:{src:null,onError:l,hasLogo:!1}:{src:null,onError:l,hasLogo:!1}}const gs=({providerId:t,alt:r,className:s,onError:n})=>{const{src:o,onError:a,hasLogo:l}=Qf(t),c=i.useCallback(()=>{a(),n?.()},[a,n]);return!l||!o?null:e.jsx("img",{src:o,alt:r||`${t} logo`,className:R("dark:invert",s),onError:c})},pc=t=>t.nativeEvent.isComposing||t.nativeEvent.keyCode===229,hc=()=>{const{providers:t}=et(),{favoriteModels:r,recentModels:s}=je(),n=i.useMemo(()=>r.map(({providerID:a,modelID:l})=>{const c=t.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null),[r,t]),o=i.useMemo(()=>s.map(({providerID:a,modelID:l})=>{const c=t.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:l})=>!r.some(c=>c.providerID===a&&c.modelID===l)),[s,t,r]);return{favoriteModelsList:n,recentModelsList:o}},Yf="h-7",Ga=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Qv=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Yv=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=Qv.format(t);return r.endsWith(".0")?r.slice(0,-2):r},Jv=({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",Yf),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(os,{className:"h-3.5 w-3.5"})})]})},Jf=({selectedModels:t,onAdd:r,onRemove:s,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:l=!0,maxModels:c})=>{const{providers:d,modelsMetadata:u}=et(),{favoriteModelsList:m,recentModelsList:f}=hc(),[p,h]=i.useState(!1),[x,g]=i.useState(""),[b,y]=i.useState(0),[w,S]=i.useState(null),C=i.useRef(null),v=i.useRef(null),j=i.useRef(null),M=i.useRef([]),k=i.useMemo(()=>{const Q=new Map;for(const ie of t){const K=`${ie.providerID}:${ie.modelID}`;Q.set(K,(Q.get(K)||0)+1)}return Q},[t]),D=i.useCallback(Q=>t.filter(K=>K.providerID===Q.providerID&&K.modelID===Q.modelID).findIndex(K=>K.instanceId===Q.instanceId)+1,[t]),N=(Q,ie)=>{const K=`${Q}/${ie}`;return u.get(K)},T=Q=>{const ie=Q?.name||Q?.id||"",K=String(ie);return K.length>40?K.substring(0,37)+"...":K},A=i.useCallback((Q,ie)=>{if(!x.trim())return!0;const K=x.toLowerCase();return Q.toLowerCase().includes(K)||ie.toLowerCase().includes(K)},[x]),E=i.useMemo(()=>m.filter(({model:Q,providerID:ie})=>{const ee=d.find(ae=>ae.id===ie)?.name||ie,V=T(Q);return A(V,ee)}),[m,d,A]),I=i.useMemo(()=>f.filter(({model:Q,providerID:ie})=>{const ee=d.find(ae=>ae.id===ie)?.name||ie,V=T(Q);return A(V,ee)}),[f,d,A]),P=i.useMemo(()=>d.map(Q=>{const K=(Array.isArray(Q.models)?Q.models:[]).filter(ee=>{const V=T(ee);return A(V,Q.name||Q.id||"")});return{...Q,models:K}}).filter(Q=>Q.models.length>0),[d,A]),F=E.length>0||I.length>0||P.length>0;i.useEffect(()=>{if(p&&j.current){const ie=j.current.getBoundingClientRect().top-100;S(Math.max(150,Math.min(400,ie)))}},[p]),i.useEffect(()=>{p&&C.current&&C.current.focus()},[p]),i.useEffect(()=>{if(!p)return;const Q=ie=>{v.current&&!v.current.contains(ie.target)&&(h(!1),g(""),y(0))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[p]),i.useEffect(()=>{y(0)},[x]);const $=(Q,ie,K,ee,V,ae)=>{const G=`${ie}:${K}`,q=k.get(G)||0,_=N(ie,K),H=Yv(_?.limit?.context),L=ee==="fav"||ee==="recent";return e.jsxs("button",{ref:B=>{M.current[V]=B},type:"button",onClick:()=>{r({providerID:ie,modelID:K,displayName:Q.name||K,instanceId:Ga()})},onMouseEnter:()=>y(V),className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",ae?"bg-accent":"hover:bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[L&&e.jsx(gs,{providerId:ie,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:T(Q)}),H&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:H})]}),q>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",q]})]},`${ee}-${G}`)};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:v,children:[e.jsxs(Se,{ref:j,type:"button",variant:"outline",size:"sm",className:Yf,onClick:()=>h(!p),children:[e.jsx(cs,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const Q=[];E.forEach(({model:V,providerID:ae,modelID:G})=>{Q.push({model:V,providerID:ae,modelID:G,section:"fav"})}),I.forEach(({model:V,providerID:ae,modelID:G})=>{Q.push({model:V,providerID:ae,modelID:G,section:"recent"})}),P.forEach(V=>{V.models.forEach(ae=>{Q.push({model:ae,providerID:V.id,modelID:ae.id,section:"provider"})})});const ie=Q.length,K=V=>{if(!pc(V))if(V.key==="ArrowDown"){V.preventDefault(),V.stopPropagation();const ae=(b+1)%Math.max(1,ie);y(ae),setTimeout(()=>{M.current[ae]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(V.key==="ArrowUp"){V.preventDefault(),V.stopPropagation();const ae=(b-1+Math.max(1,ie))%Math.max(1,ie);y(ae),setTimeout(()=>{M.current[ae]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(V.key==="Enter"){V.preventDefault(),V.stopPropagation();const ae=Q[b];ae&&r({providerID:ae.providerID,modelID:ae.modelID,displayName:ae.model.name||ae.modelID,instanceId:Ga()})}else V.key==="Escape"&&(V.preventDefault(),V.stopPropagation(),h(!1),g(""),y(0))};let ee=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(Us,{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:x,onChange:V=>g(V.target.value),onKeyDown:K,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(jt,{outerClassName:"flex-1",style:{maxHeight:w?`${w}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"}),E.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(Ir,{className:"h-4 w-4 text-primary"}),"Favorites"]}),E.map(({model:V,providerID:ae,modelID:G})=>{const q=ee++;return $(V,ae,G,"fav",q,b===q)})]}),I.length>0&&e.jsxs(e.Fragment,{children:[E.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(Sr,{className:"h-4 w-4"}),"Recent"]}),I.map(({model:V,providerID:ae,modelID:G})=>{const q=ee++;return $(V,ae,G,"recent",q,b===q)})]}),(E.length>0||I.length>0)&&P.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),P.map((V,ae)=>e.jsxs(i.Fragment,{children:[ae>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:V.id,className:"h-4 w-4 flex-shrink-0"}),V.name]}),V.models.map(G=>{const q=ee++;return $(G,V.id,G.id,"provider",q,b===q)})]},V.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"})]})})()]}),l&&t.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:t.map((Q,ie)=>{const K=`${Q.providerID}:${Q.modelID}`,ee=k.get(K)||1,V=D(Q),G=d.find(B=>B.id===Q.providerID)?.models.find(B=>B.id===Q.modelID),q=G?.variants?Object.keys(G.variants):[],_=q.length>0,H="__default__",L=Q.variant??H;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Jv,{model:Q,instanceIndex:V,totalSameModel:ee,onRemove:()=>s(ie)}),_&&e.jsxs(As,{value:L,onValueChange:B=>{if(!n)return;n(ie,{...Q,variant:B===H?void 0:B})},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(Nr,{className:R("h-3.5 w-3.5 flex-shrink-0",L===H?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(kn,{placeholder:"Thinking"})]}),e.jsxs(Is,{fitContent:!0,children:[e.jsx(Ht,{value:H,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),q.map(B=>e.jsx(Ht,{value:B,className:"pr-2 [&>span:first-child]:hidden",children:B},B))]})]})]},Q.instanceId)})})]}),o!==void 0&&t.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",c!==void 0?`to ${c} models`:"","."]})]})};function gc(t){const[r,s]=i.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=i.useState(!1),[a,l]=i.useState(null);return i.useEffect(()=>{let c=!1;if(!t){l(null),o(!1),s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),l(null),(async()=>{try{const d=await _r(t);if(c)return;if(l(d),!d){s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await oi(t).catch(()=>null);if(c)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(x=>!x.startsWith("remotes/")).sort((x,g)=>x.localeCompare(g)).forEach(x=>{m.push({value:x,label:x,group:"local"})}),u.all.filter(x=>x.startsWith("remotes/")).map(x=>x.replace(/^remotes\//,"")).sort((x,g)=>x.localeCompare(g)).forEach(x=>{m.push({value:x,label:x,group:"remote"})})),s(m)}finally{c||o(!1)}})(),()=>{c=!0}},[t]),{branches:r,isLoading:n,isGitRepository:a}}const Xf=({directory:t,value:r,onChange:s,className:n,disabled:o,id:a})=>{const{branches:l,isLoading:c,isGitRepository:d}=gc(t),u=i.useMemo(()=>l.find(f=>f.value===r)?.label??null,[l,r]);i.useEffect(()=>{!l.some(p=>p.value===r)&&l.length>0&&s("HEAD")},[l,r,s]);const m=o||!d||c;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(kn,{children:u}):e.jsx(kn,{placeholder:c?"Loading branches…":"Select a branch"})}),e.jsxs(Is,{fitContent:!0,children:[e.jsxs(yn,{children:[e.jsx(qn,{children:"Default"}),l.filter(f=>f.group==="special").map(f=>e.jsx(Ht,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),l.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(Va,{}),e.jsxs(yn,{children:[e.jsx(qn,{children:"Local branches"}),l.filter(f=>f.group==="local").map(f=>e.jsx(Ht,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,l.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(Va,{}),e.jsxs(yn,{children:[e.jsx(qn,{children:"Remote branches"}),l.filter(f=>f.group==="remote").map(f=>e.jsx(Ht,{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."})]})},Zf=({value:t,onChange:r,className:s,disabled:n,id:o})=>{const a=et(f=>f.getVisibleAgents),l=et(f=>f.loadAgents),c=et(f=>f.currentAgentName),d=a(),u=i.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{if(n)return;const f=t.trim();if(f.length>0&&u.some(x=>x.name===f))return;const p=typeof c=="string"&&c.trim().length>0?c.trim():null;if(p&&u.some(x=>x.name===p)){r(p);return}const h=u[0]?.name;h&&r(h)},[c,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(kn,{placeholder:"Select an agent"})}),e.jsx(Is,{fitContent:!0,children:u.length>0&&e.jsx(yn,{children:u.map(f=>e.jsx(Ht,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},Xv=10*1024*1024,Hd=5,Wd=({initialPrompt:t,onCreated:r,onCancel:s})=>{const[n,o]=i.useState(""),[a,l]=i.useState(()=>t??""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState([]),[h,x]=i.useState(!1),[g,b]=i.useState([]),[y,w]=i.useState(!1),[S,C]=i.useState(!1),v=i.useRef(null),j=wt(O=>O.currentDirectory??null),M=i.useMemo(()=>{if(typeof window>"u")return null;const O=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof O=="string"&&O.trim().length>0?O.trim():null},[]),k=Wt(O=>O.activeProjectId),D=Wt(O=>O.projects),N=i.useMemo(()=>{if(k){const De=D.find(z=>z.id===k);if(De?.path)return De.path}const O=j??M;if(!O)return null;const le=O.replace(/\\/g,"/").replace(/\/+$/,"")||O,pe=le.indexOf("/.openchamber/");return pe>0?le.slice(0,pe):le.endsWith("/.openchamber")?le.slice(0,le.length-13):le},[k,D,j,M]),T=je(O=>O.isSidebarOpen),[A,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 O=typeof window.opencodeDesktop<"u";E(O)},[]);const P=i.useMemo(()=>A&&I?T?"pl-0":"pl-[8.0rem]":"pl-3",[A,I,T]),[F,$]=i.useState("HEAD"),{isLoading:Q,isGitRepository:ie}=gc(j),K=No(O=>O.createMultiRun),ee=No(O=>O.error),V=No(O=>O.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&l(O=>O.trim().length>0?O:t)},[t]),i.useEffect(()=>{if(!N)return;let O=!1;return C(!0),(async()=>{try{const le=await En(N);O||b(le)}catch{}finally{O||C(!1)}})(),()=>{O=!0}},[N]);const ae=O=>{c.length>=Hd||(d(le=>[...le,O]),V())},G=O=>{d(le=>le.filter((we,pe)=>pe!==O)),V()},q=i.useCallback((O,le)=>{d(we=>we.map((pe,De)=>De===O?le:pe))},[]),_=async O=>{const le=O.target.files;if(!le)return;let we=0;for(let pe=0;pe<le.length;pe++){const De=le[pe];if(De.size>Xv){W.error(`File "${De.name}" is too large (max 10MB)`);continue}try{const z=await new Promise((Z,de)=>{const Ee=new FileReader;Ee.onload=()=>Z(Ee.result),Ee.onerror=de,Ee.readAsDataURL(De)}),he={id:Ga(),filename:De.name,mimeType:De.type||"application/octet-stream",size:De.size,dataUrl:z};p(Z=>[...Z,he]),we++}catch(z){console.error("File attach failed",z),W.error(`Failed to attach "${De.name}"`)}}we>0&&W.success(`Attached ${we} file${we>1?"s":""}`),v.current&&(v.current.value="")},H=O=>{p(le=>le.filter(we=>we.id!==O))},L=async O=>{if(O.preventDefault(),!!a.trim()&&!(c.length<2)){x(!0),V();try{const le=c.map(({instanceId:he,...Z})=>Z),we=f.map(he=>({mime:he.mimeType,filename:he.filename,url:he.dataUrl})),pe=g.filter(he=>he.trim().length>0),De={name:n.trim(),prompt:a.trim(),models:le,agent:u||void 0,worktreeBaseBranch:F,files:we.length>0?we:void 0,setupCommands:pe.length>0?pe:void 0},z=await K(De);z&&(z.firstSessionId&&ge.getState().setCurrentSession(z.firstSessionId),r?.())}finally{x(!1)}}},B=!!(n.trim()&&a.trim()&&c.length>=2&&ie&&!Q);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:R("flex h-12 items-center justify-between border-b app-region-drag",P),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:R("flex items-center gap-3",A&&I&&T&&"pl-4"),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(ht,{delayDuration:500,children:[e.jsx(gt,{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(os,{className:"h-5 w-5"})})}),e.jsx(ft,{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:L,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:O=>o(O.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(Xf,{directory:j,value:F,onChange:$,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(co,{open:y,onOpenChange:w,children:[e.jsxs($o,{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",g.filter(O=>O.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",g.filter(O=>O.trim()).length," configured)"]})]}),e.jsx(Gt,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",y&&"rotate-180")})]}),e.jsx(uo,{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_WORKTREE_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:[g.map((O,le)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(St,{value:O,onChange:we=>{const pe=[...g];pe[le]=we.target.value,b(pe)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const we=g.filter((pe,De)=>De!==le);b(we)},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(os,{className:"h-4 w-4"})})]},le)),e.jsxs("button",{type:"button",onClick:()=>b([...g,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(cs,{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(Zf,{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(Rs,{id:"prompt",value:a,onChange:O=>l(O.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:v,type:"file",multiple:!0,className:"hidden",onChange:_,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:()=>v.current?.click(),children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(O=>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:[O.mimeType.startsWith("image/")?e.jsx(kr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(wr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:O.filename,children:O.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",O.size<1024?`${O.size}B`:O.size<1024*1024?`${(O.size/1024).toFixed(1)}KB`:`${(O.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>H(O.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(os,{className:"h-3.5 w-3.5"})})]},O.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(Jf,{selectedModels:c,onAdd:ae,onRemove:G,onUpdate:q,minModels:2,maxModels:Hd})]}),ee&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:ee}),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:!B||h,children:h?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(Ng,{className:"h-4 w-4 mr-2"}),"Start (",c.length," models)"]})})]})]})})})]})},Zv=(t={})=>{const{edgeThreshold:r=30,minSwipeDistance:s=50,maxSwipeTime:n=300,enabled:o=!0}=t,{isMobile:a,setSessionSwitcherOpen:l,isSessionSwitcherOpen:c}=je(),d=_e.useRef(null),u=_e.useRef(null);return _e.useEffect(()=>{if(!o||!a)return;const m=x=>{const g=x.touches[0];if(!g){d.current=null;return}g.clientX<=r?d.current={x:g.clientX,y:g.clientY,time:Date.now()}:d.current=null},f=x=>{if(!d.current)return;const g=x.touches[0];if(!g)return;g.clientX-d.current.x>10&&x.preventDefault()},p=x=>{if(!d.current)return;const g=x.changedTouches[0];if(!g){d.current=null,u.current=null;return}u.current={x:g.clientX,y:g.clientY,time:Date.now()};const{x:b,y,time:w}=d.current,{x:S,y:C,time:v}=u.current,j=S-b,M=C-y,k=v-w,D=Math.abs(M)<Math.abs(j),N=k<=n,T=Math.abs(M)<s;j>=s&&D&&N&&T&&!c&&l(!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,l,c]),null},ep=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;_e.memo(()=>{const t=_e.useRef(null),{addAttachedFile:r}=ge(),{isMobile:s}=je(),n=Df(),o=s?"h-9 w-9":"h-7 w-7",a=s?"h-5 w-5":"h-[18px] w-[18px]",l=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],h=ge.getState().attachedFiles.length;try{await r(p),ge.getState().attachedFiles.length>h&&m++}catch(x){console.error("File attach failed",x),W.error(x instanceof Error?x.message:"Failed to attach file")}}m>0&&W.success(`Attached ${m} file${m>1?"s":""}`)},c=async u=>{const m=u.target.files;m&&(await l(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 x=p.map(g=>`${g?.name||"file"}: ${g?.reason||"skipped"}`).join(`
163
- `);W.error(`Some files were skipped:
164
- ${x}`)}const h=f.map(x=>{if(!x?.dataUrl)return null;try{const[g,b]=x.dataUrl.split(","),y=x.mimeType||g?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!b)return null;const w=atob(b),S=new Uint8Array(w.length);for(let v=0;v<w.length;v++)S[v]=w.charCodeAt(v);const C=new Blob([S],{type:y});return new File([C],x.name||"file",{type:y})}catch(g){return console.error("Failed to decode VS Code picked file",g),null}}).filter(Boolean);h.length>0&&await l(h)}catch(u){console.error("VS Code file pick failed",u),W.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:c,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(Ea,{className:R(a,"text-current")})})]})});const ej=_e.memo(({file:t,onRemove:r})=>{const s=()=>t.mimeType.startsWith("image/")?e.jsx(kr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("text")||t.mimeType.includes("code")?e.jsx(wr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("json")||t.mimeType.includes("xml")?e.jsx(Ya,{className:"h-3.5 w-3.5"}):e.jsx(wr,{className:"h-3.5 w-3.5"}),n=l=>l<1024?l+" B":l<1048576?(l/1024).toFixed(1)+" KB":(l/1048576).toFixed(1)+" MB",a=(l=>{const d=l.replace(/\\/g,"/").split("/");return d[d.length-1]||l})(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(kg,{className:"h-3 w-3 text-primary flex-shrink-0"}):e.jsx(ym,{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(os,{className:"h-4 w-4 sm:h-3 sm:w-3"})})]})}),tj=_e.memo(()=>{const{attachedFiles:t,removeAttachedFile:r}=ge();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(ej,{file:s,onRemove:()=>r(s.id)},s.id))]})})}),tp=_e.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(kr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(wr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Ya,{className:"h-3.5 w-3.5"}):e.jsx(wr,{className:"h-3.5 w-3.5"}):e.jsx(wr,{className:"h-3.5 w-3.5"}),a=s.filter(d=>d.mime?.startsWith("image/")&&d.url),l=s.filter(d=>!d.mime?.startsWith("image/")),c=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:[l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:l.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>c(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(kr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(ft,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),sp=_e.memo(({message:t,sessionId:r,onEdit:s})=>{const n=br(l=>l.removeFromQueue),o=i.useMemo(()=>{const l=t.content.split(`
165
- `),c=l[0]||"",d=50;return c.length>d?c.substring(0,d)+"...":c+(l.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(Cg,{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(os,{className:"h-3 w-3"})})]})});sp.displayName="QueuedMessageChip";const Ud=[],rp=_e.memo(({onEditMessage:t})=>{const r=ge(a=>a.currentSessionId),s=br(i.useCallback(a=>r?a.queuedMessages[r]??Ud:Ud,[r])),n=br(a=>a.popToInput),o=i.useCallback(a=>{if(!r)return;const l=n(r,a.id);if(l){if(l.attachments&&l.attachments.length>0){const c=mr.getState().attachedFiles;mr.setState({attachedFiles:[...c,...l.attachments]})}t(l.content,l.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(sp,{message:a,sessionId:r,onEdit:o},a.id))]})})});rp.displayName="QueuedMessageChips";const sj=i.forwardRef(({searchQuery:t,onFileSelect:r,onClose:s},n)=>{const{currentDirectory:o}=wt(),{addServerFile:a}=ge(),l=ri(E=>E.searchFiles),c=ui(t,180),d=Ro(),u=si(),[m,f]=i.useState([]),[p,h]=i.useState(!1),[x,g]=i.useState(0),[b,y]=i.useState(360),[w,S]=i.useState({}),[C,v]=i.useState({}),j=i.useRef([]),M=i.useRef([]),k=i.useRef([]),D=i.useRef(null),N=i.useCallback((E,I)=>{const P=E.trim().toLowerCase();if(!P)return 0;const F=I.toLowerCase();let $=0,Q=-1,ie=0;for(let K=0;K<P.length;K+=1){const ee=P[K];if(!ee||ee===" ")continue;const V=F.indexOf(ee,Q+1);if(V===-1)return null;const ae=V-Q-1;if(ae===0?ie+=1:ie=0,$+=10,$+=Math.max(0,18-V),$-=Math.max(0,ae),V===0)$+=12;else{const G=F[V-1];(G==="/"||G==="_"||G==="-"||G==="."||G===" ")&&($+=10)}$+=ie>0?12:0,Q=V}return $+=Math.max(0,24-Math.round(F.length/3)),$},[]);i.useEffect(()=>{const E=I=>{const P=I.target;!P||!D.current||D.current.contains(P)||s()};return document.addEventListener("pointerdown",E,!0),()=>{document.removeEventListener("pointerdown",E,!0)}},[s]),i.useEffect(()=>{if(!o){f([]);return}const I=(c??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();let P=!1;return h(!0),l(o,I,80,{includeHidden:d,respectGitignore:!u}).then(F=>{if(P)return;const $=I?F.map(Q=>{const ie=Q.relativePath||Q.name||Q.path,K=N(I,ie);return K===null?null:{file:Q,score:K,labelLength:ie.length}}).filter(Boolean):F.map(Q=>({file:Q,score:0,labelLength:(Q.relativePath||Q.name||Q.path).length}));$.sort((Q,ie)=>ie.score-Q.score||Q.labelLength-ie.labelLength||Q.file.path.localeCompare(ie.file.path)),f($.slice(0,15).map(Q=>Q.file))}).catch(()=>{P||f([])}).finally(()=>{P||h(!1)}),()=>{P=!0}},[o,c,N,l,d,u]),i.useEffect(()=>{g(0),S({}),v({})},[m]),i.useEffect(()=>{j.current[x]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[x]),i.useEffect(()=>{let E=null;const I=()=>{E!==null&&cancelAnimationFrame(E),E=requestAnimationFrame(()=>{const P={},F={};M.current.forEach(($,Q)=>{if(!$)return;const K=k.current[Q]?.offsetWidth??$.scrollWidth,ee=Math.max(0,K-$.clientWidth),V=ee>8;if(P[Q]=V,V){const ae=Math.max(.6,ee/110);F[Q]=ae}}),S(P),v(F)})};return I(),window.addEventListener("resize",I),()=>{E!==null&&cancelAnimationFrame(E),window.removeEventListener("resize",I)}},[m]),i.useEffect(()=>{const E=M.current[x];if(!E)return;const I=()=>{const F=E.clientWidth;F>0&&y(F)};if(I(),typeof ResizeObserver>"u")return;const P=new ResizeObserver(I);return P.observe(E),()=>{P.disconnect()}},[x]);const T=i.useCallback(async E=>{await a(E.path,E.name),r(E)},[a,r]);i.useImperativeHandle(n,()=>({handleKeyDown:E=>{if(E==="Escape"){s();return}const I=m.length;if(I!==0){if(E==="ArrowDown"){g(P=>(P+1)%I);return}if(E==="ArrowUp"){g(P=>(P-1+I)%I);return}if(E==="Enter"||E==="Tab"){const P=(x%I+I)%I,F=m[P];F&&T(F)}}}}),[m,x,s,T]);const A=E=>{switch(E.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(er,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(er,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(wr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(kr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Ya,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:D,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(jt,{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(Qr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[m.map((E,I)=>{const P=E.relativePath||E.name,F=Gm(P,{maxLength:45}),$=x===I,Q=w[I]??!1,ie=C[I]??2.6,K=e.jsxs("div",{ref:ee=>{j.current[I]=ee},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",$&&"bg-muted"),onClick:()=>T(E),onMouseEnter:()=>g(I),children:[A(E),e.jsxs("span",{ref:ee=>{M.current[I]=ee},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:$?{"--file-mention-marquee-width":`${b}px`,"--file-mention-marquee-duration":`${ie}s`}:void 0,"aria-label":P,children:[e.jsx("span",{ref:ee=>{k.current[I]=ee},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:P}),Q&&$?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:K},E.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"})]})}),np=i.forwardRef(({searchQuery:t,onCommandSelect:r,onClose:s},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=ge(_n(w=>{const S=w.currentSessionId;return{hasMessagesInCurrentSession:(S?w.messages.get(S)?.length??0:0)>0,currentSessionId:S}})),l=!!a,[c,d]=i.useState([]),[u,m]=i.useState(!1),{commands:f,loadCommands:p}=tn(),[h,x]=i.useState(0),g=i.useRef([]),b=i.useRef(null);i.useEffect(()=>{const w=S=>{const C=S.target;!C||!b.current||b.current.contains(C)||s()};return document.addEventListener("pointerdown",w,!0),()=>{document.removeEventListener("pointerdown",w,!0)}},[s]),i.useEffect(()=>{p()},[p]),i.useEffect(()=>{(async()=>{m(!0);try{const S=f.map(D=>({name:D.name,description:D.description,agent:D.agent??void 0,model:D.model??void 0,isBuiltIn:D.name==="init"||D.name==="review",scope:D.scope})),C=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{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}],v=new Map;C.forEach(D=>v.set(D.name,D)),S.forEach(D=>v.set(D.name,D));const j=Array.from(v.values()),M=!o,k=(t?j.filter(D=>Js(D.name,t)||D.description&&Js(D.description,t)):j).filter(D=>M||D.name!=="init");k.sort((D,N)=>{const T=D.name.toLowerCase().startsWith(t.toLowerCase()),A=N.name.toLowerCase().startsWith(t.toLowerCase());return T&&!A?-1:!T&&A?1:D.name.localeCompare(N.name)}),d(k)}catch{const S=!o,C=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{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}],v=(t?C.filter(j=>Js(j.name,t)||j.description&&Js(j.description,t)):C).filter(j=>S||j.name!=="init");d(v)}finally{m(!1)}})()},[t,o,l,f]),i.useEffect(()=>{x(0)},[c]),i.useEffect(()=>{g.current[h]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[h]),i.useImperativeHandle(n,()=>({handleKeyDown:w=>{const S=c.length;if(w==="Escape"){s();return}if(S!==0){if(w==="ArrowDown"){x(C=>(C+1)%S);return}if(w==="ArrowUp"){x(C=>(C-1+S)%S);return}if(w==="Enter"||w==="Tab"){const C=(h%S+S)%S,v=c[C];v&&r(v)}}}}),[c,h,s,r]);const y=w=>{switch(w.name){case"init":return e.jsx(wr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(Jn,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(Ag,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(Sr,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(Dg,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Xr,{className:"h-3.5 w-3.5 text-cyan-500"});default:return w.isBuiltIn?e.jsx(Mg,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(Dn,{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(jt,{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(Qr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[c.map((w,S)=>{const C=w.isBuiltIn,v=w.scope==="project";return e.jsxs("div",{ref:j=>{g.current[S]=j},className:R("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",S===h&&"bg-muted"),onClick:()=>r(w),onMouseEnter:()=>x(S),children:[e.jsx("div",{className:"mt-0.5",children:y(w)}),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:["/",w.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"}):w.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",v?"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:w.scope}):null,w.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:w.agent})]}),w.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:w.description})]})]},w.name)}),c.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"})]})});np.displayName="CommandAutocomplete";const rj=t=>t?t!=="primary":!1,op=i.forwardRef(({searchQuery:t,onAgentSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{getVisibleAgents:m}=et(),{agents:f,loadAgents:p}=sn();i.useEffect(()=>{f.length===0&&p()},[p,f.length]),i.useEffect(()=>{const g=m().filter(w=>rj(w.mode)).map(w=>{const S=f.find(C=>C.name===w.name);return{name:w.name,description:w.description,mode:w.mode??void 0,scope:S?.scope,isBuiltIn:S?un(S):!1}}),b=t.trim(),y=b.length?g.filter(w=>Js(w.name,b)):g;y.sort((w,S)=>w.name.localeCompare(S.name)),d(y),l(0)},[m,t,f]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const x=g=>{const b=g.target;!b||!o.current||o.current.contains(b)||s()};return document.addEventListener("pointerdown",x,!0),()=>{document.removeEventListener("pointerdown",x,!0)}},[s]),i.useImperativeHandle(n,()=>({handleKeyDown:x=>{if(x==="Escape"){s();return}if(c.length){if(x==="ArrowDown"){l(g=>(g+1)%c.length);return}if(x==="ArrowUp"){l(g=>(g-1+c.length)%c.length);return}if(x==="Enter"||x==="Tab"){const g=c[(a+c.length)%c.length];g&&r(g.name)}}}}),[c,r,s,a]);const h=(x,g)=>{const b=x.isBuiltIn,y=x.scope==="project";return e.jsx("div",{ref:w=>{u.current[g]=w},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(x.name),onMouseEnter:()=>l(g),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:["#",x.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"}):x.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:x.scope}):null]}),x.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:x.description})]})},x.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(jt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((x,g)=>h(x,g))}):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"})]})});op.displayName="AgentMentionAutocomplete";const ap=i.forwardRef(({searchQuery:t,onSkillSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{skills:m,loadSkills:f}=ur();i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const h=t.trim(),g=[...h.length?m.filter(b=>Js(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(g),l(0)},[m,t]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const h=x=>{const g=x.target;!g||!o.current||o.current.contains(g)||s()};return document.addEventListener("pointerdown",h,!0),()=>{document.removeEventListener("pointerdown",h,!0)}},[s]),i.useImperativeHandle(n,()=>({handleKeyDown:h=>{if(h==="Escape"){s();return}if(c.length){if(h==="ArrowDown"){l(x=>(x+1)%c.length);return}if(h==="ArrowUp"){l(x=>(x-1+c.length)%c.length);return}if(h==="Enter"||h==="Tab"){const x=c[a];x&&r(x.name)}}}}),[c,r,s,a]);const p=(h,x)=>{const g=h.scope==="project";return e.jsx("div",{ref:b=>{u.current[x]=b},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(h.name),onMouseEnter:()=>l(x),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",g?"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(jt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((h,x)=>p(h,x))}):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"})]})});ap.displayName="SkillAutocomplete";function nj({className:t,children:r,...s}){return e.jsxs(Eg,{"data-slot":"scroll-area",className:R("relative",t),...s,children:[e.jsx(Ig,{"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(oj,{}),e.jsx(Pg,{})]})}function oj({className:t,orientation:r="vertical",...s}){return e.jsx(Tg,{"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(Fg,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const aj=({onFilesSelected:t,multiSelect:r=!1,children:s,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:l}=Kt(),c=l,{currentDirectory:d}=wt(),u=ri(X=>X.searchFiles),m=Ro(),f=si(),[p,h]=i.useState(!1),[x,g]=i.useState(0),[b,y]=i.useState(!1),[w,S]=i.useState(""),C=ui(w,200),[v,j]=i.useState(new Set),[M,k]=i.useState(new Set),[D,N]=i.useState({}),T=i.useRef(new Set),A=i.useRef(new Set),[E,I]=i.useState([]),[P,F]=i.useState(!1),[$,Q]=i.useState(!1),[ie,K]=i.useState(!1),[ee,V]=i.useState(null),ae=n??p,G=o??h,q=i.useCallback(X=>X.slice().sort((U,Y)=>U.type!==Y.type?U.type==="directory"?-1:1:U.name.localeCompare(Y.name)),[]),_=i.useCallback((X,U)=>q(U.filter(Y=>m||!Y.name.startsWith(".")).map(Y=>{const se=Y.name,me=!Y.isDirectory&&se.includes(".")?se.split(".").pop()?.toLowerCase():void 0;return{name:se,path:Y.path||`${X}/${se}`,type:Y.isDirectory?"directory":"file",size:0,extension:me}})),[q,m]),H=i.useCallback(async X=>{Q(!0),V(null);try{const U=await Oe.listLocalDirectory(X,{respectGitignore:!f}),Y=_(X,U.map(se=>({name:se.name,path:se.path,isDirectory:se.isDirectory})));T.current=new Set([X]),A.current=new Set,N({[X]:Y}),k(new Set)}catch{V("Failed to load directory contents"),T.current=new Set([X]),A.current=new Set,N({[X]:[]}),k(new Set)}finally{Q(!1)}},[_,f]),L=i.useCallback(async X=>{const U=X.trim();if(!U)return;const Y=`${U}::${x}`;if(!T.current.has(Y)&&!A.current.has(Y)){A.current=new Set(A.current),A.current.add(Y);try{const se=await Oe.listLocalDirectory(U,{respectGitignore:!f}),me=_(U,se.map(ze=>({name:ze.name,path:ze.path,isDirectory:ze.isDirectory})));T.current=new Set(T.current),T.current.add(Y),N(ze=>({...ze,[U]:me}))}catch{N(se=>se[U]?se:{...se,[U]:[]})}finally{A.current=new Set(A.current),A.current.delete(Y)}}},[_,f,x]);i.useEffect(()=>{(ae||b)&&d&&H(d)},[ae,b,d,H]),i.useEffect(()=>{g(X=>X+1)},[m,f]),i.useEffect(()=>{if(!(ae||b)||!d){I([]),F(!1);return}const X=C.trim().replace(/^\.\//,"").replace(/^\/+/,"");if(!X){I([]),F(!1);return}const U=X.toLowerCase();let Y=!1;return F(!0),u(d,U,150,{includeHidden:m,respectGitignore:!f}).then(se=>{if(Y)return;const me=se.map(ze=>({name:ze.name,path:ze.path,type:"file",extension:ze.extension,relativePath:ze.relativePath,size:0}));I(me)}).catch(()=>{Y||I([])}).finally(()=>{Y||F(!1)}),()=>{Y=!0}},[ae,b,d,C,u,m,f]),i.useEffect(()=>{!ae&&!b&&(j(new Set),S(""),I([]),F(!1),T.current=new Set,A.current=new Set,N({}),k(new Set))},[ae,b]);const B=X=>{if(X.type==="directory")return M.has(X.path)?e.jsx(ir,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(ir,{className:"h-3.5 w-3.5 text-primary/60"});switch(X.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(er,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(er,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Kn,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(kr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Kn,{className:"h-3.5 w-3.5 text-muted-foreground"})}},O=async X=>{M.has(X)?k(Y=>{const se=new Set(Y);return se.delete(X),se}):(k(Y=>{const se=new Set(Y);return se.add(X),se}),await L(X))},le=X=>{j(r?U=>{const Y=new Set(U);return Y.has(X)?Y.delete(X):Y.add(X),Y}:new Set([X]))},we=async()=>{const X=new Map;Object.values(D).forEach(se=>{se.forEach(me=>{me.type==="file"&&X.set(me.path,me)})});const U=new Map(E.map(se=>[se.path,se])),Y=Array.from(v).map(se=>X.get(se)??U.get(se)).filter(se=>!!se);K(!0);try{await t(Y),j(new Set),G(!1),y(!1)}finally{K(!1)}},pe=i.useMemo(()=>d?D[d]??[]:[],[D,d]),De=w.trim().length>0,z=X=>D[X]??[],he=X=>{if(d&&X.startsWith(d)){const U=X.substring(d.length);return U.startsWith("/")?U.substring(1):U}return X.split("/").pop()||X},Z=(X,U)=>{const Y=De?X.relativePath||he(X.path):X.name,se=De&&Y.includes("/")&&Y.length>45,me=se?Gm(Y,{maxLength:c?42:48}):Y,ze=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",X.type==="file"&&v.has(X.path)&&"bg-primary/10"),style:{paddingLeft:`${U*12}px`},onClick:qe=>{qe.preventDefault(),qe.stopPropagation(),X.type==="file"&&le(X.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:B(X)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":Y,children:me})]}),X.type==="file"&&v.has(X.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return se?e.jsxs(ht,{delayDuration:120,children:[e.jsx(gt,{asChild:!0,children:ze}),e.jsx(ft,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:Y})})]},X.path):i.cloneElement(ze,{key:X.path})},de=(X,U)=>{const Y=X.type==="directory",se=Y?z(X.path):[],me=M.has(X.path),ze=Y&&me&&A.current.has(X.path)&&se.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",!Y&&v.has(X.path)&&"bg-primary/10"),style:{paddingLeft:`${U*12}px`},onClick:qe=>{qe.preventDefault(),qe.stopPropagation(),Y?O(X.path):le(X.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:B(X)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:X.name}),!Y&&v.has(X.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),Y&&me&&se.length>0&&e.jsx("div",{children:se.map(qe=>de(qe,U+1))}),Y&&me&&ze&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(U+1)*12}px`},children:"Loading…"})]},X.path)},Ee=v.size>0?`${v.size} file${v.size!==1?"s":""} selected`:"No files selected",ne=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:Ee}),e.jsx(Se,{size:"sm",onClick:we,disabled:v.size===0||ie,className:"h-6 typography-meta",children:ie?"Attaching...":"Attach Files"})]}),ye=c?"flex-1 min-h-[240px]":"h-[300px]",te=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(Us,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{value:w,onChange:X=>S(X.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:X=>X.stopPropagation()}),w&&e.jsx("button",{onClick:X=>{X.stopPropagation(),S("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(os,{className:"h-3 w-3"})})]})}),e.jsxs(nj,{className:ye,children:[$&&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..."})}),ee&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:ee})}),!$&&!ee&&e.jsxs("div",{className:"py-1 px-2",children:[De?P?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):E.map(X=>Z(X,0)):pe.map(X=>de(X,0)),!De&&pe.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),De&&!P&&E.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),ce=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:X=>{X.preventDefault(),X.stopPropagation(),y(!0)},children:s});return a==="modal"?e.jsxs(e.Fragment,{children:[s?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:X=>{X.preventDefault(),X.stopPropagation(),G(!0)},children:s}):null,e.jsx(zs,{open:ae,onClose:()=>G(!1),title:"Select Project Files",footer:ne,children:e.jsx("div",{className:"flex flex-col gap-0",children:te})})]}):c?e.jsxs(e.Fragment,{children:[ce,e.jsx(zs,{open:b,onClose:()=>y(!1),title:"Select Project Files",footer:ne,children:e.jsx("div",{className:"flex flex-col gap-0",children:te})})]}):e.jsxs(es,{open:ae,onOpenChange:G,children:[e.jsx(ts,{asChild:!0,children:s}),e.jsxs(ss,{className:R("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[te,e.jsx(Ds,{}),ne]})]})},ta=[{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 Ur(t){if(!t||t==="build")return ta[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)%(ta.length-1);return ta[s]}const ij=typeof window<"u"?i.useLayoutEffect:i.useEffect,lj=(t,r=[])=>{const[s,n]=i.useState(!1),o=i.useCallback(()=>{const a=t.current;if(!a)return;const l=a.scrollWidth>a.clientWidth+1;n(l)},[t]);return ij(()=>{o()},[o,...r]),i.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const l=new ResizeObserver(()=>{o()});return l.observe(a),()=>l.disconnect()},[o,t]),i.useEffect(()=>{if(typeof window>"u")return;const a=()=>o();return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[o]),s},sa=t=>t==="primary"||t==="all"||t===void 0||t===null,Nl=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},Pi=(t,r)=>{const s=Nl(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}}},cj=[{key:"tool_call",icon:Ja,label:"Tool calling",isActive:t=>t?.tool_call===!0},{key:"reasoning",icon:Nr,label:"Reasoning",isActive:t=>t?.reasoning===!0}],dj={text:{icon:bm,label:"Text"},image:{icon:kr,label:"Image"},video:{icon:Lg,label:"Video"},audio:{icon:Rg,label:"Audio"},pdf:{icon:Ya,label:"PDF"}},uj=t=>t.trim().toLowerCase(),xo=(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=>uj(o)))).map(o=>{const a=dj[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},mj=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),fj=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),nr=t=>{if(typeof t!="number"||Number.isNaN(t))return"—";if(t===0)return"0";const r=mj.format(t);return r.endsWith(".0")?r.slice(0,-2):r},ra=t=>typeof t!="number"||!Number.isFinite(t)?"—":fj.format(t),Ti=t=>cj.filter(r=>r.isActive(t)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Vd=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},Gd=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)},qd=({className:t})=>{const{providers:r,currentProviderId:s,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:l,setProvider:c,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:h,getCurrentAgent:x,getVisibleAgents:g}=et(),b=g(),{currentSessionId:y,messages:w,saveSessionAgentSelection:S,saveAgentModelForSession:C,getAgentModelForSession:v,saveAgentModelVariantForSession:j,getAgentModelVariantForSession:M,analyzeAndSaveExternalSessionChoices:k}=ge(),D=nt(re=>re.hasHydrated),N=nt(re=>y?re.sessionAgentSelections.get(y)??null:null),T=i.useRef(null);i.useEffect(()=>{if(!y){T.current=null;return}N&&(T.current=N)},[y,N]);const A=y?T.current:null,E=y&&(N||A)||a,I=y??"__global__",P=nt(re=>{if(E)return re.getSessionAgentEditMode(I,E,"ask")}),F=nt(re=>re.setSessionAgentEditMode),{toggleFavoriteModel:$,isFavoriteModel:Q,addRecentModel:ie,isModelSelectorOpen:K,setModelSelectorOpen:ee}=je(),{favoriteModelsList:V,recentModelsList:ae}=hc(),{isMobile:G}=Kt(),q=uw(),_=Df(),H=G,[L,B]=i.useState(null),[O,le]=i.useState(null),[we,pe]=i.useState(""),De=i.useCallback(()=>B(null),[]),z=i.useCallback(()=>le(null),[]),he=i.useRef(void 0),[Z,de]=i.useState(()=>{const re=new Set;return s&&re.add(s),re}),Ee=K,ne=ee,[ye,te]=i.useState(""),[ce,X]=i.useState(0),U=i.useRef([]);i.useEffect(()=>{L==="model"&&de(()=>{const re=new Set;return s&&re.add(s),re})},[L,s]),i.useEffect(()=>{L!=="model"&&pe("")},[L]);const Y=i.useRef(Ee);i.useEffect(()=>{const re=Y.current;Y.current=Ee,Ee||(te(""),X(0),re&&!H&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[Ee,H]),i.useEffect(()=>{X(0)},[ye]);const se=i.useMemo(()=>E?b.find(re=>re.name===E):x?.(),[b,x,E]),me=i.useMemo(()=>se?Pi(se.permission,"edit")??"allow":"deny",[se]),ze=!!E,qe=me==="ask",tt=qe?P==="allow"||P==="full":me==="allow",Xe=!ze||!qe,Nt=G?"mobile":_?"vscode":"default",Ne=Nt==="mobile"?"h-9":Nt==="vscode"?"h-6":"h-8",ue=Nt==="mobile"?"h-5 w-5":"h-4 w-4",We=Nt==="mobile"?"h-5 w-5":"h-4 w-4",ve=H?"typography-micro":"typography-meta",ke=Nt==="mobile"||Nt==="vscode"?"gap-x-1":"gap-x-3",Ze=i.useCallback((re,Ae=ue)=>{const be=R(Ae,"flex-shrink-0"),Qe=ep(re),yt={color:Qe?Qe.text:"var(--foreground)"};return re==="full"?e.jsx(Er,{className:be,style:yt}):re==="allow"?e.jsx(fa,{className:be,style:yt}):re==="deny"?e.jsx(Yn,{className:be,style:yt}):e.jsx(vn,{className:be,style:yt})},[ue]),ct=i.useCallback(re=>{!ze||!a||!qe||F(I,a,re?"allow":"ask","ask")},[qe,a,ze,F,I]),Ue=p(),Be=Array.isArray(Ue?.models)?Ue.models:[],Ve=s&&n?h(s,n):void 0,dt=Ti(Ve),pt=xo(Ve,"input"),Ge=xo(Ve,"output"),ut=i.useMemo(()=>`${s}/${n}`?m():[],[m,s,n]),xt=ut.length>0,kt=[{label:"Input",value:ra(Ve?.cost?.input)},{label:"Output",value:ra(Ve?.cost?.output)},{label:"Cache read",value:ra(Ve?.cost?.cache_read)},{label:"Cache write",value:ra(Ve?.cost?.cache_write)}],At=[{label:"Context",value:nr(Ve?.limit?.context)},{label:"Output",value:nr(Ve?.limit?.output)}],Xt=i.useRef(void 0),as=y?w.get(y)?.length??-1:-1,_t=i.useRef(null);i.useEffect(()=>{if(!y)return;const re=_t.current;!re||re.sessionId!==y||N&&b.some(Ae=>Ae.name===N)&&(re.resolved=!0,re.inFlight=!1)},[b,y,N]);const Mt=i.useCallback((re,Ae,be)=>{if(!re||!Ae)return"model-missing";const Qe=r.find(J=>J.id===re);return Qe?(Array.isArray(Qe.models)?Qe.models:[]).find(J=>J.id===Ae)?(c(re),d(Ae),y&&be&&C(y,be,re,Ae),"applied"):"model-missing":"provider-missing"},[r,c,d,y,C]);i.useEffect(()=>{if(!y){_t.current=null;return}if(!D||r.length===0||b.length===0)return;(!_t.current||_t.current.sessionId!==y)&&(_t.current={sessionId:y,resolved:!1,inFlight:!1});const re=_t.current;if(!re||re.resolved||re.inFlight)return;let Ae=!1;const be=()=>{if(Ae)return;const J=_t.current;J&&J.sessionId===y&&(J.resolved=!0,J.inFlight=!1)},Qe=()=>{const J=y?nt.getState().getSessionAgentSelection(y)||T.current:null;if(J){a!==J&&f(J);const Fe=v(y,J);if(Fe){const Ce=Mt(Fe.providerId,Fe.modelId,J);if(Ce==="applied")return"resolved";if(Ce==="provider-missing")return"waiting"}else return"resolved"}for(const Fe of b){const Ce=v(y,Fe.name);if(!Ce)continue;a!==Fe.name&&f(Fe.name),nt.getState().getSessionAgentSelection(y)||T.current||S(y,Fe.name);const Ye=Mt(Ce.providerId,Ce.modelId,Fe.name);if(Ye==="applied")return"resolved";if(Ye==="provider-missing")return"waiting"}return"continue"},at=()=>{if(b.length===0)return;const J=y?nt.getState().getSessionAgentSelection(y)||T.current:null,Fe=(y?nt.getState().getSessionAgentSelection(y)||T.current:null)||a;if(Fe&&b.some(Ye=>Ye.name===Fe)){a!==Fe&&f(Fe);return}const Ce=b.filter(Ye=>sa(Ye.mode)),Ke=b.find(Ye=>Ye.name==="build")||Ce[0]||b[0];Ke&&(J||S(y,Ke.name),a!==Ke.name&&f(Ke.name),Ke.model?.providerID&&Ke.model?.modelID&&Mt(Ke.model.providerID,Ke.model.modelID,Ke.name))};return(async()=>{try{const J=Qe();if(J==="resolved"){be();return}if(J==="waiting"||as===-1)return;if(as>0){re.inFlight=!0;try{const Fe=await k(y,b);if(Ae)return;if(Fe.size>0){let Ce=null,Ke=-1/0;for(const[Ye,rt]of Fe)rt.timestamp>Ke&&(Ke=rt.timestamp,Ce=Ye);if(Ce){const Ye=nt.getState().getSessionAgentSelection(y)||T.current;if(Ye&&Ye!==Ce){be();return}Ye||S(y,Ce),a!==Ce&&f(Ce);const rt=Fe.get(Ce);if(rt){const lt=Mt(rt.providerId,rt.modelId,Ce);if(lt==="applied"){be();return}if(lt==="provider-missing")return}else{be();return}}}}catch(Fe){Ae||console.error("[ModelControls] Error resolving session from messages:",Fe)}finally{const Fe=_t.current;!Ae&&Fe&&Fe.sessionId===y&&(Fe.inFlight=!1)}}if(Ae)return;at(),be()}catch(J){Ae||console.error("[ModelControls] Error in session switch:",J)}})(),()=>{Ae=!0}},[y,as,b,a,v,f,Mt,k,S,D,r,N]),i.useEffect(()=>{if(!D||!y||r.length===0||b.length===0)return;const re=N||a;if(!re)return;const Ae=v(y,re);if(!Ae)return;const be=r.find(J=>J.id===Ae.providerId);if(!be||!(Array.isArray(be.models)?be.models.some(J=>J.id===Ae.modelId):!1))return;const at=s===Ae.providerId,yt=n===Ae.modelId;at&&yt||(re!==a&&f(re),Mt(Ae.providerId,Ae.modelId,re))},[D,y,a,s,n,r,b,v,Mt,f,N]),i.useEffect(()=>{if(!D)return;(async()=>{try{if(a!==Xt.current&&(Xt.current=a,a&&y)){await new Promise(Qe=>setTimeout(Qe,50));const Ae=v(y,a);if(Ae){const Qe=Mt(Ae.providerId,Ae.modelId,a);if(Qe==="applied"||Qe==="provider-missing")return}const be=b.find(Qe=>Qe.name===a);if(be?.model?.providerID&&be?.model?.modelID&&Mt(be.model.providerID,be.model.modelID,a)==="provider-missing")return}}catch(Ae){console.error("[ModelControls] Agent change error:",Ae)}})()},[a,y,v,Mt,b,D]),i.useEffect(()=>{if(!D||!a){u(void 0);return}if(!s||!n){u(void 0);return}if(ut.length===0){u(void 0);return}if(o&&!ut.includes(o)){u(void 0);return}if(!y){if(!o){const be=l&&ut.includes(l)?l:void 0;u(be)}return}const re=M(y,a,s,n),Ae=re&&ut.includes(re)?re:void 0;u(Ae)},[ut,D,y,a,s,n,o,M,u,l]);const Rt=i.useCallback(re=>{u(re),y&&a&&s&&n&&j(y,a,s,n,re)},[a,n,s,y,j,u]),Jt=re=>{try{f(re),ne(!1),y&&S(y,re),H&&De()}catch(Ae){console.error("[ModelControls] Handle agent change error:",Ae)}},Ft=(re,Ae)=>{try{const be=Mt(re,Ae,a||void 0);if(be!=="applied"){be==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",re):be==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:re,modelId:Ae});return}ie(re,Ae),ne(!1),H&&De(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(be){console.error("[ModelControls] Handle model change error:",be)}},Qt=re=>{const Ae=typeof re?.name=="string"?re.name:typeof re?.id=="string"?re.id:"";return Ae.length>40?Ae.substring(0,37)+"...":Ae},ps=()=>r.find(Ae=>Ae.id===s)?.name||s,Lt=()=>{if(!s||!n||Be.length===0)return"Not selected";const re=Be.find(Ae=>Ae.id===n);return Qt(re)},Me=Lt(),$e=i.useRef(null),Le=lj($e,[Me,H]),ot=()=>{if(!E){const Ae=b.filter(at=>sa(at.mode)),Qe=Ae.find(at=>at.name==="build")||Ae[0];return Qe?oe(Qe.name):"Select Agent"}const re=b.find(Ae=>Ae.name===E);return oe(re?re.name:E)},oe=re=>re.charAt(0).toUpperCase()+re.slice(1),Te=(re,Ae,be)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:Ae,"aria-label":Ae,role:"img",children:e.jsx(re,{className:"h-3.5 w-3.5"})},be),Ie=i.useCallback(re=>{de(Ae=>{const be=new Set(Ae);return be.has(re)?be.delete(re):be.add(re),be})},[]),fe=i.useCallback(re=>{he.current&&clearTimeout(he.current),he.current=setTimeout(()=>{le(re)},500)},[]),xe=i.useCallback(()=>{he.current&&clearTimeout(he.current)},[]);i.useEffect(()=>()=>{he.current&&clearTimeout(he.current)},[]);const Re=()=>!H||O!=="model"?null:e.jsx(zs,{open:!0,onClose:z,title:Ve?.name||Lt(),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:ps()})]}),dt.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:dt.map(({key:re,icon:Ae,label:be})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Te(Ae,be,`cap-${re}`),e.jsx("span",{className:"typography-meta text-foreground",children:be})]},re))})]}),(pt.length>0||Ge.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:[pt.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:pt.map(({key:re,icon:Ae,label:be})=>Te(Ae,`${be} input`,`input-${re}`))})]}),Ge.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:Ge.map(({key:re,icon:Ae,label:be})=>Te(Ae,`${be} output`,`output-${re}`))})]})]})]}),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:nr(Ve?.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:nr(Ve?.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:Vd(Ve?.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:Gd(Ve?.release_date)})]})]})]})]})}),st=()=>{if(!H||O!=="agent"||!se)return null;const re=!!(se.prompt&&se.prompt.trim().length>0),Ae=se.model?.providerID&&se.model?.modelID,be=se.temperature!==void 0||se.topP!==void 0,Qe=Fe=>{const Ce=Nl(se.permission)??[],Ke=Ce.some(rt=>rt.permission===Fe&&rt.pattern!=="*"),Ye=Pi(Ce,Fe)??"ask";return Ke?{mode:"ask",label:"Custom"}:Ye==="allow"?{mode:"allow",label:"Allow"}:Ye==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},at=Qe("edit"),yt=Qe("bash"),J=Qe("webfetch");return e.jsx(zs,{open:!0,onClose:z,title:oe(se.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[se.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:se.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:se.mode==="primary"?"Primary":se.mode==="subagent"?"Subagent":se.mode==="all"?"All":"—"})]}),(Ae||be)&&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"}),Ae&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[se.model.providerID," / ",se.model.modelID]}),be&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[se.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:se.temperature})]}),se.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:se.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:[Ze(at.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:at.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:[Ze(yt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:yt.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:[Ze(J.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:J.label})]})]})]})]}),re&&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(fa,{className:"h-4 w-4 text-foreground"})]})})]})})},mt=()=>{if(!H)return null;const re=we.trim(),Ae=r.map(be=>{const Qe=Array.isArray(be.models)?be.models:[],at=re.length===0?!0:Js(be.name,re)||Js(be.id,re),yt=re.length===0?Qe:Qe.filter(J=>{const Fe=Qt(J),Ce=typeof J.id=="string"?J.id:"";return Js(Fe,re)||Js(Ce,re)});return{provider:be,providerModels:yt,matchesProvider:at}}).filter(({matchesProvider:be,providerModels:Qe})=>be||Qe.length>0);return e.jsx(zs,{open:L==="model",onClose:De,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(Us,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(St,{value:we,onChange:be=>pe(be.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),we&&e.jsx("button",{type:"button",onClick:()=>pe(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Yn,{className:"h-4 w-4"})})]})}),Ae.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."}),!we&&V.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(Ir,{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:V.map(({model:be,providerID:Qe,modelID:at})=>{const yt=Qe===s&&at===n,J=h(Qe,at);return e.jsxs("button",{type:"button",onClick:()=>Ft(Qe,at),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",yt?"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:Qe,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Qt(be)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(J?.limit?.context||J?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[J?.limit?.context?`${nr(J?.limit?.context)} ctx`:"",J?.limit?.context&&J?.limit?.output?" • ":"",J?.limit?.output?`${nr(J?.limit?.output)} out`:""]})})]},`fav-mobile-${Qe}-${at}`)})})]}),!we&&ae.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(Sr,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:ae.map(({model:be,providerID:Qe,modelID:at})=>{const yt=Qe===s&&at===n,J=h(Qe,at);return e.jsxs("button",{type:"button",onClick:()=>Ft(Qe,at),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",yt?"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:Qe,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Qt(be)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(J?.limit?.context||J?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[J?.limit?.context?`${nr(J?.limit?.context)} ctx`:"",J?.limit?.context&&J?.limit?.output?" • ":"",J?.limit?.output?`${nr(J?.limit?.output)} out`:""]})})]},`recent-mobile-${Qe}-${at}`)})})]}),Ae.map(({provider:be,providerModels:Qe})=>{if(Qe.length===0&&!re.length)return null;const at=be.id===s,yt=Z.has(be.id)||re.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:()=>Ie(be.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":yt,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{providerId:be.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:be.name}),at&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),yt?e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Hs,{className:"h-3 w-3 text-muted-foreground"})]}),yt&&Qe.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Qe.map(J=>{const Fe=at&&J.id===n,Ce=h(be.id,J.id),Ke=Ti(Ce).slice(0,3),Ye=xo(Ce,"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",!Fe&&"hover:bg-muted",Fe?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>Ft(be.id,J.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:Qt(J)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Ce?.limit?.context||Ce?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Ce?.limit?.context?e.jsxs("span",{children:[nr(Ce?.limit?.context)," ctx"]}):null,Ce?.limit?.context&&Ce?.limit?.output?e.jsx("span",{children:"•"}):null,Ce?.limit?.output?e.jsxs("span",{children:[nr(Ce?.limit?.output)," out"]}):null]}),(Ke.length>0||Ye.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Ke,...Ye].map(({key:rt,icon:lt,label:vt})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:vt,"aria-label":vt,children:e.jsx(lt,{className:"h-3 w-3"})},`meta-${be.id}-${J.id}-${rt}`))})]})]}),e.jsx("button",{type:"button",onClick:rt=>{rt.preventDefault(),rt.stopPropagation(),$(be.id,J.id)},className:R("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",Q(be.id,J.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":Q(be.id,J.id)?"Unfavorite":"Favorite",title:Q(be.id,J.id)?"Remove from favorites":"Add to favorites",children:Q(be.id,J.id)?e.jsx(Ir,{className:"h-4 w-4"}):e.jsx(Un,{className:"h-4 w-4"})})]},J.id)})})]},be.id)})]})})},Ot=()=>{if(!H||!xt)return null;const re=!o,Ae=be=>{Rt(be),De(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(zs,{open:L==="variant",onClose:De,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",re?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>Ae(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),re&&e.jsx($t,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),ut.map(be=>{const Qe=o===be,at=be.charAt(0).toUpperCase()+be.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",Qe?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>Ae(be),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:at}),Qe&&e.jsx($t,{className:"h-4 w-4 text-primary flex-shrink-0"})]},be)})]})})},Bt=()=>{if(!H)return null;const re=b.filter(Ae=>sa(Ae.mode));return e.jsx(zs,{open:L==="agent",onClose:De,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[re.map(Ae=>{const be=Ae.name===E,Qe=Ur(Ae.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",Qe.class,be?"active":"border-border/40"),onClick:()=>Jt(Ae.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:R("h-2 w-2 rounded-full",Qe.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:be?{color:`var(${Qe.var})`}:void 0,children:oe(Ae.name)})]}),Ae.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:Ae.description})]},Ae.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",Xe?"text-muted-foreground":"text-foreground"),children:"Auto-approve edits"}),e.jsx(gn,{checked:tt,disabled:Xe,onCheckedChange:ct})]})})]})})},Ms=()=>e.jsx(ft,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ve?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:Ve.name||Lt()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:ps()})]}),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:dt.length>0?dt.map(({key:re,icon:Ae,label:be})=>Te(Ae,be,`cap-${re}`)):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:pt.length>0?pt.map(({key:re,icon:Ae,label:be})=>Te(Ae,`${be} input`,`input-${re}`)):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:Ge.length>0?Ge.map(({key:re,icon:Ae,label:be})=>Te(Ae,`${be} output`,`output-${re}`)):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)"}),kt.map(re=>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:re.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:re.value})]},re.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"}),At.map(re=>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:re.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:re.value})]},re.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:Vd(Ve.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:Gd(Ve.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),vs=(re,Ae,be,Qe,at,yt)=>{const J=h(Ae,be),Fe=Ti(J).map(Et=>({...Et,id:`cap-${Et.key}`})),Ce=[...xo(J,"input"),...xo(J,"output")],Ke=Array.from(new Map(Ce.map(Et=>[Et.key,Et])).values()).map(Et=>({...Et,id:`mod-${Et.key}`})),Ye=[...Fe,...Ke],rt=nr(J?.limit?.context),lt=s===Ae&&n===be,vt=Q(Ae,be),Yt=Qe==="fav"||Qe==="recent";return e.jsxs("div",{ref:Et=>{U.current[at]=Et},className:R("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",yt?"bg-accent":"hover:bg-accent/50"),onClick:()=>Ft(Ae,be),onMouseEnter:()=>X(at),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[Yt&&e.jsx(gs,{providerId:Ae,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Qt(re)}),J?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:rt}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Ye.length>0&&e.jsx("div",{className:R("items-center gap-0.5",yt?"flex":"hidden group-hover:flex"),children:Ye.map(({id:Et,icon:ks,label:hr})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":hr,role:"img",title:hr,children:e.jsx(ks,{className:"h-2.5 w-2.5"})},Et))}),lt&&e.jsx($t,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:Et=>{Et.preventDefault(),Et.stopPropagation(),$(Ae,be)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",vt?"text-yellow-500":"text-muted-foreground"),"aria-label":vt?"Unfavorite":"Favorite",title:vt?"Remove from favorites":"Add to favorites",children:vt?e.jsx(Ir,{className:"h-3.5 w-3.5"}):e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]},`${Qe}-${Ae}-${be}`)},It=(re,Ae,be)=>be.trim()?Js(re,be)||Js(Ae,be):!0,zt=()=>{const re=V.filter(({model:Ce,providerID:Ke})=>{const rt=r.find(vt=>vt.id===Ke)?.name||Ke,lt=Qt(Ce);return It(lt,rt,ye)}),Ae=ae.filter(({model:Ce,providerID:Ke})=>{const rt=r.find(vt=>vt.id===Ke)?.name||Ke,lt=Qt(Ce);return It(lt,rt,ye)}),be=r.map(Ce=>{const Ye=(Array.isArray(Ce.models)?Ce.models:[]).filter(rt=>{const lt=Qt(rt);return It(lt,Ce.name||Ce.id||"",ye)});return{...Ce,models:Ye}}).filter(Ce=>Ce.models.length>0),Qe=re.length>0||Ae.length>0||be.length>0,at=[];re.forEach(({model:Ce,providerID:Ke,modelID:Ye})=>{at.push({model:Ce,providerID:Ke,modelID:Ye,section:"fav"})}),Ae.forEach(({model:Ce,providerID:Ke,modelID:Ye})=>{at.push({model:Ce,providerID:Ke,modelID:Ye,section:"recent"})}),be.forEach(Ce=>{Ce.models.forEach(Ke=>{at.push({model:Ke,providerID:Ce.id,modelID:Ke.id,section:"provider"})})});const yt=at.length,J=Ce=>{if(Ce.key==="ArrowDown")Ce.preventDefault(),Ce.stopPropagation(),X(Ke=>(Ke+1)%Math.max(1,yt)),setTimeout(()=>{const Ke=(ce+1)%Math.max(1,yt);U.current[Ke]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Ce.key==="ArrowUp")Ce.preventDefault(),Ce.stopPropagation(),X(Ke=>(Ke-1+Math.max(1,yt))%Math.max(1,yt)),setTimeout(()=>{const Ke=(ce-1+Math.max(1,yt))%Math.max(1,yt);U.current[Ke]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Ce.key==="Enter"){Ce.preventDefault(),Ce.stopPropagation();const Ke=at[ce];Ke&&Ft(Ke.providerID,Ke.modelID)}else Ce.key==="Escape"&&(Ce.preventDefault(),Ce.stopPropagation(),ne(!1))};let Fe=0;return e.jsxs(ht,{delayDuration:1e3,children:[H?e.jsxs("button",{type:"button",onClick:()=>B("model"),onTouchStart:()=>fe("model"),onTouchEnd:xe,onTouchCancel:xe,className:R("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",Ne),children:[s?e.jsx(gs,{providerId:s,className:R(We,"flex-shrink-0")}):e.jsx(Er,{className:R(We,"text-muted-foreground")}),e.jsx("span",{ref:$e,className:R("model-controls__model-label typography-micro font-medium overflow-hidden min-w-0",G?"max-w-[120px]":"max-w-[220px]"),children:e.jsx("span",{className:R("marquee-text",Le&&"marquee-text--active"),children:Me})})]}):e.jsxs(es,{open:Ee,onOpenChange:ne,children:[e.jsx(gt,{asChild:!0,children:e.jsx(ts,{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",Ne),children:[s?e.jsxs(e.Fragment,{children:[e.jsx(gs,{providerId:s,className:R(We,"flex-shrink-0")}),e.jsx(Er,{className:R(We,"text-primary/60 hidden")})]}):e.jsx(Er,{className:R(We,"text-muted-foreground")}),e.jsx("span",{ref:$e,className:R("model-controls__model-label overflow-hidden",ve,"font-medium whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:e.jsx("span",{className:R("marquee-text",Le&&"marquee-text--active"),children:Me})},`${s}-${n}`)]})})}),e.jsxs(ss,{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(Us,{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:ye,onChange:Ce=>te(Ce.target.value),onKeyDown:J,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(jt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!Qe&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),re.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Ir,{className:"h-4 w-4 text-primary"}),"Favorites"]}),re.map(({model:Ce,providerID:Ke,modelID:Ye})=>{const rt=Fe++;return vs(Ce,Ke,Ye,"fav",rt,ce===rt)})]}),Ae.length>0&&e.jsxs(e.Fragment,{children:[re.length>0&&e.jsx(Ds,{}),e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Sr,{className:"h-4 w-4"}),"Recent"]}),Ae.map(({model:Ce,providerID:Ke,modelID:Ye})=>{const rt=Fe++;return vs(Ce,Ke,Ye,"recent",rt,ce===rt)})]}),(re.length>0||Ae.length>0)&&be.length>0&&e.jsx(Ds,{}),be.map((Ce,Ke)=>e.jsxs(i.Fragment,{children:[Ke>0&&e.jsx(Ds,{}),e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(gs,{providerId:Ce.id,className:"h-4 w-4 flex-shrink-0"}),Ce.name]}),Ce.models.map(Ye=>{const rt=Fe++;return vs(Ye,Ce.id,Ye.id,"provider",rt,ce===rt)})]},Ce.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"})]})]}),Ms()]})},ns=()=>{if(!se)return e.jsx(ft,{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 re=!!(se.prompt&&se.prompt.trim().length>0),Ae=se.model?.providerID&&se.model?.modelID,be=se.temperature!==void 0||se.topP!==void 0,Qe=Fe=>{const Ce=Nl(se.permission)??[],Ke=Ce.some(rt=>rt.permission===Fe&&rt.pattern!=="*"),Ye=Pi(Ce,Fe)??"ask";return Ke?{mode:"ask",label:"Custom"}:Ye==="allow"?{mode:"allow",label:"Allow"}:Ye==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},at=Qe("edit"),yt=Qe("bash"),J=Qe("webfetch");return e.jsx(ft,{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:oe(se.name)}),se.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:se.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:se.mode==="primary"?"Primary":se.mode==="subagent"?"Subagent":se.mode==="all"?"All":"—"})]}),(Ae||be)&&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"}),Ae?e.jsxs("span",{className:"typography-meta text-foreground",children:[se.model.providerID," / ",se.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),be&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[se.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:se.temperature})]}),se.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:se.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:[Ze(at.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:at.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:[Ze(yt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:yt.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:[Ze(J.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:J.label})]})]})]}),re&&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(fa,{className:"h-4 w-4 text-foreground"})]})]})})},Pe=()=>{if(!xt)return null;const re=o??"Default",Ae=!o,be=Ae?"text-muted-foreground":"text-[color:var(--status-info)]";return H?e.jsxs("button",{type:"button",onClick:()=>B("variant"),className:R("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ne,"cursor-pointer hover:opacity-70"),children:[e.jsx(Nr,{className:R(We,"flex-shrink-0",be)}),e.jsx("span",{className:R("model-controls__variant-label",ve,"font-medium truncate min-w-0",G&&"max-w-[60px]",be),children:re})]}):e.jsxs(ht,{delayDuration:800,children:[e.jsxs(es,{children:[e.jsx(gt,{asChild:!0,children:e.jsx(ts,{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",Ne),children:[e.jsx(Nr,{className:R(We,"flex-shrink-0",be)}),e.jsx("span",{className:R("model-controls__variant-label",ve,"font-medium min-w-0 truncate",q?"max-w-[180px]":void 0,be),children:re})]})})}),e.jsxs(ss,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Pr,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(Ct,{className:"typography-meta",onSelect:()=>Rt(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"}),Ae&&e.jsx($t,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),ut.length>0&&e.jsx(Ds,{}),ut.map(Qe=>{const at=o===Qe,yt=Qe.charAt(0).toUpperCase()+Qe.slice(1);return e.jsx(Ct,{className:"typography-meta",onSelect:()=>Rt(Qe),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:yt}),at&&e.jsx($t,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},Qe)})]})]}),e.jsx(ft,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",re]})})]})},He=()=>H?e.jsxs("button",{type:"button",onClick:()=>B("agent"),onTouchStart:()=>fe("agent"),onTouchEnd:xe,onTouchCancel:xe,className:R("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ne,"cursor-pointer hover:opacity-70"),children:[e.jsx(jn,{className:R(We,"flex-shrink-0",E?"":"text-muted-foreground"),style:E?{color:`var(${Ur(E).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",ve,"font-medium truncate min-w-0",G&&"max-w-[60px]"),style:E?{color:`var(${Ur(E).var})`}:void 0,children:ot()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(ht,{delayDuration:1e3,children:[e.jsxs(es,{children:[e.jsx(gt,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Ne),children:[e.jsx(jn,{className:R(We,"flex-shrink-0",E?"":"text-muted-foreground"),style:E?{color:`var(${Ur(E).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",ve,"font-medium min-w-0 truncate",q?"max-w-[220px]":void 0),style:E?{color:`var(${Ur(E).var})`}:void 0,children:ot()})]})})}),e.jsxs(ss,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[b.filter(re=>sa(re.mode)).map(re=>e.jsx(Ct,{className:"typography-meta",onSelect:()=>Jt(re.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",Ur(re.name).class)}),e.jsx("span",{className:"font-medium",children:oe(re.name)})]}),re.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:re.description})]})},re.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",Xe?"text-muted-foreground":"text-foreground"),children:"Auto-approve edits"}),e.jsx(gn,{checked:tt,disabled:Xe,onCheckedChange:ct})]})})})]})]}),ns()]})}),it=R("@container/model-controls flex items-center min-w-0",G&&"w-full",t);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:it,children:e.jsxs("div",{className:R("flex items-center min-w-0 flex-1 justify-end",ke,G&&"overflow-hidden"),children:[Pe(),zt(),He()]})}),mt(),Ot(),Bt(),Re(),st()]})},pj=t=>t?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(t):!0,Kd=(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 l;for(;(l=a.exec(t))!==null;){const c=l.index,d=c+l[0].length,u=c>0?t[c-1]:null;if(!pj(u))continue;const m={name:o.name,source:{value:l[0],start:c,end:d}};n||(n=m)}}return n?{sanitizedText:t,mention:n}:{sanitizedText:t,mention:null}},ip=t=>({id:t.id,content:t.content,status:t.status||"pending",priority:t.priority||"medium"}),kl=rs()(fs((t,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async s=>{if(s){t({isLoading:!0});try{const n=ge.getState().getDirectoryForSession(s),a=(n?await Oe.withDirectory(n,()=>Oe.getSessionTodos(s)):await Oe.getSessionTodos(s)).map(ip);t(l=>{const c=new Map(l.sessionTodos);return c.set(s,a),{sessionTodos:c,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"})),hj=(t,r)=>{const s=r.map(ip);kl.getState().updateTodos(t,s)},Qd=[{variant:"shine",component:({children:t,className:r,...s})=>e.jsx($n.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)=>_e.createElement($n.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(l=>l===" "?" ":l);return e.jsxs($n.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((l,c)=>e.jsx($n.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))}),e.jsx("div",{className:R("absolute inset-0"),children:a.map((l,c)=>e.jsx($n.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))})]})}},{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 Fi({variant:t="shine",className:r,...s}){const a=Qd.find(l=>l.variant===t)?.component||Qd[0].component;return e.jsx(pm,{children:e.jsx(a,{...s,className:r})})}const Yd=1500,gj=2e3;function xj({statusText:t,isGenericStatus:r,isWaitingForPermission:s,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:l}){const[c,d]=_e.useState("idle"),[u,m]=_e.useState(null),[f,p]=_e.useState(!1),h=_e.useRef(0),x=_e.useRef(null),g=_e.useRef(null),b=_e.useRef(null),y=_e.useRef(null),w=_e.useRef(!1),S=_e.useRef(!1),C=_e.useRef(!1),v=_e.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),b.current&&(clearTimeout(b.current),b.current=null)},[]),j=_e.useCallback((E,I)=>{v(),x.current=null,m(E),p(I),d("showing"),h.current=Date.now(),w.current=!0},[v]),M=_e.useCallback(()=>{if(g.current)return;const E=Date.now()-h.current,I=Math.max(0,Yd-E);g.current=setTimeout(()=>{g.current=null;const P=x.current;P&&j(P.text,P.permission)},I)},[j]),k=_e.useCallback(E=>{if(v(),x.current=null,!w.current){d("idle"),m(null),l?.(!1);return}if(E==="done"&&o&&y.current===o){d("idle"),m(null),w.current=!1,l?.(!1);return}E==="done"&&o&&(y.current=o),d(E),m(null),l?.(!0),b.current=setTimeout(()=>{b.current=null,d("idle"),w.current=!1,l?.(!1)},gj)},[v,o,l]);if(_e.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),!(c==="done"||c==="aborted")&&t){const I=Date.now()-h.current;if(c==="idle"||!u)j(t,!!s);else if(t!==u||!!s!==f){if(r)return;I>=Yd?j(t,!!s):(x.current={text:t,permission:!!s},M())}}},[t,s,n,a,c,u,f,j,k,M,r]),_e.useEffect(()=>()=>v(),[v]),_e.useEffect(()=>{const E=()=>{typeof document>"u"||document.visibilityState==="visible"&&(c==="done"||c==="aborted")&&(v(),d("idle"),m(null),w.current=!1)};return document.addEventListener("visibilitychange",E),()=>document.removeEventListener("visibilitychange",E)},[c,v]),c==="idle"&&!u)return null;let D,N=!0;c==="done"?(D="Done",N=!1):c==="aborted"?(D="Aborted",N=!1):u?D=u.charAt(0).toUpperCase()+u.slice(1):D="Working";const T=N?`${D}...`:D,A=c!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${A?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":D,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:c==="done"?e.jsx(Fi,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):c==="aborted"?e.jsx(Fi,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(Fi,{variant:"shine",className:"typography-ui-header",children:T})})})}const Jd={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},yj=({todo:t})=>{const r=Jd[t.status]||Jd.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})})},Xd=[],bj=({isWorking:t,statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:l,isComplete:c,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=i.useState(!1),h=ge(I=>I.currentSessionId),x=kl(I=>h?I.sessionTodos.get(h)??Xd:Xd),g=kl(I=>I.loadTodos),{isMobile:b}=je(),y=b||Vt();i.useEffect(()=>{h&&g(h)},[h,g]);const w=i.useMemo(()=>{const I={in_progress:0,pending:1,completed:2,cancelled:3};return[...x].filter(P=>P.status!=="cancelled").sort((P,F)=>I[P.status]-I[F.status])},[x]),S=i.useMemo(()=>w.find(I=>I.status==="in_progress")||w.find(I=>I.status==="pending")||null,[w]),C=i.useMemo(()=>{const I=x.filter(F=>F.status!=="cancelled").length;return{completed:x.filter(F=>F.status==="completed").length,total:I}},[x]),v=w.some(I=>I.status==="in_progress"||I.status==="pending"),j=!m&&(o||!a),[M,k]=i.useState(!1),D=t||c||o||M||v||m,N=i.useRef(null);if(i.useEffect(()=>{if(!f)return;const I=P=>{N.current&&!N.current.contains(P.target)&&p(!1)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[f]),!D)return null;const T=()=>p(I=>!I),A=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(Yn,{size:18,"aria-hidden":"true"})}):null,E=v?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(Qa,{className:"h-3.5 w-3.5"}):e.jsx(Gt,{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(Yn,{size:16,"aria-hidden":"true"}),"Aborted"]})}):j?e.jsx(xj,{statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,completionId:l??null,isComplete:c,onResultVisibilityChange:k},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:N,children:[A,E,f&&v&&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:w.map(I=>e.jsx(yj,{todo:I},I.id))})]})]})]})})},Na=t=>!t||typeof t!="object"?!1:!!t.synthetic,Zd=t=>!Array.isArray(t)||t.length===0?!1:t.every(r=>Na(r)),wj=t=>!Array.isArray(t)||t.length===0?[]:t.some(s=>!Na(s))&&t.some(n=>Na(n))?t.filter(n=>!Na(n)):t,vj={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function jj(t){const r=ge(s=>!t||!s.sessionActivityPhase?"idle":s.sessionActivityPhase.get(t)??"idle");return i.useMemo(()=>{if(r==="idle")return vj;const s=r==="busy",n=r==="cooldown";return{phase:r,isWorking:s||n,isBusy:s,isCooldown:n}},[r])}function xc(){const t=ge(r=>r.currentSessionId);return jj(t)}const Sj={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},eu=t=>t.role==="assistant",Nj=t=>t.type==="reasoning",lp=t=>t.type==="text",tu=t=>{if(lp(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},su=t=>(lp(t)||Nj(t),t.time),kj=t=>{if(t.tool)return t.tool;const r=t;return typeof r.name=="string"?r.name:"tool"};function cp(){const{currentSessionId:t,messages:r,permissions:s,sessionAbortFlags:n}=ge(_n(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:l}=xc(),c=i.useMemo(()=>t?r.get(t)??[]:[],[t,r]),d=i.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=c.filter(D=>eu(D.info)&&!Zd(D.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const x=[...h].sort((D,N)=>{const T=typeof D.info.time?.created=="number"?D.info.time.created:null,A=typeof N.info.time?.created=="number"?N.info.time.created:null;return T!==null&&A!==null&&T!==A?T-A:D.info.id.localeCompare(N.info.id)}),g=x[x.length-1];let b,y;const w=new Set(["edit","write","apply_patch"]);for(let D=(g.parts??[]).length-1;D>=0;D-=1){const N=g.parts?.[D];if(N)switch(N.type){case"reasoning":{const T=N.time??su(N);(!T||typeof T.end>"u")&&!b&&(b="reasoning");break}case"tool":{const T=N.state?.status;if((T==="running"||T==="pending")&&!b){const A=kj(N);w.has(A)?b="editing":(b="tool",y=A)}break}case"text":{const T=tu(N)??"";if(typeof T=="string"&&T.trim().length>0){const A=su(N);(!A||typeof A.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"],v=D=>S[D]??`using ${D}`,j=()=>C[Math.floor(Math.random()*C.length)],M=b===void 0,k=b==="editing"?"editing file":b==="tool"&&y?v(y):b==="reasoning"?"thinking":b==="text"?"composing":j();return{activePartType:b,activeToolName:y,statusText:k,isGenericStatus:M}},[c]),u=i.useMemo(()=>{const h=t,x=h?n?.get(h)??null:null,g=!!(x&&!x.acknowledged);return{wasAborted:g,abortActive:g}},[t,n]),m=i.useMemo(()=>{if(u.wasAborted)return{...Sj,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,x=o==="busy",g=l;let b="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?b="tooling":b=g?"cooldown":"streaming"),{activity:b,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:x,isCooldown:g,lifecyclePhase:x?"streaming":g?"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:g}},[o,a,l,d,u]),f=i.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const x=c.filter(y=>eu(y.info)&&!Zd(y.parts));if(x.length===0)return{isActive:h,characterCount:0};const g=x[x.length-1];let b=0;return(g.parts??[]).forEach(y=>{if(y.type!=="text")return;const w=tu(y)??"";typeof w=="string"&&w.trim().length>0&&(b+=w.length)}),{isActive:h,characterCount:b}},[c,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 Cj=8,ru=[],Mj=t=>t==="primary"||t==="all"||t===void 0||t===null,Dj=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},Aj=(t,r)=>{const s=Dj(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}}},na=({onOpenSettings:t,scrollToBottom:r})=>{const[s,n]=i.useState(""),[o,a]=i.useState(!1),[l,c]=i.useState(!1),[d,u]=i.useState(""),[m,f]=i.useState(!1),[p,h]=i.useState(""),[x,g]=i.useState(!1),[b,y]=i.useState(""),[w,S]=i.useState(!1),[C,v]=i.useState(""),[j,M]=i.useState(null),k=i.useRef(null),D=i.useRef(null),N=i.useRef(null),T=i.useRef(null),A=i.useRef(null),E=i.useRef(null),I=ge(J=>J.sendMessage),P=ge(J=>J.currentSessionId),F=ge(J=>J.newSessionDraft?.open),$=ge(J=>J.abortCurrentOperation),Q=ge(J=>J.acknowledgeSessionAbort),ie=ge(J=>J.abortPromptSessionId),K=ge(J=>J.abortPromptExpiresAt),ee=ge(J=>J.clearAbortPrompt),V=ge(J=>J.sessionAbortFlags),ae=ge(J=>J.attachedFiles),G=ge(J=>J.addAttachedFile),q=ge(J=>J.addServerFile),_=ge(J=>J.clearAttachedFiles),H=ge(J=>J.saveSessionAgentSelection),L=ge(J=>J.consumePendingInputText),B=ge(J=>J.pendingInputText),{currentProviderId:O,currentModelId:le,currentVariant:we,currentAgentName:pe,setAgent:De,getVisibleAgents:z}=et(),he=z(),{isMobile:Z,inputBarOffset:de,isKeyboardOpen:Ee,setTimelineDialogOpen:ne,cornerRadius:ye}=je(),{working:te}=cp(),[ce,X]=i.useState(!1),U=i.useRef(null),Y=i.useRef(!1),se=i.useRef(!1),me=br(J=>J.queueModeEnabled),ze=br(i.useCallback(J=>P?J.queuedMessages[P]??ru:ru,[P])),qe=br(J=>J.addToQueue),tt=br(J=>J.clearQueue),{phase:Xe}=xc(),Nt=i.useRef(Xe),Ne=i.useRef(!1),ue=i.useCallback(J=>{if(!Z||J.pointerType!=="touch")return;const Fe=k.current;if(!Fe||document.activeElement===Fe)return;J.preventDefault(),J.stopPropagation();const Ce=document.scrollingElement;Ce&&Ce.scrollTop!==0&&(Ce.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{Fe.focus({preventScroll:!0})}catch{Fe.focus()}const Ke=Fe.value.length;try{Fe.setSelectionRange(Ke,Ke)}catch{}},[Z]);i.useEffect(()=>{if(B!==null){const J=L();J&&(n(J),setTimeout(()=>{k.current?.focus()},0))}},[B,L]);const We=i.useMemo(()=>{const J=P&&nt.getState().getSessionAgentSelection(P)||pe;if(J)return he.find(Fe=>Fe.name===J)},[he,pe,P]),ve=i.useMemo(()=>We?Aj(We.permission,"edit")??"allow":"deny",[We]),ke=nt(i.useCallback(J=>{if(!pe)return;const Fe=P??"__global__";return J.getSessionAgentEditMode(Fe,pe,"ask")},[pe,P])),Ze=!!(P&&pe),ct=i.useMemo(()=>{if(ve==="allow")return"allow";if(ve!=="ask")return"ask";const J=Ze?ke??"ask":"ask";return J==="allow"||J==="full"?"allow":"ask"},[ve,Ze,ke]),Ue=i.useMemo(()=>ep(ct),[ct]),Be=i.useCallback(J=>Vt()?`color-mix(in srgb, ${J} 55%, transparent)`:J,[]),Ve=i.useMemo(()=>{const J=Vt()?1:2,Fe={borderRadius:ye};if(!Ue)return{...Fe,borderWidth:J};const Ce=Ue.border??Ue.text;return{...Fe,borderColor:Be(Ce),borderWidth:J}},[Ue,Be,ye]),dt=s.trim()||ae.length>0,pt=ze.length>0,Ge=dt||pt,ut=te.isWorking,xt=i.useMemo(()=>P?ie===P&&!!K:!1,[ie,K,P]),kt=i.useCallback(()=>{if(!dt||!P)return;const J=s.replace(/^\n+|\n+$/g,""),Fe=ae.map(Ce=>({...Ce}));qe(P,{content:J,attachments:Fe.length>0?Fe:void 0}),n(""),Fe.length>0&&_(),Z||k.current?.focus()},[dt,P,s,ae,qe,_,Z]),At=async J=>{if(J?.preventDefault(),!Ge||!P&&!F)return;if(r?.({instant:!0,force:!0}),!O||!le){console.warn("Cannot send message: provider or model not selected");return}let Fe="",Ce=[],Ke;const Ye=[];for(let vt=0;vt<ze.length;vt++){const Yt=ze[vt],{sanitizedText:Et,mention:ks}=Kd(Yt.content,he);!Ke&&ks?.name&&(Ke=ks.name),vt===0?(Fe=Et,Ce=Yt.attachments??[]):Ye.push({text:Et,attachments:Yt.attachments})}if(dt){const vt=s.replace(/^\n+|\n+$/g,""),{sanitizedText:Yt,mention:Et}=Kd(vt,he),ks=ae.map(hr=>({...hr}));!Ke&&Et?.name&&(Ke=Et.name),ze.length===0?(Fe=Yt,Ce=ks):Ye.push({text:Yt,attachments:ks.length>0?ks:void 0})}if(!Fe&&Ye.length===0)return;P&&pt&&tt(P),n(""),ae.length>0&&_(),Z&&k.current?.blur();const rt=Fe.trimStart();if(rt.startsWith("/")){const vt=rt.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(vt==="undo"&&P){await ge.getState().handleSlashUndo(P),r?.({instant:!0,force:!0});return}else if(vt==="redo"&&P){await ge.getState().handleSlashRedo(P),r?.({instant:!0,force:!0});return}else if(vt==="timeline"&&P){ne(!0),n("");return}else if(vt==="compact"&&P){try{const{opencodeClient:Yt}=await Ss(async()=>{const{opencodeClient:hr}=await Promise.resolve().then(()=>py);return{opencodeClient:hr}},void 0),Et=Yt.getDirectory();if((await Yt.getApiClient().session.summarize({sessionID:P,directory:Et||void 0,providerID:O,modelID:le})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(Yt){console.error("Failed to compact session:",Yt),W.error("Failed to compact session")}n("");return}}const lt=[...Ce,...Ye.flatMap(vt=>vt.attachments??[])];I(Fe,O,le,pe,Ce,Ke,Ye.length>0?Ye:void 0,we).catch(vt=>{const Yt=vt instanceof Error?vt.message:typeof vt=="string"?vt:String(vt??""),Et=Yt.toLowerCase();console.error("Message send failed:",Yt||vt);const ks=Et.includes("timeout")||Et.includes("timed out")||Et.includes("may still be processing")||Et.includes("being processed")||Et.includes("failed to fetch")||Et.includes("networkerror")||Et.includes("network error")||Et.includes("gateway timeout")||Et==="failed to send message";if(Et.includes("payload too large")||Et.includes("413")||Et.includes("entity too large")){W.error("Attachments are too large to send. Please try reducing the number or size of images."),lt.length>0&&mr.setState({attachedFiles:lt});return}ks||(lt.length>0&&mr.setState({attachedFiles:lt}),W.error(Yt||"Message failed to send. Attachments restored."))}),Z||k.current?.focus()},Xt=i.useRef(At);Xt.current=At,i.useEffect(()=>{const J=Nt.current==="busy"||Nt.current==="cooldown",Fe=Xe==="idle",Ce=P&&V.has(P)&&(()=>{const Ke=V.get(P);return Ke?Date.now()-Ke.timestamp<2e3:!1})();J&&Fe&&ze.length>0&&!Ne.current&&!Ce&&(Ne.current=!0,setTimeout(()=>{P&&O&&le&&Xt.current(),Ne.current=!1},100)),Nt.current=Xe},[Xe,ze.length,P,O,le,V]);const as=J=>{if(!pc(J)){if(m&&T.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")){J.preventDefault(),T.current.handleKeyDown(J.key);return}if(x&&A.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")){J.preventDefault(),A.current.handleKeyDown(J.key);return}if(w&&E.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")){J.preventDefault(),E.current.handleKeyDown(J.key);return}if(l&&N.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")){J.preventDefault(),N.current.handleKeyDown(J.key);return}if(J.key==="Tab"&&!m&&!x&&!l){J.preventDefault(),Rt();return}if(J.key==="Enter"&&!J.shiftKey&&!Z){J.preventDefault();const Fe=J.ctrlKey||J.metaKey,Ce=dt&&P&&Xe!=="idle";me?Fe||!Ce?At():kt():Fe&&Ce?kt():At()}}},_t=i.useCallback(()=>{U.current&&(clearTimeout(U.current),U.current=null),X(!0),U.current=setTimeout(()=>{X(!1),U.current=null},1800)},[]),Mt=i.useCallback(()=>{ee(),_t(),$()},[$,ee,_t]),Rt=()=>{const J=he.filter(Ye=>Mj(Ye.mode));if(J.length<=1)return;const Ce=(J.findIndex(Ye=>Ye.name===pe)+1)%J.length,Ke=J[Ce];De(Ke.name),P&&H(P,Ke.name)},Jt=i.useCallback(()=>{const J=k.current;if(!J)return;J.style.height="auto";const Fe=J.ownerDocument?.defaultView,Ce=Fe?Fe.getComputedStyle(J):null,Ke=Ce?parseFloat(Ce.lineHeight):NaN,Ye=Ce?parseFloat(Ce.paddingTop):NaN,rt=Ce?parseFloat(Ce.paddingBottom):NaN,lt=22,Yt=Number.isNaN(Ye)||Number.isNaN(rt)?16:Ye+rt,ks=(Number.isNaN(Ke)?lt:Ke)*Cj+Yt,hr=J.scrollHeight||J.offsetHeight,zr=Math.min(hr,ks);J.style.height=`${zr}px`,J.style.maxHeight=`${ks}px`,M(Bo=>Bo&&Bo.height===zr&&Bo.maxHeight===ks?Bo:{height:zr,maxHeight:ks})},[]);i.useLayoutEffect(()=>{Jt()},[Jt,s,Z]);const Ft=i.useCallback((J,Fe)=>{if(J.startsWith("/")){const lt=J.indexOf(" "),vt=J.indexOf(`
166
- `),Yt=Math.min(lt===-1?J.length:lt,vt===-1?J.length:vt);if(Fe<=Yt&&lt===-1){const Et=J.substring(1,Yt);h(Et),f(!0),c(!1),g(!1),S(!1);return}}f(!1);const Ce=J.substring(0,Fe),Ke=Ce.lastIndexOf("#");if(Ke!==-1){const lt=Ke>0?Ce[Ke-1]:null,vt=Ce.substring(Ke+1),Yt=vt.includes(" ")||vt.includes(`
167
- `);if((!lt||/\s/.test(lt))&&!Yt){y(vt),g(!0),c(!1);return}}g(!1),y("");const Ye=Ce.lastIndexOf("/");if(Ye!==-1){const lt=Ye>0?Ce[Ye-1]:null,vt=Ce.substring(Ye+1),Yt=vt.includes(" ")||vt.includes(`
168
- `);if((!lt||/\s/.test(lt))&&!Yt){v(vt),S(!0),c(!1),g(!1);return}}S(!1),v("");const rt=Ce.lastIndexOf("@");if(rt!==-1){const lt=Ce.substring(rt+1);!lt.includes(" ")&&!lt.includes(`
169
- `)?(u(lt),c(!0)):c(!1)}else c(!1)},[y,h,u,g,f,c,S,v]),Qt=i.useCallback(J=>{if(!J)return;const Fe=k.current;if(!Fe){const lt=s+J;n(lt),Ft(lt,lt.length),requestAnimationFrame(()=>Jt());return}const Ce=Fe.selectionStart??s.length,Ke=Fe.selectionEnd??s.length,Ye=`${s.substring(0,Ce)}${J}${s.substring(Ke)}`;n(Ye);const rt=Ce+J.length;requestAnimationFrame(()=>{const lt=k.current;lt&&(lt.selectionStart=rt,lt.selectionEnd=rt),Jt()}),Ft(Ye,rt)},[Jt,s,Ft]),ps=J=>{const Fe=J.target.value,Ce=J.target.selectionStart??Fe.length;n(Fe),Jt(),Ft(Fe,Ce)},Lt=i.useCallback(async J=>{const Fe=new Map;Array.from(J.clipboardData.files||[]).forEach(rt=>{rt.type.startsWith("image/")&&Fe.set(`${rt.name}-${rt.size}`,rt)}),Array.from(J.clipboardData.items||[]).forEach(rt=>{if(rt.kind==="file"&&rt.type.startsWith("image/")){const lt=rt.getAsFile();lt&&Fe.set(`${lt.name}-${lt.size}`,lt)}});const Ce=Array.from(Fe.values());if(Ce.length===0||!P&&!F)return;J.preventDefault();const Ke=J.clipboardData.getData("text");Ke&&Qt(Ke);let Ye=0;for(const rt of Ce){const lt=ge.getState().attachedFiles.length;try{await G(rt),ge.getState().attachedFiles.length>lt&&(Ye+=1)}catch(vt){console.error("Clipboard image attach failed",vt),W.error(vt instanceof Error?vt.message:"Failed to attach image from clipboard")}}Ye>0&&W.success(`Attached ${Ye} image${Ye>1?"s":""} from clipboard`)},[G,P,F,Qt]),Me=J=>{const Fe=k.current?.selectionStart||0,Ke=s.substring(0,Fe).lastIndexOf("@");if(Ke!==-1){const Ye=s.substring(0,Ke)+J.name+s.substring(Fe);n(Ye)}c(!1),u(""),k.current?.focus()},$e=J=>{const Ce=k.current?.selectionStart??s.length,Ye=s.substring(0,Ce).lastIndexOf("#");if(Ye!==-1){const rt=s.substring(0,Ye)+`#${J} `+s.substring(Ce);n(rt);const lt=Ye+J.length+2;requestAnimationFrame(()=>{k.current&&(k.current.selectionStart=lt,k.current.selectionEnd=lt),Jt(),Ft(rt,lt)})}g(!1),y(""),k.current?.focus()},Le=J=>{const Ce=k.current?.selectionStart??s.length,Ye=s.substring(0,Ce).lastIndexOf("/");if(Ye!==-1){const rt=s.substring(0,Ye)+`${J} `+s.substring(Ce);n(rt);const lt=Ye+J.length+1;requestAnimationFrame(()=>{k.current&&(k.current.selectionStart=lt,k.current.selectionEnd=lt),Jt(),Ft(rt,lt)})}S(!1),v(""),k.current?.focus()},ot=J=>{n(`/${J.name} `);const Fe=k.current;Fe&&(Fe._commandMetadata=J),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&&!Z&&k.current.focus()},[P,Z]),i.useEffect(()=>{ie&&ie!==P&&ee()},[ie,P,ee]);const oe=J=>{J.preventDefault(),J.stopPropagation(),(P||F)&&!o&&a(!0)},Te=J=>{J.preventDefault(),J.stopPropagation(),J.currentTarget===J.target&&a(!1)},Ie=async J=>{if(J.preventDefault(),J.stopPropagation(),a(!1),!P&&!F)return;const Fe=Array.from(J.dataTransfer.files);let Ce=0;for(const Ke of Fe){const Ye=ge.getState().attachedFiles.length;try{await G(Ke),ge.getState().attachedFiles.length>Ye&&(Ce+=1)}catch(rt){console.error("File attach failed",rt),W.error(rt instanceof Error?rt.message:"Failed to attach file")}}Ce>0&&W.success(`Attached ${Ce} file${Ce>1?"s":""}`)},fe=i.useCallback(async J=>{let Fe=0;for(const Ce of J){const Ke=ge.getState().attachedFiles.length;try{await q(Ce.path,Ce.name),ge.getState().attachedFiles.length>Ke&&(Fe+=1)}catch(Ye){console.error("Server file attach failed",Ye),W.error(Ye instanceof Error?Ye.message:"Failed to attach file")}}Fe>0&&W.success(`Attached ${Fe} file${Fe>1?"s":""}`)},[q]),xe=i.useRef(null),[Re,st]=i.useState(!1),mt=i.useCallback(async J=>{let Fe=0;const Ce=Array.isArray(J)?J:Array.from(J);for(const Ke of Ce){const Ye=ge.getState().attachedFiles.length;try{await G(Ke),ge.getState().attachedFiles.length>Ye&&(Fe+=1)}catch(rt){console.error("File attach failed",rt),W.error(rt instanceof Error?rt.message:"Failed to attach file")}}Fe>0&&W.success(`Attached ${Fe} file${Fe>1?"s":""}`)},[G]),Ot=i.useCallback(async()=>{try{const Fe=await(await fetch("/api/vscode/pick-files")).json(),Ce=Array.isArray(Fe?.files)?Fe.files:[],Ke=Array.isArray(Fe?.skipped)?Fe.skipped:[];if(Ke.length>0){const rt=Ke.map(lt=>`${lt?.name||"file"}: ${lt?.reason||"skipped"}`).join(`
170
- `);W.error(`Some files were skipped:
171
- ${rt}`)}const Ye=Ce.map(rt=>{if(!rt?.dataUrl)return null;try{const[lt,vt]=rt.dataUrl.split(","),Yt=rt.mimeType||lt?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!vt)return null;const Et=atob(vt),ks=new Uint8Array(Et.length);for(let zr=0;zr<Et.length;zr++)ks[zr]=Et.charCodeAt(zr);const hr=new Blob([ks],{type:Yt});return new File([hr],rt.name||"file",{type:Yt})}catch(lt){return console.error("Failed to decode VS Code picked file",lt),null}}).filter(Boolean);Ye.length>0&&await mt(Ye)}catch(J){console.error("VS Code file pick failed",J),W.error(J instanceof Error?J.message:"Failed to pick files in VS Code")}},[mt]),Bt=i.useCallback(()=>{if(Vt()){Ot();return}xe.current?.click()},[Ot]),Ms=i.useCallback(async J=>{const Fe=J.target.files;Fe&&(await mt(Fe),J.target.value="")},[mt]),vs="gap-x-1.5 gap-y-0",It=Vt(),zt=Z?"px-1.5 py-1.5":It?"px-1.5 py-1":"px-2.5 py-1.5",ns=Z?"h-9 w-9":It?"h-[22px] w-[22px]":"h-7 w-7",Pe=Z?"h-5 w-5":It?"h-4 w-4":"h-[18px] w-[18px]",He=R(ns,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),re=!Z&&xt&&ut?e.jsx("button",{type:"button",onClick:Mt,className:R(He,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(Yn,{className:R(Pe)})}):e.jsx("button",{type:Z?"button":"submit",disabled:!Ge||!P&&!F,onPointerDownCapture:J=>{!Z||J.pointerType!=="touch"||!Ge||!P&&!F||(se.current=!0,J.preventDefault(),J.stopPropagation(),At())},onClick:J=>{if(Z){if(se.current){se.current=!1;return}J.preventDefault(),At()}},className:R(He,Ge&&(P||F)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Fo,{className:R(Pe)})}),Ae=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:xe,type:"file",multiple:!0,className:"hidden",onChange:Ms,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(aj,{onFilesSelected:fe,multiSelect:!0,presentation:Z?"modal":"dropdown",open:Re,onOpenChange:st,children:Z?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsx("button",{type:"button",className:He,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(jm,{className:R(Pe,"text-current")})})}),e.jsxs(ss,{align:"start",children:[e.jsxs(Ct,{onSelect:()=>{requestAnimationFrame(()=>Bt())},children:[e.jsx(Ea,{}),"Attach files"]}),e.jsxs(Ct,{onSelect:()=>{requestAnimationFrame(()=>{st(!0)})},children:[e.jsx(Og,{}),"Attach from project"]})]})]})]})]}),be=t?e.jsx("button",{type:"button",onClick:t,className:He,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(jn,{className:R(Pe,"text-current")})}):null,Qe=e.jsxs(e.Fragment,{children:[Ae,be]}),at=te.statusText;i.useEffect(()=>{const J=!!te.wasAborted;!Y.current&&J&&!ce&&(_t(),P&&Q(P)),Y.current=J},[Q,P,ce,_t,te.wasAborted]),i.useEffect(()=>()=>{U.current&&(clearTimeout(U.current),U.current=null)},[]);const yt=Z&&ut;return e.jsxs("form",{onSubmit:At,className:R("relative pt-0 pb-2 md:pb-4",Z&&Ee?"ios-keyboard-safe-area":"bottom-safe-area"),"data-keyboard-avoid":"true",style:Z&&de>0&&!Ee?{marginBottom:`${de}px`}:void 0,children:[e.jsx("div",{className:"absolute bottom-full left-0 right-0",children:e.jsx(bj,{isWorking:te.isWorking,statusText:at,isGenericStatus:te.isGenericStatus,isWaitingForPermission:te.isWaitingForPermission,wasAborted:te.wasAborted,abortActive:te.abortActive,completionId:te.lastCompletionId,isComplete:te.isComplete,showAbort:yt,onAbort:Mt,showAbortStatus:ce})}),e.jsxs("div",{ref:D,className:R("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:oe,onDragLeave:Te,onDrop:Ie,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:He,onClick:()=>Bt(),title:"Attach files","aria-label":"Attach files",children:e.jsx(Ea,{className:R(Pe,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(tj,{}),e.jsx(rp,{onEditMessage:J=>{n(J),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:Ve,children:[m&&e.jsx(np,{ref:T,searchQuery:p,onCommandSelect:ot,onClose:()=>f(!1)}),x&&e.jsx(op,{ref:A,searchQuery:b,onAgentSelect:$e,onClose:()=>g(!1)}),w&&e.jsx(ap,{ref:E,searchQuery:C,onSkillSelect:Le,onClose:()=>S(!1)}),l&&e.jsx(sj,{ref:N,searchQuery:d,onFileSelect:Me,onClose:()=>c(!1)}),e.jsx(Rs,{ref:k,"data-chat-input":"true",value:s,onChange:ps,onKeyDown:as,onPaste:Lt,onPointerDownCapture:ue,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",Z?"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:ye,borderTopRightRadius:ye},rows:1}),e.jsx("div",{className:R("bg-transparent",zt,Z?"flex items-center gap-x-1.5":R("flex items-center justify-between",vs)),style:{borderBottomLeftRadius:ye,borderBottomRightRadius:ye},"data-chat-input-footer":"true",children:Z?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:Qe}),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(qd,{className:R("w-full flex items-center justify-end min-w-0")})}),re]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("flex items-center flex-shrink-0",vs),children:Qe}),e.jsxs("div",{className:R("flex items-center flex-1 justify-end",vs,"md:gap-x-3"),children:[e.jsx(qd,{className:R("flex-1 min-w-0 justify-end")}),re]})]})})]})]})]})};function Ri({className:t,...r}){return e.jsx("div",{"data-slot":"skeleton",className:R("bg-accent animate-pulse rounded-xl",t),...r})}const nu=(t,r,s,n,o=4)=>{const a=[];for(let l=0;l<o;l++)for(let c=0;c<o;c++){const d=c/o,u=(c+1)/o,m=l/o,f=(l+1)/o,p=(w,S,C)=>w+(S-w)*C,h=(w,S,C,v,j,M)=>{const k=p(w,S,j),D=p(v,C,j);return p(k,D,M)},x={x:h(t.x,r.x,s.x,n.x,d,m),y:h(t.y,r.y,s.y,n.y,d,m)},g={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${x.x} ${x.y} L${g.x} ${g.y} L${b.x} ${b.y} L${y.x} ${y.y} Z`,row:l,col:c})}return a},yc=({className:t="",width:r=70,height:s=70,isAnimated:n=!1})=>{const o=li();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const l=a?"white":"black",c=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,x={x:50,y:h-m},g={x:50-m*f,y:h-m*p},b={x:50+m*f,y:h-m*p},y={x:50,y:h},w={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, ${(x.y+g.y+y.y+b.y)/4})`,M=nu(g,y,C,w),k=nu(y,b,S,C),D=_e.useMemo(()=>{const N=[];for(let T=0;T<32;T++)N.push(.1+Math.random()*.5);return N},[]);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${g.x} ${g.y} L${w.x} ${w.y} L${C.x} ${C.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),M.map((N,T)=>e.jsx("path",{d:N.path,fill:u,opacity:D[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:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),k.map((N,T)=>e.jsx("path",{d:N.path,fill:u,opacity:D[T+16]},`right-${T}`)),e.jsx("path",{d:`M${x.x} ${x.y} L${g.x} ${g.y} L${y.x} ${y.y} L${b.x} ${b.y} Z`,fill:"none",stroke:l,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 Ej({children:t,className:r,interval:s=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:l=!0,mode:c="popLayout"}){const[d,u]=_e.useState(0),m=_e.Children.toArray(t);_e.useEffect(()=>{if(!l)return;const p=s*1e3,h=setInterval(()=>{u(x=>{const g=(x+1)%m.length;return a?.(g),g})},p);return()=>clearInterval(h)},[m.length,s,a,l]);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($g,{mode:c,initial:!1,children:e.jsx($n.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const Ij=["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"],Pj=()=>{const t=li();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(yc,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(Ej,{className:"text-body-md",interval:4,transition:{duration:.5},children:Ij.map(n=>e.jsxs("span",{style:{color:s},children:['"',n,'…"']},n))})]})},Li=i.memo(Pj),Tj={'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"}},Fj={'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 Gr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Gr.instance||(Gr.instance=new Gr),Gr.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 mi(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 Rj=i.createContext(!1),fr=({children:t,className:r,skipAnimation:s})=>{const n=i.useContext(Rj),o=s||n,[a,l]=i.useState(o);return i.useEffect(()=>{if(o)return;let c=null;const d=()=>l(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?c=window.requestAnimationFrame(d):d(),()=>{c!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(c)}},[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})},Lj=({isUser:t,providerID:r,agentName:s,modelName:n,variant:o,isDarkTheme:a})=>{const{src:l,onError:c,hasLogo:d}=Qf(r);return e.jsx(fr,{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(tr,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&l?e.jsx("img",{src:l,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:c}):e.jsx(Nr,{className:"h-4 w-4",style:{color:`var(${Ur(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)]",Ur(s).class),children:[e.jsx(jn,{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(Nr,{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})]})]})]})})})})},Oj=i.memo(Lj),$j=t=>`https://opencode.ai/docs/agents/#${encodeURIComponent(t)}`,_j=({part:t,messageId:r,agentMention:s})=>{const n=t,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[l,c]=i.useState(!1),[d,u]=i.useState(!1),m=i.useRef(null);i.useEffect(()=>{const h=m.current;if(!h||l)return;const x=()=>{u(h.scrollHeight>h.clientHeight)};x();const g=new ResizeObserver(x);return g.observe(h),()=>g.disconnect()},[a,l]);const f=i.useCallback(()=>{(d||l)&&c(h=>!h)},[d,l]);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),x=a.slice(0,h),g=a.slice(h+s.token.length);return e.jsxs(e.Fragment,{children:[x,e.jsx("a",{href:$j(s.name),className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:s.token}),g]})};return e.jsx("div",{className:R("font-sans typography-markdown whitespace-pre-wrap",!l&&"line-clamp-3",(d||l)&&"cursor-pointer"),ref:m,onClick:f,children:e.jsx("span",{className:"text-foreground/90",children:p()})},t.id||`${r}-user-text`)},Bj=i.memo(_j),ou=(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(!Vt()||typeof window>"u")return vd;const t=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(t?.light&&t?.dark){const r=ou({...t.light},`vscode-shiki-light:${String(t.light?.name??"theme")}`),s=ou({...t.dark},`vscode-shiki-dark:${String(t.dark?.name??"theme")}`);return[r,s]}return vd},zj=()=>{const[t,r]=i.useState(au);return i.useEffect(()=>{if(!Vt()||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},dp=t=>{const r=[],s=[],n=t.querySelector("thead");n&&n.querySelectorAll("th").forEach(l=>r.push(l.innerText.trim()));const o=t.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(l=>{const c=l.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),s.push(d)}),{headers:r,rows:s}},up=({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
- `)},Hj=({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
- `)},Wj=({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((l,c)=>s(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
175
- `)},Uj=(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)},Vj=({tableRef:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(null);i.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const l=async c=>{const d=t.current?.querySelector("table");if(d)try{const u=dp(d),m=c==="csv"?up(u):Hj(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($t,{className:"size-3.5"}):e.jsx(sr,{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:()=>l("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:()=>l("tsv"),children:"TSV"})]})]})},Gj=({tableRef:t})=>{const[r,s]=i.useState(!1),n=i.useRef(null);i.useEffect(()=>{const a=l=>{n.current&&!n.current.contains(l.target)&&s(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const l=t.current?.querySelector("table");if(l)try{const c=dp(l),d=a==="csv"?up(c):Wj(c);Uj(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),s(!1)}catch(c){console.error("Failed to download table:",c)}};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(Yr,{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"})]})]})},qj=({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(Vj,{tableRef:s}),e.jsx(Gj,{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})})]})},Kj=({children:t,className:r,style:s,...n})=>{const[o,a]=i.useState(!1),l=i.useRef(null),c=i.useMemo(()=>{if(!s)return s;const m={...s},f=x=>{if(typeof x!="string")return{value:void 0,vars:{}};const[g,...b]=x.split(";").map(w=>w.trim()).filter(Boolean),y={};for(const w of b){const S=w.indexOf(":");if(S===-1)continue;const C=w.slice(0,S).trim(),v=w.slice(S+1).trim();!C.startsWith("--")||v.length===0||(y[C]=v)}return{value:g,vars:y}},p=f(s.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[x,g]of Object.entries(p.vars))m[x]=g;const h=f(s.color);h.value&&(m.color=h.value,m["--shiki-light"]=h.value);for(const[x,g]of Object.entries(h.vars))m[x]=g;return m},[s]),d=()=>l.current&&l.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:l,children:[e.jsx("pre",{...n,className:R(r),style:c,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($t,{className:"size-3.5"}):e.jsx(sr,{className:"size-3.5"})})})]})},Qj={pre:Kj,table:qj},bn=({content:t,className:r,variant:s="assistant"})=>{const n=zj(),o=s==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:R("break-words",r),children:e.jsx(_g,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:Qj,children:t})})},Yj=t=>{let r=t.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},Jj=t=>t?t.includes("<file_diagnostics>")||t.includes("This file has errors")||t.includes("please fix"):!1,Xj=t=>t?t.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",iu=(t,r)=>!t||typeof t!="object"?String(t):Dw(t,r||""),Oi=(t,r,s)=>{let n=Yj(t);if((r==="edit"||r==="multiedit")&&Jj(n)&&(n=Xj(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&s?.diff){const o=s.diff;return typeof o=="string"?o:String(o)}return n},Zj=(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[,l,c]=a,d=Math.floor(l.length/2),u=!c.endsWith("/");n.push({name:c.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:Tr.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}},e0=(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 l=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(l){const[,c,d,u]=l,m=u!==void 0?d:"",f=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].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:Tr.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,l])=>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:l.map((c,d)=>!c.lineNum&&!c.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:[c.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",c.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:c.content||" "})]})]},d))})]},a))]})}catch{return null}},t0=(t,r,s)=>{try{const n=t.trim().split(`
178
- `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(l=>{const c=l.lastIndexOf("/"),d=c>0?l.substring(0,c):"/",u=c>=0?l.substring(c+1):l;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:Tr.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(l=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:R("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[l,"/"]}),e.jsx("div",{className:R("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[l].sort().map(c=>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:c})]},c))})]},l))]})}catch{return null}},s0=(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 l="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:l,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:l,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:Tr.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,l)=>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||l))})]}),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,l)=>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||l))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{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,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx($t,{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||l))})]}),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,l)=>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||l))})]})]})}catch{return null}},r0=(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:Tr.tool.popup,children:e.jsx(bn,{content:t,variant:"tool"})})}catch{return null}},mp=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 l=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),c=l?parseInt(l[1]):0,d=l?parseInt(l[2]):0,u=[];let m=c,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:c,newStart:d,lines:u}),o=p;continue}o++}return n},Cl=(t,r,s)=>Cw(r,t,s),fp=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(Bg,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(Sm,{className:r}):s==="read"||s==="view"||s==="file_read"||s==="cat"?e.jsx(Kn,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"?e.jsx(Xr,{className:r}):s==="list"||s==="ls"||s==="dir"||s==="list_files"?e.jsx(ir,{className:r}):s==="search"||s==="grep"||s==="find"||s==="ripgrep"?e.jsx(zg,{className:r}):s==="glob"?e.jsx(Hg,{className:r}):s==="fetch"||s==="curl"||s==="wget"||s==="webfetch"?e.jsx(ol,{className:r}):s==="web-search"||s==="websearch"||s==="search_web"||s==="codesearch"||s==="google"||s==="bing"||s==="duckduckgo"||s==="perplexity"?e.jsx(ol,{className:r}):s==="todowrite"||s==="todoread"?e.jsx(Nm,{className:r}):s==="skill"?e.jsx(km,{className:r}):s==="question"?e.jsx(Wg,{className:r}):s==="plan_enter"?e.jsx(Ug,{className:r}):s==="plan_exit"?e.jsx(Vg,{className:r}):s.startsWith("git")?e.jsx(qt,{className:r}):e.jsx(Ja,{className:r})},n0=(t,r,s=Date.now())=>{const o=(r?r-t:s-t)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},o0=({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:n0(t,r,n)})},a0=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}},ka=(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},i0=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},l0=(t,r,s,n)=>{const o=r,a=o.metadata,l=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"?ka(m,n,s):"Patch"}if(t.tool==="question"&&l?.questions&&Array.isArray(l.questions)){const d=l.questions.length;return`Asked ${d} question${d!==1?"s":""}`}if((t.tool==="edit"||t.tool==="multiedit")&&l){const d=l?.filePath||l?.file_path||l?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return ka(d,n,s)}if((t.tool==="read"||t.tool==="write")&&l){const d=l?.filePath||l?.file_path||l?.path;if(typeof d=="string")return ka(d,n,s)}if(t.tool==="bash"&&l?.command&&typeof l.command=="string"){const d=l.command.split(`
181
- `)[0];return s?d.substring(0,50):d.substring(0,100)}if(t.tool==="task"&&l?.description&&typeof l.description=="string")return s?l.description.substring(0,40):l.description.substring(0,80);if(t.tool==="skill"&&l?.name&&typeof l.name=="string")return l.name;if(t.tool==="plan_enter")return"Switching to planning";if(t.tool==="plan_exit")return"Switching to building";const c=l?.description||a?.description||"title"in r&&r.title||"";return typeof c=="string"?c:""},Ml=({children:t,maxHeightClass:r="max-h-[60vh]",className:s,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(jt,{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})}),c0=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"},d0=t=>t.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),u0=({entries:t,isExpanded:r,hasPrevTool:s,hasNextTool:n,output:o,sessionId:a})=>{const l=ge(g=>g.setCurrentSession),c=i.useMemo(()=>t.filter(g=>g.state?.status==="completed"),[t]),d=typeof o=="string"?d0(o):"",u=d.length>0,[m,f]=i.useState(!1),p=g=>{g.stopPropagation(),a&&l(a)};if(c.length===0&&!u&&!a)return null;const h=r?c:c.slice(-6),x=Math.max(0,c.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:[c.length>0?e.jsx(Ml,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[x>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",x," more…"]}):null,h.map((g,b)=>{const y=typeof g.tool=="string"&&g.tool.trim().length>0?g.tool:"tool",w=c0(g),S=sc(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:fp(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:w})]},g.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:g=>g.stopPropagation(),onClick:p,children:[e.jsx(Xs,{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",(c.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:g=>g.stopPropagation(),onClick:g=>{g.stopPropagation(),f(b=>!b)},children:[m?e.jsx(Gt,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Hs,{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(Ml,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(bn,{content:d,variant:"tool"})})}):null]}):null]})},pp=i.memo(({diff:t,syntaxTheme:r,input:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:mp(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,l)=>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(Fr,{style:r,language:Cr(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})})]},l))})]},o))}));pp.displayName="DiffPreview";const hp=i.memo(({content:t,syntaxTheme:r,filePath:s,displayPath:n})=>{const o=i.useMemo(()=>t.split(`
182
- `),[t]),a=i.useMemo(()=>Cr(s??"")||Cl(t,"write",s?{filePath:s}:void 0),[t,s]),l=Math.max(o.length,1),c=l===1?"line 1":`lines 1-${l}`;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} (${c})`}),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(Fr,{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))})]})});hp.displayName="WriteInputPreview";const gp=i.memo(({content:t,filePath:r,displayPath:s})=>{const n=yl(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"}})})]})});gp.displayName="ImagePreview";const xp=i.memo(({part:t,state:r,syntaxTheme:s,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:l})=>{const c=r,d=c.metadata,u=c.input,m=c.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",h=typeof d?.diff=="string"?d.diff:null,x=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,g=t.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,b=t.tool==="write"&&!!g,y=x?Po(x):!1,w=b?x?ka(x,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"?iu(u,t.tool):typeof u.content=="string"?u.content??"":iu(u,t.tool),[u,t.tool]),C=t.tool!=="apply_patch"&&S.trim().length>0,v=(M,k)=>e.jsx(Ml,{maxHeightClass:k?.maxHeightClass,className:k?.className,disableHorizontal:k?.disableHorizontal,outerClassName:k?.outerClassName,children:M}),j=()=>{if(t.tool==="question"){if(r.status==="completed"&&f){const M=i0(p);if(M&&M.length>0)return v(e.jsx("div",{className:"space-y-2",children:M.map((k,D)=>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})]},D))}),{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 M=s0(p,{unstyled:!0});return v(M??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 M=Zj(p,{unstyled:!0});return v(M??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 M=e0(p,n,{unstyled:!0});return v(M??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 M=t0(p,n,{unstyled:!0});return v(M??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 v(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(bn,{content:p,variant:"tool"})}));if((t.tool==="web-search"||t.tool==="websearch"||t.tool==="search_web")&&f){const M=r0(p,s,{unstyled:!0});return v(M??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 v(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(bn,{content:p,variant:"tool"})}));if(t.tool==="skill"&&f)return v(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(bn,{content:p,variant:"tool"})}));if((t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch")&&h)return v(e.jsx(pp,{diff:h,syntaxTheme:s,input:u}),{className:"p-1"});if(f&&p.trim()){if(t.tool==="read"){const M=Oi(p,t.tool,d),k=M.split(`
183
- `),D=typeof u?.offset=="number"?u.offset:0,N=typeof u?.limit=="number"?u.limit:void 0,T=A=>A.trim().startsWith("(");return v(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:k.map((A,E)=>{const I=T(A),P=D+E+1,F=!I&&(N===void 0||E<N);return e.jsxs("div",{className:R("typography-code font-mono flex w-full min-w-0",I&&"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:I?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:A}):e.jsx(Fr,{style:s,language:Cl(M,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:A})})]},E)})}),{className:"p-1"})}return v(e.jsx(Fr,{style:s,language:Cl(Oi(p,t.tool,d),t.tool,u),PreTag:"div",customStyle:{...pa.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Oi(p,t.tool,d)}),{className:"p-1"})}return v(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]",l?"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:v(e.jsx(gp,{content:g,filePath:x,displayPath:w??"New file"}))}):b?e.jsx("div",{className:"my-1",children:v(e.jsx(hp,{content:g,syntaxTheme:s,filePath:x,displayPath:w??"New file"}))}):C?e.jsx("div",{className:"my-1",children:v(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})]})]})})});xp.displayName="ToolExpandedContent";const Dl=({part:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:l=!1,hasNextTool:c=!1})=>{const d=t.state,u=wt(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",x=i.useRef(r);i.useEffect(()=>{!f&&!m||x.current!==r&&(x.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const g=d,b=g.metadata,y=g.input,w=g.time,S=i.useRef({}),C=i.useRef(t.id);if(C.current!==t.id&&(C.current=t.id,S.current={}),m){if(typeof w?.start=="number"){const P=S.current.start;(typeof P!="number"||w.start<P)&&(S.current.start=w.start)}typeof w?.end=="number"&&(S.current.end=w.end)}const v=m?S.current.start??w?.start:w?.start,j=m?S.current.end??w?.end:w?.end,M=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]),D=i.useRef(k.length);i.useEffect(()=>{m&&D.current!==k.length&&(D.current=k.length,a?.("structural"))},[m,a,k.length]);const N=t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch"?a0(b):null,T=l0(t,d,o,u),A=sc(t.tool).displayName,E=i.useContext(Zl),I=P=>{if(m||!E?.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 $=F;F.startsWith("/")||($=u.endsWith("/")?u+F:u+"/"+F),E.editor.openFile($)}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:I,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:fp(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(Gt,{className:"h-3.5 w-3.5"}):e.jsx(Hs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:A})]}),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}),N&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",N.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",N.removed]})]}),typeof v=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(o0,{start:v,end:typeof j=="number"?j:void 0,active:!!(m&&p&&typeof j!="number")})})]})]}),m&&(k.length>0||p||f||M)?e.jsx(u0,{entries:k,isExpanded:r,hasPrevTool:l,hasNextTool:c,output:typeof g.output=="string"?g.output:void 0,sessionId:M}):null,!m&&r?e.jsx(xp,{part:t,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:l,hasNextTool:c}):null]})},m0={thinking:{label:"Thinking",Icon:Nr},justification:{label:"Justification",Icon:_l}},f0=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(),p0=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},yp=({text:t,variant:r,onContentChange:s,blockId:n})=>{const[o,a]=i.useState(!1),l=i.useMemo(()=>p0(t),[t]),{label:c,Icon:d}=m0[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(Gt,{className:"h-3.5 w-3.5"}):e.jsx(Hs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:c})]}),l&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:l})})]}),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(jt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:t})})]})},h0=({part:t,onContentChange:r,messageId:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>f0(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(yp,{text:a,variant:"thinking",onContentChange:r,blockId:t.id||`${s}-reasoning`}):null},g0=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(),x0=({part:t,messageId:r,onContentChange:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>g0(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(yp,{text:a,variant:"justification",onContentChange:s,blockId:t.id||`${r}-justification`}):null},y0=i.memo(x0),lu=6,b0=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}),cu=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},w0=({parts:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:l,onContentChange:c,diffStats:d})=>{const u=i.useRef(r),[m,f]=i.useState(!1),[p,h]=i.useState(0),x=i.useRef(new Set);i.useEffect(()=>{if(u.current===r)return;const k=u.current===!1;if(u.current=r,c?.("structural"),r&&k){h(N=>N+1),f(!0),x.current.clear();const D=setTimeout(()=>f(!1),50);return()=>clearTimeout(D)}else f(!1)},[r,c]);const g=i.useMemo(()=>b0(t),[t]),b=cu(g),y=i.useMemo(()=>g.slice(-lu),[g]),w=i.useMemo(()=>{const k=new Set;return y.forEach(D=>{D.part.id&&k.add(D.part.id)}),k},[y]),S=i.useMemo(()=>cu(y),[y]),C=Math.max(0,g.length-lu);if(g.length===0)return null;const v=r?g:y,j=r?b:S,M=C>0;return e.jsx(fr,{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",M&&"cursor-pointer"),onClick:M?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:M?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(Xn,{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(Gt,{className:"h-3.5 w-3.5"}):e.jsx(Hs,{className:"h-3.5 w-3.5"})})]}):e.jsx(Xn,{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..."]}),v.map((k,D)=>{const N=k.part.id||`group-part-${D}`,T=j[N],A=`${N}-exp${p}`,E=k.part.id?w.has(k.part.id):!1;let I=!1;switch(m&&E?I=!0:!r&&k.part.id&&(x.current.has(k.part.id)?I=!0:x.current.add(k.part.id)),k.kind){case"tool":return e.jsx(fr,{skipAnimation:I,children:e.jsx(Dl,{part:k.part,isExpanded:a.has(N),onToggle:l,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:T?.hasPrev??!1,hasNextTool:T?.hasNext??!1})},A);case"reasoning":return e.jsx(fr,{skipAnimation:I,children:e.jsx(h0,{part:k.part,messageId:k.messageId,onContentChange:c})},A);case"justification":return e.jsx(fr,{skipAnimation:I,children:e.jsx(y0,{part:k.part,messageId:k.messageId,onContentChange:c})},A);default:return null}})]})]})})},v0=i.memo(w0),bc=t=>{const r=t,s=r.text;return typeof s=="string"?s:r.content||r.value||""},bp=t=>{if(t.type!=="text")return!1;const r=bc(t);return!r||r.trim().length===0},j0=(t,r={})=>{const{includeReasoning:s=!0}=r,n=t.some(o=>!o.synthetic);return t.filter(o=>{const l=!!o.synthetic;return l&&o.type==="text"&&bc(o).includes("<system-reminder>")||l&&n||!s&&o.type==="reasoning"?!1:!(o.type==="patch")})},S0=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`},N0=new Set(["task"]),oa=t=>typeof t=="string"&&N0.has(t.toLowerCase()),k0=({messageId:t,parts:r,isMobile:s,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:l,onShowPopup:c,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=i.useState(!1),h=i.useRef(null),x=i.useMemo(()=>r.filter(k=>k.type!=="text"?!1:!bp(k)),[r]),g=d?.token;let b=!1;const y=!!a,w=!!l,S=!!(n??s),C=!!o,v=i.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),j=i.useCallback(()=>{!S||!y||!C||typeof window>"u"||(v(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[y,v,C,S]);i.useEffect(()=>{C||(p(!1),v())},[v,C]);const M=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:x.map((k,D)=>{let N;return d&&g&&!b&&bc(k).includes(g)&&(N=d,b=!0),e.jsx(fr,{children:e.jsx(Bj,{part:k,messageId:t,isMobile:s,agentMention:N})},`user-text-${D}`)})}),e.jsx(tp,{files:r,onShowPopup:c}),y&&C||u||m?e.jsxs("div",{className:R("mt-1 flex items-center justify-end gap-2"),children:[u&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{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(Jn,{className:"h-3.5 w-3.5"})})}),e.jsx(ft,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{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(qt,{className:"h-3.5 w-3.5"})})}),e.jsx(ft,{sideOffset:6,children:"Fork from here"})]}),y&&C&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Se,{type:"button",variant:"ghost",size:"icon","data-visible":f||w?"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:M,onFocus:()=>p(!0),onBlur:()=>{w||p(!1)},children:w?e.jsx($t,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(sr,{className:"h-3.5 w-3.5"})})}),e.jsx(ft,{sideOffset:6,children:"Copy message"})]})]}):null]})},C0=({messageId:t,parts:r,isMessageCompleted:s,messageFinish:n,messageCompletedAt:o,syntaxTheme:a,isMobile:l,hasTouchInput:c,expandedTools:d,onToggleTool:u,onShowPopup:m,streamPhase:f,allowAnimation:p,onContentChange:h,hasTextContent:x=!1,onCopyMessage:g,copiedMessage:b=!1,onAuxiliaryContentComplete:y,showReasoningTraces:w=!1,turnGroupingContext:S,errorMessage:C})=>{const[v,j]=i.useState(!1),M=i.useRef(null),k=!!g,D=!!b,N=!!(c??l),T=!s,A=i.useMemo(()=>r.filter(Ge=>!bp(Ge)).filter(Ge=>Ge.type!=="compaction"),[r]),E=i.useMemo(()=>A.filter(Ge=>Ge.type==="tool"),[A]),I=i.useMemo(()=>A.filter(Ge=>Ge.type==="text"),[A]),P=ge(Ge=>Ge.createSessionFromAssistantMessage),F=je(Ge=>Ge.openMultiRunLauncherWithPrompt),$=S?.isLastAssistantInTurn??!1,Q=n==="stop",ie=E.length>0,K=i.useMemo(()=>E.some(Ge=>{const xt=(Ge.state??{})?.status;return xt==="pending"||xt==="running"||xt==="started"}),[E]),ee=i.useCallback(Ge=>{const ut=Ge.state??{},xt=ut?.status;if(xt==="pending"||xt==="running"||xt==="started")return!1;const kt=ut?.time??{},At=typeof kt?.end=="number"?kt.end:void 0,Xt=typeof kt?.start=="number"?kt.start:void 0;return!(typeof At!="number"||typeof Xt=="number"&&At<Xt)},[]),V=i.useMemo(()=>E.length===0?!0:K?!1:E.every(Ge=>ee(Ge)),[E,K,ee]),ae=i.useMemo(()=>A.filter(Ge=>Ge.type==="reasoning"),[A]),G=i.useMemo(()=>ae.length===0?!0:ae.every(Ge=>typeof Ge.time?.end=="number"),[ae]),q=typeof n!="string",_=ae.length>0&&ie&&(K||q||!V),H=T||ie&&(K||q||!V),L=T||_,B=ie||ae.length>0,O=I.length===0,le=B&&O&&!H&&!L&&V&&G,we=i.useRef(!1),pe=i.useRef(!1);i.useEffect(()=>{pe.current=!1},[t]),i.useEffect(()=>{if(!le){we.current=!1;return}we.current||(we.current=!0,y?.())},[le,y]),i.useEffect(()=>{if(T){pe.current=!1;return}if(ie){pe.current=!1;return}ae.length!==0&&(L||!G||pe.current||(pe.current=!0,h?.("structural")))},[T,ie,h,G,ae.length,L]);const De=!!x&&!T,z=i.useCallback(()=>{M.current!==null&&typeof window<"u"&&(window.clearTimeout(M.current),M.current=null)},[]),he=i.useCallback(()=>{!N||!k||!De||typeof window>"u"||(z(),j(!0),M.current=window.setTimeout(()=>{j(!1),M.current=null},1800))},[k,z,De,N]);i.useEffect(()=>{De||(j(!1),z())},[z,De]);const Z=i.useCallback(Ge=>{!g||!De||(Ge.stopPropagation(),Ge.preventDefault(),g(),N&&he())},[De,N,g,he]),de=i.useCallback(Ge=>{Ge.stopPropagation(),Ge.preventDefault(),P&&P(t)},[P,t]),Ee=i.useCallback(Ge=>{Ge.stopPropagation(),Ge.preventDefault();const ut=Xl(I);if(!ut.trim())return;const xt=`${Bb}
189
-
190
- ${ut}`;F(xt)},[I,F]);i.useEffect(()=>()=>{z()},[z]);const ne=i.useMemo(()=>{const Ge={},ut=E.filter(xt=>oa(xt.tool)||H?!1:ee(xt));return ut.forEach((xt,kt)=>{Ge[xt.id]={hasPrev:kt>0,hasNext:kt<ut.length-1}}),Ge},[E,H,ee]),ye=i.useMemo(()=>S?.activityParts??[],[S]),te=i.useMemo(()=>S?ye.filter(Ge=>Ge.messageId===t):[],[ye,t,S]),ce=i.useMemo(()=>S?S.activityGroupSegments.filter(Ge=>Ge.anchorMessageId===t):[],[t,S]),X=i.useMemo(()=>{const Ge=new Map;return te.forEach(ut=>{Ge.set(ut.part,ut)}),Ge},[te]),U=i.useMemo(()=>S?(w?ye:ye.filter(ut=>ut.kind==="tool")).filter(ut=>{if(ut.kind!=="tool")return!0;const xt=ut.part.tool;return!oa(xt)}):[],[ye,w,S]),[Y,se]=i.useState(!1);i.useEffect(()=>{if(!S)return;const Ge=S.activityGroupSegments.some(ut=>ut.afterToolPartId!==null);(U.length>1||Ge&&U.length>0)&&se(!0)},[S,U.length]);const me=!!(S&&Y),ze=!!(S&&me&&U.length>0&&ce.length>0),qe=i.useMemo(()=>E.filter(Ge=>oa(Ge.tool)),[E]),tt=i.useMemo(()=>{const Ge=[],ut=kt=>{!S||!ze||ce.filter(At=>(At.afterToolPartId??null)===kt).forEach(At=>{const Xt=w?At.parts:At.parts.filter(as=>as.kind==="tool");Xt.length!==0&&Ge.push(e.jsx(v0,{parts:Xt,isExpanded:S.isGroupExpanded,onToggle:S.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,diffStats:S.diffStats},`progressive-group-${At.id}`))})};ut(null),qe.forEach(kt=>{Ge.push(e.jsx(fr,{children:e.jsx(Dl,{part:kt,isExpanded:d.has(kt.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${kt.id}`)),ut(kt.id)});const xt=[];return A.forEach((kt,At)=>{const Xt=X.get(kt);if(!Xt||!S)return;let as=null,_t=null;if(!me){if(Xt.kind==="tool"){const Mt=kt;if(oa(Mt.tool))return;const Jt=Mt.state?.time,Ft=ee(Mt);if(!(!H&&Ft))return;const ps=ne[Mt.id];_t=e.jsx(fr,{children:e.jsx(Dl,{part:Mt,isExpanded:d.has(Mt.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:ps?.hasPrev??!1,hasNextTool:ps?.hasNext??!1})},`tool-${Mt.id}`),as=Ft&&typeof Jt?.end=="number"?Jt.end:null}_t&&xt.push({part:kt,index:At,endTime:as,element:_t})}}),xt.sort((kt,At)=>kt.endTime===null&&At.endTime===null?kt.index-At.index:kt.endTime===null?1:At.endTime===null?-1:kt.endTime-At.endTime),xt.forEach(({element:kt})=>{Ge.push(kt)}),Ge},[X,ce,d,l,ee,h,m,u,H,me,w,a,ne,S,A,qe,ze]),Xe=S?.turnId,Nt=ge(Ge=>Ge.currentSessionId),Ne=Dt(Ge=>{if(!Xe||!Nt)return;const ut=Ge.messages.get(Nt);if(!ut)return;const xt=ut.find(Xt=>Xt.info?.id===Xe);if(!xt)return;const At=xt.info.summary?.body;return typeof At=="string"&&At.trim().length>0?At:void 0}),ue=typeof S?.summaryBody=="string"&&S.summaryBody.trim().length>0?S.summaryBody:Ne,We=i.useRef(void 0);ue&&ue.trim().length>0&&(We.current=ue);const ve=i.useRef(Xe);ve.current!==Xe&&(ve.current=Xe,We.current=void 0);const ke=We.current,Ze=S?.isLastAssistantInTurn&&ke&&ke.trim().length>0,ct=!!C,Ue=$&&x&&(Q||!!C),[Be,Ve]=i.useState(!1),dt=i.useMemo(()=>{if(!$||!Q)return;const Ge=S?.userMessageCreatedAt;if(!(typeof Ge!="number"||typeof o!="number")&&!(o<=Ge))return S0(o-Ge)},[$,Q,S?.userMessageCreatedAt,o]),pt=e.jsxs(e.Fragment,{children:[e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{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:Ge=>Ge.stopPropagation(),onClick:de,children:e.jsx(Gg,{className:"h-4 w-4"})})}),e.jsx(ft,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{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:Ge=>Ge.stopPropagation(),onClick:Ee,children:e.jsx(qf,{className:"h-4 w-4"})})}),e.jsx(ft,{sideOffset:6,children:"Start new multi-run from this answer"})]}),g&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Se,{type:"button",variant:"ghost",size:"icon","data-visible":v||D?"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",!De&&"opacity-50"),disabled:!De,"aria-label":"Copy message text","aria-hidden":!De,onPointerDown:Ge=>Ge.stopPropagation(),onClick:Z,onFocus:()=>{De&&j(!0)},onBlur:()=>{D||j(!1)},children:D?e.jsx($t,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(sr,{className:"h-3.5 w-3.5"})})}),e.jsx(ft,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:R("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:N&&k&&De?he: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:[tt,ct&&e.jsx(fr,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(bn,{content:C??""})})},"assistant-error"),Ze&&e.jsx(fr,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Ve(!0),onMouseLeave:()=>Ve(!1),children:[e.jsx(bn,{content:ke}),Ue&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[dt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Ic,{className:"h-3.5 w-3.5"}),dt]}):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",Be&&"opacity-100 pointer-events-auto"),children:pt})]})]})},"summary-body")]}),e.jsx(tp,{files:r,onShowPopup:m}),!Ze&&Ue&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[dt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Ic,{className:"h-3.5 w-3.5"}),dt]}):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:pt})]})]})})},M0=({isUser:t,...r})=>t?e.jsx(k0,{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(C0,{...r}),du=i.memo(M0),$i=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}},D0=i.lazy(()=>Ss(()=>import("./ToolOutputDialog-DtvujDp_.js"),__vite__mapDeps([2,0,1,3,4]))),A0=new Set(["task","edit","multiedit","write","bash"]),uu=t=>typeof t=="string"&&A0.has(t.toLowerCase());function _i(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]},E0=({message:t,previousMessage:r,nextMessage:s,onContentChange:n,animationHandlers:o,turnGroupingContext:a})=>{const{isMobile:l,hasTouchInput:c}=Kt(),{currentTheme:d}=Br(),u=i.useRef(null),m=ge(_n(fe=>({lifecyclePhase:fe.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const xe=t.info.sessionID??fe.currentSessionId??null;return xe?(fe.streamingMessageIds.get(xe)??null)===t.info.id:!1})(),currentSessionId:fe.currentSessionId,getAgentModelForSession:fe.getAgentModelForSession,getSessionModelSelection:fe.getSessionModelSelection,revertToMessage:fe.revertToMessage,forkFromMessage:fe.forkFromMessage}))),{lifecyclePhase:f,isStreamingMessage:p,currentSessionId:h,getAgentModelForSession:x,getSessionModelSelection:g,revertToMessage:b,forkFromMessage:y}=m,w=et(fe=>fe.providers),{showReasoningTraces:S,toolCallExpansion:C}=je(_n(fe=>({showReasoningTraces:fe.showReasoningTraces,toolCallExpansion:fe.toolCallExpansion})));i.useEffect(()=>{h&&Gr.getInstance().recordSessionStart(h)},[h]);const[v,j]=i.useState(null),[M,k]=i.useState(!1),[D,N]=i.useState(new Set),[T,A]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{N(new Set)},[t.info.id,C]);const I=i.useMemo(()=>$i(t.info),[t.info]).isUser,P=t.info.sessionID,{currentContextAgent:F,savedSessionAgentSelection:$}=nt(_n(fe=>({currentContextAgent:P?fe.currentAgentContext.get(P):void 0,savedSessionAgentSelection:P?fe.sessionAgentSelections.get(P):void 0}))),Q=i.useMemo(()=>{if(!I)return t.parts;const fe=xe=>{const Re=xe.trim();return!!(Re.startsWith("User has requested to enter plan mode")||Re.startsWith("The plan at "))};return t.parts.filter(xe=>{if(!(xe?.synthetic===!0))return!0;if(xe.type!=="text")return!1;const st=xe?.text;return typeof st=="string"?fe(st):!1}).map(xe=>xe.type==="compaction"?{type:"text",text:"/compact"}:xe)},[I,t.parts]),ie=i.useMemo(()=>{if(I||!r)return null;const fe=Qs(r.info,"clientRole"),xe=Qs(r.info,"role");if((typeof fe=="string"?fe:typeof xe=="string"?xe:void 0)!=="user")return null;const st=Qs(r.info,"mode"),mt=Qs(r.info,"agent"),Ot=Qs(r.info,"providerID"),Bt=Qs(r.info,"modelID"),Ms=Qs(r.info,"variant"),vs=typeof st=="string"&&st.trim().length>0?st:typeof mt=="string"&&mt.trim().length>0?mt:void 0,It=typeof Ot=="string"&&Ot.trim().length>0?Ot:void 0,zt=typeof Bt=="string"&&Bt.trim().length>0?Bt:void 0,ns=typeof Ms=="string"&&Ms.trim().length>0?Ms:void 0;return!vs&&!It&&!zt&&!ns?null:{agentName:vs,providerId:It,modelId:zt,variant:ns}},[I,r]),K=i.useMemo(()=>{if(I||!r)return!1;const fe=Array.isArray(r.parts)?r.parts:[];for(let xe=0;xe<fe.length;xe++){const Re=fe[xe];if(Re?.type!=="text"||Re?.synthetic!==!0)continue;const st=typeof Re.text=="string"?Re.text.trim():"";if(st.startsWith("User has requested to enter plan mode")||st.startsWith("The plan at "))return!0}return!1},[I,r]),ee=i.useMemo(()=>{if(I)return;const fe=t.info.time;if(!(typeof fe?.completed=="number"&&fe.completed>0)&&K&&ie?.agentName)return ie.agentName;const Re=Qs(t.info,"mode");if(typeof Re=="string"&&Re.trim().length>0)return Re;const st=Qs(t.info,"agent");if(typeof st=="string"&&st.trim().length>0)return st;if(ie?.agentName)return ie.agentName;if(P)return F||($??void 0)},[I,t.info,K,ie,P,F,$]),V=I?null:Qs(t.info,"providerID"),ae=I?null:Qs(t.info,"modelID"),G=i.useMemo(()=>{if(I||!P)return null;if(ie?.providerId&&ie?.modelId)return{providerId:ie.providerId,modelId:ie.modelId};if(ee){const xe=x(P,ee);if(xe?.providerId&&xe?.modelId)return xe}const fe=g(P);return fe?.providerId&&fe?.modelId?fe:null},[I,P,ee,ie,x,g]),q=i.useMemo(()=>I?null:typeof V=="string"&&V.trim().length>0?V:G?.providerId??null,[I,V,G]),_=i.useMemo(()=>I?null:typeof ae=="string"&&ae.trim().length>0?ae:G?.modelId??null,[I,ae,G]),H=i.useMemo(()=>{if(!I&&q&&_&&w.length>0){const fe=w.find(xe=>xe.id===q);if(fe?.models&&Array.isArray(fe.models)){const st=fe.models.find(mt=>mt.id===_)?.name;return typeof st=="string"?st:void 0}}},[I,q,_,w]),L=i.useMemo(()=>{if(I||!q||!_)return!1;const fe=w.find(st=>st.id===q);if(!fe?.models||!Array.isArray(fe.models))return!1;const Re=fe.models.find(st=>st.id===_)?.variants;return!!(Re&&Object.keys(Re).length>0)},[I,_,q,w]),B=_i(ee),O=_i(q??void 0),le=_i(H),we=B??void 0,pe=O??null,De=le??void 0,z=i.useMemo(()=>{const fe=t.info.time;return typeof fe?.completed=="number"?fe.completed:null},[t.info.time]),he=i.useMemo(()=>I?!0:!!(z&&z>0),[I,z]),Z=i.useMemo(()=>{const fe=t.info.finish;return typeof fe=="string"?fe:void 0},[t.info]),de=i.useMemo(()=>j0(Q,{includeReasoning:S}),[Q,S]),Ee=i.useMemo(()=>I||he?de:[],[I,he,de]),ne=i.useMemo(()=>I?[]:de.filter(fe=>fe.type==="text"),[I,de]),ye=i.useMemo(()=>I?[]:de.filter(xe=>xe.type==="tool"),[I,de]),te=i.useMemo(()=>{if(C==="collapsed"||C==="activity")return D;const fe=new Set;for(const Re of ye){const st=Re.tool;Re.id&&uu(st)&&fe.add(Re.id)}if(a?.isFirstAssistantInTurn)for(const Re of a.activityParts){if(Re.kind!=="tool")continue;const st=Re.part;st.id&&uu(st.tool)&&fe.add(st.id)}const xe=new Set(fe);for(const Re of D)xe.has(Re)?xe.delete(Re):xe.add(Re);return xe},[D,C,ye,a]),ce=i.useMemo(()=>{if(!I)return;const fe=t.parts.find(mt=>mt.type==="agent");if(!fe)return;const xe=fe,Re=typeof xe.name=="string"?xe.name:void 0;if(!Re)return;const st=xe.source&&typeof xe.source.value=="string"&&xe.source.value.trim().length>0?xe.source.value:`#${Re}`;return{name:Re,token:st}},[I,t.parts]),X=typeof Z!="string",U=i.useMemo(()=>I?!1:ne.length===0||ye.length===0?X:!0,[ne.length,ye.length,X,I]),Y=d?.metadata.variant,se=i.useMemo(()=>Y?Y==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[Y]),me=i.useMemo(()=>d?mi(d):se?Tj:Fj,[d,se]),ze=i.useMemo(()=>I?!1:Gr.getInstance().shouldAnimateMessage(t.info,h||t.info.sessionID),[t.info,h,I]),qe=i.useRef(!1),tt=i.useMemo(()=>r?$i(r.info):null,[r]),Xe=i.useMemo(()=>s?$i(s.info):null,[s]),Nt=i.useMemo(()=>I||!Xe?!1:!Xe.isUser&&Xe.role==="assistant",[I,Xe]),Ne=i.useMemo(()=>he?"completed":f||(p?"streaming":"completed"),[he,f,p]),ue=i.useMemo(()=>{if(I)return!0;const fe=a?.headerMessageId;if(fe){if(t.info.id===fe){if(Ne==="completed")return!0;const Re=Ne==="streaming"||Ne==="cooldown",st=qe.current;return Re&&!st&&(qe.current=!0),st||Re}return!1}return tt?tt.isUser:!0},[I,tt,a,Ne,t.info]),We=i.useCallback(fe=>{navigator.clipboard.writeText(fe),j(fe),setTimeout(()=>j(null),2e3)},[]),ve=a?.turnId,{assistantSummaryFromStore:ke,variantFromTurnStore:Ze}=Dt(_n(fe=>{if(!ve||!t.info.sessionID)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const xe=fe.messages.get(t.info.sessionID);if(!xe)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const Re=xe.find(Bt=>Bt.info?.id===ve);if(!Re)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const mt=Re.info.summary?.body,Ot=Re.info.variant;return{assistantSummaryFromStore:typeof mt=="string"&&mt.trim().length>0?mt:void 0,variantFromTurnStore:typeof Ot=="string"&&Ot.trim().length>0?Ot:void 0}})),ct=I?void 0:Ze??ie?.variant,Ue=!I&&L?ct??"Default":void 0,Be=typeof a?.summaryBody=="string"&&a.summaryBody.trim().length>0?a.summaryBody:ke,Ve=i.useRef(void 0);Be&&Be.trim().length>0&&(Ve.current=Be);const dt=i.useRef(ve);dt.current!==ve&&(dt.current=ve,Ve.current=void 0);const pt=Ve.current,Ge=i.useMemo(()=>{if(I)return;const fe=t.info?.error;if(!fe)return;const xe=typeof fe.data?.message=="string"?fe.data.message:void 0,Re=typeof fe.message=="string"?fe.message:void 0,st=typeof fe.name=="string"?fe.name:void 0,mt=xe||Re||st;if(mt)return`Opencode failed to send message with error:
191
- \`${mt}\``},[I,t.info]),ut=i.useMemo(()=>I?Ee.filter(Re=>Re.type==="text").map(Re=>(Re.text||Re.content||"").trim()).filter(Re=>Re.length>0).join(`
192
- `).replace(/\n\s*\n+/g,`
193
- `):Ge&&Ge.trim().length>0?Ge:pt&&pt.trim().length>0?pt:Xl(Ee),[Ge,pt,Ee,I]),xt=ut.length>0,kt=i.useCallback(async fe=>{if(!fe)return!1;if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(fe),!0}catch{}if(typeof document>"u")return!1;const xe=document.createElement("textarea");xe.value=fe,xe.setAttribute("readonly",""),xe.style.position="fixed",xe.style.top="-1000px",xe.style.left="-1000px",document.body.appendChild(xe),xe.select(),xe.setSelectionRange(0,xe.value.length);const Re=document.execCommand("copy");return document.body.removeChild(xe),Re},[]),At=i.useCallback(async()=>{await kt(ut)&&(k(!0),setTimeout(()=>k(!1),2e3))},[kt,ut]),Xt=i.useCallback(()=>{!P||!t.info.id||b(P,t.info.id)},[P,t.info.id,b]),as=i.useCallback(()=>{!P||!t.info.id||y(P,t.info.id)},[P,t.info.id,y]),_t=i.useCallback(fe=>{N(xe=>{const Re=new Set(xe);return Re.has(fe)?Re.delete(fe):Re.add(fe),Re})},[]),Mt=o??null,Rt=i.useRef(!1),Jt=i.useRef(!1),Ft=i.useRef(!1),Qt=i.useRef(!1),ps=i.useRef(!1);i.useEffect(()=>{Jt.current=!1,Ft.current=!1,Qt.current=!1,ps.current=!1,Rt.current=!1},[t.info.id]);const Lt=i.useCallback(()=>{I||Rt.current||(Rt.current=!0,n?.("structural"))},[I,n]),Me=i.useCallback(fe=>{fe.image&&A(fe)},[]),$e=i.useCallback(fe=>{A(xe=>({...xe,open:fe}))},[]),Le=!!Qs(t.info,"animationSettled"),ot=Ne==="streaming",oe=i.useMemo(()=>I?!1:de.some(fe=>fe.type==="reasoning"),[I,de]),Te=ze&&!Le&&!ot,Ie=!I&&ze&&ne.length>0&&!U;return i.useEffect(()=>{if(Mt?.onStreamingCandidate){if(!Ie){Ft.current&&(oe&&Mt?.onReasoningBlock?Mt.onReasoningBlock():Mt?.onReservationCancelled&&Mt.onReservationCancelled(),Ft.current=!1);return}ps.current||(ps.current=!0,Mt.onStreamingCandidate(),Ft.current=!0)}},[Mt,Ie,oe]),i.useEffect(()=>{Mt?.onAnimationStart&&Te&&(Qt.current||(Mt.onAnimationStart(),Qt.current=!0))},[Mt,Te]),i.useEffect(()=>{if(I)return;const fe=Mt?.onAnimatedHeightChange;if(!fe||!(Te||Ie))return;const Re=u.current;if(!Re)return;if(typeof window>"u"||typeof ResizeObserver>"u"){fe(Re.getBoundingClientRect().height);return}let st=null;const mt=Bt=>{if(typeof window>"u"){fe(Bt);return}st!==null&&window.cancelAnimationFrame(st),st=window.requestAnimationFrame(()=>{fe(Bt)})},Ot=new ResizeObserver(Bt=>{const Ms=Bt[0];Ms&&mt(Ms.contentRect.height)});return Ot.observe(Re),mt(Re.getBoundingClientRect().height),()=>{st!==null&&(window.cancelAnimationFrame(st),st=null),Ot.disconnect()}},[Te,I,Mt,Ie]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("group w-full",ue?"pt-6":"pt-0",I?"pb-4":Nt?"pb-0":"pb-8"),"data-message-id":t.info.id,ref:u,children:e.jsx("div",{className:"chat-message-column relative",children:I?Ee.length===0?null:e.jsx(fr,{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(du,{messageId:t.info.id,parts:Ee,isUser:I,isMessageCompleted:he,messageFinish:Z,syntaxTheme:me,isMobile:l,hasTouchInput:c,copiedCode:v,onCopyCode:We,expandedTools:D,onToggleTool:_t,onShowPopup:Me,streamPhase:Ne,allowAnimation:Te,onContentChange:n,shouldShowHeader:!1,hasTextContent:xt,onCopyMessage:At,copiedMessage:M,showReasoningTraces:S,onAuxiliaryContentComplete:Lt,agentMention:ce,onRevert:Xt,onFork:I?as:void 0,errorMessage:Ge})})})}):e.jsxs("div",{className:"relative pl-4 ml-1",children:[ue&&e.jsx(Oj,{isUser:I,providerID:pe,agentName:we,modelName:De,variant:Ue,isDarkTheme:se}),e.jsx(du,{messageId:t.info.id,parts:de,isUser:I,isMessageCompleted:he,messageFinish:Z,messageCompletedAt:z??void 0,syntaxTheme:me,isMobile:l,hasTouchInput:c,copiedCode:v,onCopyCode:We,expandedTools:te,onToggleTool:_t,onShowPopup:Me,streamPhase:Ne,allowAnimation:Te,onContentChange:n,shouldShowHeader:ue,hasTextContent:xt,onCopyMessage:At,copiedMessage:M,onAuxiliaryContentComplete:Lt,showReasoningTraces:S,agentMention:ce,turnGroupingContext:a,errorMessage:Ge})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(D0,{popup:T,onOpenChange:$e,syntaxTheme:me,isMobile:l})})]})},wp=i.memo(E0),I0=({diff:t,syntaxTheme:r,filePath:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:mp(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,l)=>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(Fr,{style:r,language:Cr(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})})]},l))})]},o))}),P0=({content:t,syntaxTheme:r,filePath:s})=>{const n=t.split(`
194
- `),o=Cr(s??"")||"text",a=s?.split("/").pop()||"New file",l=Math.max(n.length,1),c=l===1?"line 1":`lines 1-${l}`;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} (${c})`}),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(Fr,{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))})]})},T0=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(Er,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(Sm,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?e.jsx(Xr,{className:r}):s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?e.jsx(ol,{className:r}):e.jsx(Ja,{className:r})},F0=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},R0=({permission:t,onResponse:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(!1),{respondToPermission:l}=ge(),{currentTheme:c}=Br(),d=i.useMemo(()=>mi(c),[c]),u=async y=>{n(!0);try{await l(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,w="")=>{const S=t.metadata[y];return typeof S=="string"?S:typeof S=="number"?String(S):w},h=y=>{const w=t.metadata[y];return typeof w=="number"?w:void 0},x=y=>!!t.metadata[y],g=F0(m),b=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const S=p("command")||p("cmd")||p("script"),C=p("description"),v=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}),v&&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:v})]}),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(Fr,{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"),v=x("replace_all")||x("replaceAll");return e.jsxs(e.Fragment,{children:[v&&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(jt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(I0,{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(jt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(P0,{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",v=t.metadata.headers&&typeof t.metadata.headers=="object"?t.metadata.headers:void 0,j=p("body")||p("data")||p("payload"),M=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})]})]}),v&&Object.keys(v).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(jt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(Fr,{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(v,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(jt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(Fr,{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)})})]}),(M||k)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[M&&e.jsxs("span",{children:["Timeout: ",M,"ms"]}),M&&k&&e.jsx("span",{children:" • "}),k&&e.jsxs("span",{children:["Response format: ",k]})]})]})}const y=p("command")||p("content")||p("action")||p("operation"),w=p("description");return e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:w}),y&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(jt,{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&&!w&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(jt,{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(vn,{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:[T0(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:g})]})]})}),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($t,{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(Sr,{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(Sr,{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(os,{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"})})]})]})})})},Bi="summary",L0=({question:t})=>{const{respondToQuestion:r,rejectQuestion:s}=ge(),[n,o]=i.useState("0"),[a,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState({}),[f,p]=i.useState({}),[h,x]=i.useState({}),g=i.useMemo(()=>t.questions??[],[t.questions]),b=n===Bi,y=b?-1:Math.max(0,Math.min(g.length-1,Number(n)||0)),w=b?null:g[y],S=i.useMemo(()=>{if(b)return null;const P=w?.header?.trim();return P&&P.length>0?P:null},[w?.header,b]);i.useEffect(()=>{o("0"),m({}),p({}),x({}),d(!1)},[t.id]);const C=i.useMemo(()=>{const P=g.map((F,$)=>({value:String($),label:F.header?.trim()||`Q${$+1}`}));return g.length>1&&P.push({value:Bi,label:"Summary"}),P},[g]),v=i.useCallback(P=>{if(!!f[P])return(h[P]??"").trim()||"(no answer)";const $=u[P]??[];return $.length>0?$.join(", "):"(no answer)"},[f,h,u]),j=!!w?.multiple,M=u[y]??[],k=!!f[y],D=i.useMemo(()=>{if(g.length===0)return!1;for(let P=0;P<g.length;P+=1){if(!!f[P]){if(!(h[P]??"").trim())return!1;continue}if((u[P]??[]).length===0)return!1}return!0},[f,h,g.length,u]),N=i.useCallback(()=>{const P=[];for(let F=0;F<g.length;F+=1){if(!!f[F]){const Q=(h[F]??"").trim();P.push(Q?[Q]:[]);continue}P.push(u[F]??[])}return P},[f,h,g.length,u]),T=i.useCallback(P=>{w&&(p(F=>({...F,[y]:!1})),m(F=>{const $=F[y]??[];if(j){const ie=$.includes(P)?$.filter(K=>K!==P):[...$,P];return{...F,[y]:ie}}return{...F,[y]:[P]}}))},[y,w,j]),A=i.useCallback(()=>{p(P=>({...P,[y]:!0})),m(P=>({...P,[y]:[]}))},[y]),E=i.useCallback(async()=>{if(D){l(!0);try{const P=N();await r(t.sessionID,t.id,P),d(!0)}catch{}finally{l(!1)}}},[N,t.id,t.sessionID,D,r]),I=i.useCallback(async()=>{l(!0);try{await s(t.sessionID,t.id),d(!0)}catch{}finally{l(!1)}},[t.id,t.sessionID,s]);return c||g.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(vn,{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,$=P.value===Bi;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:[$?e.jsx(Nm,{className:"h-3 w-3"}):null,P.label]},P.value)})}):null,b?e.jsx("div",{className:"space-y-2",children:g.map((P,F)=>{const $=v(F),Q=$!=="(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",Q?"text-foreground":"text-muted-foreground/50 italic"),children:$})]},F)})}):w?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:w.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:[w.options.map((P,F)=>{const $=M.includes(P.label),Q=/\(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",$?"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:$?e.jsx(qg,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(al,{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",$?"text-foreground font-medium":"text-foreground/80"),children:P.label}),Q?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:A,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(ao,{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,$=F*2,Q=F*4;P.style.height=`${Math.min(Math.max(P.scrollHeight,$),Q)}px`}},value:h[y]??"",onChange:P=>{const F=P.target;F.style.height="auto";const $=20,Q=$*2,ie=$*4;F.style.height=`${Math.min(Math.max(F.scrollHeight,Q),ie)}px`,x(K=>({...K,[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:E,disabled:a||!D,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($t,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:I,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(os,{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]})]})})})},O0=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},_o=i.createContext(null),wc=i.createContext(null),vp=i.createContext(null);let mu=null;const Ln=new Map,$0=t=>{const r=i.useContext(_o),s=i.useContext(wc),n=i.useContext(vp);return i.useMemo(()=>{if(!r||!s||!n)return;mu!==r&&(Ln.clear(),mu=r);const o=r.messageToTurn.get(t);if(!o||!o.assistantMessages.some(T=>T.info.id===t))return;const l=r.lastTurnId===o.turnId,d=(s.turnUiStates.get(o.turnId)??{isExpanded:r.defaultActivityExpanded}).isExpanded,u=l?`${t}-${d}-${n.sessionIsWorking}`:`${t}-${d}`,m=Ln.get(u);if(m)return m;const f=r.turnActivityInfo.get(o.turnId),p=f?.activityParts??[],h=f?.activityGroupSegments??[],x=!!f?.hasTools,g=!!f?.hasReasoning,b=f?.summaryBody,y=f?.diffStats,w=o.assistantMessages[0]?.info.id,S=t===w,C=o.assistantMessages[o.assistantMessages.length-1]?.info.id,v=t===C,j=w,M=l&&n.sessionIsWorking,k=o.userMessage.info.time,D=typeof k?.created=="number"?k.created:void 0,N={turnId:o.turnId,isFirstAssistantInTurn:S,isLastAssistantInTurn:v,summaryBody:b,activityParts:p,activityGroupSegments:h,headerMessageId:j,hasTools:x,hasReasoning:g,diffStats:y,userMessageCreatedAt:D,isWorking:M,isGroupExpanded:d,toggleGroup:()=>s.toggleGroup(o.turnId)};if(Ln.size>500){const T=Ln.keys().next().value;T&&Ln.delete(T)}return Ln.set(u,N),N},[r,s,n,t])},jp=t=>{const r=i.useContext(_o);return i.useMemo(()=>r?r.messageNeighbors.get(t)??{}:{},[r,t])},_0=()=>i.useContext(_o)?.lastTurnMessageIds??new Set,B0=t=>{const r=i.useContext(_o),s=i.useContext(wc);return i.useMemo(()=>{if(!r||!s)return;const n=r.messageToTurn.get(t);if(!n||!n.assistantMessages.some(v=>v.info.id===t))return;const a=r.turnActivityInfo.get(n.turnId),l=a?.activityParts??[],c=a?.activityGroupSegments??[],d=!!a?.hasTools,u=!!a?.hasReasoning,m=a?.summaryBody,f=a?.diffStats,p=n.assistantMessages[0]?.info.id,h=t===p,x=n.assistantMessages[n.assistantMessages.length-1]?.info.id,g=t===x,b=p,y=s.turnUiStates.get(n.turnId)??{isExpanded:r.defaultActivityExpanded},w=n.userMessage.info.time,S=typeof w?.created=="number"?w.created:void 0;return{turnId:n.turnId,isFirstAssistantInTurn:h,isLastAssistantInTurn:g,summaryBody:m,activityParts:l,activityGroupSegments:c,headerMessageId:b,hasTools:d,hasReasoning:u,diffStats:f,userMessageCreatedAt:S,isWorking:!1,isGroupExpanded:y.isExpanded,toggleGroup:()=>s.toggleGroup(n.turnId)}},[r,s,t])},z0=new Set(["task"]),fu=t=>typeof t=="string"&&z0.has(t.toLowerCase()),H0=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}}},W0=t=>{const r=H0(t);let s;const o=t.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let y=0,w=0,S=0;o.forEach(C=>{if(!C)return;const v=typeof C.additions=="number"?C.additions:0,j=typeof C.deletions=="number"?C.deletions:0;(v!==0||j!==0)&&(S+=1),y+=v,w+=j}),S>0&&(s={additions:y,deletions:w,files:S})}let a=!1,l=!1;t.assistantMessages.forEach(y=>{y.parts.forEach(w=>{w.type==="tool"?a=!0:w.type==="reasoning"&&(l=!0)})});const c=[];let d=0;t.assistantMessages.forEach(y=>{const w=y.info.id;y.info.finish,y.parts.forEach(S=>{const C=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${w}-activity-${d++}`;if(S.type==="tool"){const j=S.state?.time,M=typeof j?.end=="number"?j.end:void 0;c.push({id:C,turnId:t.turnId,messageId:w,kind:"tool",part:S,endedAt:M});return}if(S.type==="reasoning"){const v=S.text??S.content;if(typeof v!="string"||v.trim().length===0)return;const j=S.time,M=typeof j?.end=="number"?j.end:void 0;c.push({id:C,turnId:t.turnId,messageId:w,kind:"reasoning",part:S,endedAt:M});return}})});const u=[],m=new WeakMap;c.forEach(y=>{m.set(y.part,y)});const f=new Map,p=[],h=new Map;let x=null;t.assistantMessages.forEach(y=>{const w=y.info.id;y.parts.forEach(S=>{if(S.type==="tool"){const j=S.tool;if(fu(j)){const M=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${w}-task-${p.length+1}`;f.has(M)||(f.set(M,w),p.push(M)),x=M;return}}const C=m.get(S);if(!C)return;if(C.kind==="tool"){const j=C.part.tool;if(fu(j))return}const v=h.get(x)??[];v.push(C),h.set(x,v)})});const g=y=>{if(y.length===0)return;const w=new Map;y.forEach(v=>{w.set(v.messageId,(w.get(v.messageId)??0)+1)});let S,C=0;for(const v of t.assistantMessages){const j=w.get(v.info.id)??0;if(j>0&&!S&&(S=v.info.id),C+=j,C>=2)return v.info.id}return S};return[null,...p].forEach(y=>{const w=h.get(y)??[];if(w.length===0)return;const S=y===null?g(w):f.get(y);S&&u.push({id:`${t.turnId}:${S}:${y??"start"}`,anchorMessageId:S,afterToolPartId:y,parts:w})}),{activityParts:c,activityGroupSegments:u,hasTools:a,hasReasoning:l,summaryBody:r,diffStats:s}},U0=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},V0=({messages:t,children:r})=>{const{isWorking:s}=xc(),n=je(f=>f.toolCallExpansion),o=n==="activity"||n==="detailed",a=i.useMemo(()=>{const f=O0(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(w=>{h.set(w.info.id,y)})});const x=new Map;f.forEach(y=>{x.set(y.turnId,W0(y))});const g=U0(t),b=new Set;if(f.length>0){const y=f[f.length-1];b.add(y.userMessage.info.id),y.assistantMessages.forEach(w=>{b.add(w.info.id)})}return{turns:f,messageToTurn:h,turnActivityInfo:x,lastTurnId:p,lastTurnMessageIds:b,defaultActivityExpanded:o,messageNeighbors:g}},[t,o]),[l,c]=i.useState(()=>new Map);i.useEffect(()=>{c(new Map)},[n]);const d=i.useCallback(f=>{c(p=>{const h=new Map(p),x=h.get(f)??{isExpanded:o};return h.set(f,{isExpanded:!x.isExpanded}),h})},[o]),u=i.useMemo(()=>({turnUiStates:l,toggleGroup:d}),[l,d]),m=i.useMemo(()=>({sessionIsWorking:s}),[s]);return e.jsx(_o.Provider,{value:a,children:e.jsx(wc.Provider,{value:u,children:e.jsx(vp.Provider,{value:m,children:r})})})},Sp=i.memo(({message:t,onContentChange:r,animationHandlers:s,scrollToBottom:n})=>{const{previousMessage:o,nextMessage:a}=jp(t.info.id),l=B0(t.info.id);return e.jsx(wp,{message:t,previousMessage:o,nextMessage:a,onContentChange:r,animationHandlers:s,scrollToBottom:n,turnGroupingContext:l})});Sp.displayName="StaticMessageRow";const Np=i.memo(({message:t,onContentChange:r,animationHandlers:s,scrollToBottom:n})=>{const{previousMessage:o,nextMessage:a}=jp(t.info.id),l=$0(t.info.id);return e.jsx(wp,{message:t,previousMessage:o,nextMessage:a,onContentChange:r,animationHandlers:s,scrollToBottom:n,turnGroupingContext:l})});Np.displayName="DynamicMessageRow";const G0=({displayMessages:t,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:n})=>{const o=_0();return e.jsx(e.Fragment,{children:t.map(a=>{const c=o.has(a.info.id)?Np:Sp;return e.jsx(c,{message:a,onContentChange:r,animationHandlers:s(a.info.id),scrollToBottom:n},a.info.id)})})},q0=({messages:t,permissions:r,questions:s,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:l,onLoadOlder:c,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=wj(f.parts);return p===f.parts?f:{...f,parts:p}})},[t]);return e.jsx(V0,{messages:u,children:e.jsxs("div",{children:[a&&e.jsx("div",{className:"flex justify-center py-3",children:l?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:c,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx(G0,{displayMessages:u,onMessageContentChange:n,getAnimationHandlers:o,scrollToBottom:d}),(s.length>0||r.length>0)&&e.jsxs("div",{children:[s.map(m=>e.jsx(L0,{question:m},m.id)),r.map(m=>e.jsx(R0,{permission:m},m.id))]}),e.jsx("div",{className:"flex-shrink-0",style:{height:"10vh"},"aria-hidden":"true"})]})})},K0=i.memo(q0);function Q0(...t){return r=>{t.forEach(s=>{typeof s=="function"?s(r):s&&typeof s=="object"&&(s.current=r)})}}const kp=i.forwardRef(({orientation:t="vertical",offset:r=72,size:s=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:l,className:c,children:d,...u},m)=>{const f=i.useRef(null),p=i.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const x=i.useMemo(()=>{const w={...l};return w["--scroll-shadow-size"]=`${s}px`,w},[s,l]),g=i.useCallback((w,S,C,v,j)=>{const M=`${v}${j.charAt(0).toUpperCase()}${j.slice(1)}Scroll`;S&&C?(w.dataset[M]="true",w.removeAttribute(`data-${v}-scroll`),w.removeAttribute(`data-${j}-scroll`)):(w.dataset[`${v}Scroll`]=String(S),w.dataset[`${j}Scroll`]=String(C),w.removeAttribute(`data-${v}-${j}-scroll`))},[]),b=i.useCallback(w=>{["top","bottom","top-bottom","left","right","left-right"].forEach(S=>{w.removeAttribute(`data-${S}-scroll`)})},[]),y=i.useCallback(()=>{const w=f.current;if(!w)return;if(!n){b(w);return}const S=t==="vertical"?w.scrollTop>r:w.scrollLeft>r;let C=t==="vertical"?w.scrollTop+w.clientHeight+r<w.scrollHeight:w.scrollLeft+w.clientWidth+r<w.scrollWidth;o&&t==="vertical"&&(C=!1),g(w,S,C,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const v=S&&C?"both":S?t==="vertical"?"top":"left":C?t==="vertical"?"bottom":"right":"none";v!==p.current&&(p.current=v,a?.(v))},[b,o,n,r,a,t,g]);return i.useEffect(()=>{const w=f.current;if(!w)return;let S=null;const C=()=>{S===null&&(S=requestAnimationFrame(()=>{S=null,y()}))},v=()=>y(),j=typeof ResizeObserver<"u"?new ResizeObserver(C):null,M=typeof MutationObserver<"u"?new MutationObserver(C):null;return y(),w.addEventListener("scroll",v,{passive:!0}),j?.observe(w),M?.observe(w,{childList:!0,subtree:!0,characterData:!0}),()=>{S!==null&&cancelAnimationFrame(S),w.removeEventListener("scroll",v),j?.disconnect(),M?.disconnect()}},[y]),e.jsx("div",{...u,ref:Q0(f,m),className:c,"data-orientation":t,"data-scroll-shadow":h??!0,style:x,children:d})});kp.displayName="ScrollShadow";const Y0=160,J0=({containerRef:t})=>{const[r,s]=i.useState(!0),n=i.useRef(!0),o=i.useRef(!1),a=i.useRef(null),l=i.useRef(null),c=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,l.current=null,u.current=!1},[]),f=i.useCallback(C=>{const v=t.current;if(!v){m();return}l.current===null&&(l.current=C),u.current&&(d.current=v.scrollHeight-v.clientHeight);const j=Math.min(1,(C-l.current)/Y0),M=1-Math.pow(1-j,3),k=c.current,D=d.current,N=k+(D-k)*M;if(v.scrollTop=N,j<1){a.current=window.requestAnimationFrame(f);return}v.scrollTop=D,m(),n.current&&(n.current=!1,s(!1))},[m,t,s]),p=i.useCallback((C,v)=>{const j=t.current;if(!j)return;const M=Math.max(0,C),k=v?.instant??!1,D=v?.followBottom??!1;if(o.current=!1,typeof window>"u"||k){m(),j.scrollTop=M;const T=M<=1;n.current!==T&&(n.current=T,s(T));return}if(D&&u.current&&a.current!==null)return;if(m(),Math.abs(M-j.scrollTop)<=.5){j.scrollTop=M;const T=M<=1;n.current!==T&&(n.current=T,s(T));return}c.current=j.scrollTop,d.current=M,l.current=null,u.current=D,a.current=window.requestAnimationFrame(f)},[m,t,f,s]),h=i.useCallback(()=>{o.current=!0},[]),x=i.useCallback(()=>{o.current=!0},[]),g=i.useCallback(()=>o.current,[]),b=i.useCallback(()=>t.current?.scrollTop??0,[t]),y=i.useCallback(()=>t.current?.scrollHeight??0,[t]),w=i.useCallback(()=>t.current?.clientHeight??0,[t]),S=i.useCallback(()=>{const C=t.current;if(!C)return;o.current&&a.current!==null&&m();const v=C.scrollTop<=1;n.current!==v&&(n.current=v,s(v))},[m,t]);return i.useEffect(()=>{const C=t.current;if(C)return C.addEventListener("wheel",x,{passive:!0}),C.addEventListener("touchstart",x,{passive:!0}),()=>{C.removeEventListener("wheel",x),C.removeEventListener("touchstart",x)}},[t,x]),i.useEffect(()=>()=>{m()},[m]),i.useMemo(()=>({handleScroll:S,scrollToPosition:p,forceManualMode:h,isAtTop:r,isManualOverrideActive:g,getScrollTop:b,getScrollHeight:y,getClientHeight:w}),[S,p,h,r,g,b,y,w])},X0=typeof window<"u"?i.useLayoutEffect:i.useEffect,Z0=200,eS=250,tS=.1,sS=({currentSessionId:t,sessionMessages:r,updateViewportAnchor:s,isSyncing:n,isMobile:o})=>{const a=i.useRef(null),l=J0({containerRef:a}),c=i.useCallback(()=>{const E=a.current;if(!E||E.clientHeight<=0)return 0;const I=E.clientHeight*tS;return Math.max(24,Math.min(200,I))},[]),[d,u]=i.useState(!1),[m,f]=i.useState(!0),p=i.useRef(null),h=i.useRef(t??null),x=i.useRef(0),g=i.useRef(0),b=i.useRef(!0),y=i.useRef(0);i.useEffect(()=>{h.current=t??null},[t]);const w=i.useCallback(()=>{x.current=Date.now()+Z0},[]),S=i.useCallback(()=>{const E=a.current;return E?E.scrollHeight-E.scrollTop-E.clientHeight:0},[]),C=i.useCallback(E=>{b.current!==E&&(b.current=E,f(E))},[]),v=i.useCallback(E=>{const I=a.current;if(!I)return;const P=I.scrollHeight-I.clientHeight;w(),l.scrollToPosition(Math.max(0,P),E)},[w,l]),j=i.useCallback(()=>{const E=a.current;if(!E){u(!1);return}if(!(E.scrollHeight>E.clientHeight)){u(!1);return}const P=S();u(P>c())},[S,c]),M=i.useCallback((E,I)=>{a.current&&(w(),l.scrollToPosition(Math.max(0,E),I))},[w,l]),k=i.useCallback(E=>{a.current&&(C(!0),v(E),u(!1))},[v,C]),D=i.useCallback(E=>{const I=a.current;if(!I||!t)return;const P=Date.now(),F=P<x.current,$=P-g.current<=eS;l.handleScroll(),j();const Q=I.scrollTop;E?.isTrusted&&!F&&$&&Q<y.current&&b.current&&C(!1),b.current||S()<=c()&&C(!0),y.current=Q;const{scrollTop:ie,scrollHeight:K,clientHeight:ee}=I,V=(ie+ee/2)/Math.max(K,1),ae=Math.floor(V*r.length);s(t,ae)},[t,S,c,l,r.length,C,j,s]);i.useEffect(()=>{const E=a.current;if(!E)return;const I=()=>{g.current=Date.now()};return E.addEventListener("scroll",D,{passive:!0}),E.addEventListener("wheel",I,{passive:!0}),E.addEventListener("touchmove",I,{passive:!0}),()=>{E.removeEventListener("scroll",D),E.removeEventListener("wheel",I),E.removeEventListener("touchmove",I)}},[D]),X0(()=>{if(!t||t===p.current)return;p.current=t,Gr.getInstance().recordSessionStart(t),C(!0),u(!1),a.current&&(w(),v({instant:!0}))},[t,w,v,C]),i.useEffect(()=>{if(!b.current||n||!a.current)return;S()>c()&&(w(),v({instant:!0}))},[S,c,n,w,v,r]),i.useEffect(()=>{const E=a.current;if(!E||typeof ResizeObserver>"u")return;const I=new ResizeObserver(()=>{j(),b.current&&S()>c()&&v({instant:!0})});I.observe(E);const P=new MutationObserver(()=>{b.current&&S()>c()&&v({instant:!0})});return P.observe(E,{childList:!0,subtree:!0}),()=>{I.disconnect(),P.disconnect()}},[S,c,v,j]),i.useEffect(()=>{if(typeof window>"u"){j();return}const E=window.requestAnimationFrame(()=>{j()});return()=>{window.cancelAnimationFrame(E)}},[t,r.length,j]);const N=i.useRef(new Map),T=i.useCallback(()=>{j(),b.current&&S()>c()&&v({instant:!0})},[S,c,v,j]),A=i.useCallback(E=>{const I=N.current.get(E);if(I)return I;const P={onChunk:()=>{j(),b.current&&S()>c()&&v({instant:!0})},onComplete:()=>{j()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{j(),b.current&&S()>c()&&v({instant:!0})},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return N.current.set(E,P),P},[S,c,v,j]);return{scrollRef:a,handleMessageContentChange:T,getAnimationHandlers:A,showScrollButton:d,scrollToBottom:k,scrollToPosition:M,isPinned:m}};function rS(t){const s=Date.now()-t,n=Math.floor(s/1e3),o=Math.floor(n/60),a=Math.floor(o/60),l=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:l<7?`${l}d ago`:new Date(t).toLocaleDateString()}const nS=({open:t,onOpenChange:r,onScrollToMessage:s})=>{const n=ge(g=>g.currentSessionId),o=Dt(g=>n?g.messages.get(n)||[]:[]),a=ge(g=>g.revertToMessage),l=ge(g=>g.forkFromMessage),c=ge(g=>g.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 g=m.toLowerCase();return p.filter(b=>pu(b.parts).toLowerCase().includes(g))},[p,m]),x=async g=>{if(n){u(g);try{await l(n,g),await c(),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(Sr,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Ns,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Us,{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:g=>f(g.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(g=>{const b=pu(g.parts),y=g.info.time.created,w=rS(y),S=p.length-p.indexOf(g);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?.(g.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:w}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{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,g.info.id),r(!1)},children:e.jsx(Jn,{className:"h-4 w-4"})})}),e.jsx(ft,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{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(),x(g.info.id)},disabled:d===g.info.id,children:d===g.info.id?e.jsx(Tt,{className:"h-4 w-4 animate-spin"}):e.jsx(qt,{className:"h-4 w-4"})})}),e.jsx(ft,{sideOffset:6,children:"Fork from here"})]})]})]})]},g.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(Jn,{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(qt,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function pu(t){const r=t.find(s=>s.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const Cp=()=>{const{currentSessionId:t,messages:r,permissions:s,questions:n,streamingMessageIds:o,isLoading:a,loadMessages:l,loadMoreMessages:c,updateViewportAnchor:d,sessionMemoryState:u,openNewSessionDraft:m,isSyncing:f,messageStreamStates:p,trimToViewportWindow:h,sessionActivityPhase:x,newSessionDraft:g}=ge(),{isTimelineDialogOpen:b,setTimelineDialogOpen:y}=je(),w=i.useMemo(()=>t?o.get(t)??null:null,[t,o]),{isMobile:S}=Kt(),C=!!g?.open;i.useEffect(()=>{!t&&!C&&m()},[t,C,m]);const v=i.useMemo(()=>t?r.get(t)||[]:[],[t,r]),j=i.useMemo(()=>t?s.get(t)||[]:[],[t,s]),M=i.useMemo(()=>t?n.get(t)||[]:[],[t,n]);i.useMemo(()=>[...j,...M],[j,M]);const{scrollRef:k,handleMessageContentChange:D,getAnimationHandlers:N,showScrollButton:T,scrollToBottom:A,scrollToPosition:E,isPinned:I}=sS({currentSessionId:t,sessionMessages:v,updateViewportAnchor:d,isSyncing:f,isMobile:S}),F=!!i.useMemo(()=>t?u.get(t)??null:null,[t,u])?.hasMoreAbove,[$,Q]=i.useState(!1);i.useEffect(()=>{Q(!1)},[t]);const ie=i.useCallback(async()=>{if(!t||$)return;const ee=k.current,V=ee?.scrollHeight??null,ae=ee?.scrollTop??null;Q(!0);try{if(await c(t,"up"),ee&&V!==null&&ae!==null){const G=ee.scrollHeight-V;E(ae+G,{instant:!0})}}finally{Q(!1)}},[t,$,c,k,E]),K=i.useCallback(ee=>{const V=k.current;if(!V)return;const ae=V.querySelector(`[data-message-id="${ee}"]`);if(ae){const G=V.getBoundingClientRect(),H=ae.getBoundingClientRect().top-G.top+V.scrollTop-50;V.scrollTo({top:H,behavior:"smooth"})}},[k]);return i.useEffect(()=>{if(!t||(r.has(t)?r.get(t)??[]:[]).length>0)return;(async()=>{try{await l(t)}finally{const G=x?.get(t)??"idle";(G==="busy"||G==="cooldown")&&I||(typeof window>"u"?A():window.requestAnimationFrame(()=>{A()}))}})()},[t,I,l,r,A,x]),!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(Li,{})}):!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(Li,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(na,{scrollToBottom:A})})]}):t?a&&v.length===0&&!w&&!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(V=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(Ri,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ri,{className:"h-4 w-24"}),e.jsx(Ri,{className:"h-20 w-full"})]})]},V))})}),e.jsx(na,{scrollToBottom:A})]}):v.length===0&&!w?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(Li,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(na,{scrollToBottom:A})})]}):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(kp,{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(K0,{messages:v,permissions:j,questions:M,onMessageContentChange:D,getAnimationHandlers:N,hasMoreAbove:F,isLoadingOlder:$,onLoadOlder:ie,scrollToBottom:A})})}),e.jsx(ec,{containerRef:k})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[T&&v.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:()=>A({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(io,{className:"h-4 w-4"})})}),e.jsx(na,{scrollToBottom:A})]}),e.jsx(nS,{open:b,onOpenChange:y,onScrollToMessage:K})]}):null};class Mp 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(lc,{className:"w-full max-w-md",children:[e.jsx(Bf,{className:"text-center",children:e.jsxs(zf,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Kg,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(Hf,{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 ko=()=>{const t=ge(r=>r.currentSessionId);return e.jsx(Mp,{sessionId:t||void 0,children:e.jsx(Cp,{})})},hu=new Xa,gu=new Xa,xu=new Xa,yu=new Xa,bu=t=>{if(!t)return[];const r=Math.max(1,t.start),s=Math.max(r,t.end);return rx.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 nx;for(let a=r;a<=s&&a<=n.state.doc.lines;a+=1){const l=n.state.doc.line(a);o.add(l.from,l.from,ox.line({class:"oc-cm-selected-line"}))}return o.finish()}},{decorations:n=>n.decorations})};function Dp({value:t,onChange:r,extensions:s,className:n,readOnly:o,lineNumbersConfig:a,highlightLines:l}){const c=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(!c.current)return;const f=Qg.create({doc:u.current,extensions:[Yg({fixed:!0}),hu.of(Pc(a)),Jg(),Xg.of(" "),Zg.of([ex,...tx,...sx]),dn.updateListener.of(p=>{if(!p.docChanged)return;const h=p.state.doc.toString();u.current=h,m.current(h)}),gu.of(dn.editable.of(!o)),xu.of(s??[]),yu.of(bu(l))]});return d.current=new dn({state:f,parent:c.current}),()=>{d.current?.destroy(),d.current=null}},[]),i.useEffect(()=>{const f=d.current;f&&f.dispatch({effects:[hu.reconfigure(Pc(a)),gu.reconfigure(dn.editable.of(!o)),xu.reconfigure(s??[]),yu.reconfigure(bu(l))]})},[s,l,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:c,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)})}function Al(t){const r=t.metadata.variant==="dark",s=t.config?.fonts?.mono||"monospace",n=t.colors.syntax.highlights||{},o=t.colors.syntax.tokens||{},a=dn.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}),l=Cm.define([{tag:Je.comment,color:t.colors.syntax.base.comment},{tag:Je.docComment,color:o.commentDoc||t.colors.syntax.base.comment},{tag:Je.keyword,color:t.colors.syntax.base.keyword},{tag:Je.controlKeyword,color:t.colors.syntax.base.keyword},{tag:Je.operatorKeyword,color:t.colors.syntax.base.operator},{tag:Je.moduleKeyword,color:o.keywordImport||t.colors.syntax.base.keyword},{tag:[Je.definitionKeyword,Je.modifier],color:o.storageModifier||t.colors.syntax.base.keyword},{tag:Je.atom,color:o.boolean||t.colors.syntax.base.number},{tag:[Je.null,Je.self],color:t.colors.syntax.base.number},{tag:[Je.meta,Je.documentMeta],color:t.colors.syntax.base.comment},{tag:Je.string,color:t.colors.syntax.base.string},{tag:Je.escape,color:o.stringEscape||t.colors.syntax.base.foreground},{tag:Je.regexp,color:o.regex||t.colors.syntax.base.string},{tag:Je.number,color:t.colors.syntax.base.number},{tag:Je.bool,color:o.boolean||t.colors.syntax.base.number},{tag:Je.operator,color:t.colors.syntax.base.operator},{tag:[Je.derefOperator,Je.updateOperator,Je.definitionOperator,Je.typeOperator,Je.controlOperator],color:t.colors.syntax.base.operator},{tag:[Je.logicOperator,Je.bitwiseOperator,Je.arithmeticOperator],color:t.colors.syntax.base.operator},{tag:[Je.compareOperator],color:o.diffModified||t.colors.syntax.base.operator},{tag:[Je.punctuation,Je.separator,Je.bracket,Je.paren,Je.brace,Je.squareBracket,Je.angleBracket],color:o.punctuation||t.colors.syntax.base.comment},{tag:Je.function(Je.variableName),color:o.functionCall||t.colors.syntax.base.function},{tag:Je.function(Je.definition(Je.variableName)),color:t.colors.syntax.base.function},{tag:Je.function(Je.propertyName),color:o.method||o.functionCall||t.colors.syntax.base.function},{tag:Je.namespace,color:o.namespace||t.colors.syntax.base.type},{tag:Je.moduleKeyword,color:o.module||t.colors.syntax.base.keyword},{tag:Je.macroName,color:o.macro||t.colors.syntax.base.keyword},{tag:Je.labelName,color:o.label||t.colors.syntax.base.keyword},{tag:Je.annotation,color:o.decorator||t.colors.syntax.base.keyword},{tag:Je.propertyName,color:o.variableProperty||t.colors.syntax.base.keyword},{tag:Je.attributeName,color:o.tagAttribute||t.colors.syntax.base.keyword},{tag:Je.standard(Je.variableName),color:o.method||t.colors.syntax.base.function},{tag:Je.definition(Je.variableName),color:t.colors.syntax.base.variable},{tag:Je.local(Je.variableName),color:t.colors.syntax.base.variable},{tag:Je.special(Je.variableName),color:o.variableOther||t.colors.syntax.base.function},{tag:Je.variableName,color:t.colors.syntax.base.variable},{tag:Je.special(Je.string),color:t.colors.syntax.base.string},{tag:Je.className,color:o.className||t.colors.syntax.base.type},{tag:Je.typeName,color:t.colors.syntax.base.type},{tag:Je.constant(Je.variableName),color:o.constant||t.colors.syntax.base.variable},{tag:Je.literal,color:o.constant||t.colors.syntax.base.variable},{tag:Je.tagName,color:o.tag||t.colors.syntax.base.keyword},{tag:Je.attributeValue,color:o.tagAttributeValue||t.colors.syntax.base.string},{tag:[Je.heading,Je.heading1,Je.heading2,Je.heading3,Je.heading4,Je.heading5,Je.heading6],color:t.colors.syntax.base.keyword,fontWeight:"600"},{tag:Je.monospace,color:t.colors.syntax.base.string},{tag:Je.link,color:o.url||t.colors.syntax.base.keyword,textDecoration:"underline"}]);return[a,Mm(l)]}const El=lo.define(ax),Ap=lo.define(ix),oS=lo.define(lx),aS=lo.define(cx),iS=lo.define(dx),lS=lo.define(ux);function cS(t){const r=t.trim().toLowerCase();switch(r){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return El;case"toml":return Ap;case"diff":case"patch":return oS;case"json":case"jsonc":case"json5":return Rm().language;case"js":case"javascript":return Bn().language;case"jsx":return Bn({jsx:!0}).language;case"ts":case"typescript":return Bn({typescript:!0}).language;case"tsx":return Bn({typescript:!0,jsx:!0}).language;case"yaml":case"yml":return Pm().language;case"html":return Tm().language;case"css":return Fm().language;case"xml":case"svg":return Am().language;case"py":case"python":return Im().language;case"sql":return Em().language;case"rs":case"rust":return Dm().language;default:return fx.matchLanguageName(px,r,!0)}}const dS=t=>t.split("/").pop()?.toLowerCase()??"",uS=()=>Mm(Cm.define([{tag:[Je.heading1,Je.heading2,Je.heading3,Je.heading4,Je.heading5,Je.heading6],fontWeight:"600"},{tag:Je.strong,fontWeight:"600"},{tag:Je.emphasis,fontStyle:"italic"},{tag:Je.strikethrough,textDecoration:"line-through"},{tag:[Je.link,Je.url],color:"var(--markdown-link, currentColor)",textDecoration:"underline"},{tag:Je.monospace,color:"var(--markdown-inline-code, currentColor)",backgroundColor:"var(--markdown-inline-code-bg, transparent)"},{tag:Je.quote,color:"var(--markdown-blockquote, currentColor)",fontStyle:"italic"},{tag:Je.list,color:"color-mix(in srgb, var(--muted-foreground) 40%, var(--foreground) 60%)"},{tag:Je.heading,color:"var(--markdown-heading1, currentColor)"}]));function Ep(t){const r=t.toLowerCase();switch(dS(r)){case"dockerfile":return aS;case"makefile":case"gnumakefile":return El}const n=r.lastIndexOf("."),o=n>=0?r.slice(n+1):"";switch(o){case"ts":case"tsx":case"mts":case"cts":return Bn({typescript:!0,jsx:o==="tsx"});case"js":case"jsx":case"mjs":case"cjs":return Bn({typescript:!1,jsx:o==="jsx"});case"json":case"jsonc":case"json5":case"jsonl":case"ndjson":case"geojson":return Rm();case"css":case"scss":case"sass":case"less":return Fm();case"html":case"htm":return Tm();case"md":case"mdx":case"markdown":case"mdown":case"mkd":return[mx({codeLanguages:cS}),uS()];case"yml":case"yaml":return Pm();case"toml":return Ap;case"ini":case"cfg":case"conf":case"config":case"properties":return lS;case"sh":case"bash":case"zsh":case"fish":case"env":return El;case"py":case"pyw":case"pyi":return Im();case"sql":case"psql":case"plsql":return Em();case"xml":case"xsl":case"xslt":case"xsd":case"dtd":case"plist":case"svg":return Am();case"rs":return Dm();case"rb":case"erb":case"rake":case"gemspec":return iS;default:return null}}const Co=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},zi=(t,r)=>{const s=Co(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},mS=(t,r,s)=>zi(zi(zi(t,".opencode"),"plans"),`${r}-${s}.md`),fS=(t,r)=>`~/.opencode/plans/${t}-${r}.md`,pS=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},hS=(t,r)=>{const s=Co(r.currentDirectory),n=Co(r.homeDirectory),o=Co(t);return s&&o.startsWith(s+"/")?o.slice(s.length+1):n&&o===n?"~":n&&o.startsWith(n+"/")?`~${o.slice(n.length)}`:o},gS=()=>{const t=ge(_=>_.currentSessionId),r=ge(_=>_.sessions),s=wt(_=>_.homeDirectory),n=Bs(),o=ge(_=>_.sendMessage),{currentProviderId:a,currentModelId:l,currentAgentName:c,currentVariant:d}=et(),u=nt(_=>_.getSessionAgentSelection),m=nt(_=>_.getAgentModelForSession),f=nt(_=>_.getAgentModelVariantForSession),p=je(_=>_.setActiveMainTab),{inputBarOffset:h,isKeyboardOpen:x}=je(),{isMobile:g}=Kt(),{currentTheme:b}=Br();i.useMemo(()=>mi(b),[b]);const y=i.useMemo(()=>t?r.find(_=>_.id===t)??null:null,[t,r]),w=i.useMemo(()=>{const _=typeof y?.directory=="string"?y.directory:"";return Co(_||"")},[y?.directory]),[S,C]=i.useState(null),v=i.useMemo(()=>!S||!w||!s?S:hS(S,{currentDirectory:w,homeDirectory:s}),[S,w,s]),[j,M]=i.useState(""),[k,D]=i.useState(!1),[N,T]=i.useState(!1),[A,E]=i.useState(!1),I=i.useRef(null),P=i.useRef(null),[F,$]=i.useState(null),[Q,ie]=i.useState(""),K=i.useRef(!1),ee=i.useRef(null);i.useEffect(()=>{const _=()=>{K.current=!1,ee.current=null};return document.addEventListener("mouseup",_),()=>document.removeEventListener("mouseup",_)},[]),i.useEffect(()=>{$(null),ie("")},[j]),i.useEffect(()=>{if(!F)return;const _=L=>{const B=L.target;document.querySelector("[data-comment-ui]")?.contains(B)||B.closest(".cm-gutterElement")||B.closest("[data-sonner-toast]")||B.closest("[data-sonner-toaster]")||($(null),ie(""))},H=window.setTimeout(()=>{document.addEventListener("click",_)},100);return()=>{window.clearTimeout(H),document.removeEventListener("click",_)}},[F]);const V=i.useCallback((_,H)=>{const L=_.split(`
195
- `),B=Math.max(1,H.start),O=Math.min(L.length,H.end);return B>O?"":L.slice(B-1,O).join(`
196
- `)},[]),ae=i.useCallback(async()=>{if(!F||!Q.trim()||!t)return;const _=u(t)||c,H=_?m(t,_):null,L=H?.providerId||a,B=H?.modelId||l;if(!L||!B)return;const O=_&&L&&B?f(t,_,L,B)??d:d,le=F.start,we=F.end,pe=V(j,F),De=v&&v.split("/").pop()||"plan",z=S&&Cr(S)||"markdown",he=`Comment on \`${De}\` lines ${le}-${we}:
197
-
198
- \`\`\`${z}
199
- ${pe}
200
- \`\`\`
201
-
202
- ${Q}`;ie(""),$(null),p("chat"),o(he,L,B,_,void 0,void 0,void 0,O).catch(()=>{})},[F,Q,t,a,l,c,d,j,S,v,V,o,p,u,m,f]),G=i.useMemo(()=>{const _=[Al(b)],H=Ep(S||"plan.md");return H&&_.push(H),_.push(dn.lineWrapping),_},[b,S]);i.useEffect(()=>{let _=!1;const H=async O=>{if(n.files?.readFile)return(await n.files.readFile(O))?.content??"";const le=await fetch(`/api/fs/read?path=${encodeURIComponent(O)}`);if(!le.ok)throw new Error(`Failed to read plan file (${le.status})`);return le.text()},L=async O=>{if(O&&(C(null),M("")),!y?.slug||!y?.time?.created||!w){C(null),M("");return}O&&D(!0);try{const le=mS(w,y.time.created,y.slug),we=pS(fS(y.time.created,y.slug),s||null);let pe=null,De=null;try{De=await H(le),pe=le}catch{}if(!pe)try{De=await H(we),pe=we}catch{}if(_)return;if(!pe||De===null){C(null),M("");return}C(pe),M(De)}catch{if(_)return;C(null),M("")}finally{!_&&O&&D(!1)}};L(!0);const B=window.setInterval(()=>{L(!1)},3e3);return()=>{_=!0,window.clearInterval(B)}},[w,y?.slug,y?.time?.created,s,n.files]),i.useEffect(()=>()=>{I.current!==null&&window.clearTimeout(I.current),P.current!==null&&window.clearTimeout(P.current)},[]);const q=()=>F?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(Rs,{value:Q,onChange:_=>{ie(_.target.value);const H=_.target;H.style.height="auto";const B=20*5+8;H.style.height=`${Math.min(H.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:!g,rows:1,onKeyDown:_=>{_.key==="Enter"&&(_.metaKey||_.ctrlKey)&&(_.preventDefault(),ae()),_.key==="Escape"&&(_.preventDefault(),$(null),ie(""))}}),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:",F.start,"-",F.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!g&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Zt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:_=>{Q.trim()&&(_.preventDefault(),ae())},onClick:()=>{g||ae()},disabled:!Q.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",Q.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Fo,{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:v??S,children:v??S}):null]}),S?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(j),E(!0),P.current!==null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{E(!1)},1200)}catch{}},className:"h-5 w-5 p-0",title:"Copy plan contents","aria-label":"Copy plan contents",children:A?e.jsx($t,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx($l,{className:"h-4 w-4"})}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(v??S),T(!0),I.current!==null&&window.clearTimeout(I.current),I.current=window.setTimeout(()=>{T(!1)},1200)}catch{}},className:"h-5 w-5 p-0",title:`Copy plan path (${v??S})`,"aria-label":`Copy plan path (${v??S})`,children:N?e.jsx($t,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Lm,{className:"h-4 w-4"})})]}):null]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(jt,{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":F?g?"calc(var(--oc-keyboard-inset, 0px) + 140px)":"140px":"0px"},children:e.jsx("div",{className:"h-full oc-plan-editor",children:e.jsx(Dp,{value:j,onChange:()=>{},readOnly:!0,className:"h-full [&_.cm-scroller]:pb-[var(--oc-plan-comment-pad)]",extensions:G,highlightLines:F?{start:Math.min(F.start,F.end),end:Math.max(F.start,F.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(_,H,L)=>{if(!(L instanceof MouseEvent)||L.button!==0)return!1;L.preventDefault();const B=_.state.doc.lineAt(H.from).number;if(g&&F&&!L.shiftKey){const O=Math.min(F.start,F.end,B),le=Math.max(F.start,F.end,B);return $({start:O,end:le}),K.current=!1,ee.current=null,!0}if(K.current=!0,ee.current=B,F&&L.shiftKey){const O=Math.min(F.start,B),le=Math.max(F.end,B);$({start:O,end:le})}else $({start:B,end:B});return!0},mouseover:(_,H,L)=>{if(!(L instanceof MouseEvent)||L.buttons!==1||!K.current||ee.current===null)return!1;const B=_.state.doc.lineAt(H.from).number,O=Math.min(ee.current,B),le=Math.max(ee.current,B);return $({start:O,end:le}),!1},mouseup:()=>(K.current=!1,ee.current=null,!1)}}})})})})})}),F&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex flex-col justify-end",style:{paddingBottom:g?"var(--oc-keyboard-inset, 0px)":"0px"},children:e.jsx("div",{className:R("pointer-events-auto pb-2 transition-none w-full flex justify-center",g&&x?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:g&&!x&&h>0?`${h}px`:"16px"},"data-keyboard-avoid":"true",children:q()})})]})},wu=12,xS=[{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"}],yS=({isActive:t,burstKey:r=0,className:s,durationMs:n=900,bursts:o=xS,onComplete:a})=>{const l=_e.useRef(!1);_e.useEffect(()=>{!t&&l.current&&a?.(),t&&(l.current=!0)},[t,a]);const c=_e.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:c.map((m,f)=>{const p=m.x*d.radius,h=m.y*d.radius,x={"--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:x},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},bS=({durationMs:t=3400}={})=>{const[r,s]=_e.useState({isActive:!1,cycle:0}),n=_e.useRef(null),o=_e.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=_e.useCallback(()=>{o(),s(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=_e.useCallback(()=>{o(),s(c=>({isActive:!0,cycle:c.cycle+1})),n.current=window.setTimeout(()=>{s(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},t)},[o,t]);return _e.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:l,dismissFireworks:a}},Ip=i.createContext(void 0),vu=({children:t})=>{const{isActive:r,burstKey:s,triggerFireworks:n,dismissFireworks:o}=bS(),a=i.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(Ip.Provider,{value:a,children:[t,e.jsx(yS,{isActive:r,burstKey:s})]})},wS=()=>{const t=i.useContext(Ip);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},ro=rs()(fs(Gs((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 vb();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 Cb();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 kb();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 $r();n=s(o?.defaultGitIdentityId)}else{const o=Ps()?.settings;if(o)try{const l=(await o.load())?.settings||{};n=s(l.defaultGitIdentityId)}catch{}if(n===null)try{const a=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(a.ok){const l=await a.json().catch(()=>null);n=s(l?.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 is({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 jb(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(l=>l.id===s);if(!o)throw new Error("Profile not found");const a={...o,...n};return await Sb(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 Nb(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:qs(()=>ws()),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=ro);const vS=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),jS=({currentBranch:t,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:o,onCreate:a,disabled:l=!1})=>{const[c,d]=i.useState(!1),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,x]=i.useState(""),[g,b]=i.useState(!1),y=i.useRef(null),w=i.useMemo(()=>vS(h),[h]),S=i.useMemo(()=>{const D=u.toLowerCase();return D?r.filter(N=>N.toLowerCase().includes(D)):r},[u,r]),C=i.useMemo(()=>{const D=u.toLowerCase();return D?s.filter(N=>N.toLowerCase().includes(D)):s},[u,s]),v=D=>{if(D===t){d(!1);return}o(D),d(!1),m("")},j=()=>{p(!0),setTimeout(()=>y.current?.focus(),50)},M=async()=>{if(!(!w||g)){b(!0);try{await a(w),x(""),p(!1),d(!1)}finally{b(!1)}}},k=()=>{x(""),p(!1)};return i.useEffect(()=>{c||(m(""),p(!1),x(""))},[c]),e.jsxs(es,{open:c,onOpenChange:d,children:[e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:l,children:[e.jsx(qt,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:t||"Detached HEAD"}),e.jsx(Gt,{className:"size-4 opacity-60"})]})})}),e.jsxs(ft,{sideOffset:8,children:["Switch branch (",r.length," local · ",s.length," remote)"]})]}),e.jsx(ss,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(cc,{className:"h-full min-h-0",children:[e.jsx(dc,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(uc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(mc,{children:"No branches found."}),e.jsx(xn,{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:D=>x(D.target.value),onKeyDown:D=>{D.key==="Enter"?(D.preventDefault(),M()):D.key==="Escape"&&(D.preventDefault(),k())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:M,disabled:!w||g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:g?e.jsx(Tt,{className:"size-4 animate-spin"}):e.jsx(cs,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:k,disabled:g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(os,{className:"size-4"})})]}):e.jsxs(js,{onSelect:j,children:[e.jsx(cs,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(Wa,{}),e.jsxs(xn,{heading:"Local branches",children:[S.map(D=>e.jsxs(js,{onSelect:()=>v(D),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:D}),(n?.[D]?.ahead||n?.[D]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[D].ahead||0," ahead ·"," ",n[D].behind||0," behind"]})]}),t===D&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${D}`)),S.length===0&&e.jsx(js,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Wa,{}),e.jsxs(xn,{heading:"Remote branches",children:[C.map(D=>e.jsx(js,{onSelect:()=>v(D),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:D})},`remote-${D}`)),C.length===0&&e.jsx(js,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},SS=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),NS=({currentBranch:t,onRename:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(t||""),[l,c]=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=SS(o);if(h===t){n(!1);return}c(!0);try{await r(t,h),n(!1),a("")}finally{c(!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(qt,{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:l,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:l?e.jsx(Tt,{className:"size-4 animate-spin"}):e.jsx($t,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:l,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(os,{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(qt,{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(ao,{className:"size-4"})})]})},kS=({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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[t==="fetch"?e.jsx(Tt,{className:"size-4 animate-spin"}):e.jsx(Qr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(ft,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:s,disabled:a,children:[t==="pull"?e.jsx(Tt,{className:"size-4 animate-spin"}):e.jsx(io,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(ft,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsxs(Se,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[t==="push"?e.jsx(Tt,{className:"size-4 animate-spin"}):e.jsx(Qn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(ft,{sideOffset:8,children:"Push changes"})]})]})},CS={branch:qt,briefcase:Wl,house:Hl,graduation:zl,code:er,heart:Om,user:tr},MS={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 Pp(t){return t&&MS[t]||"var(--primary)"}const ju=({icon:t,className:r,colorToken:s})=>{const n=CS[t??"branch"]??tr;return e.jsx(n,{className:r,style:{color:Pp(s)}})},DS=({activeProfile:t,identities:r,onSelect:s,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(es,{children:[e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(ts,{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:Pp(t?.color)},disabled:o,children:[n?e.jsx(Tt,{className:"size-4 animate-spin"}):e.jsx(ju,{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(Gt,{className:"size-4 opacity-60"})]})})}),e.jsxs(ft,{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(ss,{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(Ct,{onSelect:()=>s(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ju,{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))})]})},AS=({status:t,localBranches:r,remoteBranches:s,branchInfo:n,syncAction:o,onFetch:a,onPull:l,onPush:c,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:h,isApplyingIdentity:x,isWorktreeMode:g})=>t?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[g?e.jsx(NS,{currentBranch:t.current,onRename:m}):e.jsx(jS,{currentBranch:t.current,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:d,onCreate:u}),(!!t.tracking||t.ahead>0||t.behind>0)&&e.jsxs(ht,{delayDuration:800,children:[e.jsx(gt,{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(Qn,{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(io,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:t.behind})]})]})}),e.jsx(ft,{sideOffset:8,children:t.tracking?`Upstream: ${t.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(kS,{syncAction:o,onFetch:a,onPull:l,onPush:c,disabled:!t}),e.jsx("div",{className:"flex-1"}),e.jsx(DS,{activeProfile:f,identities:p,onSelect:h,isApplying:x})]}):null,ES=({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(Rl,{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(Tt,{className:"size-4 animate-spin"}):e.jsx(io,{className:"size-4"}),"Pull ",t," commit",t===1?"":"s"]})]}),Tp={"?":{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"}},IS=Tp.M;function PS(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 TS(t){const r=PS(t);return Tp[r]??IS}const FS=i.memo(function({file:r,checked:s,onToggle:n,onViewDiff:o,onRevert:a,isReverting:l,stats:c}){const d=_e.useMemo(()=>TS(r),[r]),u=d.description,m=c?.insertions??0,f=c?.deletions??0,p=_e.useCallback(g=>{g.key===" "?(g.preventDefault(),n()):g.key==="Enter"&&(g.preventDefault(),o())},[n,o]),h=_e.useCallback(g=>{g.preventDefault(),g.stopPropagation(),n()},[n]),x=_e.useCallback(g=>{g.preventDefault(),g.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(Sn,{className:"size-4 text-primary"}):e.jsx(Nn,{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(ht,{delayDuration:200,children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:x,disabled:l,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:l?e.jsx(Tt,{className:"size-3.5 animate-spin"}):e.jsx(Jn,{className:"size-3.5"})})}),e.jsx(ft,{sideOffset:8,children:"Revert changes"})]})]})})}),RS=({changeEntries:t,selectedPaths:r,diffStats:s,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:l,onViewDiff:c,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:l,disabled:u===0,children:"None"})]})]})]}),e.jsx(jt,{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(FS,{file:f,checked:r.has(f.path),stats:s?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>c(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function Cn({className:t,variant:r,...s}){return e.jsx(Se,{variant:r,size:"sm",className:R("h-7 px-2 py-0",t),...s})}const Hi=38,Su=200,LS=({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=`${Hi}px`;const l=Math.min(Math.max(a.scrollHeight,Hi),Su);a.style.height=`${l}px`},[t]),e.jsx(Rs,{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:Hi,maxHeight:Su}})},OS=({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(ht,{delayDuration:1e3,children:[e.jsx(gt,{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(io,{className:"size-4"})})}),e.jsx(ft,{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))})]})},$S=({selectedCount:t,commitMessage:r,onCommitMessageChange:s,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:l,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f,gitmojiEnabled:p,onOpenGitmojiPicker:h})=>{const x=t>0,g=r.trim()&&x&&m===null,{isMobile:b}=Kt();return e.jsxs(co,{open:x,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:x?`${t} file${t===1?"":"s"} selected`:"No files selected"})]}),e.jsx(uo,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(OS,{highlights:n,onInsert:o,onClear:a}),e.jsx(LS,{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(hx,{className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Se,{variant:"outline",size:"sm",onClick:l,disabled:c||m!==null||t===0||f,type:"button",children:[c?e.jsx(Tt,{className:"size-4 animate-spin"}):e.jsx(Bl,{className:"size-4 text-primary"}),"Generate"]}),e.jsx("div",{className:"flex-1"}),e.jsx(Cn,{variant:"outline",onClick:d,disabled:!g||c,className:"whitespace-nowrap",children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Tt,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rl,{className:"size-4"}),"Commit"]})}),b?e.jsxs(ht,{children:[e.jsx(gt,{asChild:!0,children:e.jsx(Se,{variant:"default",size:"sm",onClick:u,disabled:!g||c,className:"h-7 w-7 p-0","aria-label":"Commit & Push",children:m==="commitAndPush"?e.jsx(Tt,{className:"size-4 animate-spin"}):e.jsx(Qn,{className:"size-4"})})}),e.jsx(ft,{side:"top",children:e.jsx("p",{children:"Commit & Push"})})]}):e.jsx(Cn,{variant:"default",onClick:u,disabled:!g||c,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Tt,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qn,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function Nu(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 _S(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 BS=({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:Nu(t.date),children:Nu(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(ht,{delayDuration:500,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Se,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:l=>{l.stopPropagation(),a(t.hash)},children:e.jsx(sr,{className:"size-3"})})}),e.jsx(ft,{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(Tt,{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(l=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:R("font-semibold w-3 text-center",_S(l.changeType)),children:l.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:l.path,children:l.path}),!l.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",l.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",l.deletions]})]}),l.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},l.path))})})]}),zS=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],HS=({log:t,isLogLoading:r,logMaxCount:s,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:l,loadingCommitHashes:c,onCopyHash:d})=>{const[u,m]=i.useState(!0);return t?e.jsxs(co,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs($o,{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(kn,{placeholder:"Commits"})}),e.jsx(Is,{children:zS.map(f=>e.jsx(Ht,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(Qa,{className:"size-4 text-muted-foreground"}):e.jsx(Gt,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(uo,{children:e.jsx(jt,{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(BS,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:l.get(f.hash)??[],isLoadingFiles:c.has(f.hash),onCopyHash:d},f.hash))})})})]}):null},WS=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()),Wi=new Map,Cu=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{}},US=({directory:t,branch:r,baseBranch:s})=>{const{github:n}=Bs(),o=_s(ce=>ce.status),a=_s(ce=>ce.hasChecked),l=je(ce=>ce.setSettingsDialogOpen),c=je(ce=>ce.setSidebarSection),d=je(ce=>ce.setActiveMainTab),u=ge(ce=>ce.currentSessionId),m=i.useCallback(()=>{c("settings"),l(!0)},[l,c]),f=i.useMemo(()=>`${t}::${r}`,[t,r]),p=i.useMemo(()=>Wi.get(f)??null,[f]),[h,x]=i.useState(p?.isOpen??!0),[g,b]=i.useState(!1),[y,w]=i.useState(null),[S,C]=i.useState(null),[v,j]=i.useState(()=>p?.title??ku(r)),[M,k]=i.useState(()=>p?.body??""),[D,N]=i.useState(()=>p?.draft??!1),[T,A]=i.useState("squash"),[E,I]=i.useState(!1),[P,F]=i.useState(!1),[$,Q]=i.useState(!1),[ie,K]=i.useState(!1),[ee,V]=i.useState(!1),[ae,G]=i.useState(null),[q,_]=i.useState(!1),H=!!(t&&r&&s&&r!==s),L=y?.pr??null,B=i.useCallback(async()=>{if(!n?.prContext){W.error("GitHub runtime API unavailable");return}if(L){V(!0),_(!0);try{const ce=await n.prContext(t,L.number,{includeDiff:!1,includeCheckDetails:!0});G(ce)}catch(ce){const X=ce instanceof Error?ce.message:String(ce);W.error("Failed to load check details",{description:X})}finally{_(!1)}}},[t,n,L]),O=i.useCallback(ce=>{const X=ce.status||"unknown",U=ce.conclusion??void 0,Y=U?`${X} / ${U}`:X,se=ce.app?.name||ce.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:ce.name}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:se?`${se} · ${Y}`:Y}),ce.output?.summary?e.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap line-clamp-4 mt-2",children:ce.output.summary}):null,ce.job?.steps&&ce.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:ce.job.steps.map((me,ze)=>{const qe=(me.conclusion||"").toLowerCase(),tt=qe&&!["success","neutral","skipped"].includes(qe);return e.jsxs("div",{className:"typography-micro flex items-center gap-2 rounded px-2 py-1 "+(tt?"bg-destructive/10 text-destructive":"text-muted-foreground"),children:[e.jsx("span",{className:"truncate",children:me.name}),me.conclusion?e.jsx("span",{className:"ml-auto flex-shrink-0",children:me.conclusion}):null]},`${me.name}-${ze}`)})})]}):null]}),ce.detailsUrl?e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:e.jsxs("a",{href:ce.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Open"]})}):null]})},[]),le=i.useCallback(async()=>{if(d("chat"),!n?.prContext){W.error("GitHub runtime API unavailable");return}if(!t||!L)return;if(!u){W.error("No active session",{description:"Open a chat session first."});return}const{currentProviderId:ce,currentModelId:X,currentAgentName:U,currentVariant:Y}=et.getState(),se=Dt.getState().lastUsedProvider,me=ce||se?.providerID,ze=X||se?.modelID;if(!me||!ze){W.error("No model selected");return}try{const qe=await n.prContext(t,L.number,{includeDiff:!1,includeCheckDetails:!0}),Xe=(qe.checkRuns??[]).filter(We=>{const ve=typeof We.conclusion=="string"?We.conclusion.toLowerCase():"";return ve?!["success","neutral","skipped"].includes(ve):!1});if(Xe.length===0){W.message("No failed checks");return}const Nt="Review these PR failed checks and propose likely fixes. Do not implement until I confirm.",Ne=`Use the attached checks payload.
203
- - Summarize what is failing.
204
- - Identify likely root cause(s).
205
- - Propose a minimal fix plan and verification steps.
206
- - No speculation: ask for missing info if needed.`,ue=`GitHub PR failed checks (JSON)
207
- ${JSON.stringify({repo:qe.repo??null,pr:qe.pr??null,failedChecks:Xe},null,2)}`;Dt.getState().sendMessage(Nt,me,ze,U??void 0,u,void 0,null,[{text:Ne,synthetic:!0},{text:ue,synthetic:!0}],Y).catch(We=>{const ve=We instanceof Error?We.message:String(We);W.error("Failed to send message",{description:ve})})}catch(qe){const tt=qe instanceof Error?qe.message:String(qe);W.error("Failed to load checks",{description:tt})}},[u,t,n,L,d]),we=i.useCallback(async()=>{if(d("chat"),!n?.prContext){W.error("GitHub runtime API unavailable");return}if(!t||!L)return;if(!u){W.error("No active session",{description:"Open a chat session first."});return}const{currentProviderId:ce,currentModelId:X,currentAgentName:U,currentVariant:Y}=et.getState(),se=Dt.getState().lastUsedProvider,me=ce||se?.providerID,ze=X||se?.modelID;if(!me||!ze){W.error("No model selected");return}try{const qe=await n.prContext(t,L.number,{includeDiff:!1,includeCheckDetails:!1}),tt=qe.issueComments??[],Xe=qe.reviewComments??[];if(tt.length+Xe.length===0){W.message("No PR comments");return}const Ne="Review these PR comments and propose the required changes and next actions. Do not implement until I confirm.",ue=`Use the attached comments payload.
208
- - Identify required vs optional changes.
209
- - Call out intent/implementation mismatch if present.
210
- - Propose a minimal plan and verification steps.
211
- - No speculation: ask for missing info if needed.`,We=`GitHub PR comments (JSON)
212
- ${JSON.stringify({repo:qe.repo??null,pr:qe.pr??null,issueComments:tt,reviewComments:Xe},null,2)}`;Dt.getState().sendMessage(Ne,me,ze,U??void 0,u,void 0,null,[{text:ue,synthetic:!0},{text:We,synthetic:!0}],Y).catch(ve=>{const ke=ve instanceof Error?ve.message:String(ve);W.error("Failed to send message",{description:ke})})}catch(qe){const tt=qe instanceof Error?qe.message:String(qe);W.error("Failed to load PR comments",{description:tt})}},[u,t,n,L,d]),pe=i.useCallback(async()=>{if(H){if(a&&o?.connected===!1){w({connected:!1}),C(null),b(!1);return}if(!n?.prStatus){w(null),C("GitHub runtime API unavailable");return}b(!0),C(null);try{const ce=await n.prStatus(t,r);w(ce),ce.connected===!1&&C(null)}catch(ce){const X=ce instanceof Error?ce.message:String(ce);C(X||"Failed to load PR status")}finally{b(!1)}}},[r,H,t,n,a,o]);i.useEffect(()=>{const ce=Wi.get(f)??null;j(ce?.title??ku(r)),k(ce?.body??""),N(ce?.draft??!1),x(ce?.isOpen??!0),pe()},[r,pe,f]),i.useEffect(()=>{a&&o?.connected===!1&&(w({connected:!1}),C(null))},[a,o]),i.useEffect(()=>{!t||!r||Wi.set(f,{title:v,body:M,draft:D,isOpen:h})},[f,v,M,D,h,t,r]);const De=i.useCallback(async()=>{if(!E&&t){I(!0);try{const ce=await xb(t,{base:s,head:r});ce.title?.trim()&&j(ce.title.trim()),ce.body?.trim()&&k(ce.body.trim()),W.success("PR description generated")}catch(ce){const X=ce instanceof Error?ce.message:String(ce);W.error("Failed to generate description",{description:X})}finally{I(!1)}}},[s,r,t,E]),z=i.useCallback(async()=>{if(!n?.prCreate){W.error("GitHub runtime API unavailable");return}const ce=v.trim();if(!ce){W.error("Title is required");return}F(!0);try{const X=await n.prCreate({directory:t,title:ce,head:r,base:s,...M.trim()?{body:M}:{},draft:D});W.success("PR created"),w(U=>U&&{...U,pr:X}),await pe()}catch(X){const U=X instanceof Error?X.message:String(X);W.error("Failed to create PR",{description:U})}finally{F(!1)}},[s,M,r,t,D,n,pe,v]),he=i.useCallback(async ce=>{if(!n?.prMerge){W.error("GitHub runtime API unavailable");return}Q(!0);try{const X=await n.prMerge({directory:t,number:ce.number,method:T});X.merged?W.success("PR merged"):W.message("PR not merged",{description:X.message||"Not mergeable"}),await pe()}catch(X){const U=X instanceof Error?X.message:String(X);W.error("Merge failed",{description:U}),ce.url&&Cu(ce.url)}finally{Q(!1)}},[t,n,T,pe]),Z=i.useCallback(async ce=>{if(!n?.prReady){W.error("GitHub runtime API unavailable");return}K(!0);try{await n.prReady({directory:t,number:ce.number}),W.success("Marked ready for review"),await pe()}catch(X){const U=X instanceof Error?X.message:String(X);W.error("Failed to mark ready",{description:U}),ce.url&&Cu(ce.url)}finally{K(!1)}},[t,n,pe]);if(!H)return null;const de=y?.repo?.url||null,Ee=y?.checks??null,ne=!!y?.canMerge,ye=!!y?.connected,te=a&&y?.connected===!1;return e.jsxs(co,{open:h,onOpenChange:x,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs($o,{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(Aa,{className:"size-4 text-muted-foreground"}),e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:"Pull Request"}),L?e.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",L.number]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g?e.jsx(Tt,{className:"size-4 animate-spin text-muted-foreground"}):null,Ee?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 ${WS(Ee.state)}`}),Ee.total>0?`${Ee.success}/${Ee.total} checks`:`${Ee.state} checks`]}):null]})]}),e.jsx(uo,{children:e.jsx("div",{className:"border-t border-border/40",children:e.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[te?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}),de?e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:e.jsxs("a",{href:de,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Open Repo"]})}):null]}):null,L?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:L.title}),e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[L.state,L.draft?" (draft)":"",L.mergeable===!1?" · not mergeable":"",typeof L.mergeableState=="string"&&L.mergeableState?` · ${L.mergeableState}`:""]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[Ee?e.jsxs(Se,{variant:"outline",size:"sm",onClick:B,disabled:q,children:[q?e.jsx(Tt,{className:"size-4 animate-spin"}):null,"Check details"]}):null,Ee?.failure?e.jsx(Se,{variant:"outline",size:"sm",onClick:le,children:"Send failed checks to chat"}):null,e.jsx(Se,{variant:"outline",size:"sm",onClick:we,children:"Send PR comments to chat"})]}),ne&&L.draft?e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Draft PRs must be marked ready before merge."}):null,ne?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:L.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Open"]})}),ne&&L.draft&&L.state==="open"?e.jsxs(Se,{variant:"outline",size:"sm",onClick:()=>Z(L),disabled:ie||$,children:[ie?e.jsx(Tt,{className:"size-4 animate-spin"}):null,"Ready"]}):null,ne?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:ce=>A(ce.target.value),disabled:$||L.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:()=>he(L),disabled:$||ie||L.state!=="open"||L.draft,children:[$?e.jsx(Tt,{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]})]}),de?e.jsx(Se,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:de,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{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:v,onChange:ce=>j(ce.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(Rs,{value:M,onChange:ce=>k(ce.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":D,onClick:()=>N(ce=>!ce),onKeyDown:ce=>{(ce.key===" "||ce.key==="Enter")&&(ce.preventDefault(),N(X=>!X))},children:[e.jsx("button",{type:"button",onClick:ce=>{ce.preventDefault(),ce.stopPropagation(),N(X=>!X)},"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:D?e.jsx(Sn,{className:"size-4 text-primary"}):e.jsx(Nn,{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:De,disabled:E||P,children:[E?e.jsx(Tt,{className:"size-4 animate-spin"}):e.jsx(Bl,{className:"size-4 text-primary"}),"Generate"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(Se,{size:"sm",onClick:z,disabled:P||!ye,children:[P?e.jsx(Tt,{className:"size-4 animate-spin"}):null,"Create PR"]})]})]})]})})}),e.jsx(us,{open:ee,onOpenChange:V,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(Aa,{className:"h-5 w-5"}),"Check Details"]}),e.jsx(Ns,{children:L?`PR #${L.number}`:"Pull request"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[q?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Tt,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):null,q?null:e.jsx("div",{className:"space-y-3",children:Array.isArray(ae?.checkRuns)&&ae?.checkRuns.length>0?ae.checkRuns.map((ce,X)=>e.jsx("div",{className:"rounded-md border border-border/60 p-3",children:O(ce)},`${ce.name}-${X}`)):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:()=>V(!1),children:"Close"})]})]})})]})},Fp="gitmojiCache",VS=1e3*60*60*24*7,Rp="1",GS="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Mu={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:"},Lp=t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.emoji=="string"&&typeof r.code=="string"&&typeof r.description=="string"},qS=()=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Fp);if(!t)return null;const r=JSON.parse(t);return!r||r.version!==Rp||typeof r.fetchedAt!="number"||!Array.isArray(r.gitmojis)?null:{gitmojis:r.gitmojis.filter(Lp),fetchedAt:r.fetchedAt,version:r.version}}catch{return null}},KS=t=>{if(!(typeof window>"u"))try{const r={gitmojis:t,fetchedAt:Date.now(),version:Rp};localStorage.setItem(Fp,JSON.stringify(r))}catch{return}},QS=t=>Date.now()-t.fetchedAt<VS,YS=(t,r)=>{const s=t.toLowerCase(),n=/^([a-z]+)(?:\(.*\))?!?:/,o=s.match(n);if(o){const c=o[1],d=Mu[c];if(d)return r.find(u=>u.code===d)||null}const a=s.split(" ")[0],l=Mu[a];return l&&r.find(c=>c.code===l)||null},Du=new Map,JS=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=ge(),{currentDirectory:n}=wt(),o=t?s.get(t)??void 0:void 0,l=r.find(c=>c.id===t)?.directory;return o?.path??l??n??void 0},XS=()=>{const{git:t}=Bs(),r=JS(),{currentSessionId:s,worktreeMetadata:n}=ge(),o=s?n.get(s)??void 0:void 0,{profiles:a,globalIdentity:l,defaultGitIdentityId:c,loadProfiles:d,loadGlobalIdentity:u,loadDefaultGitIdentityId:m}=ro(),f=tc(r??null),p=Ef(r??null),h=If(r??null),x=vw(r??null),g=jw(r??null),b=ls(Me=>Me.isLoadingStatus),y=ls(Me=>Me.isLoadingLog),{setActiveDirectory:w,fetchAll:S,fetchStatus:C,fetchBranches:v,fetchLog:j,fetchIdentity:M,setLogMaxCount:k}=ls(),D=i.useMemo(()=>r?Du.get(r)??null:null,[r]),N=et(Me=>Me.settingsGitmojiEnabled),T=Wt(Me=>Me.getActiveProject()),A=i.useMemo(()=>{const Me=T?.worktreeDefaults?.baseBranch;return typeof Me=="string"&&Me.trim().length>0?Me.trim():"main"},[T?.worktreeDefaults?.baseBranch]),[E,I]=i.useState(D?.commitMessage??""),[P,F]=i.useState(!1),[$,Q]=i.useState(null),[ie,K]=i.useState(null),[ee,V]=i.useState(25),[ae,G]=i.useState(!1),{triggerFireworks:q}=wS(),_=i.useRef(new Map),H=i.useRef(0),L=i.useCallback(()=>{H.current+=1,G(!0)},[]),B=i.useCallback(()=>{H.current=Math.max(0,H.current-1),H.current===0&&G(!1)},[]),[O,le]=i.useState(()=>new Set(D?.selectedPaths??[])),[we,pe]=i.useState(!1),[De,z]=i.useState(new Set),[he,Z]=i.useState(!1),[de,Ee]=i.useState(D?.generatedHighlights??[]),ne=i.useCallback(()=>{Ee([])},[]),[ye,te]=i.useState(new Set),[ce,X]=i.useState(new Map),[U,Y]=i.useState(new Set),[se,me]=i.useState(null),[ze,qe]=i.useState([]),[tt,Xe]=i.useState(""),Nt=i.useCallback(Me=>{navigator.clipboard.writeText(Me).then(()=>{W.success("Commit hash copied")}).catch(()=>{W.error("Failed to copy")})},[]),Ne=i.useCallback(Me=>{te($e=>{const Le=new Set($e);return Le.has(Me)?Le.delete(Me):Le.add(Me),Le})},[]);i.useEffect(()=>{if(!r||!t)return;const Me=Array.from(ye).filter($e=>!ce.has($e)&&!U.has($e));if(Me.length!==0){Y($e=>{const Le=new Set($e);for(const ot of Me)Le.add(ot);return Le});for(const $e of Me)t.getCommitFiles(r,$e).then(Le=>{X(ot=>new Map(ot).set($e,Le.files))}).catch(Le=>{console.error("Failed to fetch commit files:",Le),X(ot=>new Map(ot).set($e,[]))}).finally(()=>{Y(Le=>{const ot=new Set(Le);return ot.delete($e),ot})})}},[ye,r,t,ce,U]),i.useEffect(()=>{r&&Du.set(r,{directory:r,selectedPaths:Array.from(O),commitMessage:E,generatedHighlights:de})},[E,r,O,de]),i.useEffect(()=>{d(),u(),m()},[d,u,m]),i.useEffect(()=>{if(!r||!t?.getRemoteUrl){me(null);return}t.getRemoteUrl(r).then(me).catch(()=>me(null))},[r,t]),i.useEffect(()=>{if(!N){qe([]);return}let Me=!1;const $e=qS();return $e&&(qe($e.gitmojis),QS($e))?()=>{Me=!0}:((async()=>{try{const ot=await fetch(GS);if(!ot.ok)throw new Error(`Failed to load gitmojis: ${ot.statusText}`);const oe=await ot.json(),Te=Array.isArray(oe.gitmojis)?oe.gitmojis.filter(Lp):[];Me||(qe(Te),KS(Te))}catch(ot){Me||console.warn("Failed to load gitmoji list:",ot)}})(),()=>{Me=!0})},[N]),i.useEffect(()=>{r&&(w(r),ls.getState().directories.get(r)?.status||S(r,t,{force:!0}))},[r,w,S,t]);const ue=i.useCallback(async(Me=!0)=>{if(r)try{await Promise.all([C(r,t),v(r,t)])}catch($e){if(Me){const Le=$e instanceof Error?$e.message:"Failed to refresh repository state";W.error(Le)}}},[r,t,C,v]),We=i.useCallback(async()=>{r&&await j(r,t,ee)},[r,t,j,ee]),ve=i.useCallback(async()=>{r&&await M(r,t)},[r,t,M]);i.useEffect(()=>{if(!r||!t?.hasLocalIdentity||f!==!0)return;const Me=typeof c=="string"?c.trim():"";if(!Me||Me==="global"||_.current.get(r)===Me)return;let Le=!1;return(async()=>{try{const oe=await t.hasLocalIdentity?.(r);if(Le||oe===!0)return;L(),await t.setGitIdentity(r,Me),_.current.set(r,Me),await ve()}catch(oe){console.warn("Failed to auto-apply default git identity:",oe)}finally{Le||B()}})(),()=>{Le=!0}},[L,r,c,B,t,f,ve]);const ke=i.useMemo(()=>{if(!p)return[];const Me=p.files??[],$e=new Map;for(const Le of Me)$e.set(Le.path,Le);return Array.from($e.values()).sort((Le,ot)=>Le.path.localeCompare(ot.path))},[p]);i.useEffect(()=>{if(!p||ke.length===0){le(new Set),pe(!1);return}le(Me=>{const $e=new Set,Le=Me??new Set;for(const ot of ke)Le.has(ot.path)?$e.add(ot.path):we||$e.add(ot.path);return $e})},[p,ke,we]);const Ze=async Me=>{if(r){Q(Me);try{if(Me==="fetch")await t.gitFetch(r),W.success("Fetched latest updates");else if(Me==="pull"){const $e=await t.gitPull(r);W.success(`Pulled ${$e.files.length} file${$e.files.length===1?"":"s"}`)}else Me==="push"&&(await t.gitPush(r),W.success("Pushed to remote"));await ue(!1),await We()}catch($e){const Le=$e instanceof Error?$e.message:`Failed to ${Me==="pull"?"pull":Me}`;W.error(Le)}finally{Q(null)}}},ct=async(Me={})=>{if(!r)return;if(!E.trim()){W.error("Please enter a commit message");return}const $e=Array.from(O).sort();if($e.length===0){W.error("Select at least one file to commit");return}const Le=Me.pushAfter?"commitAndPush":"commit";K(Le);try{await t.createGitCommit(r,E.trim(),{files:$e}),W.success("Commit created successfully"),I(""),le(new Set),pe(!1),ne(),await ue(),Me.pushAfter?(await t.gitPush(r),W.success("Pushed to remote"),q(),await ue(!1)):await ue(!1),await We()}catch(ot){const oe=ot instanceof Error?ot.message:"Failed to create commit";W.error(oe)}finally{K(null)}},Ue=i.useCallback(async()=>{if(r){if(O.size===0){W.error("Select at least one file to describe");return}Z(!0);try{const{message:Me}=await t.generateCommitMessage(r,Array.from(O)),$e=Me.subject?.trim()??"",Le=Array.isArray(Me.highlights)?Me.highlights:[];if($e){let ot=$e;if(N&&ze.length>0){const oe=YS($e,ze);if(oe){const{code:Te,emoji:Ie}=oe;!$e.startsWith(Te)&&!$e.startsWith(Ie)&&(ot=`${Te} ${$e}`)}}I(ot)}Ee(Le),W.success("Commit message generated")}catch(Me){const $e=Me instanceof Error?Me.message:"Failed to generate commit message";W.error($e)}finally{Z(!1)}}},[r,O,t,N,ze]),Be=async Me=>{if(!r||!p)return;const $e=p.current??null;try{await t.createBranch(r,Me,$e??"HEAD"),W.success(`Created branch ${Me}`);let Le=!1;try{await t.checkoutBranch(r,Me),await t.gitPush(r,{remote:"origin",branch:Me,options:["--set-upstream"]}),Le=!0}catch(ot){const oe=ot instanceof Error?ot.message:"Unable to push new branch to origin.";W.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",oe]})})}finally{if($e)try{await t.checkoutBranch(r,$e)}catch(ot){console.warn("Failed to restore original branch after creation:",ot)}}await ue(),await We(),Le&&W.success(`Upstream set for ${Me}`)}catch(Le){const ot=Le instanceof Error?Le.message:"Failed to create branch";throw W.error(ot),Le}},Ve=async(Me,$e)=>{if(r)try{await t.renameBranch(r,Me,$e),W.success(`Renamed branch ${Me} to ${$e}`),await ue(),await We()}catch(Le){const ot=Le instanceof Error?Le.message:`Failed to rename branch ${Me} to ${$e}`;W.error(ot)}},dt=async Me=>{if(!r)return;const $e=Me.replace(/^remotes\//,"");if(p?.current!==$e)try{await t.checkoutBranch(r,$e),W.success(`Checked out ${$e}`),await ue(),await We()}catch(Le){const ot=Le instanceof Error?Le.message:`Failed to checkout ${$e}`;W.error(ot)}},pt=async Me=>{if(r){L();try{await t.setGitIdentity(r,Me.id),W.success(`Applied "${Me.name}" to repository`),await ve()}catch($e){const Le=$e instanceof Error?$e.message:"Failed to apply git identity";W.error(Le)}finally{B()}}},Ge=i.useMemo(()=>h?.all?h.all.filter(Me=>!Me.startsWith("remotes/")).sort():[],[h]),ut=i.useMemo(()=>h?.all?h.all.filter(Me=>Me.startsWith("remotes/")).map(Me=>Me.replace(/^remotes\//,"")).sort():[],[h]),xt=i.useMemo(()=>{const Me=new Map;l&&Me.set(l.id,l);let $e=null;if(se)try{let Le=se.trim();Le.startsWith("git@")&&(Le=`https://${Le.slice(4).replace(":","/")}`),Le.endsWith(".git")&&(Le=Le.slice(0,-4));const ot=new URL(Le);$e=ot.hostname+ot.pathname}catch{}for(const Le of a){if(Le.authType!=="token"){Me.set(Le.id,Le);continue}const ot=Le.host;if(!ot){Me.set(Le.id,Le);continue}if(!ot.includes("/")){Me.set(Le.id,Le);continue}$e&&$e===ot&&Me.set(Le.id,Le)}return Array.from(Me.values())},[a,l,se]),kt=i.useMemo(()=>{if(g?.userName&&g?.userEmail){const Me=a.find($e=>$e.userName===g.userName&&$e.userEmail===g.userEmail);return Me||(l&&l.userName===g.userName&&l.userEmail===g.userEmail?l:{id:"local-config",name:g.userName,userName:g.userName,userEmail:g.userEmail,sshKey:g.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return l??null},[g,a,l]),At=ke.length,Xt=O.size,as=b||$!==null||ie!==null,_t=At>0,Mt=Me=>{le($e=>{const Le=new Set($e);return Le.has(Me)?Le.delete(Me):Le.add(Me),Le}),pe(!0)},Rt=()=>{const Me=new Set(ke.map($e=>$e.path));le(Me),pe(!0)},Jt=()=>{le(new Set),pe(!0)},Ft=i.useCallback(async Me=>{if(r){z($e=>{const Le=new Set($e);return Le.add(Me),Le});try{await t.revertGitFile(r,Me),W.success(`Reverted ${Me}`),await ue(!1)}catch($e){const Le=$e instanceof Error?$e.message:"Failed to revert changes";W.error(Le)}finally{z($e=>{const Le=new Set($e);return Le.delete(Me),Le})}}},[r,ue,t]),Qt=i.useCallback(()=>{if(de.length===0)return;const Me=de.map($e=>$e.trim()).filter(Boolean);if(Me.length===0){ne();return}I($e=>{const Le=$e.trim(),ot=Le.length>0?`
213
-
214
- `:"";return`${Le}${ot}${Me.join(`
215
- `)}`.trim()})},[de,ne]),ps=i.useCallback((Me,$e)=>{const Le=$e||Me;I(ot=>{const oe=ot.trimStart();return oe.startsWith(Me)||$e&&oe.startsWith($e)?ot:`${Le.endsWith(" ")?Le:`${Le} `}${ot}`.trimStart()}),Xe(""),F(!1)},[]),Lt=i.useCallback(Me=>{V(Me),r&&(k(r,Me),j(r,t,Me))},[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(Tt,{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(qt,{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(AS,{status:p,localBranches:Ge,remoteBranches:ut,branchInfo:h?.branches,syncAction:$,onFetch:()=>Ze("fetch"),onPull:()=>Ze("pull"),onPush:()=>Ze("push"),onCheckoutBranch:dt,onCreateBranch:Be,onRenameBranch:Ve,activeIdentityProfile:kt,availableIdentities:xt,onSelectIdentity:pt,isApplyingIdentity:ae,isWorktreeMode:!!o}),e.jsx(jt,{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:[_t?e.jsx(RS,{changeEntries:ke,selectedPaths:O,diffStats:p?.diffStats,revertingPaths:De,onToggleFile:Mt,onSelectAll:Rt,onClearSelection:Jt,onViewDiff:Me=>je.getState().navigateToDiff(Me),onRevertFile:Ft}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(ES,{behind:p?.behind??0,onPull:()=>Ze("pull"),isPulling:$==="pull"})}),ke.length>0&&e.jsx($S,{selectedCount:Xt,commitMessage:E,onCommitMessageChange:I,generatedHighlights:de,onInsertHighlights:Qt,onClearHighlights:ne,onGenerateMessage:Ue,isGeneratingMessage:he,onCommit:()=>ct({pushAfter:!1}),onCommitAndPush:()=>ct({pushAfter:!0}),commitAction:ie,isBusy:as,gitmojiEnabled:N,onOpenGitmojiPicker:()=>F(!0)})]}),r&&p?.current?e.jsx(US,{directory:r,branch:p.current,baseBranch:A}):null,e.jsx(HS,{log:x,isLogLoading:y,logMaxCount:ee,onLogMaxCountChange:Lt,expandedCommitHashes:ye,onToggleCommit:Ne,commitFilesMap:ce,loadingCommitHashes:U,onCopyHash:Nt})]})}),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(cc,{className:"h-[420px]",children:[e.jsx(dc,{placeholder:"Search gitmojis...",value:tt,onValueChange:Xe}),e.jsxs(uc,{children:[e.jsx(mc,{children:"No gitmojis found."}),e.jsx(xn,{children:(ze.length===0?[]:ze.filter(Me=>{const $e=tt.trim().toLowerCase();return $e?Me.emoji.includes($e)||Me.code.toLowerCase().includes($e)||Me.description.toLowerCase().includes($e):!0})).map(Me=>e.jsxs(js,{onSelect:()=>ps(Me.emoji,Me.code),children:[e.jsx("span",{className:"text-lg",children:Me.emoji}),e.jsx("span",{className:"typography-ui-label text-foreground",children:Me.code}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:Me.description})]},Me.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."})})},ZS=1e6;function on(t){let r=t.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const aa=t=>({directory:t,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),Au=rs((t,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:s=>{const n=on(s);return r().sessions.get(n)},setTerminalSession:(s,n)=>{const o=on(s);t(a=>{const l=new Map(a.sessions),c=l.get(o),u=!c||c.terminalSessionId!==n.sessionId?aa(o):c??aa(o);return l.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:l}})},setConnecting:(s,n)=>{const o=on(s);t(a=>{const l=new Map(a.sessions),c=l.get(o)??aa(o);return l.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(s,n)=>{if(!n)return;const o=on(s);t(a=>{const l=new Map(a.sessions),c=l.get(o)??aa(o),d=a.nextChunkId,u={id:d,data:n},m=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>ZS&&m.length>1;){const h=m.shift();if(!h)break;f-=h.data.length}const p=m.map(h=>h.data).join("");return l.set(o,{...c,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:l,nextChunkId:d+1}})},clearTerminalSession:s=>{const n=on(s);t(o=>{const a=new Map(o.sessions),l=a.get(n);return l&&a.set(n,{...l,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:s=>{const n=on(s);t(o=>{const a=new Map(o.sessions),l=a.get(n);return l?(a.set(n,{...l,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:s=>{const n=on(s);t(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{t({sessions:new Map,nextChunkId:1})}})),Op=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),eN=[{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'}],tN=[{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'}],$p=t=>Object.fromEntries(t.map(r=>[r.id,r])),Eu=$p(eN),ln=$p(tN),sN="ibm-plex-sans",Ca="ibm-plex-mono";function rN(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 nN(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 Ui=null;function oN(){return Ui||(Ui=yx.load()),Ui}function aN(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 Il=i.forwardRef(({sessionKey:t,chunks:r,onInput:s,onResize:n,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d},u)=>{const m=i.useRef(null),f=i.useRef(null),p=i.useRef(null),h=i.useRef(null),x=i.useRef(s),g=i.useRef(n),b=i.useRef(null),y=i.useRef(""),w=i.useRef(null),S=i.useRef(!1),C=i.useRef(null),v=i.useRef(null),j=i.useRef(null),M=i.useRef(0),k=i.useRef(null),[,D]=i.useReducer(K=>K+1,0),[N,T]=i.useReducer(K=>K+1,0);x.current=s,g.current=n;const A=i.useCallback((K,ee)=>{const V=k.current,ae=m.current;if(!V||!ae)return;const G=ae.getBoundingClientRect(),q=G.left+G.width/2,_=G.top+G.height-12,H=typeof K=="number"?K:q,L=typeof ee=="number"?ee:_,B=8,O=Math.max(B,Math.min(G.width-B,H-G.left)),le=Math.max(B,Math.min(G.height-B,L-G.top));V.style.left=`${O}px`,V.style.top=`${le}px`,V.style.bottom="";try{V.focus({preventScroll:!0})}catch{try{V.focus()}catch{}}},[]),E=i.useCallback(async()=>{if(typeof window>"u"||typeof document>"u")return;const K=window.getSelection();if(!K)return;const ee=K.toString();if(!ee.trim())return;const V=m.current;if(!V)return;const ae=K.anchorNode,G=K.focusNode;if(!(ae&&!V.contains(ae))&&!(G&&!V.contains(G))){try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(ee);return}}catch{}try{const q=document.createElement("textarea");q.value=ee,q.style.position="fixed",q.style.opacity="0",document.body.appendChild(q),q.focus(),q.select(),document.execCommand("copy"),document.body.removeChild(q)}catch{}}},[]),I=i.useCallback(()=>{y.current="",w.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(w.current),w.current=null,S.current=!1,C.current=null},[]),P=i.useCallback(()=>{const K=h.current,ee=p.current,V=m.current;if(!K||!ee||!V)return;const ae=V.getBoundingClientRect();if(!(ae.width<24||ae.height<24))try{K.fit();const G={cols:ee.cols,rows:ee.rows},q=b.current;(!q||q.cols!==G.cols||q.rows!==G.rows)&&(b.current=G,g.current(G.cols,G.rows))}catch{}},[]),F=i.useCallback(()=>{if(S.current)return;const K=p.current;if(!K){I();return}if(!y.current)return;const ee=y.current;y.current="",S.current=!0,K.write(ee,()=>{S.current=!1,y.current&&(typeof window<"u"?w.current=window.requestAnimationFrame(()=>{w.current=null,F()}):F())})},[I]),$=i.useCallback(()=>{w.current===null&&(typeof window<"u"?w.current=window.requestAnimationFrame(()=>{w.current=null,F()}):F())},[F]),Q=i.useCallback(K=>{K&&(y.current+=K,$())},[$]),ie=i.useCallback(()=>{if(v.current?.(),v.current=null,j.current!==null&&typeof window<"u"&&(window.clearTimeout(j.current),j.current=null),!d){M.current=0;return}const K=m.current;if(!K)return;const ee=p.current;if(!ee)return;M.current=0;const V=2.2,ae=2.8,G=25,q=.25,_=8,H=.05,L=.015,B={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},O=()=>typeof performance<"u"?performance.now():Date.now(),le=Math.max(12,Math.round(l*1.35));let we=0;const pe=te=>{if(!te)return!1;const ce=ee.getViewportY(),X=we+te,U=Math.trunc(X/le);return we=X-U*le,U!==0&&ee.scrollLines(U),ee.getViewportY()!==ce},De=()=>{B.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(B.rafId),B.rafId=null},z={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const te=Object.assign(B,{pointerId:null,startX:null,startY:null,moved:!1}),ce=6,X=me=>{if(me.pointerType==="touch"){De(),te.pointerId=me.pointerId,te.startX=me.clientX,te.startY=me.clientY,te.moved=!1,te.lastY=me.clientY,te.lastTime=O(),te.velocity=0;try{K.setPointerCapture(me.pointerId)}catch{}}},U=me=>{if(me.pointerType!=="touch"||te.pointerId!==me.pointerId)return;if(te.startX!==null&&te.startY!==null&&!te.moved){const ve=me.clientX-te.startX,ke=me.clientY-te.startY;Math.hypot(ve,ke)>=ce&&(te.moved=!0)}if(te.lastY===null){te.lastY=me.clientY,te.lastTime=O();return}const ze=te.lastY,qe=te.lastTime??O(),tt=O();te.lastY=me.clientY,te.lastTime=tt;const Xe=ze-me.clientY;if(Math.abs(Xe)<1)return;const Nt=Math.max(tt-qe,8),Ne=V+Math.min(ae,Math.abs(Xe)/G),ue=Xe*Ne,We=ue/Nt;te.velocity=te.velocity*(1-q)+We*q,te.velocity>_?te.velocity=_:te.velocity<-_&&(te.velocity=-_),te.moved&&(me.cancelable&&me.preventDefault(),me.stopPropagation()),pe(ue)},Y=me=>{if(me.pointerType!=="touch"||te.pointerId!==me.pointerId)return;const ze=!te.moved;te.pointerId=null,te.startX=null,te.startY=null,te.moved=!1,te.lastY=null,te.lastTime=null;try{K.releasePointerCapture(me.pointerId)}catch{}if(ze){A(me.clientX,me.clientY);return}if(typeof window>"u")return;if(Math.abs(te.velocity)<H){te.velocity=0;return}let qe=O();const tt=()=>{const Xe=O(),Nt=Math.max(Xe-qe,8);qe=Xe;const Ne=pe(te.velocity*Nt)??!1,ue=Math.sign(te.velocity),We=Math.max(0,Math.abs(te.velocity)-L*Nt);if(te.velocity=We*ue,!Ne||We<=H){De(),te.velocity=0;return}te.rafId=window.requestAnimationFrame(tt)};te.rafId=window.requestAnimationFrame(tt)};K.addEventListener("pointerdown",X,z),K.addEventListener("pointermove",U,z),K.addEventListener("pointerup",Y,z),K.addEventListener("pointercancel",Y,z);const se=K.style.touchAction;K.style.touchAction="manipulation",v.current=()=>{De(),j.current!==null&&typeof window<"u"&&(window.clearTimeout(j.current),j.current=null),M.current=0,K.removeEventListener("pointerdown",X,z),K.removeEventListener("pointermove",U,z),K.removeEventListener("pointerup",Y,z),K.removeEventListener("pointercancel",Y,z),K.style.touchAction=se};return}const Z=6,de=te=>{te.touches.length===1&&(De(),B.lastY=te.touches[0].clientY,B.lastTime=O(),B.velocity=0,B.startX=te.touches[0].clientX,B.startY=te.touches[0].clientY,B.didMove=!1)},Ee=te=>{if(te.touches.length!==1){B.lastY=null,B.lastTime=null,B.velocity=0,B.startX=null,B.startY=null,B.didMove=!1,De();return}const ce=te.touches[0].clientX,X=te.touches[0].clientY;if(B.startX!==null&&B.startY!==null&&!B.didMove){const Nt=ce-B.startX,Ne=X-B.startY;Math.hypot(Nt,Ne)>=Z&&(B.didMove=!0)}if(B.lastY===null){B.lastY=X,B.lastTime=O();return}const U=B.lastY,Y=B.lastTime??O(),se=O();B.lastY=X,B.lastTime=se;const me=U-X;if(Math.abs(me)<1)return;const ze=Math.max(se-Y,8),qe=V+Math.min(ae,Math.abs(me)/G),tt=me*qe,Xe=tt/ze;B.velocity=B.velocity*(1-q)+Xe*q,B.velocity>_?B.velocity=_:B.velocity<-_&&(B.velocity=-_),B.didMove&&(te.preventDefault(),te.stopPropagation()),pe(tt)},ne=te=>{const ce=!B.didMove;B.lastY=null,B.lastTime=null;const X=B.velocity;if(B.startX=null,B.startY=null,B.didMove=!1,ce){const se=te.changedTouches?.[0];A(se?.clientX,se?.clientY);return}if(typeof window>"u")return;if(Math.abs(X)<H){B.velocity=0;return}let U=O();const Y=()=>{const se=O(),me=Math.max(se-U,8);U=se;const ze=pe(B.velocity*me)??!1,qe=Math.sign(B.velocity),tt=Math.max(0,Math.abs(B.velocity)-L*me);if(B.velocity=tt*qe,!ze||tt<=H){De(),B.velocity=0;return}B.rafId=window.requestAnimationFrame(Y)};B.rafId=window.requestAnimationFrame(Y)};K.addEventListener("touchstart",de,z),K.addEventListener("touchmove",Ee,z),K.addEventListener("touchend",ne,z),K.addEventListener("touchcancel",ne,z);const ye=K.style.touchAction;K.style.touchAction="manipulation",v.current=()=>{De(),j.current!==null&&typeof window<"u"&&(window.clearTimeout(j.current),j.current=null),M.current=0,K.removeEventListener("touchstart",de,z),K.removeEventListener("touchmove",Ee,z),K.removeEventListener("touchend",ne,z),K.removeEventListener("touchcancel",ne,z),K.style.touchAction=ye}},[d,A,l]);return i.useEffect(()=>{let K=!1,ee=null,V=null,ae=[];const G=m.current;return G?(G.tabIndex=0,(async()=>{try{const _=await oN();if(K)return;const H=nN(a,l,o,_),L=new gx(H),B=new xx;ee=L,p.current=L,h.current=B,L.loadAddon(B),L.open(G),T();const O=aN(G);O?(O.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=O,D()):f.current=null,P(),ie(),L.focus(),ae=[L.onData(le=>{x.current(le)})],V=new ResizeObserver(()=>{P()}),V.observe(G),typeof window<"u"&&window.setTimeout(()=>{P()},0)}catch{}})(),()=>{K=!0,v.current?.(),v.current=null,ae.forEach(_=>_.dispose()),V?.disconnect(),ee?.dispose(),p.current=null,h.current=null,f.current=null,b.current=null,I()}):void 0},[P,a,l,ie,o,I]),i.useEffect(()=>{const K=p.current;K&&(K.reset(),I(),b.current=null,P(),K.focus())},[t,N,P,I]),i.useEffect(()=>(ie(),()=>{v.current?.(),v.current=null}),[ie,t]),i.useEffect(()=>{const K=p.current;if(!K)return;if(r.length===0){C.current!==null&&(K.reset(),I(),P());return}const ee=C.current;let V;if(ee===null)V=r;else{const ae=r.findIndex(G=>G.id===ee);V=ae>=0?r.slice(ae+1):r}V.length>0&&Q(V.map(ae=>ae.data).join("")),C.current=r[r.length-1].id},[r,N,Q,P,I]),i.useImperativeHandle(u,()=>({focus:()=>{if(d){A();return}p.current?.focus()},clear:()=>{const K=p.current;K&&(K.reset(),I(),P())},fit:()=>{P()}}),[d,A,P,I]),e.jsxs("div",{ref:m,className:R("relative h-full w-full terminal-viewport-container",c),style:{backgroundColor:o.background},onClick:K=>{d?A(K.clientX,K.clientY):p.current?.focus()},onMouseUp:()=>{E()},onTouchEnd:()=>{E()},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:K=>{const ee=String(K.currentTarget.value||"");if(!ee)return;const V=ee.replace(/\r\n|\r|\n/g,"\r");x.current(V),K.currentTarget.value=""},onKeyDown:K=>{K.key==="Backspace"&&(K.currentTarget.value||x.current(""))}}):null,f.current&&!d?e.jsx(ec,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});Il.displayName="TerminalViewport";const Iu=13,iN={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},ia={ctrl:"5",cmd:"3"},lN={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},cN=(t,r)=>{if(r)switch(t){case"arrow-up":return`\x1B[1;${ia[r]}A`;case"arrow-down":return`\x1B[1;${ia[r]}B`;case"arrow-right":return`\x1B[1;${ia[r]}C`;case"arrow-left":return`\x1B[1;${ia[r]}D`}return iN[t]??null},dN=()=>{const{terminal:t}=Bs(),{currentTheme:r}=Br(),{monoFont:s}=Op(),{isMobile:n,hasTouchInput:o}=Kt(),{currentSessionId:a,sessions:l,worktreeMetadata:c}=ge(),d=a?c.get(a)??void 0:void 0,u=i.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const te=l.find(X=>X.id===a),ce=typeof te?.directory=="string"?te.directory:null;return ce&&ce.length>0?ce:null},[a,l,d]),{currentDirectory:m,homeDirectory:f}=wt(),p=u||m||null,h=i.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),x=Au(),g=x.sessions,b=x.setTerminalSession,y=x.setConnecting,w=x.appendToBuffer,S=x.clearTerminalSession,C=x.removeTerminalSession,v=x.clearBuffer,j=i.useMemo(()=>{if(p)return g.get(p)},[g,p]),M=j?.terminalSessionId??null,k=j?.bufferChunks??[],D=j?.bufferLength??0,N=j?.isConnecting??!1,T=M,[A,E]=i.useState(null),[I,P]=i.useState(!1),[F,$]=i.useState(null),[Q,ie]=i.useState(!1),K=i.useRef(null),ee=i.useRef(null),V=i.useRef(T),ae=i.useRef(p),G=i.useRef(null),_=je(te=>te.activeMainTab)==="terminal";i.useEffect(()=>{V.current=T},[T]),i.useEffect(()=>{ae.current=p},[p]),i.useEffect(()=>{!n&&F!==null&&$(null)},[n,F,$]),i.useEffect(()=>{!T&&F!==null&&$(null)},[T,F,$]);const H=i.useCallback(()=>{K.current?.(),K.current=null,ee.current=null},[]);i.useEffect(()=>()=>{H(),V.current=null},[H]);const L=i.useCallback(te=>{if(ee.current===te)return;H();const ce=t.connect(te,{onEvent:X=>{const U=ae.current;if(U)switch(X.type){case"connected":{(X.runtime||X.ptyBackend)&&console.log(`[Terminal] connected runtime=${X.runtime??"unknown"} pty=${X.ptyBackend??"unknown"}`),y(U,!1),E(null),P(!1),G.current?.focus();break}case"reconnecting":{const Y=X.attempt??0,se=X.maxAttempts??3;E(`Reconnecting (${Y}/${se})...`),P(!1);break}case"data":{X.data&&w(U,X.data);break}case"exit":{const Y=typeof X.exitCode=="number"?X.exitCode:null,se=typeof X.signal=="number"?X.signal:null;w(U,`\r
216
- [Process exited${Y!==null?` with code ${Y}`:""}${se!==null?` (signal ${se})`:""}]\r
217
- `),S(U),y(U,!1),E("Terminal session ended"),P(!1),H();break}}},onError:(X,U)=>{const Y=ae.current;if(!Y)return;const se=U?`Connection failed: ${X.message}`:X.message||"Terminal stream connection error";E(se),P(!!U),U&&(y(Y,!1),H(),C(Y))}},lN);K.current=()=>{ce.close(),ee.current=null},ee.current=te},[w,S,H,C,y,t,E]);i.useEffect(()=>{let te=!1;if(!p){E(a?"No working directory available for terminal.":"Select a session to open the terminal."),H();return}return(async()=>{const X=p;if(!ae.current||ae.current!==X)return;let Y=Au.getState().getTerminalSession(X)?.terminalSessionId??null;if(!Y){E(null),P(!1),y(X,!0);try{const se=await t.createSession({cwd:X});if(te){try{await t.close(se.sessionId)}catch{}return}b(X,se),Y=se.sessionId}catch(se){te||(E(se instanceof Error?se.message:"Failed to start terminal session"),P(!0),y(X,!1));return}}!Y||te||(V.current=Y,L(Y))})(),()=>{te=!0,V.current=null,H()}},[a,p,T,C,y,b,L,H,t]);const B=i.useCallback(async()=>{if(!p||Q)return;ie(!0),E(null),P(!1),H();const te=V.current;try{if(t.restartSession&&te){const ce=await t.restartSession(te,{cwd:p});b(p,ce),V.current=ce.sessionId,L(ce.sessionId)}else{if(te)try{await t.close(te)}catch{}C(p)}}catch(ce){E(ce instanceof Error?ce.message:"Failed to restart terminal"),P(!0)}finally{ie(!1)}},[p,Q,H,t,b,L,C]),O=i.useCallback(async()=>{if(p&&!Q){ie(!0),E(null),P(!1),H();try{t.forceKill&&await t.forceKill({cwd:p})}catch{}C(p),v(p),G.current?.clear(),await new Promise(te=>setTimeout(te,100));try{y(p,!0);const te=await t.createSession({cwd:p});b(p,te),V.current=te.sessionId,L(te.sessionId)}catch(te){E(te instanceof Error?te.message:"Failed to create terminal"),P(!0),y(p,!1)}finally{ie(!1)}}},[p,Q,H,t,C,v,y,b,L]),le=i.useCallback(()=>{if(!p)return;v(p),G.current?.clear(),G.current?.focus();const te=V.current;te&&t.sendInput(te,"\f").catch(ce=>{E(ce instanceof Error?ce.message:"Failed to refresh prompt")})},[v,p,E,t]),we=i.useCallback(te=>{if(!te)return;let ce=te,X=!1;if(F&&te.length>0){const Y=te[0];if(Y.length===1&&/[a-zA-Z]/.test(Y)){const se=Y.toUpperCase();(F==="ctrl"||F==="cmd")&&(ce=String.fromCharCode(se.charCodeAt(0)&31),X=!0)}X||(X=!0)}const U=V.current;U&&(t.sendInput(U,ce).catch(Y=>{E(Y instanceof Error?Y.message:"Failed to send input")}),X&&($(null),G.current?.focus()))},[F,$,t]),pe=i.useCallback((te,ce)=>{const X=V.current;X&&t.resize({sessionId:X,cols:te,rows:ce}).catch(()=>{})},[t]),De=i.useCallback(te=>{$(ce=>ce===te?null:te),G.current?.focus()},[$]),z=i.useCallback(te=>{const ce=cN(te,F);ce&&(we(ce),$(null),G.current?.focus())},[F,we,$]);i.useEffect(()=>{if(!n||!F||!T)return;const te=ce=>{if(ce.repeat)return;const X=ce.key;if(!X||X==="Control"||X==="Meta"||X==="Alt"||X==="Shift")return;const U=X.length===1?X.toLowerCase():X,Y=ce.code??"",se=Y.startsWith("Key")&&Y.length===4?Y.slice(3).toUpperCase():null,me=X.length===1&&/[a-zA-Z]/.test(X)?X.toUpperCase():se,ze={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(U in ze){ce.preventDefault(),ce.stopPropagation(),z(ze[U]);return}if(F==="ctrl"&&me&&me.length===1&&me>="A"&&me<="Z"){const qe=String.fromCharCode(me.charCodeAt(0)&31);ce.preventDefault(),ce.stopPropagation(),we(qe),$(null),G.current?.focus()}};return window.addEventListener("keydown",te),()=>{window.removeEventListener("keydown",te)}},[F,z,we,n,$,T]);const he=i.useMemo(()=>{const te=ln[Ca].stack;if(typeof window>"u")return(ln[s]??ln[Ca]).stack;const X=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return X&&X.trim().length>0?X.trim():(ln[s]??ln[Ca]).stack??te},[s]),Z=i.useMemo(()=>rN(r),[r]),de=i.useMemo(()=>`${p??"no-dir"}::${T??"pending"}`,[p,T]);i.useEffect(()=>{if(!_)return;const te=G.current;if(!te)return;const ce=()=>{te.fit()};if(typeof window<"u"){const X=window.requestAnimationFrame(()=>{ce(),te.focus()}),U=[220,400].map(Y=>window.setTimeout(ce,Y));return()=>{window.cancelAnimationFrame(X),U.forEach(Y=>window.clearTimeout(Y))}}ce()},[_,de,T]);const Ee=A?.includes("Reconnecting"),ne=A?Ee?e.jsx(bx,{size:20,className:"text-amber-400"}):e.jsx(os,{size:20,className:"text-destructive"}):T&&!N&&!Q?e.jsx(fa,{size:20,className:"text-emerald-400"}):N||Q?e.jsx(al,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(al,{size:20,className:"text-muted-foreground"});if(!a)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(!p)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:B,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const ye=!T||N||Q;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:h})}),e.jsxs("div",{className:"flex items-center gap-2",children:[ne,e.jsxs(Se,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:le,disabled:!D,title:"Clear output",type:"button",children:[e.jsx(Ks,{size:16}),"Clear"]}),e.jsxs(Se,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:B,disabled:Q,title:"Restart terminal session",type:"button",children:[e.jsx(Ls,{size:16,className:R((N||Q)&&"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:()=>z("esc"),disabled:ye,children:"Esc"}),e.jsxs(Se,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>z("tab"),disabled:ye,children:[e.jsx(Tc,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Se,{type:"button",size:"sm",variant:F==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>De("ctrl"),disabled:ye,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:F==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>De("cmd"),disabled:ye,children:[e.jsx(Dn,{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:()=>z("arrow-up"),disabled:ye,children:[e.jsx(Qn,{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:()=>z("arrow-left"),disabled:ye,children:[e.jsx($m,{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:()=>z("arrow-down"),disabled:ye,children:[e.jsx(io,{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:()=>z("arrow-right"),disabled:ye,children:[e.jsx(Tc,{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:()=>z("enter"),disabled:ye,children:[e.jsx(Jn,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Z.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:_?n?e.jsx(Il,{ref:te=>{G.current=te},sessionKey:de,chunks:k,onInput:we,onResize:pe,theme:Z,fontFamily:he,fontSize:Iu,enableTouchScroll:o},de):e.jsx(jt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Il,{ref:te=>{G.current=te},sessionKey:de,chunks:k,onInput:we,onResize:pe,theme:Z,fontFamily:he,fontSize:Iu,enableTouchScroll:o},de)}):null}),A&&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:A}),I&&e.jsx(Se,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:O,disabled:Q,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},uN=t=>t.slice().sort((r,s)=>r.type!==s.type?r.type==="directory"?-1:1:r.name.localeCompare(s.name)),or=t=>t.replace(/\\/g,"/"),mN=new Set(["node_modules"]),fN=t=>mN.has(t),pN=t=>{const r=or(t);return r==="node_modules"||r.endsWith("/node_modules")||r.includes("/node_modules/")},hN=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=ge(),{currentDirectory:n}=wt(),o=t?s.get(t)??void 0:void 0,l=r.find(c=>c.id===t)?.directory;return o?.path??l??n??""},yo=2e5,gN=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"]),xN=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"]),yN=new Set(["png","jpg","jpeg","gif","svg","webp","ico","icns","bmp","tiff","tif","psd","ai","eps","raw","cr2","nef","heic","heif","avif","jxl"]),bN=new Set(["md","mdx","markdown","mdown","mkd","txt","text","rtf","doc","docx","odt","pdf","rst","adoc","asciidoc","org","tex","latex","bib"]),Pu=t=>{const r=t?.toLowerCase();return r&&gN.has(r)?e.jsx(er,{className:"h-4 w-4 flex-shrink-0 text-blue-500"}):r&&xN.has(r)?e.jsx(er,{className:"h-4 w-4 flex-shrink-0 text-yellow-500"}):r&&yN.has(r)?e.jsx(kr,{className:"h-4 w-4 flex-shrink-0 text-green-500"}):r&&bN.has(r)?e.jsx(Kn,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(Kn,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})},wN=()=>{const{files:t,runtime:r}=Bs(),{currentTheme:s}=Br();i.useMemo(()=>mi(s),[s]);const{isMobile:n,screenWidth:o}=Kt(),a=Ro(),l=si(),c=hN(),d=or(c),u=ri(Pe=>Pe.searchFiles),[m,f]=i.useState(""),p=ui(m,200),h=i.useRef(null),[x,g]=i.useState(!1),[b,y]=i.useState(n),[w,S]=i.useState(new Set),[C,v]=i.useState({}),j=i.useRef(new Set),M=i.useRef(new Set),[k,D]=i.useState([]),[N,T]=i.useState(!1),[A,E]=i.useState(null),[I,P]=i.useState(""),[F,$]=i.useState(!1),[Q,ie]=i.useState(null),[K,ee]=i.useState(""),[V,ae]=i.useState(""),[G,q]=i.useState(!1),[_,H]=i.useState(!1),L=i.useRef(null),B=i.useRef(null),O=i.useRef(!1),le=i.useRef(null),we=i.useRef(null),[pe,De]=i.useState(null),[z,he]=i.useState(null),[Z,de]=i.useState(""),[Ee,ne]=i.useState(!1),[ye,te]=i.useState(null),[ce,X]=i.useState(!1),[U,Y]=i.useState(!1),se=!!t.writeFile,me=!!t.createDirectory,ze=!!t.rename,qe=!!t.delete,tt=i.useCallback((Pe,He)=>{De(Pe),he(He),de(Pe==="rename"&&He.name||""),ne(!1)},[]),[Xe,Nt]=i.useState(null),[Ne,ue]=i.useState(""),We=i.useRef(!1),ve=i.useRef(null),ke=ge(Pe=>Pe.sendMessage),Ze=ge(Pe=>Pe.currentSessionId),{currentProviderId:ct,currentModelId:Ue,currentAgentName:Be,currentVariant:Ve}=et(),dt=nt(Pe=>Pe.getSessionAgentSelection),pt=nt(Pe=>Pe.getAgentModelForSession),Ge=nt(Pe=>Pe.getAgentModelVariantForSession),ut=je(Pe=>Pe.setActiveMainTab),xt=je(Pe=>Pe.setMainTabGuard),{inputBarOffset:kt,isKeyboardOpen:At}=je();i.useEffect(()=>{const Pe=()=>{We.current=!1,ve.current=null};return document.addEventListener("mouseup",Pe),()=>document.removeEventListener("mouseup",Pe)},[]),i.useEffect(()=>{Nt(null),ue(""),xt(null),ae(""),q(!1)},[A?.path,xt]),i.useEffect(()=>()=>{le.current!==null&&window.clearTimeout(le.current),we.current!==null&&window.clearTimeout(we.current)},[]),i.useEffect(()=>{if(!Xe)return;const Pe=it=>{const re=it.target;document.querySelector("[data-comment-ui]")?.contains(re)||re.closest(".cm-gutterElement")||re.closest("[data-sonner-toast]")||re.closest("[data-sonner-toaster]")||(Nt(null),ue(""))},He=setTimeout(()=>{document.addEventListener("click",Pe)},100);return()=>{clearTimeout(He),document.removeEventListener("click",Pe)}},[Xe]);const Xt=i.useCallback((Pe,He)=>{const it=Pe.split(`
218
- `),re=Math.max(1,He.start),Ae=Math.min(it.length,He.end);return re>Ae?"":it.slice(re-1,Ae).join(`
219
- `)},[]),as=i.useCallback(async()=>{if(!Xe||!Ne.trim()||!A)return;if(!Ze){W.error("Select a session to send comment");return}const Pe=dt(Ze)||Be,He=Pe?pt(Ze,Pe):null,it=He?.providerId||ct,re=He?.modelId||Ue;if(!it||!re){W.error("Select a model to send comment");return}const Ae=Pe&&it&&re?Ge(Ze,Pe,it,re)??Ve:Ve,be=Xt(I,Xe),Qe=Cr(A.path)||"text",at=A.name,yt=Xe.start,J=Xe.end,Fe=`Comment on \`${at}\` lines ${yt}-${J}:
220
- \`\`\`${Qe}
221
- ${be}
222
- \`\`\`
223
-
224
- ${Ne}`;ue(""),Nt(null),ut("chat"),ke(Fe,it,re,Pe,void 0,void 0,void 0,Ae).catch(Ce=>{console.error("Failed to send comment",Ce)})},[Xe,Ne,A,I,Ze,ct,Ue,Be,Ve,Xt,ke,ut,dt,pt,Ge]),_t=i.useCallback((Pe,He)=>{const it=He.filter(re=>re&&typeof re.name=="string"&&re.name.length>0).filter(re=>a||!re.name.startsWith(".")).filter(re=>l||!fN(re.name)).map(re=>{const Ae=re.name,be=or(re.path||`${Pe}/${Ae}`),Qe=re.isDirectory?"directory":"file",at=Qe==="file"&&Ae.includes(".")?Ae.split(".").pop()?.toLowerCase():void 0;return{name:Ae,path:be,type:Qe,extension:at}});return uN(it)},[l,a]),Mt=i.useCallback(async Pe=>{const He=or(Pe.trim());if(He&&!(j.current.has(He)||M.current.has(He))){M.current=new Set(M.current),M.current.add(He);try{const it=!l;let re;r.isDesktop?re=(await t.listDirectory(He,{respectGitignore:it})).entries.map(Qe=>({name:Qe.name,path:Qe.path,isDirectory:Qe.isDirectory})):re=(await Oe.listLocalDirectory(He,{respectGitignore:it})).map(Qe=>({name:Qe.name,path:Qe.path,isDirectory:Qe.isDirectory}));const Ae=_t(He,re);j.current=new Set(j.current),j.current.add(He),v(be=>({...be,[He]:Ae}))}catch{v(it=>({...it,[He]:it[He]??[]}))}finally{M.current=new Set(M.current),M.current.delete(He)}}},[t,_t,r.isDesktop,l]),Rt=i.useCallback(async()=>{const Pe=or(c.trim());Pe&&(j.current=new Set,M.current=new Set,S(new Set),v({}),await Mt(Pe))},[c,Mt]);i.useEffect(()=>{c&&(Rt(),E(null),P(""),ie(null),ee(""),g(!1))},[c,Rt]),i.useEffect(()=>{c&&Rt()},[c,Rt,l]);const Jt=i.useCallback(async Pe=>{if(Pe?.preventDefault(),!(!z||!pe)){ne(!0);try{if(pe==="createFile"){if(!Z.trim())throw new Error("Filename is required");const He=z.path,it=He?`${He}/`:"",re=or(`${it}${Z.trim()}`);if(!t.writeFile)throw new Error("Write not supported");(await t.writeFile(re,"")).success&&(W.success("File created"),await Rt())}else if(pe==="createFolder"){if(!Z.trim())throw new Error("Folder name is required");const He=z.path,it=He?`${He}/`:"",re=or(`${it}${Z.trim()}`);(await t.createDirectory(re)).success&&(W.success("Folder created"),await Rt())}else if(pe==="rename"){if(!Z.trim())throw new Error("Name is required");const He=z.path,it=He.split("/").slice(0,-1).join("/"),re=it?`${it}/`:"",Ae=or(`${re}${Z.trim()}`);t.rename?(await t.rename(He,Ae)).success&&(W.success("Renamed successfully"),await Rt(),A?.path===He&&E(null)):W.error("Rename not supported")}else pe==="delete"&&(t.delete?(await t.delete(z.path)).success&&(W.success("Deleted successfully"),await Rt(),(A?.path===z.path||A?.path.startsWith(z.path+"/"))&&(E(null),P(""))):W.error("Delete not supported"));De(null)}catch(He){W.error(He instanceof Error?He.message:"Operation failed")}finally{ne(!1)}}},[pe,z,Z,t,Rt,A]),Ft=i.useCallback((Pe,He)=>{const it=Pe.trim().toLowerCase();if(!it)return 0;const re=He.toLowerCase();let Ae=0,be=-1,Qe=0;for(let at=0;at<it.length;at+=1){const yt=it[at];if(!yt||yt===" ")continue;const J=re.indexOf(yt,be+1);if(J===-1)return null;const Fe=J-be-1;if(Fe===0?Qe+=1:Qe=0,Ae+=10,Ae+=Math.max(0,18-J),Ae-=Math.max(0,Fe),J===0)Ae+=12;else{const Ce=re[J-1];(Ce==="/"||Ce==="_"||Ce==="-"||Ce==="."||Ce===" ")&&(Ae+=10)}Ae+=Qe>0?12:0,be=J}return Ae+=Math.max(0,24-Math.round(re.length/3)),Ae},[]);i.useEffect(()=>{c&&Rt()},[c,Rt,l]),i.useEffect(()=>{if(!c){D([]),T(!1);return}const Pe=p.trim();if(!Pe){D([]),T(!1);return}const He=Pe.toLowerCase();let it=!1;return T(!0),u(c,Pe,150,{includeHidden:a,respectGitignore:!l}).then(re=>{if(it)return;const be=re.filter(at=>l||!pN(at.path)).map(at=>{const yt=at.relativePath||at.name||at.path,J=Ft(He,yt);return J===null?null:{hit:at,score:J,labelLength:yt.length}}).filter(Boolean);be.sort((at,yt)=>yt.score-at.score||at.labelLength-yt.labelLength||at.hit.path.localeCompare(yt.hit.path));const Qe=be.map(({hit:at})=>({name:at.name,path:or(at.path),type:"file",extension:at.extension,relativePath:at.relativePath}));D(Qe)}).catch(()=>{it||D([])}).finally(()=>{it||T(!1)}),()=>{it=!0}},[c,p,Ft,u,a,l]);const Qt=i.useCallback(async Pe=>{if(t.readFile)return(await t.readFile(Pe)).content??"";const He=await fetch(`/api/fs/read?path=${encodeURIComponent(Pe)}`);if(!He.ok){const it=await He.json().catch(()=>({error:He.statusText}));throw new Error(it.error||"Failed to read file")}return He.text()},[t]),ps=i.useMemo(()=>I.length>yo?`${I.slice(0,yo)}
225
-
226
- … truncated …`:I,[I]),Lt=i.useMemo(()=>V!==ps,[V,ps]),Me=i.useCallback(async()=>{if(!A||!t.writeFile){W.error("Saving not supported");return}if(Lt){q(!0);try{if(!(await t.writeFile(A.path,V))?.success)throw new Error("Failed to write file");P(V)}catch(Pe){W.error(Pe instanceof Error?Pe.message:"Save failed")}finally{q(!1)}}},[V,t,Lt,A]);i.useEffect(()=>{if(!Lt){xt(null);return}const Pe=He=>O.current?(O.current=!1,!0):(H(!0),B.current=He,!1);return xt(Pe),()=>{je.getState().mainTabGuard===Pe&&xt(null)}},[Lt,xt]),i.useEffect(()=>{const Pe=He=>{$s(He)&&He.key.toLowerCase()==="s"&&(He.preventDefault(),G||Me())};return window.addEventListener("keydown",Pe),()=>window.removeEventListener("keydown",Pe)},[G,Me]);const $e=i.useCallback(async Pe=>{if(O.current)O.current=!1;else if(Lt){H(!0),L.current=Pe;return}E(Pe),ie(null),ee("");const He=Po(Pe.path);n&&g(!0);const it=Pe.path.toLowerCase().endsWith(".svg");if(r.isDesktop&&He&&!it){P(""),$(!0);return}if(!r.isDesktop&&He&&!it){P(""),$(!1);return}$(!0);try{const re=await Qt(Pe.path);P(re),ae(re.length>yo?`${re.slice(0,yo)}
227
-
228
- … truncated …`:re)}catch(re){P(""),ae(""),ie(re instanceof Error?re.message:"Failed to read file")}finally{$(!1)}},[Lt,n,Qt,r.isDesktop]),Le=i.useCallback(()=>{const Pe=L.current,He=B.current;if(L.current=null,B.current=null,O.current=!0,H(!1),ae(ps),Pe){$e(Pe);return}He&&(xt(null),je.getState().setActiveMainTab(He))},[ps,$e,xt]),ot=i.useCallback(async()=>{const Pe=L.current,He=B.current;if(L.current=null,B.current=null,O.current=!0,H(!1),await Me(),Pe){await $e(Pe);return}He&&(xt(null),je.getState().setActiveMainTab(He))},[$e,Me,xt]),oe=i.useCallback(async Pe=>{const He=or(Pe);S(it=>{const re=new Set(it);return re.has(He)?re.delete(He):re.add(He),re}),j.current.has(He)||await Mt(He)},[Mt]),Te=i.useCallback((Pe,He)=>{const it=C[Pe]??[];return it.map((re,Ae)=>{const be=re.type==="directory",Qe=be&&w.has(re.path),at=A?.path===re.path,yt=be&&M.current.has(re.path),J=Ae===it.length-1;return e.jsxs("li",{className:"relative",children:[He>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),J&&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:Fe=>{!ze&&!se&&!me&&!qe||(Fe.preventDefault(),te(re.path))},children:[e.jsxs("button",{type:"button",onClick:()=>{be?oe(re.path):$e(re)},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",at?"bg-accent/70":"hover:bg-accent/40"),children:[be?yt?e.jsx(Tt,{className:"h-4 w-4 flex-shrink-0 animate-spin"}):Qe?e.jsx(wx,{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"}):Pu(re.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:re.path,children:re.name})]}),(ze||se||me||qe)&&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(es,{open:ye===re.path,onOpenChange:Fe=>te(Fe?re.path:null),children:[e.jsx(ts,{asChild:!0,children:e.jsx(Se,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(jx,{className:"h-4 w-4"})})}),e.jsxs(ss,{align:"end",onCloseAutoFocus:()=>te(null),children:[ze&&e.jsxs(Ct,{onClick:Fe=>{Fe.stopPropagation(),tt("rename",re)},children:[e.jsx(ao,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(Ct,{onClick:Fe=>{Fe.stopPropagation(),navigator.clipboard.writeText(re.path),W.success("Path copied")},children:[e.jsx(sr,{className:"mr-2 h-4 w-4"})," Copy Path"]}),be&&(se||me)&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),se&&e.jsxs(Ct,{onClick:Fe=>{Fe.stopPropagation(),tt("createFile",re)},children:[e.jsx(Fc,{className:"mr-2 h-4 w-4"})," New File"]}),me&&e.jsxs(Ct,{onClick:Fe=>{Fe.stopPropagation(),tt("createFolder",re)},children:[e.jsx(nl,{className:"mr-2 h-4 w-4"})," New Folder"]})]}),qe&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),e.jsxs(Ct,{onClick:Fe=>{Fe.stopPropagation(),tt("delete",re)},className:"text-destructive focus:text-destructive",children:[e.jsx(Ks,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]})})]}),be&&Qe&&e.jsx("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:Te(re.path,He+1)})]},re.path)})},[C,w,$e,A?.path,oe,tt,se,me,ze,qe,ye,te]),Ie=!!(A?.path&&Po(A.path)),fe=!!(A?.path&&A.path.toLowerCase().endsWith(".svg")),xe=i.useMemo(()=>{if(!A?.path)return"";const Pe=or(A.path);if(d&&Pe.startsWith(d)){const He=Pe.slice(d.length);return He.startsWith("/")?He.slice(1):He}return Pe},[A?.path,d]),Re=!!(A&&(!Ie||fe)&&I.length>0),st=!!(A&&xe.length>0),mt=!!(A&&!Ie&&t.writeFile&&I.length<=yo),Ot=i.useMemo(()=>{if(!A?.path)return[Al(s)];const Pe=[Al(s)],He=Ep(A.path);return He&&Pe.push(He),b&&Pe.push(dn.lineWrapping),Pe},[s,A?.path,b]),Bt=A?.path&&Ie?r.isDesktop?fe?`data:${yl(A.path)};utf8,${encodeURIComponent(I)}`:K:fe?`data:${yl(A.path)};utf8,${encodeURIComponent(I)}`:`/api/fs/raw?path=${encodeURIComponent(A.path)}`:"";i.useEffect(()=>{let Pe=!1;return(async()=>{if(!r.isDesktop||!A?.path||!Ie||fe){ee("");return}ie(null);try{if(t.readFileBinary){const be=await t.readFileBinary(A.path);Pe||ee(be.dataUrl);return}const re=(await Ss(()=>import("./vendor-.bun-koHRsLHN.js").then(be=>be.dg),__vite__mapDeps([0,1]))).convertFileSrc;if(!re)return;const Ae=re(A.path,"asset");Pe||ee(Ae)}catch(it){Pe||(ee(""),ie(it instanceof Error?it.message:"Failed to read file"))}finally{Pe||$(!1)}})(),()=>{Pe=!0}},[t,Ie,fe,r.isDesktop,A?.path]);const Ms=()=>e.jsx(us,{open:!!pe,onOpenChange:Pe=>!Pe&&De(null),children:e.jsxs(ms,{children:[e.jsxs(xs,{children:[e.jsxs(ys,{children:[pe==="createFile"&&"Create File",pe==="createFolder"&&"Create Folder",pe==="rename"&&"Rename",pe==="delete"&&"Delete"]}),e.jsxs(Ns,{children:[pe==="createFile"&&`Create a new file in ${z?.path??"root"}`,pe==="createFolder"&&`Create a new folder in ${z?.path??"root"}`,pe==="rename"&&`Rename ${z?.name}`,pe==="delete"&&`Are you sure you want to delete ${z?.name}? This action cannot be undone.`]})]}),pe!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(St,{value:Z,onChange:Pe=>de(Pe.target.value),placeholder:pe==="rename"?"New name":"Name",onKeyDown:Pe=>{Pe.key==="Enter"&&Jt()},autoFocus:!0})}),e.jsxs(Vs,{children:[e.jsx(Se,{variant:"outline",onClick:()=>De(null),disabled:Ee,children:"Cancel"}),e.jsx(Se,{variant:pe==="delete"?"destructive":"default",onClick:()=>{Jt()},disabled:Ee||pe!=="delete"&&!Z.trim(),children:Ee?e.jsx(Tt,{className:"animate-spin"}):pe==="delete"?"Delete":"Confirm"})]})]})}),vs=()=>!Xe||!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(Rs,{value:Ne,onChange:Pe=>{ue(Pe.target.value);const He=Pe.target;He.style.height="auto";const re=20*5+8;He.style.height=`${Math.min(He.scrollHeight,re)}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:Pe=>{Pe.key==="Enter"&&(Pe.metaKey||Pe.ctrlKey)&&(Pe.preventDefault(),as()),Pe.key==="Escape"&&(Pe.preventDefault(),Nt(null),ue(""))}}),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,":",Xe.start,"-",Xe.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!n&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Zt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:Pe=>{Ne.trim()&&(Pe.preventDefault(),as())},onClick:()=>{n||as()},disabled:!Ne.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",Ne.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Fo,{className:"h-[18px] w-[18px]"})})]})]})]})}),It=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:_,onOpenChange:Pe=>{Pe||H(!0)},children:e.jsxs(ms,{showCloseButton:!1,className:"max-w-md",children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Unsaved changes"}),e.jsx(Ns,{children:"Save your edits before continuing?"})]}),e.jsxs(Vs,{children:[e.jsx(Se,{variant:"outline",onClick:()=>{ot()},disabled:G,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:Le,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&&x&&e.jsx("button",{type:"button",onClick:()=>g(!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(Ll,{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:xe,children:xe})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[mt&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>{Me()},disabled:!Lt||G,className:"h-5 w-5 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Zt()}+S)`,"aria-label":`Save (${Zt()}+S)`,children:G?e.jsx(Tt,{className:"h-4 w-4 animate-spin"}):e.jsx(Sx,{className:"h-4 w-4"})}),mt&&A&&!Ie&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),A&&!Ie&&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(hm,{className:"size-4"})}),(Re||st)&&(mt||A&&!Ie)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),Re&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(I),X(!0),le.current!==null&&window.clearTimeout(le.current),le.current=window.setTimeout(()=>{X(!1)},1200)}catch{W.error("Copy failed")}},className:"h-5 w-5 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:ce?e.jsx($t,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx($l,{className:"h-4 w-4"})}),st&&e.jsx(Se,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(xe),Y(!0),we.current!==null&&window.clearTimeout(we.current),we.current=window.setTimeout(()=>{Y(!1)},1200)}catch{W.error("Copy failed")}},className:"h-5 w-5 p-0",title:`Copy file path (${xe})`,"aria-label":`Copy file path (${xe})`,children:U?e.jsx($t,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Lm,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(jt,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:A?F?e.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Tt,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):Q?e.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:Q}):Ie?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("img",{src:Bt,alt:A?.name??"Image",className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"})}):e.jsx("div",{className:"h-full",children:e.jsx(Dp,{value:V,onChange:ae,extensions:Ot,className:"h-full",highlightLines:Xe?{start:Math.min(Xe.start,Xe.end),end:Math.max(Xe.start,Xe.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(Pe,He,it)=>{if(!(it instanceof MouseEvent)||it.button!==0)return!1;it.preventDefault();const re=Pe.state.doc.lineAt(He.from).number;if(n&&Xe&&!it.shiftKey){const Ae=Math.min(Xe.start,Xe.end,re),be=Math.max(Xe.start,Xe.end,re);return Nt({start:Ae,end:be}),We.current=!1,ve.current=null,!0}if(We.current=!0,ve.current=re,Xe&&it.shiftKey){const Ae=Math.min(Xe.start,re),be=Math.max(Xe.end,re);Nt({start:Ae,end:be})}else Nt({start:re,end:re});return!0},mouseover:(Pe,He,it)=>{if(!(it instanceof MouseEvent)||it.buttons!==1||!We.current||ve.current===null)return!1;const re=Pe.state.doc.lineAt(He.from).number,Ae=Math.min(ve.current,re),be=Math.max(ve.current,re);return Nt({start:Ae,end:be}),!1},mouseup:()=>(We.current=!1,ve.current=null,!1)}}})}):e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}),Xe&&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&&At?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:n&&!At&&kt>0?`${kt}px`:"16px"},"data-keyboard-avoid":"true",children:vs()})})]}),zt=!!(d&&C[d]),ns=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(Us,{className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(St,{ref:h,value:m,onChange:Pe=>f(Pe.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(os,{className:"h-4 w-4"})})]}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>tt("createFile",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File",children:e.jsx(Fc,{className:"h-4 w-4"})}),e.jsx(Se,{variant:"ghost",size:"sm",onClick:()=>tt("createFolder",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder",children:e.jsx(nl,{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(Qr,{className:"h-4 w-4"})})]})}),e.jsx(jt,{outerClassName:"flex-1 min-h-0",className:R("py-2",n?"px-3":"px-2"),children:e.jsx("ul",{className:"flex flex-col",children:N?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(Tt,{className:"h-4 w-4 animate-spin"}),"Searching…"]}):k.length>0?k.map(Pe=>{const He=A?.path===Pe.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{$e(Pe)},className:R("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",He?"bg-accent/70":"hover:bg-accent/40"),children:[Pu(Pe.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:Pe.path,children:Pe.relativePath??Pe.path})]})},Pe.path)}):zt?Te(d,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading…"})})})]});return e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background",children:[Ms(),n?x?It:ns: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:ns}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:It})]})]})},_p=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:_l},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Nr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:Dn},{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:Xn},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:qt},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:wn}],vN={},jN={},SN={};_p.forEach(t=>{vN[t.id]=t.label,jN[t.id]=t.description,SN[t.id]=t});const NN=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},kN=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())},Tu=t=>{const r=kN(NN(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 l=Object.keys(a);if(l.length===1&&l[0]==="*"){n[o]=a["*"];continue}n[o]=a}return Object.keys(n).length>0?n:void 0},CN=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedAgentName:a,agents:l,setSelectedAgent:c,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=sn(),{setSidebarOpen:p}=je(),{isMobile:h}=Kt(),[x,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=x?"bg-transparent":b?"bg-background":"bg-sidebar",w=()=>{const A="new-agent";let E=A,I=1;for(;l.some(P=>P.name===E);)E=`${A}-${I}`,I++;d({name:E,scope:"user"}),c(E),t?.(),h&&p(!1)},S=async A=>{if(un(A)){W.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${A.name}"?`)&&(await m(A.name)?W.success(`Agent "${A.name}" deleted successfully`):W.error("Failed to delete agent"))},C=async A=>{un(A)&&window.confirm(`Are you sure you want to reset agent "${A.name}" to its default configuration?`)&&(await m(A.name)?W.success(`Agent "${A.name}" reset to default`):W.error("Failed to reset agent"))},v=A=>{const E=A.name;let I=1,P=`${E}-copy`;for(;l.some(ie=>ie.name===P);)I++,P=`${E}-copy-${I}`;const F=A,$=A.model?.providerID&&A.model?.modelID?`${A.model.providerID}/${A.model.modelID}`:null,Q=A;d({name:P,scope:F.scope||"user",description:A.description,model:$,temperature:A.temperature,top_p:A.topP,prompt:A.prompt,mode:A.mode,permission:Tu(A.permission),disable:Q.disable}),c(P),h&&p(!1)},j=A=>{o(A.name),s(A)},M=async()=>{if(!r)return;const A=n.trim().replace(/\s+/g,"-");if(!A){W.error("Agent name is required");return}if(A===r.name){s(null);return}if(l.some(F=>F.name===A)){W.error("An agent with this name already exists");return}const E=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,I=r;await u({name:A,description:r.description,model:E,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:Tu(r.permission),disable:I.disable,scope:I.scope})?await m(r.name)?(W.success(`Agent renamed to "${A}"`),c(A)):W.error("Failed to remove old agent after rename"):W.error("Failed to rename agent"),s(null)},k=A=>{switch(A){case"primary":return e.jsx(jn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Bm,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(_m,{className:"h-3 w-3 text-primary"});default:return null}},D=l.filter(A=>!lf(A)),N=D.filter(un),T=D.filter(A=>!un(A));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 ",D.length]}),e.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(cs,{className:"size-4"})})]})}),e.jsx(jt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:D.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Mo,{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:[N.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"}),N.map(A=>e.jsx(Fu,{agent:A,isSelected:a===A.name,onSelect:()=>{c(A.name),t?.(),h&&p(!1)},onReset:()=>C(A),onDuplicate:()=>v(A),getAgentModeIcon:k},A.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(A=>e.jsx(Fu,{agent:A,isSelected:a===A.name,onSelect:()=>{c(A.name),t?.(),h&&p(!1)},onRename:()=>j(A),onDelete:()=>S(A),onDuplicate:()=>v(A),getAgentModeIcon:k},A.name))]})]})}),e.jsx(us,{open:r!==null,onOpenChange:A=>!A&&s(null),children:e.jsxs(ms,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Agent"}),e.jsxs(Ns,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(St,{value:n,onChange:A=>o(A.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:A=>{A.key==="Enter"&&M()}}),e.jsxs(Vs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cn,{onClick:M,children:"Rename"})]})]})})]})},Fu=({agent:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:l,getAgentModeIcon:c})=>{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}),c(t.mode),(d.scope||un(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:un(t)?"system":d.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(es,{children:[e.jsx(ts,{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(Zr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Ct,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(ao,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Ct,{onClick:u=>{u.stopPropagation(),l()},children:[e.jsx(sr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Ct,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Ct,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ks,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Fs({className:t,variant:r,...s}){return e.jsx(Se,{variant:r,size:"sm",className:R("h-6 px-2 text-xs",t),...s})}const MN=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),DN=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=MN.format(t);return r.endsWith(".0")?r.slice(0,-2):r},vc=({providerId:t,modelId:r,onChange:s,className:n,allowedProviderIds:o})=>{const{providers:a,modelsMetadata:l}=et(),c=je(G=>G.isMobile),{toggleFavoriteModel:d,isFavoriteModel:u,addRecentModel:m}=je(),{favoriteModelsList:f,recentModelsList:p}=hc(),{isMobile:h}=Kt(),x=c||h,[g,b]=i.useState(!1),[y,w]=i.useState(new Set),[S,C]=i.useState(!1),[v,j]=i.useState(""),[M,k]=i.useState(0),D=i.useRef([]),N=i.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),T=i.useMemo(()=>N?a.filter(G=>N.has(String(G.id))):a,[a,N]),A=()=>b(!1),E=G=>{w(q=>{const _=new Set(q);return _.has(G)?_.delete(G):_.add(G),_})};i.useEffect(()=>{S||(j(""),k(0))},[S]),i.useEffect(()=>{k(0)},[v]);const I=G=>{const q=G?.name||G?.id||"",_=String(q);return _.length>40?_.substring(0,37)+"...":_},P=(G,q)=>{const _=`${G}/${q}`;return l.get(_)},F=(G,q)=>{s(G,q),G&&q&&m(G,q),C(!1)},$=(G,q)=>{if(!v.trim())return!0;const _=v.toLowerCase();return G.toLowerCase().includes(_)||q.toLowerCase().includes(_)},Q=(G,q,_,H,L,B)=>{const O=P(q,_),le=DN(O?.limit?.context),we=t===q&&r===_,pe=u(q,_),De=H==="fav"||H==="recent";return e.jsxs("div",{ref:z=>{D.current[L]=z},className:R("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",B?"bg-accent":"hover:bg-accent/50"),onClick:()=>F(q,_),onMouseEnter:()=>k(L),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[De&&e.jsx(gs,{providerId:q,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:I(G)}),le?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:le}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[we&&e.jsx($t,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:z=>{z.preventDefault(),z.stopPropagation(),d(q,_)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",pe?"text-yellow-500":"text-muted-foreground"),"aria-label":pe?"Unfavorite":"Favorite",title:pe?"Remove from favorites":"Add to favorites",children:pe?e.jsx(Ir,{className:"h-3.5 w-3.5"}):e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]},`${H}-${q}-${_}`)},ie=f.filter(({model:G,providerID:q})=>{if(N&&!N.has(q))return!1;const H=a.find(B=>B.id===q)?.name||q,L=I(G);return $(L,H)}),K=p.filter(({model:G,providerID:q})=>{if(N&&!N.has(q))return!1;const H=a.find(B=>B.id===q)?.name||q,L=I(G);return $(L,H)}),ee=T.map(G=>{const _=(Array.isArray(G.models)?G.models:[]).filter(H=>{const L=I(H);return $(L,G.name||G.id||"")});return{...G,models:_}}).filter(G=>G.models.length>0),V=ie.length>0||K.length>0||ee.length>0,ae=()=>x?e.jsx(zs,{open:g,onClose:A,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:G,providerID:q,modelID:_})=>{const H=q===t&&_===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",H?"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(q,_),A()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{providerId:q,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:I(G)})]})}),e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),d(q,_)},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(Ir,{className:"h-4 w-4"})})]},`fav-mobile-${q}-${_}`)})})]}),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:G,providerID:q,modelID:_})=>{const H=q===t&&_===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",H?"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(q,_),A()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{providerId:q,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:I(G)})]})}),e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),d(q,_)},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(Un,{className:"h-4 w-4"})})]},`recent-mobile-${q}-${_}`)})})]}),T.map(G=>{const q=Array.isArray(G.models)?G.models:[];if(q.length===0)return null;const _=G.id===t,H=y.has(G.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:()=>E(G.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{providerId:G.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:G.name}),_&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),H?e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Hs,{className:"h-3 w-3 text-muted-foreground"})]}),H&&e.jsx("div",{className:"border-t border-border/20",children:q.map(L=>{const B=G.id===t&&L.id===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",B?"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(G.id,L.id),A()},children:e.jsx("span",{className:"font-medium truncate",children:I(L)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),d(G.id,L.id)},className:R("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",u(G.id,L.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":u(G.id,L.id)?"Unfavorite":"Favorite",children:u(G.id,L.id)?e.jsx(Ir,{className:"h-4 w-4"}):e.jsx(Un,{className:"h-4 w-4"})}),B&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},L.id)})})]},G.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("",""),A()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[x?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(Er,{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(Gt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(es,{open:S,onOpenChange:C,children:[e.jsx(ts,{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(Er,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Er,{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(Gt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(ss,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const G=[];ie.forEach(({model:L,providerID:B,modelID:O})=>{G.push({model:L,providerID:B,modelID:O,section:"fav"})}),K.forEach(({model:L,providerID:B,modelID:O})=>{G.push({model:L,providerID:B,modelID:O,section:"recent"})}),ee.forEach(L=>{L.models.forEach(B=>{G.push({model:B,providerID:L.id,modelID:B.id,section:"provider"})})});const q=G.length,_=L=>{if(L.key==="ArrowDown"){L.preventDefault(),L.stopPropagation();const B=(M+1)%Math.max(1,q);k(B),setTimeout(()=>{D.current[B]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(L.key==="ArrowUp"){L.preventDefault(),L.stopPropagation();const B=(M-1+Math.max(1,q))%Math.max(1,q);k(B),setTimeout(()=>{D.current[B]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(L.key==="Enter"){L.preventDefault(),L.stopPropagation();const B=G[M];B&&F(B.providerID,B.modelID)}else L.key==="Escape"&&(L.preventDefault(),L.stopPropagation(),C(!1))};let H=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(Us,{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:v,onChange:L=>j(L.target.value),onKeyDown:_,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(jt,{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(os,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!t&&!r&&e.jsx($t,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Ds,{}),!V&&v&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),ie.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Ir,{className:"h-4 w-4 text-primary"}),"Favorites"]}),ie.map(({model:L,providerID:B,modelID:O})=>{const le=H++;return Q(L,B,O,"fav",le,M===le)})]}),K.length>0&&e.jsxs(e.Fragment,{children:[ie.length>0&&e.jsx(Ds,{}),e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Sr,{className:"h-4 w-4"}),"Recent"]}),K.map(({model:L,providerID:B,modelID:O})=>{const le=H++;return Q(L,B,O,"recent",le,M===le)})]}),(ie.length>0||K.length>0)&&ee.length>0&&e.jsx(Ds,{}),ee.map((L,B)=>e.jsxs(i.Fragment,{children:[B>0&&e.jsx(Ds,{}),e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(gs,{providerId:L.id,className:"h-4 w-4 flex-shrink-0"}),L.name]}),L.models.map(O=>{const le=H++;return Q(O,L.id,O.id,"provider",le,M===le)})]},L.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"})]})})()})]}),ae()]})},Ru=["*","read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop","question","plan_enter","plan_exit"],Ma=t=>t==="allow"||t==="ask"||t==="deny",cn=(t,r)=>`${t}::${r}`,Mn=t=>{const r=new Map;for(const s of t)!s.permission||s.permission==="invalid"||s.pattern&&Ma(s.action)&&r.set(cn(s.permission,s.pattern),{permission:s.permission,pattern:s.pattern,action:s.action});return Array.from(r.values())},la=t=>{const r=new Map;for(const s of Mn(t))r.set(cn(s.permission,s.pattern),s);return r},Lu=t=>[...t].sort((r,s)=>{const n=r.permission.localeCompare(s.permission);return n!==0?n:r.pattern.localeCompare(s.pattern)}),AN=(t,r)=>{const s=Lu(Mn(t)),n=Lu(Mn(r));return s.length!==n.length?!1:s.every((o,a)=>{const l=n[a];return o.permission===l.permission&&o.pattern===l.pattern&&o.action===l.action})},EN=t=>t.find(s=>s.permission==="*"&&s.pattern==="*")?.action??"allow",IN=(t,r)=>Mn(t).filter(s=>!(s.permission==="*"&&s.pattern==="*")).filter(s=>s.pattern!=="*"||s.action!==r),PN=t=>{if(Ma(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(Ma(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))Ma(a)&&r.push({permission:s,pattern:o,action:a})}return r},TN=(t,r)=>{const s=Mn(r),n={};for(const a of s)(n[a.permission]||={})[a.pattern]=a.action;const o={"*":t};for(const[a,l]of Object.entries(n))if(a!=="*"){if(Object.keys(l).length===1&&l["*"]){o[a]=l["*"];continue}o[a]=l}return o},FN=()=>{const{selectedAgentName:t,getAgentByName:r,createAgent:s,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:l}=sn();et();const c=t?r(t):null,d=!!(a&&a.name===t&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,x]=i.useState(""),[g,b]=i.useState("subagent"),[y,w]=i.useState(""),[S,C]=i.useState(void 0),[v,j]=i.useState(void 0),[M,k]=i.useState(""),[D,N]=i.useState("allow"),[T,A]=i.useState([]),[E,I]=i.useState([]),[P,F]=i.useState(""),[$,Q]=i.useState("*"),[ie,K]=i.useState(!1),[ee,V]=i.useState(!1),ae=i.useRef(null),G=wt(U=>U.currentDirectory??null),[q,_]=i.useState([]),H=Io(U=>U.permissions);i.useEffect(()=>{let U=!1;return(async()=>{const se=await Oe.listToolIds({directory:G});if(U)return;const me=new Set(["write","patch","multiedit"]),ze=se.map(qe=>typeof qe=="string"?qe.trim():"").filter(Boolean).filter(qe=>qe!=="*").filter(qe=>qe!=="invalid").filter(qe=>!me.has(qe));_(Array.from(new Set(ze)).sort((qe,tt)=>qe.localeCompare(tt)))})(),()=>{U=!0}},[G]);const L=i.useMemo(()=>{const U=new Set;for(const Y of o){const se=Mn(Array.isArray(Y.permission)?Y.permission:[]);for(const me of se)me.permission&&me.permission!=="*"&&me.permission!=="invalid"&&U.add(me.permission)}for(const Y of H.values())for(const se of Y){const me=se.permission?.trim();me&&me!=="invalid"&&U.add(me)}for(const Y of q)U.add(Y);return Array.from(U).sort((Y,se)=>Y.localeCompare(se))},[o,H,q]),B=i.useMemo(()=>la(T),[T]),O=i.useMemo(()=>la(E),[E]),le=i.useCallback(U=>O.get(cn(U,"*"))?.action,[O]),we=i.useCallback(U=>E.filter(Y=>Y.permission===U&&Y.pattern!=="*").sort((Y,se)=>Y.pattern.localeCompare(se.pattern)),[E]),pe=i.useMemo(()=>{const U=new Set;for(const Y of Ru)U.add(Y);for(const Y of L)U.add(Y);return Array.from(U).sort((Y,se)=>Y.localeCompare(se))},[L]),De=i.useCallback(U=>{const Y=U==="*"?D:le(U)??D,se=we(U),me=!1,ze=se.reduce((tt,Xe)=>(tt[Xe.action]=(tt[Xe.action]??0)+1,tt),{allow:0,ask:0,deny:0}),qe=["allow","ask","deny"].filter(tt=>ze[tt]>0).map(tt=>`${ze[tt]} ${tt}`).join(", ");return{defaultAction:Y,patternRulesCount:se.length,patternSummary:qe,hasDefaultHint:me}},[we,le,D]),z=i.useMemo(()=>{const U=new Set;for(const Y of Ru)U.add(Y);for(const Y of L)U.add(Y);return Array.from(U).sort((Y,se)=>Y.localeCompare(se))},[L]),he=i.useCallback((U,Y,se)=>{I(me=>{const ze=la(me);return ze.set(cn(U,Y),{permission:U,pattern:Y,action:se}),Array.from(ze.values())})},[]),Z=i.useCallback((U,Y)=>{I(se=>{const me=la(se);return me.delete(cn(U,Y)),Array.from(me.values())})},[]),de=i.useCallback((U,Y)=>{const se=B.get(cn(U,Y));if(se){he(U,Y,se.action);return}Z(U,Y)},[B,Z,he]),Ee=i.useCallback((U,Y,se)=>{he(U,Y,se)},[he]),ne=i.useCallback(U=>{N(U),I(Y=>Y.filter(se=>!(se.pattern==="*"&&se.action===U)))},[]),ye=i.useCallback(U=>{const Y=P.trim();if(!Y){W.error("Permission name is required");return}const se=$.trim()||"*";if(Y==="*"&&se==="*"){ne(U),F(""),Q("*");return}se==="*"&&Y!=="*"&&U===D?Z(Y,"*"):he(Y,se,U),F(""),Q("*")},[D,P,$,Z,ne,he]),te=i.useCallback(U=>U==="*"?"Default":U==="webfetch"?"WebFetch":U==="websearch"?"WebSearch":U==="codesearch"?"CodeSearch":U==="doom_loop"?"Doom Loop":U==="external_directory"?"External Directory":U==="todowrite"?"TodoWrite":U==="todoread"?"TodoRead":U.split(/[_-]+/g).filter(Boolean).map(Y=>Y.charAt(0).toUpperCase()+Y.slice(1)).join(" "),[]);i.useEffect(()=>{F(""),Q("*");const U=Y=>{const se=Mn(Y),me=EN(se),ze=IN(se,me);return N(me),A(ze),I(ze),{global:me,rules:ze}};if(d&&a){const Y=a.name||"",se=a.scope||"user",me=a.description||"",ze=a.mode||"subagent",qe=a.model||"",tt=a.temperature,Xe=a.top_p,Nt=a.prompt||"";m(Y),p(se),x(me),b(ze),w(qe),C(tt),j(Xe),k(Nt);const Ne=PN(a.permission),ue=U(Ne);ae.current={draftName:Y,draftScope:se,description:me,mode:ze,model:qe,temperature:tt,topP:Xe,prompt:Nt,globalPermission:ue.global,permissionRules:ue.rules};return}if(c&&t===c.name){const Y=c.description||"",se=c.mode||"subagent",me=c.model?.providerID&&c.model?.modelID?`${c.model.providerID}/${c.model.modelID}`:"",ze=c.temperature,qe=c.topP,tt=c.prompt||"";x(Y),b(se),w(me),C(ze),j(qe),k(tt);const Xe=U(Array.isArray(c.permission)?c.permission:[]);ae.current={draftName:"",draftScope:"user",description:Y,mode:se,model:me,temperature:ze,topP:qe,prompt:tt,globalPermission:Xe.global,permissionRules:Xe.rules}}},[a,d,c,t]);const ce=i.useMemo(()=>{const U=ae.current;return U?!!(d&&(u!==U.draftName||f!==U.draftScope)||h!==U.description||g!==U.mode||y!==U.model||S!==U.temperature||v!==U.topP||M!==U.prompt||D!==U.globalPermission||!AN(E,U.permissionRules)):!1},[h,u,f,D,d,g,y,E,M,S,v]),X=async()=>{const U=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!U){W.error("Agent name is required");return}if(d&&o.some(Y=>Y.name===U)){W.error("An agent with this name already exists");return}V(!0);try{const Y=y.trim(),se=TN(D,E),me={name:U,description:h.trim()||void 0,mode:g,model:Y===""?null:Y,temperature:S,top_p:v,prompt:M.trim()||void 0,permission:se,scope:d?f:void 0};let ze;d?(ze=await s(me),ze&&l(null)):ze=await n(U,me),ze?W.success(d?"Agent created successfully":"Agent updated successfully"):W.error(d?"Failed to create agent":"Failed to update agent")}catch(Y){console.error("Error saving agent:",Y);const se=Y instanceof Error&&Y.message?Y.message:"An error occurred while saving";W.error(se)}finally{V(!1)}};return t?e.jsx(jt,{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:U=>m(U.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(As,{value:f,onValueChange:U=>p(U),children:[e.jsxs(Es,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(tr,{className:"h-4 w-4"}):e.jsx(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Is,{align:"end",children:[e.jsx(Ht,{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(tr,{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(Ht,{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(pr,{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(Rs,{value:h,onChange:U=>x(U.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(Fs,{variant:g==="primary"?"default":"outline",onClick:()=>b("primary"),className:R("gap-2",g==="primary"?void 0:"text-foreground"),children:[e.jsx(jn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Fs,{variant:g==="subagent"?"default":"outline",onClick:()=>b("subagent"),className:R("gap-2",g==="subagent"?void 0:"text-foreground"),children:[e.jsx(_m,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Fs,{variant:g==="all"?"default":"outline",onClick:()=>b("all"),className:R("gap-2",g==="all"?void 0:"text-foreground"),children:[e.jsx(Bm,{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(vc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(U,Y)=>{w(U&&Y?`${U}/${Y}`:"")}})]}),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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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 Y=Math.max(0,(S!==void 0?S:.7)-.1);C(parseFloat(Y.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(mo,{className:"h-3.5 w-3.5"})}),e.jsx(St,{type:"text",inputMode:"decimal",value:S!==void 0?S:"",onChange:U=>{const Y=U.target.value;if(Y===""){C(void 0);return}const se=parseFloat(Y);!isNaN(se)&&se>=0&&se<=2&&C(se)},onBlur:U=>{const Y=U.target.value;if(Y!==""){const se=parseFloat(Y);if(!isNaN(se)){const me=Math.max(0,Math.min(2,se));C(parseFloat(me.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 Y=Math.min(2,(S!==void 0?S:.7)+.1);C(parseFloat(Y.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(cs,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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 Y=Math.max(0,(v!==void 0?v:.9)-.1);j(parseFloat(Y.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(mo,{className:"h-3.5 w-3.5"})}),e.jsx(St,{type:"text",inputMode:"decimal",value:v!==void 0?v:"",onChange:U=>{const Y=U.target.value;if(Y===""){j(void 0);return}const se=parseFloat(Y);!isNaN(se)&&se>=0&&se<=1&&j(se)},onBlur:U=>{const Y=U.target.value;if(Y!==""){const se=parseFloat(Y);if(!isNaN(se)){const me=Math.max(0,Math.min(1,se));j(parseFloat(me.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 Y=Math.min(1,(v!==void 0?v:.9)+.1);j(parseFloat(Y.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(cs,{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(Rs,{value:M,onChange:U=>k(U.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:()=>K(U=>!U),className:"h-8",children:ie?"Hide":"Edit"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:ie?"Set a global default; tools only saved when different from global.":"Summary shows default actions; edit to manage granular rules."})]}),ie?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:D,onValueChange:U=>ne(U),children:[e.jsx(Es,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:D})}),e.jsxs(Is,{children:[e.jsx(Ht,{value:"allow",className:"pr-2 [&>span:first-child]:hidden",children:"Allow"}),e.jsx(Ht,{value:"ask",className:"pr-2 [&>span:first-child]:hidden",children:"Ask"}),e.jsx(Ht,{value:"deny",className:"pr-2 [&>span:first-child]:hidden",children:"Deny"})]})]})]})}),e.jsx("div",{className:"space-y-6",children:pe.filter(U=>U!=="*").map(U=>{const Y=te(U),{defaultAction:se,patternRulesCount:me,patternSummary:ze}=De(U),qe=le(U),tt=qe??"global",Xe=we(U),Nt=["allow","ask","deny"].filter(Ne=>Ne!==D);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:Y}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:U})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[me>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Global: ",se]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:se}),me>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Patterns: ",ze]}):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:"*"}),qe?e.jsxs(Se,{size:"sm",variant:"outline",onClick:()=>de(U,"*"),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(mo,{className:"h-3 w-3"}),"Revert"]}):null]}),e.jsxs(As,{value:tt,onValueChange:Ne=>{if(Ne==="global"){Z(U,"*");return}he(U,"*",Ne)},children:[e.jsx(Es,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:tt==="global"?"Global":tt})}),e.jsxs(Is,{children:[e.jsx(Ht,{value:"global",className:"pr-2 [&>span:first-child]:hidden",children:"Global"}),Nt.map(Ne=>e.jsx(Ht,{value:Ne,className:"pr-2 [&>span:first-child]:hidden",children:Ne.charAt(0).toUpperCase()+Ne.slice(1)},Ne))]})]})]}),Xe.map(Ne=>{const ue=cn(Ne.permission,Ne.pattern),We=B.get(ue),ve=!We,ke=!!(We&&We.action!==Ne.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:Ne.pattern}),ve?e.jsx("span",{className:"typography-micro text-emerald-500",children:"New"}):null,ke?e.jsx("span",{className:"typography-micro text-amber-500",children:"Modified"}):null,ve?e.jsxs(Se,{size:"sm",variant:"outline",onClick:()=>Z(Ne.permission,Ne.pattern),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(mo,{className:"h-3 w-3"}),"Remove"]}):ke?e.jsxs(Se,{size:"sm",variant:"outline",onClick:()=>de(Ne.permission,Ne.pattern),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(mo,{className:"h-3 w-3"}),"Revert"]}):null]}),e.jsxs(As,{value:Ne.action,onValueChange:Ze=>Ee(Ne.permission,Ne.pattern,Ze),children:[e.jsx(Es,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:Ne.action})}),e.jsxs(Is,{children:[e.jsx(Ht,{value:"allow",className:"pr-2 [&>span:first-child]:hidden",children:"Allow"}),e.jsx(Ht,{value:"ask",className:"pr-2 [&>span:first-child]:hidden",children:"Ask"}),e.jsx(Ht,{value:"deny",className:"pr-2 [&>span:first-child]:hidden",children:"Deny"})]})]})]},ue)})]})]},U)})}),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:te(P)}):e.jsx("span",{className:"text-muted-foreground",children:"Permission…"})}),e.jsx(Is,{children:z.map(U=>e.jsx(Ht,{value:U,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:te(U)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:U})]})},U))})]}),e.jsx(St,{value:$,onChange:U=>Q(U.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:()=>ye("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>ye("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>ye("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:pe.map(U=>{const{defaultAction:Y,patternRulesCount:se,patternSummary:me,hasDefaultHint:ze}=De(U),qe=te(U),tt=ze?`${Y} (env blocked)`:Y;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:qe}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:U})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[se>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Global: ",tt]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:tt}),se>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Patterns: ",me]}):null]})]},U)})}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Se,{size:"sm",variant:"default",onClick:X,disabled:ee||!ce,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Za,{className:"h-3 w-3"}),ee?"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(Mo,{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"})]})})},RN=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedCommandName:a,commands:l,setSelectedCommand:c,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=tn(),{setSidebarOpen:p}=je(),{isMobile:h}=Kt(),[x,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=x?"bg-transparent":b?"bg-background":"bg-sidebar",w=()=>{const N="new-command";let T=N,A=1;for(;l.some(E=>E.name===T);)T=`${N}-${A}`,A++;d({name:T,scope:"user"}),c(T),t?.(),h&&p(!1)},S=async N=>{if(zn(N)){W.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${N.name}"?`)&&(await m(N.name)?W.success(`Command "${N.name}" deleted successfully`):W.error("Failed to delete command"))},C=async N=>{zn(N)&&window.confirm(`Are you sure you want to reset command "${N.name}" to its default configuration?`)&&(await m(N.name)?W.success(`Command "${N.name}" reset to default`):W.error("Failed to reset command"))},v=N=>{const T=N.name;let A=1,E=`${T}-copy`;for(;l.some(I=>I.name===E);)A++,E=`${T}-copy-${A}`;d({name:E,scope:N.scope||"user",description:N.description,template:N.template,agent:N.agent,model:N.model,subtask:N.subtask}),c(E),h&&p(!1)},j=N=>{o(N.name),s(N)},M=async()=>{if(!r)return;const N=n.trim().replace(/\s+/g,"-");if(!N){W.error("Command name is required");return}if(N===r.name){s(null);return}if(l.some(A=>A.name===N)){W.error("A command with this name already exists");return}await u({name:N,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(W.success(`Command renamed to "${N}"`),c(N)):W.error("Failed to remove old command after rename"):W.error("Failed to rename command"),s(null)},k=l.filter(zn),D=l.filter(N=>!zn(N));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 ",l.length]}),e.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(cs,{className:"size-4"})})]})}),e.jsx(jt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Xr,{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((N,T)=>N.name.localeCompare(T.name)).map(N=>e.jsx(Ou,{command:N,isSelected:a===N.name,onSelect:()=>{c(N.name),t?.(),h&&p(!1)},onReset:()=>C(N),onDuplicate:()=>v(N)},N.name))]}),D.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"}),[...D].sort((N,T)=>N.name.localeCompare(T.name)).map(N=>e.jsx(Ou,{command:N,isSelected:a===N.name,onSelect:()=>{c(N.name),t?.(),h&&p(!1)},onRename:()=>j(N),onDelete:()=>S(N),onDuplicate:()=>v(N)},N.name))]})]})}),e.jsx(us,{open:r!==null,onOpenChange:N=>!N&&s(null),children:e.jsxs(ms,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Command"}),e.jsxs(Ns,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(St,{value:n,onChange:N=>o(N.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:N=>{N.key==="Enter"&&M()}}),e.jsxs(Vs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cn,{onClick:M,children:"Rename"})]})]})})]})},Ou=({command:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:l})=>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||zn(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:zn(t)?"system":t.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(es,{children:[e.jsx(ts,{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(Zr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Ct,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(ao,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Ct,{onClick:c=>{c.stopPropagation(),l()},children:[e.jsx(sr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Ct,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Ct,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ks,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),Bp=({agentName:t,onChange:r,className:s})=>{const{loadAgents:n,getVisibleAgents:o}=sn(),a=o(),l=je(x=>x.isMobile),{isMobile:c}=Kt(),d=l||c,[u,m]=i.useState(!1);i.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=x=>{r(x)},h=()=>d?e.jsx(zs,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(x=>{const g=x.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",g?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(x.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:x.name}),x.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:x.description})]}),g&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},x.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(Mo,{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(Gt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(es,{children:[e.jsx(ts,{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(Mo,{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(Gt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(ss,{className:"max-w-[300px]",children:[a.map(x=>e.jsx(Ct,{className:"typography-meta",onSelect:()=>p(x.name),children:e.jsx("span",{className:"font-medium",children:x.name})},x.name)),e.jsx(Ct,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},LN=()=>{const{selectedCommandName:t,getCommandByName:r,createCommand:s,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:l}=tn(),c=t?r(t):null,d=!!(a&&a.name===t&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,x]=i.useState(""),[g,b]=i.useState(""),[y,w]=i.useState(""),[S,C]=i.useState(""),[v,j]=i.useState(!1),[M,k]=i.useState(!1),D=i.useRef(null);i.useEffect(()=>{if(d&&a){const A=a.name||"",E=a.scope||"user",I=a.description||"",P=a.agent||"",F=a.model||"",$=a.template||"",Q=a.subtask||!1;m(A),p(E),x(I),b(P),w(F),C($),j(Q),D.current={draftName:A,draftScope:E,description:I,agent:P,model:F,template:$,subtask:Q}}else if(c){const A=c.description||"",E=c.agent||"",I=c.model||"",P=c.template||"",F=c.subtask||!1;x(A),b(E),w(I),C(P),j(F),D.current={draftName:"",draftScope:"user",description:A,agent:E,model:I,template:P,subtask:F}}},[c,d,t,o,a]);const N=i.useMemo(()=>{const A=D.current;return A?!!(d&&(u!==A.draftName||f!==A.draftScope)||h!==A.description||g!==A.agent||y!==A.model||S!==A.template||v!==A.subtask):!1},[g,h,u,f,d,y,v,S]),T=async()=>{const A=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!A){W.error("Command name is required");return}if(!S.trim()){W.error("Command template is required");return}if(d&&o.some(E=>E.name===A)){W.error("A command with this name already exists");return}k(!0);try{const E=g.trim(),I=y.trim(),P=S.trim(),F={name:A,description:h.trim()||void 0,agent:E===""?null:E,model:I===""?null:I,template:P,subtask:v,scope:d?f:void 0};let $;d?($=await s(F),$&&l(null)):$=await n(A,F),$?W.success(d?"Command created successfully":"Command updated successfully"):W.error(d?"Failed to create command":"Failed to update command")}catch(E){console.error("Error saving command:",E),W.error("An error occurred while saving")}finally{k(!1)}};return t?e.jsx(jt,{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:A=>m(A.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(As,{value:f,onValueChange:A=>p(A),children:[e.jsxs(Es,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(tr,{className:"h-4 w-4"}):e.jsx(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Is,{align:"end",children:[e.jsx(Ht,{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(tr,{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(Ht,{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(pr,{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(Rs,{value:h,onChange:A=>x(A.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(Bp,{agentName:g,onChange:A=>b(A)}),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(vc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(A,E)=>{w(A&&E?`${A}/${E}`:"")}}),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:v,onChange:A=>j(A.target.checked),className:"sr-only"}),e.jsx("div",{className:R("w-5 h-5 rounded border-2 flex items-center justify-center",v?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:v&&e.jsx($t,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(Rs,{value:S,onChange:A=>C(A.target.value),placeholder:`Your command template here...
229
-
230
- Use $ARGUMENTS to reference user input.
231
- Use !\`shell command\` to inject shell output.
232
- 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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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:M||!N,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Za,{className:"h-3 w-3"}),M?"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(Xr,{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"})]})})},ON=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedSkillName:a,skills:l,setSelectedSkill:c,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=ur(),{setSidebarOpen:h}=je(),{isMobile:x}=Kt(),[g,b]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||b(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const w=g?"bg-transparent":y?"bg-background":"bg-sidebar",S=()=>{const N="new-skill";let T=N,A=1;for(;l.some(E=>E.name===T);)T=`${N}-${A}`,A++;d({name:T,scope:"user",description:""}),c(T),t?.(),x&&h(!1)},C=async N=>{window.confirm(`Are you sure you want to delete skill "${N.name}"?`)&&(await m(N.name)?W.success(`Skill "${N.name}" deleted successfully`):W.error("Failed to delete skill"))},v=async N=>{const T=N.name;let A=1,E=`${T}-copy`;for(;l.some(P=>P.name===E);)A++,E=`${T}-copy-${A}`;const I=await p(N.name);if(!I){W.error("Failed to load skill details for duplication");return}d({name:E,scope:N.scope||"user",description:(I.sources.md.fields.includes("description"),""),instructions:""}),c(E),x&&h(!1)},j=N=>{o(N.name),s(N)},M=async()=>{if(!r)return;const N=n.trim().replace(/\s+/g,"-").toLowerCase();if(!N){W.error("Skill name is required");return}if(N===r.name){s(null);return}if(l.some(E=>E.name===N)){W.error("A skill with this name already exists");return}if(!await p(r.name)){W.error("Failed to load skill details"),s(null);return}await u({name:N,description:"Renamed skill",scope:r.scope})?await m(r.name)?(W.success(`Skill renamed to "${N}"`),c(N)):W.error("Failed to remove old skill after rename"):W.error("Failed to rename skill"),s(null)},k=l.filter(N=>N.scope==="project"),D=l.filter(N=>N.scope==="user");return e.jsxs("div",{className:R("flex h-full flex-col",w),children:[e.jsx("div",{className:R("border-b px-3",x?"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 ",l.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(cs,{className:"size-4"})})]})}),e.jsx(jt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(zm,{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(N=>e.jsx($u,{skill:N,isSelected:a===N.name,onSelect:()=>{c(N.name),t?.(),x&&h(!1)},onRename:()=>j(N),onDelete:()=>C(N),onDuplicate:()=>v(N)},N.name))]}),D.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"}),D.map(N=>e.jsx($u,{skill:N,isSelected:a===N.name,onSelect:()=>{c(N.name),t?.(),x&&h(!1)},onRename:()=>j(N),onDelete:()=>C(N),onDuplicate:()=>v(N)},N.name))]})]})}),e.jsx(us,{open:r!==null,onOpenChange:N=>!N&&s(null),children:e.jsxs(ms,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Skill"}),e.jsxs(Ns,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(St,{value:n,onChange:N=>o(N.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:N=>{N.key==="Enter"&&M()}}),e.jsxs(Vs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cn,{onClick:M,children:"Rename"})]})]})})]})},$u=({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(es,{children:[e.jsx(ts,{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(Zr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(Ct,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(ao,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Ct,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(sr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(Ct,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ks,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function zp({tabs:t,value:r,onValueChange:s,className:n,isInteractive:o=!0,animate:a=!0}){const l=i.useRef(null),c=i.useRef(null),d=i.useCallback(()=>{const u=l.current,m=c.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:h}=m,x=Math.max(0,Math.min(100,p/f*100)),g=Math.max(0,Math.min(100,(p+h)/f*100));u.style.clipPath=`inset(0 ${Number(100-g).toFixed(2)}% 0 ${Number(x).toFixed(2)}% round 8px)`},[]);return i.useLayoutEffect(()=>{d()},[d,r,t.length]),i.useEffect(()=>{const u=l.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:l,"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?c: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 $N=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,_N=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},BN=async()=>{try{if(ds())return await $r();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}},zN=({open:t,onOpenChange:r})=>{const{scanRepo:s,loadCatalog:n,isScanning:o}=Lo(),a=ro(N=>N.defaultGitIdentityId),l=ro(N=>N.loadDefaultGitIdentityId),[c,d]=i.useState(""),[u,m]=i.useState(""),[f,p]=i.useState(""),[h,x]=i.useState([]),[g,b]=i.useState(null),[y,w]=i.useState(!1),[S,C]=i.useState([]),[v,j]=i.useState(null);i.useEffect(()=>{t&&(d(""),m(""),p(""),b(null),w(!1),C([]),j(null),l(),(async()=>{const N=await BN(),T=Array.isArray(N?.skillCatalogs)?N?.skillCatalogs:[];x(T||[])})())},[t,l]);const M=i.useMemo(()=>{const N=u.trim(),T=f.trim();return h.some(A=>{const E=(A.source||"").trim(),I=(A.subpath||"").trim();return E===N&&I===T})},[h,u,f]),k=async()=>{const N=u.trim();if(!N){W.error("Repository source is required");return}c.trim()||d(_N(N)),w(!1),b(null);const T=await s({source:N,subpath:f.trim()||void 0,gitIdentityId:v||void 0});if(!T.ok){if(T.error?.kind==="authRequired"){if(Vt()){W.error("Private repositories are not supported in VS Code yet");return}const E=T.error.identities||[];if(C(E),!v&&E.length>0){const I=a&&a!=="global"&&E.some(P=>P.id===a)?a:E[0].id;j(I)}W.error("Authentication required. Select a Git identity and scan again.");return}W.error(T.error?.message||"Failed to scan repository");return}const A=T.items?.length||0;if(b(A),A===0){W.error("No skills found in this repository"),w(!1);return}C([]),w(!0),W.success(`Found ${A} skill(s)`)},D=async()=>{const N=c.trim(),T=u.trim(),A=f.trim();if(!N){W.error("Catalog name is required");return}if(!T){W.error("Repository source is required");return}if(!y){W.error("Scan the repository before adding this catalog");return}if(M){W.error("This catalog already exists");return}const E={id:$N(),label:N,source:T,...A?{subpath:A}:{},...v?{gitIdentityId:v}:{}},I=[...h,E];try{await is({skillCatalogs:I}),x(I),W.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(P){W.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(Ns,{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:c,onChange:N=>d(N.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:N=>{m(N.target.value),w(!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:N=>{p(N.target.value),w(!1),b(null)},placeholder:"e.g. skills"})]}),S.length>0&&!Vt()?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:v||"",onValueChange:N=>j(N),children:[e.jsx(Es,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:S.find(N=>N.id===v)?.name||"Choose identity"})}),e.jsx(Is,{align:"start",children:S.map(N=>e.jsx(Ht,{value:N.id,className:"pr-2 [&>span:first-child]:hidden",children:N.name},N.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,g!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",g," skill(s) found"]}):null,M?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Vs,{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(vm,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Se,{variant:"default",onClick:()=>{D()},disabled:!y||M||!c.trim()||!u.trim(),children:"Add catalog"})]})]})})},HN=({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 l=d=>{const u={};for(const m of s)u[m.skillName]=d;a(u)},c=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(Ns,{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:()=>l("skip"),children:"Skip all"}),e.jsx(Se,{variant:"outline",size:"sm",onClick:()=>l("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(Ht,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Ht,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Vs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Cn,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},WN=({open:t,onOpenChange:r,item:s})=>{const{installSkills:n,isInstalling:o}=Lo(),[a,l]=i.useState("user"),[c,d]=i.useState(!1),[u,m]=i.useState([]),[f,p]=i.useState(null);i.useEffect(()=>{t&&(l("user"),d(!1),m([]),p(null))},[t]);const h=async x=>{const g={skillDir:x.skillDir};s?.clawdhub&&(g.clawdhub={slug:s.clawdhub.slug,version:s.clawdhub.version});const b=await n({source:x.source,subpath:x.subpath,gitIdentityId:s?.gitIdentityId,scope:x.scope,selections:[g],conflictPolicy:"prompt",conflictDecisions:x.conflictDecisions});if(b.ok){W.success("Skill installed successfully"),r(!1);return}if(b.error?.kind==="conflicts"){p({source:x.source,subpath:x.subpath,scope:x.scope,skillDir:x.skillDir}),m(b.error.conflicts),d(!0);return}if(b.error?.kind==="authRequired"){W.error(b.error.message||"Authentication required");return}W.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(Ns,{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(x=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:x},x))})]}):null}),e.jsxs(Vs,{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:x=>l(x),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(tr,{className:"h-4 w-4"}):e.jsx(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Is,{align:"start",children:[e.jsx(Ht,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tr,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Ht,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{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(HN,{open:c,onOpenChange:d,conflicts:u,onConfirm:x=>{f&&(h({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:x}),d(!1))}})]}):null},UN=async()=>{try{if(ds())return await $r();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}},VN=({mode:t,onModeChange:r})=>{const{sources:s,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:l,loadSource:c,loadMoreClawdHub:d,isLoadingCatalog:u,isLoadingSource:m,isLoadingMore:f,loadedSourceIds:p,clawdhubHasMoreBySource:h,lastCatalogError:x}=Lo(),[g,b]=i.useState(""),[y,w]=i.useState(!1),[S,C]=i.useState(!1),[v,j]=i.useState(null),[M,k]=i.useState(!1);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{o&&(p[o]||c(o))},[o,p,c]);const D=i.useMemo(()=>o?n[o]||[]:[],[n,o]),N=i.useMemo(()=>{const F=g.trim().toLowerCase();return F?D.filter($=>{const Q=$.skillName.toLowerCase(),ie=($.description||"").toLowerCase(),K=($.frontmatterName||"").toLowerCase();return Q.includes(F)||ie.includes(F)||K.includes(F)}):D},[D,g]),T=i.useMemo(()=>s.find(F=>F.id===o)||null,[s,o]),A=!!(o&&o.startsWith("custom:")),E=T?.source==="clawdhub:registry"||T?.sourceType==="clawdhub",I=!!(o&&(h[o]??!0)),P=async()=>{if(!(!o||!A)&&window.confirm("Remove this catalog?")){k(!0);try{const F=await UN(),Q=(Array.isArray(F?.skillCatalogs)?F?.skillCatalogs:[]).filter(ie=>ie.id!==o);await is({skillCatalogs:Q}),await l({refresh:!0})}finally{k(!1)}}};return e.jsx(jt,{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(zp,{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(Ht,{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?c(o,{refresh:!0}):l({refresh:!0})},disabled:u||m,className:"gap-2",children:[e.jsx(Qr,{className:"h-4 w-4"}),"Refresh"]}),A?e.jsxs(Se,{type:"button",variant:"outline",onClick:()=>{P()},disabled:M,className:"gap-2",children:[e.jsx(Ks,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Se,{type:"button",variant:"default",onClick:()=>w(!0),className:"gap-2",children:[e.jsx(cs,{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:g,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…":`${N.length} skill(s)`})]}),x?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:x.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:N.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:[N.map(F=>{const $=F.installed?.isInstalled,Q=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}),$?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 (",Q||"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(Yr,{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(Un,{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}`)}),E&&I?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(zN,{open:y,onOpenChange:w}),e.jsx(WN,{open:S,onOpenChange:C,item:v})]})})},GN=()=>{const{selectedSkillName:t,getSkillByName:r,getSkillDetail:s,createSkill:n,updateSkill:o,skills:a,skillDraft:l,setSkillDraft:c,setSelectedSkill:d}=ur(),u=t?r(t):null,m=!!(l&&l.name===t&&!u),f=!!(t&&!u&&!l),[p,h]=i.useState("manual");i.useEffect(()=>{!m&&p!=="manual"&&h("manual")},[m,p]),i.useEffect(()=>{f&&d(null)},[f,d]);const x=m?e.jsx(zp,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[g,b]=i.useState(""),[y,w]=i.useState("user"),[S,C]=i.useState(""),[v,j]=i.useState(""),[M,k]=i.useState([]),[D,N]=i.useState([]),[T,A]=i.useState(!1),[E,I]=i.useState(!1),[P,F]=i.useState(""),[$,Q]=i.useState(""),[ie,K]=i.useState(!1),[ee,V]=i.useState(""),[ae,G]=i.useState(""),[q,_]=i.useState(null),[H,L]=i.useState(!1),[B,O]=i.useState(""),le=m?g.trim()!==""||S.trim()!==""||v.trim()!==""||D.length>0:S!==P||v!==$,we=q?ae!==B:ee.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&l)b(l.name||""),w(l.scope||"user"),C(l.description||""),j(l.instructions||""),F(""),Q(""),k([]),N(l.pendingFiles||[]);else if(t&&u){I(!0);try{const Ee=await s(t);if(Ee){const ne=Ee.sources.md;C(ne.description||""),j(ne.instructions||""),F(ne.description||""),Q(ne.instructions||""),k(ne.supportingFiles||[])}}catch(Ee){console.error("Failed to load skill details:",Ee)}finally{I(!1)}}})()},[u,m,t,a,l,s,p]);const pe=async()=>{const de=m?g.trim().replace(/\s+/g,"-").toLowerCase():t?.trim();if(!de){W.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(de)||de.length>64){W.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!S.trim()){W.error("Description is required");return}if(m&&a.some(Ee=>Ee.name===de)){W.error("A skill with this name already exists");return}A(!0);try{const Ee={name:de,description:S.trim(),instructions:v.trim()||void 0,scope:m?y:void 0,supportingFiles:m&&D.length>0?D:void 0};let ne;m?(ne=await n(Ee),ne&&(c(null),N([]),d(de))):(ne=await o(de,Ee),ne&&(F(S.trim()),Q(v.trim()))),ne?W.success(m?"Skill created successfully":"Skill updated successfully"):W.error(m?"Failed to create skill":"Failed to update skill")}catch(Ee){console.error("Error saving skill:",Ee),W.error("An error occurred while saving")}finally{A(!1)}},De=()=>{_(null),V(""),G(""),O(""),K(!0)},z=async de=>{if(_(de),V(de),m){const ne=D.find(ye=>ye.path===de)?.content||"";G(ne),O(ne),K(!0);return}if(t){L(!0),K(!0);try{const{readSupportingFile:Ee}=ur.getState(),ne=await Ee(t,de);G(ne||""),O(ne||"")}catch{W.error("Failed to load file content"),G(""),O("")}finally{L(!1)}}},he=async()=>{if(!ee.trim()){W.error("File name is required");return}const de=ee.trim(),Ee=q!==null;if(m){if(Ee)N(te=>te.map(ce=>ce.path===q?{path:de,content:ae}:ce)),W.success(`File "${de}" updated`);else{if(D.some(te=>te.path===de)){W.error("A file with this name already exists");return}N(te=>[...te,{path:de,content:ae}]),W.success(`File "${de}" added`)}K(!1),_(null);return}if(!t){W.error("No skill selected");return}const{writeSupportingFile:ne}=ur.getState();if(await ne(t,de,ae)){W.success(Ee?`File "${de}" updated`:`File "${de}" created`),K(!1),_(null);const te=await s(t);te&&k(te.sources.md.supportingFiles||[])}else W.error(Ee?"Failed to update file":"Failed to create file")},Z=async de=>{if(m){N(Ee=>Ee.filter(ne=>ne.path!==de)),W.success(`File "${de}" removed`);return}if(t&&window.confirm(`Are you sure you want to delete "${de}"?`)){const{deleteSupportingFile:Ee}=ur.getState();if(await Ee(t,de)){W.success(`File "${de}" deleted`);const ye=await s(t);ye&&k(ye.sources.md.supportingFiles||[])}else W.error("Failed to delete file")}};return m&&p==="external"?e.jsx(VN,{mode:p,onModeChange:h}):!t&&!l||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(zm,{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"})]})}):E?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(jt,{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?x: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:g,onChange:de=>b(de.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(As,{value:y,onValueChange:de=>w(de),children:[e.jsxs(Es,{className:"!h-9 w-auto gap-1.5",children:[y==="user"?e.jsx(tr,{className:"h-4 w-4"}):e.jsx(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:y})]}),e.jsxs(Is,{align:"end",children:[e.jsx(Ht,{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(tr,{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(Ht,{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(pr,{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(Rs,{value:S,onChange:de=>C(de.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(Rs,{value:v,onChange:de=>j(de.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:De,className:"gap-1.5",children:[e.jsx(cs,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const de=m?D:M;return de.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:de.map(Ee=>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:()=>z(Ee.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(wr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:Ee.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:ne=>{ne.stopPropagation(),Z(Ee.path)},children:e.jsx(Ks,{className:"h-3.5 w-3.5"})})]},Ee.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Se,{size:"sm",variant:"default",onClick:pe,disabled:T||!le,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Za,{className:"h-3 w-3"}),T?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(us,{open:ie,onOpenChange:de=>{K(de),de||_(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:q?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ns,{children:q?"Modify the file content":"Create a new file in the skill directory"})]}),H?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:ee,onChange:de=>V(de.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:q!==null}),!q&&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(Rs,{value:ae,onChange:de=>G(de.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Vs,{children:[e.jsx(Se,{variant:"ghost",onClick:()=>{K(!1),_(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cn,{onClick:he,disabled:H||!we,children:q?"Save Changes":"Create File"})]})]})})]})})},qN="__add_provider__",KN=({onItemSelect:t})=>{const r=et(u=>u.providers),s=et(u=>u.selectedProviderId),n=et(u=>u.setSelectedProvider),{isMobile:o}=Kt(),[a,l]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||l(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":c?"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(qN),t?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(cs,{className:"size-4"})})]})}),e.jsx(jt,{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(Xn,{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)})})]})},QN=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),_u=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const r=QN.format(t);return r.endsWith(".0")?r.slice(0,-2):r},On="__add_provider__",no=t=>typeof t=="object"&&t!==null,Bu=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()},YN=t=>{if(!no(t))return{};const r={};for(const[s,n]of Object.entries(t))Array.isArray(n)&&(r[s]=n.filter(o=>no(o)));return r},JN=t=>{if(typeof t=="string")return{id:t};if(!no(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}},XN=t=>{let r=[];Array.isArray(t)?r=t:no(t)&&(Array.isArray(t.all)?r=t.all:Array.isArray(t.providers)&&(r=t.providers));const s=r.map(o=>JN(o)).filter(o=>!!o),n=new Set;return s.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},ZN=()=>{const t=et(z=>z.providers),r=et(z=>z.selectedProviderId),s=et(z=>z.setSelectedProvider),n=et(z=>z.getModelMetadata),[o,a]=i.useState({}),[l,c]=i.useState(!1),[d,u]=i.useState({}),[m,f]=i.useState(null),[p,h]=i.useState(""),[x,g]=i.useState(null),[b,y]=i.useState({}),[w,S]=i.useState({}),[C,v]=i.useState([]),[j,M]=i.useState(!1),[k,D]=i.useState(null),[N,T]=i.useState(""),[A,E]=i.useState(""),[I,P]=i.useState(!1),[F,$]=i.useState({}),[Q,ie]=i.useState(!1);i.useEffect(()=>{!r&&t.length>0&&s(t[0].id)},[t,r,s]),i.useEffect(()=>{let z=!0;return(async()=>{c(!0);try{const Z=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!Z.ok)throw new Error(`Auth methods request failed (${Z.status})`);const de=await Z.json().catch(()=>({}));if(!z)return;a(YN(de))}catch(Z){if(!z)return;console.error("Failed to load provider auth methods:",Z),W.error("Failed to load provider authentication methods")}finally{z&&c(!1)}})(),()=>{z=!1}},[]),i.useEffect(()=>{let z=!0;return(async()=>{M(!0),D(null);try{const Z=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!Z.ok)throw new Error(`Provider list request failed (${Z.status})`);const de=await Z.json().catch(()=>({}));if(!z)return;v(XN(de))}catch(Z){if(!z)return;console.error("Failed to load available providers:",Z),D("Unable to load provider list")}finally{z&&M(!1)}})(),()=>{z=!1}},[]);const K=i.useMemo(()=>new Set(t.map(z=>z.id)),[t]),ee=i.useMemo(()=>C.filter(z=>!K.has(z.id)),[C,K]);i.useEffect(()=>{if(r===On){if(!N&&ee.length>0){T(ee[0].id);return}N&&!ee.some(z=>z.id===N)&&T(ee[0]?.id??"")}},[r,N,ee]),i.useEffect(()=>{if(r===On){ie(!0);return}ie(!1)},[r]),i.useEffect(()=>{if(!r||r===On)return;let z=!1;return(async()=>{try{const Z=await fetch(`/api/provider/${encodeURIComponent(r)}/source`,{method:"GET",headers:{Accept:"application/json"}}),de=await Z.json().catch(()=>null);if(!Z.ok)throw new Error(de?.error||"Failed to load provider sources");const Ee=de?.sources??de?.data?.sources;!z&&Ee&&$(ne=>({...ne,[r]:Ee}))}catch(Z){z||console.error("Failed to load provider sources:",Z)}})(),()=>{z=!0}},[r]);const V=t.find(z=>z.id===r),ae=r?F[r]:void 0,G=async z=>{const he=d[z]?.trim()??"";if(!he){W.error("API key is required");return}const Z=`api:${z}`;f(Z);try{const de=await fetch(`/api/auth/${encodeURIComponent(z)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:he})}),Ee=await de.json().catch(()=>null);if(!de.ok){const ne=Ee?.error||"Failed to save API key";throw new Error(ne)}W.success("API key saved"),u(ne=>({...ne,[z]:""})),await jo({scopes:["providers"],mode:"active"}),s(z)}catch(de){console.error("Failed to save API key:",de),W.error("Failed to save API key")}finally{f(null)}},q=async(z,he)=>{const Z=`oauth:${z}:${he}`;f(Z);try{const de=await fetch(`/api/provider/${encodeURIComponent(z)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:he})}),Ee=await de.json().catch(()=>null);if(!de.ok){const Y=Ee?.error||"Failed to start OAuth flow";throw new Error(Y)}const ne=no(Ee)?Ee:{},ye=no(ne.data)?ne.data:ne,te=typeof ye.url=="string"&&ye.url||typeof ye.verification_uri_complete=="string"&&ye.verification_uri_complete||typeof ye.verification_uri=="string"&&ye.verification_uri||void 0,ce=typeof ye.instructions=="string"&&ye.instructions||typeof ye.message=="string"&&ye.message||void 0,X=typeof ye.user_code=="string"&&ye.user_code||typeof ye.code=="string"&&ye.code||typeof ye.userCode=="string"&&ye.userCode||void 0;if(!te&&!ce&&!X)throw new Error("No OAuth details returned");const U=`${z}:${he}`;S(Y=>({...Y,[U]:{url:te,instructions:ce,userCode:X}})),te&&window.open(te,"_blank","noopener,noreferrer"),g({providerId:z,methodIndex:he}),W.message("Complete the OAuth flow in your browser")}catch(de){console.error("Failed to start OAuth flow:",de),W.error("Failed to start OAuth flow")}finally{f(null)}},_=async(z,he)=>{const Z=`${z}:${he}`,de=b[Z]?.trim(),Ee=`oauth-complete:${z}:${he}`;f(Ee);try{const ne={method:he};de&&(ne.code=de);const ye=await fetch(`/api/provider/${encodeURIComponent(z)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ne)}),te=await ye.json().catch(()=>null);if(!ye.ok){const ce=te?.error||"Failed to complete OAuth flow";throw new Error(ce)}W.success("OAuth connection completed"),y(ce=>({...ce,[Z]:""})),g(null),await jo({scopes:["providers"],mode:"active"}),s(z)}catch(ne){console.error("Failed to complete OAuth flow:",ne),W.error("Failed to complete OAuth flow")}finally{f(null)}},H=async z=>{try{await navigator.clipboard.writeText(z),W.success("OAuth link copied")}catch(he){console.error("Failed to copy OAuth link:",he),W.error("Failed to copy OAuth link")}},L=async z=>{try{await navigator.clipboard.writeText(z),W.success("Device code copied")}catch(he){console.error("Failed to copy device code:",he),W.error("Failed to copy device code")}},B=async z=>{const he=`disconnect:${z}`;f(he);try{const Z=await fetch(`/api/provider/${encodeURIComponent(z)}/auth?scope=all`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),de=await Z.json().catch(()=>null);if(!Z.ok){const Ee=de?.error||"Failed to disconnect provider";throw new Error(Ee)}W.success("Provider disconnected"),await jo({scopes:["providers"],mode:"active"})}catch(Z){console.error("Failed to disconnect provider:",Z),W.error("Failed to disconnect provider")}finally{f(null)}},O=r===On;if(!O&&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(Xn,{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(O)return e.jsx(jt,{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}):ee.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(es,{open:I,onOpenChange:z=>{P(z),z||E("")},children:[e.jsx(ts,{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:N?"text-foreground":"text-muted-foreground",children:N?ee.find(z=>z.id===N)?.name||N:"Select provider"}),e.jsx(Gt,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(ss,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:z=>z.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:z=>z.stopPropagation(),children:[e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:A,onChange:z=>E(z.target.value),onKeyDown:z=>z.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(jt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const z=ee.filter(he=>{const Z=A.toLowerCase();return(he.name||he.id).toLowerCase().includes(Z)||he.id.toLowerCase().includes(Z)});return z.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):z.map(he=>e.jsxs(Ct,{onSelect:()=>{T(he.id),P(!1),E("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:he.name||he.id}),N===he.id&&e.jsx($t,{className:"h-4 w-4 text-primary"})]},he.id))})()})]})]})]}),N&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),l?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[N]??"",onChange:z=>u(he=>({...he,[N]:z.target.value})),placeholder:"sk-..."}),e.jsx(Se,{size:"sm",onClick:()=>G(N),disabled:m===`api:${N}`,className:"h-8",children:m===`api:${N}`?"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 he=(o[N]??[]).filter(Z=>Bu(Z)==="oauth");return he.length===0?null:e.jsx("div",{className:"space-y-3",children:he.map((Z,de)=>{const Ee=Z.label||Z.name||`OAuth method ${de+1}`,ne=`${N}:${de}`,ye=x?.providerId===N&&x?.methodIndex===de;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}),(Z.description||Z.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(Z.description||Z.help)})]}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>q(N,de),disabled:m===`oauth:${N}:${de}`,className:"h-8",children:"Connect"})]}),w[ne]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:w[ne]?.instructions}),w[ne]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:w[ne]?.userCode,readOnly:!0}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>L(w[ne]?.userCode??""),className:"h-8",children:"Copy code"})]}),w[ne]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:w[ne]?.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:w[ne]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>H(w[ne]?.url??""),className:"h-8",children:"Copy link"})]})]}),ye&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:b[ne]??"",onChange:te=>y(ce=>({...ce,[ne]:te.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Se,{size:"sm",onClick:()=>_(N,de),disabled:m===`oauth-complete:${N}:${de}`,className:"h-8",children:m===`oauth-complete:${N}:${de}`?"Saving…":"Complete"})]})]},`${N}-${Ee}`)})})})()]})]})]})});if(!V)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(Xn,{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 le=Array.isArray(V.models)?V.models:[],pe=(o[V.id]??[]).filter(z=>Bu(z)==="oauth"),De=le.filter(z=>{const he=typeof z?.name=="string"?z.name:"",Z=typeof z?.id=="string"?z.id:"",de=p.trim().toLowerCase();return de?he.toLowerCase().includes(de)||Z.toLowerCase().includes(de):!0});return e.jsx(jt,{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:V.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:V.name||V.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",V.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!==On&&e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>ie(z=>!z),className:"h-8",children:Q?"Hide":"Reconnect"})]}),!Q&&r!==On?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Connected. Use Reconnect to update credentials."}):l?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[V.id]??"",onChange:z=>u(he=>({...he,[V.id]:z.target.value})),placeholder:"sk-..."}),e.jsx(Se,{size:"sm",onClick:()=>G(V.id),disabled:m===`api:${V.id}`,className:"h-8",children:m===`api:${V.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."})]}),pe.length>0&&e.jsx("div",{className:"space-y-3",children:pe.map((z,he)=>{const Z=z.label||z.name||`OAuth method ${he+1}`,de=`${V.id}:${he}`,Ee=x?.providerId===V.id&&x?.methodIndex===he;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:Z}),(z.description||z.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(z.description||z.help)})]}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>q(V.id,he),disabled:m===`oauth:${V.id}:${he}`,className:"h-8",children:"Connect"})]}),w[de]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:w[de]?.instructions}),w[de]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:w[de]?.userCode,readOnly:!0}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>L(w[de]?.userCode??""),className:"h-8",children:"Copy code"})]}),w[de]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:w[de]?.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:w[de]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>H(w[de]?.url??""),className:"h-8",children:"Copy link"})]})]}),Ee&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(St,{value:b[de]??"",onChange:ne=>y(ye=>({...ye,[de]:ne.target.value})),placeholder:"Paste authorization code"}),e.jsx(Se,{size:"sm",onClick:()=>_(V.id,he),disabled:m===`oauth-complete:${V.id}:${he}`,className:"h-8",children:m===`oauth-complete:${V.id}:${he}`?"Saving…":"Complete"})]})]},`${V.id}-${Z}`)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Connection"}),ae&&(ae.auth.exists||ae.user.exists||ae.project.exists||ae.custom?.exists)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Configured in: ",[ae.auth.exists?"auth credentials":null,ae.user.exists?"user config":null,ae.project.exists?"project config":null,ae.custom?.exists?"custom config":null].filter(Boolean).join(", ")]}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>B(V.id),disabled:m===`disconnect:${V.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${V.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:z=>h(z.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:De.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):De.map(z=>{const he=typeof z?.id=="string"?z.id:"",Z=typeof z?.name=="string"?z.name:he,de=he?n(V.id,he):void 0,Ee=_u(de?.limit?.context),ne=_u(de?.limit?.output),ye=[];return de?.tool_call&&ye.push({key:"tools",icon:Ja,label:"Tool calling"}),de?.reasoning&&ye.push({key:"reasoning",icon:Nr,label:"Reasoning"}),de?.attachment&&ye.push({key:"image",icon:kr,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:Z}),(Ee||ne)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[Ee?`${Ee} ctx`:"",Ee&&ne?" · ":"",ne?`${ne} out`:""]}),ye.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:ye.map(({key:te,icon:ce,label:X})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:X,"aria-label":X,children:e.jsx(ce,{className:"h-3 w-3"})},te))})]},he)})})]})]})})},ek={branch:qt,briefcase:Wl,house:Hl,graduation:zl,code:er,heart:Om},tk={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},sk=({onItemSelect:t})=>{const{selectedProfileId:r,defaultGitIdentityId:s,profiles:n,globalIdentity:o,setSelectedProfile:a,deleteProfile:l,loadProfiles:c,loadGlobalIdentity:d,loadDiscoveredCredentials:u,loadDefaultGitIdentityId:m,setDefaultGitIdentityId:f,getUnimportedCredentials:p}=ro(),{setSidebarOpen:h}=je(),{isMobile:x}=Kt(),[g,b]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||b(typeof window.opencodeDesktop<"u")},[]);const w=p();i.useEffect(()=>{c(),d(),u(),m()},[c,d,u,m]);const S=k=>{a(`import:${k.host}:${k.username}`),t?.(),x&&h(!1)},C=g?"bg-transparent":y?"bg-background":"bg-sidebar",v=()=>{a("new"),t?.(),x&&h(!1)},j=async k=>{window.confirm(`Are you sure you want to delete profile "${k.name}"?`)&&(await l(k.id)?W.success(`Profile "${k.name}" deleted successfully`):W.error("Failed to delete profile"))},M=async k=>{const D=s===k?null:k;if(!await f(D)){W.error("Failed to update default identity");return}W.success(D?"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",x?"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:v,"aria-label":"Create new profile",children:e.jsx(cs,{className:"size-4"})})]})}),e.jsxs(jt,{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(zu,{profile:o,isSelected:r==="global",isDefault:s==="global",onSelect:()=>{a("global"),t?.(),x&&h(!1)},onToggleDefault:()=>M("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&&w.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(qt,{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(zu,{profile:k,isSelected:r===k.id,isDefault:s===k.id,onSelect:()=>{a(k.id),t?.(),x&&h(!1)},onToggleDefault:()=>M(k.id),onDelete:()=>j(k)},k.id))}),w.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"}),w.map(k=>e.jsx(nk,{credential:k,onImport:()=>S(k)},`${k.host}-${k.username}`))]})]})]})},zu=({profile:t,isSelected:r,isDefault:s=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:l=!1})=>{const c=ek[t.icon||"branch"]||qt,d=tk[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(c,{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||!l&&a)&&e.jsxs(es,{children:[e.jsx(ts,{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(Zr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(Ct,{onClick:m=>{m.stopPropagation(),o()},children:s?"Unset default":"Set as default"}),!l&&a&&e.jsxs(Ct,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ks,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},rk=t=>{const r=t.split("/");return r.length>=3?r[r.length-1]:t},nk=({credential:t,onImport:r})=>{const s=rk(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(Yr,{className:"h-3 w-3"}),"Import"]})]})})},Hu=[{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)"}],ok=[{key:"branch",Icon:qt,label:"Branch"},{key:"briefcase",Icon:Wl,label:"Work"},{key:"house",Icon:Hl,label:"Personal"},{key:"graduation",Icon:zl,label:"School"},{key:"code",Icon:er,label:"Code"}],ak=()=>{const{selectedProfileId:t,getProfileById:r,createProfile:s,updateProfile:n,deleteProfile:o}=ro(),a=i.useMemo(()=>{if(t?.startsWith("import:")){const[,I,P]=t.split(":");return{host:I,username:P}}return null},[t]),l=i.useMemo(()=>t&&t!=="new"&&!a?r(t):null,[t,r,a]),c=t==="new"||a!==null,d=t==="global",[u,m]=i.useState(""),[f,p]=i.useState(""),[h,x]=i.useState(""),[g,b]=i.useState("ssh"),[y,w]=i.useState(""),[S,C]=i.useState(""),[v,j]=i.useState("keyword"),[M,k]=i.useState("branch"),[D,N]=i.useState(!1);i.useEffect(()=>{if(a){const I=a.host.split("/"),P=I.length>=3?I[I.length-1]:a.host;m(P),p(a.username),x(""),b("token"),w(""),C(a.host),j("string"),k("code")}else c?(m(""),p(""),x(""),b("ssh"),w(""),C(""),j("keyword"),k("branch")):l&&(m(l.name),p(l.userName),x(l.userEmail),b(l.authType||"ssh"),w(l.sshKey||""),C(l.host||""),j(l.color||"keyword"),k(l.icon||"branch"))},[l,c,t,a]);const T=async()=>{if(!f.trim()||!h.trim()){W.error("User name and email are required");return}if(g==="token"&&!S.trim()){W.error("Host is required for token-based authentication");return}N(!0);try{const I={name:u.trim()||f.trim(),userName:f.trim(),userEmail:h.trim(),authType:g,sshKey:g==="ssh"&&y.trim()||null,host:g==="token"&&S.trim()||null,color:v,icon:M};let P;if(c)P=await s(I);else if(t)P=await n(t,I);else return;P?W.success(c?"Profile created successfully":"Profile updated successfully"):W.error(c?"Failed to create profile":"Failed to update profile")}catch(I){console.error("Error saving profile:",I),W.error("An error occurred while saving")}finally{N(!1)}},A=async()=>{if(!(!t||c)&&confirm("Are you sure you want to delete this profile?"))try{await o(t)?W.success("Profile deleted successfully"):W.error("Failed to delete profile")}catch(I){console.error("Error deleting profile:",I),W.error("An error occurred while deleting")}},E=i.useMemo(()=>Hu.find(P=>P.key===v)?.cssVar||"var(--syntax-keyword)",[v]);return t?e.jsx(jt,{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":c?"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`:c?"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:I=>m(I.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:Hu.map(I=>e.jsx("button",{onClick:()=>j(I.key),className:R("w-8 h-8 rounded-lg border-2 transition-all",v===I.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:I.cssVar},title:I.label},I.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:ok.map(I=>{const P=I.Icon;return e.jsx("button",{onClick:()=>k(I.key),className:R("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",M===I.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:I.label,children:e.jsx(P,{className:"w-4 h-4",style:{color:E}})},I.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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:I=>p(I.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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:I=>x(I.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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",g==="ssh"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx(Nx,{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",g==="token"?"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:"Token (HTTPS)"})]})]})]}),g==="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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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:I=>w(I.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)"})]}),g==="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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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:I=>C(I.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:[!c&&e.jsxs(Se,{size:"sm",variant:"destructive",onClick:A,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Ks,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:R("flex gap-2",c&&"ml-auto"),children:e.jsxs(Se,{size:"sm",variant:"default",onClick:T,disabled:D,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Za,{className:"h-3 w-3"}),D?"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(tr,{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 Vi(t,r,s){return Math.min(s,Math.max(r,t))}const fn=_e.forwardRef(({value:t,onValueChange:r,min:s=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:l,onBlur:c,onKeyDown:d,disabled:u,...m},f)=>{const p=_e.useRef(null);_e.useImperativeHandle(f,()=>p.current);const[h,x]=_e.useState(()=>String(t));_e.useEffect(()=>{document.activeElement!==p.current&&x(String(t))},[t]);const g=_e.useCallback(()=>{p.current?.focus()},[]),b=_e.useCallback(N=>{const T=Vi(N,s,n);r(T),x(String(T))},[n,s,r]),y=_e.useCallback(()=>{const N=Number(h);return Number.isFinite(N)?N:t},[h,t]),w=_e.useCallback(()=>{b(y()+o),g()},[b,y,g,o]),S=_e.useCallback(()=>{b(y()-o),g()},[b,y,g,o]),C=N=>{const T=N.target.value;x(T);const A=Number(T);Number.isFinite(A)&&r(Vi(A,s,n))},v=N=>{const T=Number(h);if(!Number.isFinite(T))x(String(t));else{const A=Vi(T,s,n);A!==T&&r(A),x(String(A))}c?.(N)},j=N=>{if(N.key==="ArrowUp"){N.preventDefault(),w();return}if(N.key==="ArrowDown"){N.preventDefault(),S();return}d?.(N)},M=y(),k=u||M<=s,D=u||M>=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",l),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:v,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:D,onClick:w,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(Qa,{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(Gt,{className:"h-3.5 w-3.5"})})]})]})});fn.displayName="NumberInput";const ik=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Wu=[{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"}],Uu=[{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."}],Vu=[{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."}],jc=({visibleSettings:t})=>{const{isMobile:r}=Kt(),s=Ro(),n=je(N=>N.showReasoningTraces),o=je(N=>N.setShowReasoningTraces),a=je(N=>N.showTextJustificationActivity),l=je(N=>N.setShowTextJustificationActivity),c=je(N=>N.toolCallExpansion),d=je(N=>N.setToolCallExpansion),u=je(N=>N.fontSize),m=je(N=>N.setFontSize),f=je(N=>N.padding),p=je(N=>N.setPadding),h=je(N=>N.cornerRadius),x=je(N=>N.setCornerRadius),g=je(N=>N.inputBarOffset),b=je(N=>N.setInputBarOffset),y=je(N=>N.diffLayoutPreference),w=je(N=>N.setDiffLayoutPreference),S=je(N=>N.diffViewMode),C=je(N=>N.setDiffViewMode),v=br(N=>N.queueModeEnabled),j=br(N=>N.setQueueMode),{themeMode:M,setThemeMode:k}=Br(),D=N=>t?t.includes(N):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[D("theme")&&!Vt()&&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:ik.map(N=>e.jsx(Fs,{variant:M===N.value?"default":"outline",className:R(M===N.value?void 0:"text-foreground"),onClick:()=>k(N.value),children:N.label},N.value))})]}),D("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:N=>m(Number(N.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(fn,{value:u,onValueChange:m,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Fs,{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"})})]})]}),D("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:N=>p(Number(N.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(Fs,{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:N=>p(Number(N.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(fn,{value:f,onValueChange:p,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Fs,{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"})})]})]}),D("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:N=>x(Number(N.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(Fs,{type:"button",variant:"ghost",onClick:()=>x(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:N=>x(Number(N.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(fn,{value:h,onValueChange:x,min:0,max:32,step:1,"aria-label":"Corner radius in pixels"}),e.jsx(Fs,{type:"button",variant:"ghost",onClick:()=>x(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"})})]})]}),D("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:g,onChange:N=>b(Number(N.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:[g,"px"]}),e.jsx(Fs,{type:"button",variant:"ghost",onClick:()=>b(0),disabled:g===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:g,onChange:N=>b(Number(N.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(fn,{value:g,onValueChange:b,min:0,max:100,step:5,"aria-label":"Input bar offset in pixels"}),e.jsx(Fs,{type:"button",variant:"ghost",onClick:()=>b(0),disabled:g===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"})})]})]}),D("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:Wu.find(N=>N.value===c)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Wu.map(N=>e.jsx(Fs,{variant:c===N.value?"default":"outline",className:R(c===N.value?void 0:"text-foreground"),onClick:()=>d(N.value),children:N.label},N.value))})]}),D("diffLayout")&&!r&&!Vt()&&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:Uu.map(N=>e.jsx(Fs,{variant:y===N.id?"default":"outline",className:R(y===N.id?void 0:"text-foreground"),onClick:()=>w(N.id),children:N.label},N.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Uu.find(N=>N.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:Vu.map(N=>e.jsx(Fs,{variant:S===N.id?"default":"outline",className:R(S===N.id?void 0:"text-foreground"),onClick:()=>C(N.id),children:N.label},N.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Vu.find(N=>N.id===S)?.description})]})]}),D("dotfiles")&&!Vt()&&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(N=>e.jsx(Fs,{variant:s===N.value?"default":"outline",className:R(s===N.value?void 0:"text-foreground"),onClick:()=>Gl(N.value),children:N.label},N.id))})})]}),D("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:N=>o(N.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),D("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:N=>l(N.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show text justification in activity"})]}),D("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:v,onChange:N=>j(N.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:v?`Enter queues messages, ${Zt()}+Enter sends immediately.`:`Enter sends immediately, ${Zt()}+Enter queues messages.`})]})]})},Gu="https://github.com/btriapitsyn/openchamber",lk=800,Hp=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),o=ei(),{isMobile:a}=Kt(),l=o.info?.currentVersion||"unknown",c=i.useRef(!1);i.useEffect(()=>{if(o.checking)n(!0),c.current=!0;else if(s){const u=setTimeout(()=>{n(!1),c.current&&!o.available&&!o.error&&(W.success("You are on the latest version"),c.current=!1)},lk);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:()=>jo(),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",l]}),!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(Yr,{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:Gu,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(Hm,{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(il,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(vl,{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:l})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ma,{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(Yr,{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:Gu,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(il,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(vl,{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})]})},ck=1440*60*1e3,Wp=5,qu=1440*60*1e3,Gi=t=>t.time?.updated??t.time?.created??0,Ku=({sessions:t,currentSessionId:r,cutoffDays:s,keepRecent:n=Wp,now:o=Date.now()})=>{if(!Array.isArray(t)||s<=0)return[];const a=o-s*ck,l=[...t].sort((d,u)=>Gi(u)-Gi(d)),c=new Set(l.slice(0,n).map(d=>d.id));return l.filter(d=>{if(!d?.id||c.has(d.id)||d.id===r||d.share)return!1;const u=Gi(d);return u?u<a:!1}).map(d=>d.id)},Up=t=>{const r=t?.autoRun!==!1,s=ge(g=>g.sessions),n=ge(g=>g.currentSessionId),o=ge(g=>g.isLoading),a=ge(g=>g.deleteSessions),l=je(g=>g.autoDeleteEnabled),c=je(g=>g.autoDeleteAfterDays),d=je(g=>g.autoDeleteLastRunAt),u=je(g=>g.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),h=i.useMemo(()=>c<=0?[]:Ku({sessions:s,currentSessionId:n,cutoffDays:c}),[c,n,s]),x=i.useCallback(async({force:g=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!l||c<=0)&&!g)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const b=Date.now();if(!g&&d&&b-d<qu)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(s.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const y=Ku({sessions:s,currentSessionId:n,cutoffDays:c,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())}},[c,l,d,n,a,o,s,u]);return i.useEffect(()=>{if(!r||!l||c<=0||o||s.length===0)return;const g=Date.now();d&&g-d<qu||x()},[c,l,d,r,o,s.length,x]),{candidates:h,isRunning:m,runCleanup:x,keepRecentCount:Wp}},qi=1,Ki=365,Vp=()=>{const{isMobile:t}=Kt(),r=je(p=>p.autoDeleteEnabled),s=je(p=>p.autoDeleteAfterDays),n=je(p=>p.setAutoDeleteEnabled),o=je(p=>p.setAutoDeleteAfterDays),[a,l]=i.useState(String(s));i.useEffect(()=>{l(String(s))},[s]);const{candidates:c,isRunning:d,runCleanup:u}=Up({autoRun:!1}),m=c.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){W.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&W.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&W.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(l(h),h.trim()==="")return;const x=Number(h);if(!Number.isFinite(x))return;const g=Math.min(Ki,Math.max(qi,Math.round(x)));o(g)},onBlur:()=>{if(a.trim()===""){l(String(s));return}const p=Number(a);if(!Number.isFinite(p)){l(String(s));return}const h=Math.min(Ki,Math.max(qi,Math.round(p)));o(h),l(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(fn,{value:s,onValueChange:o,min:qi,max:Ki,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(Fs,{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]})]})},dk=10,uk=500,mk=20,fk=500,pk=30,hk=1e3,gk=()=>{const{isMobile:t}=Kt(),r=je(h=>h.memoryLimitHistorical),s=je(h=>h.memoryLimitViewport),n=je(h=>h.memoryLimitActiveSession),o=je(h=>h.setMemoryLimitHistorical),a=je(h=>h.setMemoryLimitViewport),l=je(h=>h.setMemoryLimitActiveSession),[c,d]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let x=null;if(ds())x=await $r();else{const g=Ps()?.settings;if(g)try{const y=(await g.load())?.settings;y&&(x={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(!x){const b=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});b.ok&&(x=await b.json())}}x&&(typeof x.memoryLimitHistorical=="number"&&o(x.memoryLimitHistorical),typeof x.memoryLimitViewport=="number"&&a(x.memoryLimitViewport),typeof x.memoryLimitActiveSession=="number"&&l(x.memoryLimitActiveSession))}catch(x){console.warn("Failed to load memory limits settings:",x)}finally{d(!1)}})()},[o,a,l]);const u=i.useCallback(async(h,x)=>{try{if(await is({[h]:x}),!ds()){const g=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({[h]:x})});g.ok||console.warn(`Failed to save ${h} to server:`,g.status,g.statusText)}}catch(g){console.warn(`Failed to save ${h}:`,g)}},[]),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=>{l(h),u("memoryLimitActiveSession",h)},[l,u]);return c?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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(Qi,{label:"Initial load limit",description:"Messages loaded when opening a session",value:r,defaultValue:mn.HISTORICAL_MESSAGES,min:dk,max:uk,onChange:m,isMobile:t}),e.jsx(Qi,{label:"Background trim limit",description:"Max messages kept when switching away",value:s,defaultValue:mn.VIEWPORT_MESSAGES,min:mk,max:fk,onChange:f,isMobile:t}),e.jsx(Qi,{label:"Active session limit",description:"Max messages for active session",value:n,defaultValue:pl,min:pk,max:hk,onChange:p,isMobile:t})]})]})},Qi=({label:t,description:r,value:s,defaultValue:n,min:o,max:a,onChange:l,isMobile:c})=>{const[d,u]=i.useState(String(s));i.useEffect(()=>{u(String(s))},[s]);const m=i.useCallback(h=>{const x=h.target.value;if(u(x),x.trim()==="")return;const g=Number(x);if(!Number.isFinite(g))return;const b=Math.min(a,Math.max(o,Math.round(g)));l(b)},[o,a,l]),f=i.useCallback(()=>{if(d.trim()===""){u(String(s));return}const h=Number(d);if(!Number.isFinite(h)){u(String(s));return}const x=Math.min(a,Math.max(o,Math.round(h)));l(x),u(String(x))},[d,s,o,a,l]),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,")"]}),c?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(fn,{value:s,onValueChange:l,min:o,max:a,step:10,"aria-label":t})]})]})})},Qu="opencode",Yu="big-pickle",xk=(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===Qu)?.models.some(o=>o.id===Yu))return{providerId:Qu,modelId:Yu};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},Gp=()=>{const t=et(T=>T.setProvider),r=et(T=>T.setModel),s=et(T=>T.setAgent),n=et(T=>T.setCurrentVariant),o=et(T=>T.setSettingsDefaultModel),a=et(T=>T.setSettingsDefaultVariant),l=et(T=>T.setSettingsDefaultAgent),c=et(T=>T.settingsAutoCreateWorktree),d=et(T=>T.setSettingsAutoCreateWorktree),u=et(T=>T.providers),[m,f]=i.useState(),[p,h]=i.useState(),[x,g]=i.useState(),[b,y]=i.useState(!0),w=i.useMemo(()=>xk(m,u),[m,u]),S=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{(async()=>{try{let A=null;if(ds())A=await $r();else{const E=Ps()?.settings;if(E)try{const P=(await E.load())?.settings;P&&(A={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(!A){const I=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});I.ok&&(A=await I.json())}}if(A){const E=typeof A.defaultModel=="string"&&A.defaultModel.trim().length>0?A.defaultModel.trim():void 0,I=typeof A.defaultVariant=="string"&&A.defaultVariant.trim().length>0?A.defaultVariant.trim():void 0,P=typeof A.defaultAgent=="string"&&A.defaultAgent.trim().length>0?A.defaultAgent.trim():void 0;E!==void 0&&f(E),I!==void 0&&h(I),P!==void 0&&g(P)}}catch(A){console.warn("Failed to load defaults settings:",A)}finally{y(!1)}})()},[]);const C=i.useCallback(async(T,A)=>{const E=T&&A?`${T}/${A}`:void 0;f(E),h(void 0),a(void 0),n(void 0),o(E),T&&A&&u.find(P=>P.id===T)&&(t(T),r(A));try{if(await is({defaultModel:E??"",defaultVariant:""}),!ds()){const I=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:E})});I.ok||console.warn("Failed to save default model to server:",I.status,I.statusText)}}catch(I){console.warn("Failed to save default model:",I)}},[u,n,t,r,o,a]),v="__default__",j=i.useCallback(async T=>{const A=T===v?void 0:T||void 0;h(A),a(A),n(A);try{await is({defaultVariant:A??""})}catch(E){console.warn("Failed to save default variant:",E)}},[n,a]),M=i.useCallback(async T=>{const A=T||void 0;g(A),l(A),T&&s(T);try{await is({defaultAgent:A??""})}catch(E){console.warn("Failed to save default agent:",E)}},[s,l]),k=i.useMemo(()=>{if(!w.providerId||!w.modelId)return[];const E=u.find(I=>I.id===w.providerId)?.models.find(I=>I.id===w.modelId)?.variants;return E?Object.keys(E):[]},[w.modelId,w.providerId,u]),D=k.length>0;i.useEffect(()=>{!D&&p&&(h(void 0),a(void 0),n(void 0),is({defaultVariant:""}).catch(()=>{}))},[p,n,a,D]);const N=i.useCallback(async T=>{const A=T.target.checked;d(A);try{await is({autoCreateWorktree:A})}catch(E){console.warn("Failed to save auto create worktree setting:",E)}},[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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ft,{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(vc,{providerId:w.providerId,modelId:w.modelId,onChange:C})]}),D&&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??v,onValueChange:j,children:[e.jsx(Es,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(kn,{placeholder:"Thinking"})}),e.jsxs(Is,{children:[e.jsx(Ht,{value:v,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),k.map(T=>e.jsx(Ht,{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(Bp,{agentName:x||"",onChange:M})]})]}),(w.providerId||x)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",w.providerId&&e.jsxs("span",{className:"text-foreground",children:[w.providerId,"/",w.modelId,D?` (${p??"default"})`:""]}),w.providerId&&x&&" / ",x&&e.jsx("span",{className:"text-foreground",children:x})]}),!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:c,onChange:N}),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:c?`New session (Worktree): ${Zt()} + N • New session (Standard): Shift + ${Zt()} + N`:`New session (Standard): ${Zt()} + N • New session (Worktree): Shift + ${Zt()} + N`})]})]})},yk=()=>{const t=et(l=>l.settingsGitmojiEnabled),r=et(l=>l.setSettingsGitmojiEnabled),s=si(),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let c=null;if(ds())c=await $r();else{const d=Ps()?.settings;if(d)try{const m=(await d.load())?.settings;m&&(c={gitmojiEnabled:typeof m.gitmojiEnabled=="boolean"?m.gitmojiEnabled:void 0})}catch{}if(!c){const u=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});u.ok&&(c=await u.json())}}c&&typeof c.gitmojiEnabled=="boolean"&&r(c.gitmojiEnabled)}catch(c){console.warn("Failed to load git settings:",c)}finally{o(!1)}})()},[r]);const a=i.useCallback(async l=>{const c=l.target.checked;r(c);try{await is({gitmojiEnabled:c})}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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ft,{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:l=>Qm(l.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."})]})})]})},bk=()=>{const t=Wt(L=>L.getActiveProject()),r=Wt(L=>L.updateWorktreeDefaults),s=t?.path??null,n=t?.worktreeDefaults,o=tc(s),a=If(s),{sessions:l,getWorktreeMetadata:c}=ge(),[d,u]=i.useState(n?.branchPrefix??""),[m,f]=i.useState(n?.baseBranch??"HEAD"),[p,h]=i.useState([]),[x,g]=i.useState(!1),[b,y]=i.useState(!1),[w,S]=i.useState(null),[C,v]=i.useState(null),[j,M]=i.useState([]),[k,D]=i.useState(!1),N=".openchamber",T=i.useCallback((L,B)=>{const O=L.replace(/\\/g,"/").replace(/\/+$/,""),le=!O||O==="/"?`/${N}`:`${O}/${N}`;return B?`${le}/${B}`:le},[]),A=i.useCallback(async()=>{if(!(!s||w===!1))try{const B=(await Zn(s)).map(pe=>eo(s,pe)),le=`${T(s,"")}/`,we=B.filter(pe=>pe.path.startsWith(le));M(we)}catch{}},[s,w,T]);i.useEffect(()=>{if(!s)return;let L=!1;return y(!0),D(!0),S(null),v(null),M([]),(async()=>{try{const B=await _r(s);if(L)return;if(S(B),B){const[O,le]=await Promise.all([oi(s),Zn(s).catch(()=>[])]);if(!L){O&&v({all:O.all,current:O.current});const we=le.map(he=>eo(s,he)),De=`${`${s.replace(/\\/g,"/").replace(/\/+$/,"")}/${N}`}/`,z=we.filter(he=>he.path.startsWith(De));M(z)}}}catch{}finally{L||(y(!1),D(!1))}})(),()=>{L=!0}},[s]),i.useEffect(()=>{if(!s)return;let L=!1;return g(!0),(async()=>{try{const B=await En(s);L||h(B.length>0?B:[""])}catch{L||h([""])}finally{L||g(!1)}})(),()=>{L=!0}},[s]),i.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const E=C??a,I=w??o,P=i.useMemo(()=>{const L=[],B=E?.current?`Current (HEAD: ${E.current})`:"Current (HEAD)";return L.push({value:"HEAD",label:B,group:"special"}),E&&(E.all.filter(we=>!we.startsWith("remotes/")).sort((we,pe)=>we.localeCompare(pe)).forEach(we=>{L.push({value:we,label:we,group:"local"})}),E.all.filter(we=>we.startsWith("remotes/")).map(we=>we.replace(/^remotes\//,"")).sort((we,pe)=>we.localeCompare(pe)).forEach(we=>{L.push({value:we,label:we,group:"remote"})})),L},[E]),F=i.useRef(null),$=i.useCallback(L=>{u(L),F.current=L},[]),Q=i.useCallback(L=>{t?.id&&(r(t.id,{branchPrefix:L}),F.current=null)},[t?.id,r]),ie=i.useCallback(()=>{Q(d)},[d,Q]);i.useEffect(()=>()=>{F.current!==null&&t?.id&&r(t.id,{branchPrefix:F.current})},[t?.id,r]);const K=i.useCallback(L=>{f(L),t?.id&&r(t.id,{baseBranch:L})},[t?.id,r]),ee=i.useCallback((L,B)=>{h(O=>{const le=[...O];return le[L]=B,le})},[]),V=i.useCallback(()=>{h(L=>[...L,""])},[]),ae=i.useCallback(L=>{h(B=>B.filter((O,le)=>le!==L))},[]),G=i.useCallback(async()=>{if(!s)return;const L=p.filter(B=>B.trim().length>0);await xf(s,L)},[s,p]),q=i.useCallback(()=>{G()},[G]),_=i.useCallback(L=>{const B=L.path.replace(/\\/g,"/").replace(/\/+$/,""),O=l.filter(he=>{if(c(he.id)?.path===L.path)return!0;const de=he.directory;return!!(de&&de.replace(/\\/g,"/").replace(/\/+$/,"")===B)}),le=new Set(O.map(he=>he.id)),we=he=>{const Z=l.filter(Ee=>{const ne=Ee.parentID;return ne&&he.has(ne)});if(Z.length===0)return[];const de=new Set(Z.map(Ee=>Ee.id));return[...Z,...we(de)]},pe=we(le),De=new Set,z=[...O,...pe].filter(he=>De.has(he.id)?!1:(De.add(he.id),!0));so.requestDelete({sessions:z,mode:"worktree",worktree:L})},[l,c]),H=i.useMemo(()=>l.map(L=>L.id).join(","),[l]);return i.useEffect(()=>{w&&s&&A()},[H,w,s,A]),s?b?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):I===!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:"Branch prefix"}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ft,{sideOffset:8,className:"max-w-xs",children:"Prefix for auto-generated branch names when creating new worktrees."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"e.g. feature, bugfix, wip (no trailing slash)"})]}),e.jsx(St,{value:d,onChange:L=>$(L.target.value),onBlur:ie,placeholder:"feature",className:"max-w-xs"})]}),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:"Base branch"}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ft,{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"})]}),e.jsxs(As,{value:m,onValueChange:K,children:[e.jsx(Es,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(kn,{placeholder:"Select a branch"})}),e.jsxs(Is,{children:[e.jsxs(yn,{children:[e.jsx(qn,{children:"Default"}),P.filter(L=>L.group==="special").map(L=>e.jsx(Ht,{value:L.value,children:L.label},L.value))]}),P.some(L=>L.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(Va,{}),e.jsxs(yn,{children:[e.jsx(qn,{children:"Local branches"}),P.filter(L=>L.group==="local").map(L=>e.jsx(Ht,{value:L.value,children:L.label},L.value))]})]}),P.some(L=>L.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(Va,{}),e.jsxs(yn,{children:[e.jsx(qn,{children:"Remote branches"}),P.filter(L=>L.group==="remote").map(L=>e.jsx(Ht,{value:L.value,children:L.label},L.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 when a new worktree is created. Use ",e.jsx("code",{className:"font-mono text-xs bg-sidebar-accent/50 px-1 rounded",children:"$ROOT_WORKTREE_PATH"})," for the project root."]})]}),x?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[p.map((L,B)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(St,{value:L,onChange:O=>ee(B,O.target.value),onBlur:q,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{ae(B),setTimeout(G,0)},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(os,{className:"h-4 w-4"})})]},B)),e.jsxs("button",{type:"button",onClick:V,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(cs,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{sideOffset:8,className:"max-w-xs",children:["Worktrees created under ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})," directory. Deleting a worktree will also remove any linked sessions."]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Manage worktrees for this project"})]}),k?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):j.length===0?e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["No worktrees found under ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})]}):e.jsx("div",{className:"space-y-1",children:j.map(L=>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.jsx("p",{className:"typography-meta text-foreground truncate",children:L.label||L.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:L.relativePath||L.path})]}),e.jsx("button",{type:"button",onClick:()=>_(L),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 ${L.branch||L.label}`,children:e.jsx(Ks,{className:"h-4 w-4"})})]},L.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},wk=()=>{const t=je(j=>j.nativeNotificationsEnabled),r=je(j=>j.setNativeNotificationsEnabled),s=je(j=>j.notificationMode),n=je(j=>j.setNotificationMode),[o,a]=i.useState("default"),[l,c]=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;c(j),(async()=>{if(!j){u(!1);return}try{const k=await navigator.serviceWorker.getRegistration();if(!k){u(!1);return}const D=await k.pushManager.getSubscription();u(!!D)}catch{u(!1)}})()},[]);const p=async j=>{if(j&&typeof Notification<"u"&&Notification.permission==="default")try{const M=await Notification.requestPermission();a(M),M==="granted"?r(!0):W.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(M){console.error("Failed to request notification permission:",M),W.error("Failed to request notification permission")}else r(!!(j&&o==="granted"))},h=typeof Notification<"u"&&Notification.permission==="granted",x=j=>{const M="=".repeat((4-j.length%4)%4),k=(j+M).replace(/-/g,"+").replace(/_/g,"/"),D=atob(k),N=new Uint8Array(D.length);for(let T=0;T<D.length;T+=1)N[T]=D.charCodeAt(T);return N},g=async(j,M,k)=>{let D=null;const N=new Promise((T,A)=>{D=setTimeout(()=>{A(new Error(k))},M)});try{return await Promise.race([j,N])}finally{D&&clearTimeout(D)}},b=async j=>{if(j.active)return;const M=j.installing||j.waiting;M&&M.state!=="activated"&&await g(new Promise(k=>{const D=()=>{M.state==="activated"&&(M.removeEventListener("statechange",D),k())};M.addEventListener("statechange",D),D()}),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 M=null;for(const k of j)try{const D=k.opts?navigator.serviceWorker.register("/sw.js",k.opts):navigator.serviceWorker.register("/sw.js");return await g(D,1e4,`Service worker registration timed out (${k.label})`)}catch(D){M=D}throw M instanceof Error?M:new Error("Service worker registration failed")},w=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const j=await navigator.serviceWorker.getRegistration();if(j)return j;const M=await y();try{await M.update()}catch{}return await b(M),M},S=j=>{const M=j,k=[`type=${typeof j}`,`toString=${String(j)}`,`name=${String(M?.name??"")}`,`message=${String(M?.message??"")}`];let D="";try{D=JSON.stringify(j)}catch{}return{summary:k.filter(Boolean).join(" | "),json:D,stack:typeof M?.stack=="string"?M.stack:""}},C=async()=>{if(!l){W.error("Push notifications not supported");return}const j=Ps();if(!j?.push){W.error("Push API not available");return}f(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const I=await Notification.requestPermission();if(a(I),I!=="granted"){W.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){W.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}const M=await j.push.getVapidPublicKey();if(!M?.publicKey){W.error("Failed to load push key");return}const k=await w();await b(k);const D=await k.pushManager.getSubscription();if(!("pushManager"in k)||!k.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const T=(D??await g(k.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x(M.publicKey)}),15e3,"Push subscription timed out")).toJSON(),A=T.keys;if(!T.endpoint||!A?.p256dh||!A.auth)throw new Error("Push subscription missing keys");if(!(await g(j.push.subscribe({endpoint:T.endpoint,keys:{p256dh:A.p256dh,auth:A.auth},origin:typeof window<"u"?window.location.origin:void 0}),15e3,"Push subscribe request timed out"))?.ok){W.error("Failed to enable background notifications");return}u(!0),W.success("Background notifications enabled")}catch(M){console.error("[Push] Enable failed:",M);const k=S(M);W.error("Failed to enable background notifications",{description:k.summary})}finally{f(!1)}},v=async()=>{if(!l){u(!1);return}const j=Ps();if(!j?.push){W.error("Push API not available");return}f(!0);try{const k=await(await w()).pushManager.getSubscription();if(!k){u(!1);return}const D=k.endpoint;await k.unsubscribe(),await j.push.unsubscribe({endpoint:D}),u(!1),W.success("Background notifications disabled")}finally{f(!1)}};return dr()?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(gn,{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(gn,{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."})]}),l?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."}),l&&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(Gf,{size:"sm"})}),e.jsx(gn,{checked:d,disabled:m,onCheckedChange:j=>{j?C():v()},className:"data-[state=checked]:bg-status-info"})]})]})]}):null},vk=()=>{const t=Ps()?.github,r=_s(j=>j.status),s=_s(j=>j.isLoading),n=_s(j=>j.hasChecked),o=_s(j=>j.refreshStatus),a=_s(j=>j.setStatus),l=i.useCallback(async j=>{if(typeof window>"u")return;const M=window.opencodeDesktop;if(M?.openExternal)try{const k=await M.openExternal(j);if(k&&typeof k=="object"&&"success"in k&&k.success===!0)return}catch{}try{window.open(j,"_blank","noopener,noreferrer")}catch{}},[]),[c,d]=i.useState(!1),[u,m]=i.useState(null),[f,p]=i.useState(null),h=i.useRef(null),x=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)}})(),()=>{x()}),[n,o,t,x]);const g=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({})}),D=await k.json().catch(()=>null);if(!k.ok||!D||!("deviceCode"in D))throw new Error(D?.error||k.statusText);return D})();m(j),p(Math.max(1,j.interval)*1e3);const M=j.verificationUriComplete||j.verificationUri;l(M)}catch(j){console.error("Failed to start GitHub connect:",j),Ys.error("Failed to start GitHub connect")}finally{d(!1)}},[l,t]),b=i.useCallback(async j=>{if(t)return t.authComplete(j);const M=await fetch("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:j})}),k=await M.json().catch(()=>null);if(!M.ok||!k)throw new Error(k?.error||M.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),x(),await o(t,{force:!0});return}j.status==="slow_down"&&p(M=>M?M+5e3:5e3),(j.status==="expired_token"||j.status==="access_denied")&&(Ys.error(j.error||"GitHub authorization failed"),m(null),x())}catch(j){console.warn("GitHub polling failed:",j)}})()},f),()=>{h.current!=null&&(window.clearInterval(h.current),h.current=null)}},[u,f,b,o,t,x]);const y=i.useCallback(async()=>{d(!0);try{if(x(),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,x]),w=i.useCallback(async j=>{if(j){d(!0);try{const M=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})}),D=await k.json().catch(()=>null);if(!k.ok||!D)throw new Error(D?.error||k.statusText);return D})();a(M),Ys.success("GitHub account switched")}catch(M){console.error("Failed to switch GitHub account:",M),Ys.error("Failed to switch GitHub account")}finally{d(!1)}}},[t,a]);if(s)return null;const S=!!r?.connected,C=r?.user,v=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:c,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:g,disabled:c,children:"Connect"})]}),S?e.jsx("div",{className:"flex justify-end",children:e.jsx(Se,{variant:"ghost",onClick:g,disabled:c,children:"Add account"})}):null,v.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:v.map(j=>{const M=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:[M?.avatarUrl?e.jsx("img",{src:M.avatarUrl,alt:M.login?`${M.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:M?.name?.trim()||M?.login||"GitHub"}),M?.login?e.jsx("div",{className:"typography-micro text-muted-foreground truncate font-mono",children:M.login}):null]})]}),k?e.jsx("span",{className:"typography-micro text-primary",children:"Active"}):e.jsx(Se,{size:"sm",variant:"ghost",onClick:()=>w(j.id),disabled:c,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:c,onClick:()=>{x(),m(null)},children:"Cancel"})})]}):null]})},jk=({section:t})=>{const{isMobile:r}=Kt(),s=r&&dr();if(!t)return e.jsx(jt,{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(jc,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Gp,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Vp,{})}),s&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Hp,{})})]})});const n=()=>{switch(t){case"visual":return e.jsx(Sk,{});case"chat":return e.jsx(Nk,{});case"sessions":return e.jsx(kk,{});case"git":return e.jsx(Ck,{});case"github":return e.jsx(Mk,{});case"notifications":return e.jsx(Dk,{});default:return null}};return e.jsx(jt,{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()})})},Sk=()=>e.jsx(jc,{visibleSettings:["theme","fontSize","spacing","cornerRadius","inputBarOffset"]}),Nk=()=>e.jsx(jc,{visibleSettings:["toolOutput","diffLayout","dotfiles","reasoning","textJustificationActivity","queueMode"]}),kk=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Gp,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Vp,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gk,{})})]}),Ck=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(yk,{}),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(bk,{})]})]}),Mk=()=>Vt()?null:e.jsx(vk,{}),Dk=()=>e.jsx(wk,{}),Ak=[{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}],Ek=({selectedSection:t,onSelectSection:r})=>{const{isMobile:s}=Kt(),n=s&&dr(),[o,a]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=i.useMemo(()=>Vt(),[]),c=i.useMemo(()=>dr(),[]);i.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=i.useMemo(()=>Ak.filter(m=>!(m.webOnly&&!c||m.hideInVSCode&&l)),[c,l]),u=o?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",u),children:[e.jsx(jt,{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(Hp,{})})]})},Ik=t=>{let r=_p.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},Yi=200,Ji=500,Pk=264,Tk=940,Pl=({onClose:t,forceMobile:r})=>{const s=Kt(),n=r??s.isMobile,o=je(O=>O.sidebarSection),a=je(O=>O.setSidebarSection),l=i.useMemo(()=>o!=="sessions"?o:"settings",[o]),c=i.useCallback(O=>{a(O)},[a]),[d,u]=i.useState("visual"),[m,f]=i.useState(!1),[p,h]=i.useState(()=>typeof window<"u"?Math.min(Ji,Math.max(Yi,Math.floor(window.innerWidth*.2))):Pk),[x,g]=i.useState(!1),[b,y]=i.useState(!1),[w,S]=i.useState(0),C=i.useRef(null),v=i.useRef(0),j=i.useRef(p),[M,k]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),D=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),N=i.useMemo(()=>Vt(),[]),T=i.useMemo(()=>Ik(N),[N]);i.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{const O=C.current;if(!O)return;const le=new ResizeObserver(we=>{for(const pe of we)S(pe.contentRect.width)});return le.observe(O),S(O.clientWidth),()=>le.disconnect()},[]);const A=Wt(O=>O.projects),E=Wt(O=>O.activeProjectId),I=Wt(O=>O.setActiveProject),P=i.useMemo(()=>[...A].sort((O,le)=>(O.label||O.path).localeCompare(le.label||le.path)),[A]),F=i.useMemo(()=>P.length===0?null:P.find(O=>O.id===E)??P[0],[E,P]),$=i.useCallback(O=>O.replace(/[-_]/g," ").replace(/\b\w/g,le=>le.toUpperCase()),[]),Q=i.useMemo(()=>{if(!F)return"Project";const O=F.label&&F.label.trim().length>0?F.label:F.path.split("/").filter(Boolean).pop()||F.path;return $(O)},[F,$]),ie=P.length>0&&!N,K=w===0||w>=Tk;i.useEffect(()=>{if(l==="agents"){setTimeout(()=>{sn.getState().loadAgents()},0);return}if(l==="commands"){setTimeout(()=>{tn.getState().loadCommands()},0);return}l==="skills"&&(ur.getState().loadSkills(),Lo.getState().loadCatalog())},[E,l]),i.useEffect(()=>{if(typeof window>"u")return;const O=()=>{if(!x){const le=Math.min(Ji,Math.max(Yi,Math.floor(window.innerWidth*.2)));h(le)}};return window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[x]),i.useEffect(()=>{if(!b)return;const O=we=>{const pe=we.clientX-v.current,De=Math.min(Ji,Math.max(Yi,j.current+pe));h(De),g(!0)},le=()=>y(!1);return window.addEventListener("pointermove",O),window.addEventListener("pointerup",le,{once:!0}),()=>{window.removeEventListener("pointermove",O),window.removeEventListener("pointerup",le)}},[b]);const ee=O=>{y(!0),v.current=O.clientX,j.current=p,O.preventDefault()},V=i.useCallback(async O=>{if(!O.target.closest("button, a, input, select, textarea")&&O.button===0&&M)try{const{getCurrentWindow:le}=await Ss(async()=>{const{getCurrentWindow:pe}=await import("./vendor-.bun-koHRsLHN.js").then(De=>De.dh);return{getCurrentWindow:pe}},__vite__mapDeps([0,1]));await le().startDragging()}catch(le){console.error("Failed to start window dragging:",le)}},[M]),ae=i.useCallback(async O=>{if(O.button===0&&M)try{const{getCurrentWindow:le}=await Ss(async()=>{const{getCurrentWindow:pe}=await import("./vendor-.bun-koHRsLHN.js").then(De=>De.dh);return{getCurrentWindow:pe}},__vite__mapDeps([0,1]));await le().startDragging()}catch(le){console.error("Failed to start window dragging:",le)}},[M]),G=i.useCallback(O=>{c(O),f(!1)},[c]),q=i.useCallback(()=>{n&&f(!0)},[n]),_=()=>{switch(l){case"settings":return e.jsx(Ek,{selectedSection:d,onSelectSection:O=>{u(O),q()}});case"agents":return e.jsx(CN,{onItemSelect:q});case"commands":return e.jsx(RN,{onItemSelect:q});case"skills":return e.jsx(ON,{onItemSelect:q});case"providers":return e.jsx(KN,{onItemSelect:q});case"git-identities":return e.jsx(sk,{onItemSelect:q});default:return null}},H=()=>{switch(l){case"agents":return e.jsx(FN,{});case"commands":return e.jsx(LN,{});case"skills":return e.jsx(GN,{});case"providers":return e.jsx(ZN,{});case"git-identities":return e.jsx(ak,{});case"settings":return e.jsx(jk,{section:d});default:return null}},L=Zt(),B=i.useMemo(()=>M&&D?"pl-[5.75rem]":"",[M,D]);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:V,className:R("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&B,M?"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(Ll,{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:O,label:le,icon:we})=>{const pe=l===O,De=we;return n?e.jsxs(ht,{delayDuration:500,children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{onClick:()=>G(O),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",pe?"bg-secondary text-foreground shadow-sm":"text-muted-foreground"),"aria-pressed":pe,"aria-label":le,children:e.jsx(De,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(ft,{children:e.jsx("p",{children:le})})]},O):e.jsxs("button",{onClick:()=>G(O),onMouseDown:pe?ae:void 0,className:R("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",pe?"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":pe,"aria-label":le,children:[e.jsx(De,{className:"h-4 w-4",weight:"regular"}),K&&e.jsx("span",{children:le})]},O)})})}),(t||ie)&&e.jsxs("div",{className:R("flex items-center gap-2",n?"":"pr-3"),children:[ie&&e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:Q,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(pr,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:Q,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:Q}),e.jsx(Gt,{className:"size-4 opacity-50"})]})}),e.jsx(ss,{align:"end",className:"w-auto",children:e.jsx(Pa,{value:F?.id??"",onValueChange:O=>{O&&I(O)},children:P.map(O=>{const le=O.label?.trim()?O.label.trim():O.path.split("/").filter(Boolean).pop()||O.path,we=$(le);return e.jsx(Ta,{value:O.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:we})},O.id)})})})]}),t&&e.jsxs(ht,{delayDuration:500,children:[e.jsx(gt,{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(os,{className:"h-5 w-5"})})}),e.jsx(ft,{children:e.jsxs("p",{children:["Close Settings (",L,"+,)"]})})]})]})]}),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(bs,{children:H()})}):e.jsx("div",{className:R("flex-1 overflow-hidden",N?"bg-background":"bg-sidebar"),children:e.jsx(bs,{children:_()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:R("relative overflow-hidden border-r",M?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":N?"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:ee,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(bs,{children:_()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(bs,{children:H()})})]})})]})},Fk=()=>{const{isSidebarOpen:t,activeMainTab:r,setIsMobile:s,isSessionSwitcherOpen:n,isSettingsDialogOpen:o,setSettingsDialogOpen:a,isMultiRunLauncherOpen:l,setMultiRunLauncherOpen:c,multiRunLauncherPrefillPrompt:d}=je(),{isMobile:u}=Kt();Zv({enabled:!0});const m=ei(x=>x.checkForUpdates);i.useEffect(()=>{const x=setTimeout(()=>{m()},3e3);return()=>clearTimeout(x)},[m]),i.useEffect(()=>{je.getState().isMobile!==u&&s(u)},[u,s]),i.useEffect(()=>{if(typeof window>"u")return;let x;const g=()=>{x!==void 0&&window.clearTimeout(x),x=window.setTimeout(()=>{je.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",g),()=>{window.removeEventListener("resize",g),x!==void 0&&window.clearTimeout(x)}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const x=document.documentElement;let g=0,b=!1,y=0,w=null;const S=je.getState().setKeyboardOpen,C=()=>{w&&(w.style.setProperty("--oc-keyboard-avoid-offset","0px"),w.removeAttribute("data-keyboard-avoid-active"),w=null)},v=T=>{if(!T)return null;const A=T.closest("[data-keyboard-avoid]");if(A)return A;if(T.classList.contains("overlay-scrollbar-container")){const E=T.parentElement;if(E instanceof HTMLElement)return E}return T},j=()=>{g=0,b=!0,x.style.setProperty("--oc-keyboard-inset","0px"),S(!1)},M=()=>{const T=window.visualViewport,A=T?Math.round(T.height):window.innerHeight,E=T?Math.max(0,Math.round(T.offsetTop)):0;x.style.setProperty("--oc-visual-viewport-offset-top",`${E}px`);const I=document.activeElement,P=I?.tagName,$=P==="INPUT"||P==="TEXTAREA"||P==="SELECT"||!!I?.isContentEditable,Q=Math.round(x.clientHeight||window.innerHeight),ie=A+E,K=Math.max(0,Q-ie),V=K>=($?120:180)?K:0;if(b)V===0&&(b=!1),g=0;else if(g===0)V>0&&$&&(g=V);else{const _=!$&&A>y+6;V===0?(g=0,S(!1)):_?j():(V>0&&$||V>g)&&(g=V,S(!0))}x.style.setProperty("--oc-keyboard-inset",`${g}px`),y=A;const G=/iPad|iPhone|iPod/.test(navigator.userAgent)&&g>0?34:0;x.style.setProperty("--oc-keyboard-home-indicator",`${G}px`);const q=$?v(I):null;if(!u||!q||!I)C();else{q!==w&&(C(),w=q);const _=E+A,L=I.getBoundingClientRect().bottom-_,B=8,O=Math.max(g,V),le=L>B&&O>0?Math.min(L,O):0,we=w;we&&(we.style.setProperty("--oc-keyboard-avoid-offset",`${le}px`),we.setAttribute("data-keyboard-avoid-active","true"))}if(u&&$){const _=document.scrollingElement;_&&_.scrollTop!==0&&(_.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};M();const k=window.visualViewport;k?.addEventListener("resize",M),k?.addEventListener("scroll",M),window.addEventListener("resize",M),window.addEventListener("orientationchange",M);const D=T=>{const A=T.target;if(!A)return;const E=A.tagName;(E==="INPUT"||E==="TEXTAREA"||E==="SELECT"||A.isContentEditable)&&(b=!1),M()};document.addEventListener("focusin",D,!0);const N=T=>{const A=T.target;if(!A)return;const E=A.tagName;if(E==="INPUT"||E==="TEXTAREA"||E==="SELECT"||A.isContentEditable){const P=T.relatedTarget,F=P?.tagName;if(F==="INPUT"||F==="TEXTAREA"||F==="SELECT"||P?.isContentEditable)return;j()}};return document.addEventListener("focusout",N,!0),()=>{k?.removeEventListener("resize",M),k?.removeEventListener("scroll",M),window.removeEventListener("resize",M),window.removeEventListener("orientationchange",M),document.removeEventListener("focusin",D,!0),document.removeEventListener("focusout",N,!0),C()}},[u]);const f=i.useMemo(()=>{switch(r){case"plan":return e.jsx(gS,{});case"git":return e.jsx(XS,{});case"diff":return e.jsx(nv,{});case"terminal":return e.jsx(dN,{});case"files":return e.jsx(wN,{});default:return null}},[r]),p=r==="chat",h=o&&!u;return e.jsx(Wv,{children:e.jsxs("div",{className:R("main-content-safe-area h-[100dvh]",u?"flex flex-col":"flex","bg-background"),children:[e.jsx(jv,{}),e.jsx(kv,{}),e.jsx($v,{}),u?e.jsxs(e.Fragment,{children:[!(o||l)&&e.jsx(Cd,{}),e.jsx("div",{className:R("flex flex-1 overflow-hidden",(o||l)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:n?e.jsx("div",{className:"flex-1 overflow-hidden bg-sidebar",children:e.jsx(bs,{children:e.jsx(Ua,{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(bs,{children:e.jsx(ko,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(bs,{children:f})})]})}),l&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(bs,{children:e.jsx(Wd,{initialPrompt:d,onCreated:()=>c(!1),onCancel:()=>c(!1)})})}),o&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(bs,{children:e.jsx(Pl,{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||l)&&"invisible"),children:[e.jsx(Cd,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx(xv,{isOpen:t,isMobile:u,children:e.jsx(Ua,{})}),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(bs,{children:e.jsx(ko,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(bs,{children:f})})]})]})]}),l&&e.jsx("div",{className:R("absolute inset-0 z-10 bg-background"),children:e.jsx(bs,{children:e.jsx(Wd,{initialPrompt:d,onCreated:()=>c(!1),onCancel:()=>c(!1)})})})]}),h&&e.jsx("div",{className:R("absolute inset-0 z-10 bg-background"),children:e.jsx(bs,{children:e.jsx(Pl,{onClose:()=>a(!1)})})})]})]})})},Rk=550,Lk=1400,Ok=280,$k=()=>{const t=Bs(),r=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),s=i.useMemo(()=>{const E=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof E=="string"&&E.trim().length>0?E.trim():null},[]),n=i.useRef(!1),[o,a]=i.useState("sessions"),[l,c]=i.useState(0),d=i.useRef(null),u=ge(E=>E.currentSessionId),m=ge(E=>E.sessions),f=i.useMemo(()=>u?m.find(E=>E.id===u)?.title||"Session":null,[u,m]),p=ge(E=>!!E.newSessionDraft?.open),h=ge(E=>E.openNewSessionDraft),[x,g]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),b=et(E=>E.isInitialized),y=et(E=>E.initializeApp),w=ge(E=>E.loadSessions),S=ge(E=>E.loadMessages),C=ge(E=>E.messages),[v,j]=i.useState(()=>b),[M,k]=i.useState(!1),D=i.useRef(0);i.useEffect(()=>{u&&a("chat")},[u]),i.useEffect(()=>{const E=t.vscode;E&&E.executeCommand("openchamber.setActiveSession",u,f)},[f,u,t.vscode]),i.useEffect(()=>{r!=="editor"&&!u&&!p&&o==="chat"&&a("sessions")},[u,p,o,r]);const N=i.useCallback(()=>{a("sessions")},[]);i.useEffect(()=>{const E=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(E==="connected"||E==="connecting"||E==="error"||E==="disconnected")&&g(E);const I=P=>{const $=P.detail?.status;($==="connected"||$==="connecting"||$==="error"||$==="disconnected")&&g($)};return window.addEventListener("openchamber:connection-status",I),()=>window.removeEventListener("openchamber:connection-status",I)},[]),i.useEffect(()=>{const E=I=>{const F=I.detail?.view;F==="settings"?a("settings"):F==="chat"?a("chat"):F==="sessions"&&a("sessions")};return window.addEventListener("openchamber:navigate",E),()=>window.removeEventListener("openchamber:navigate",E)},[]),i.useEffect(()=>{(async()=>{if(M||v||x!=="connected")return;const I=Date.now();if(!(I-D.current<750)){D.current=I,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=et.getState();if(!F.isInitialized||!F.isConnected||F.providers.length===0||F.agents.length===0)return;await w();const $=ge.getState().error;if(P&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:F.providers.length,agents:F.agents.length,sessions:ge.getState().sessions.length,sessionsError:$}),typeof $=="string"&&$.length>0)return;j(!0)}catch{}finally{k(!1)}}})()},[x,b,v,y,M,w]),i.useEffect(()=>{if(r==="editor"&&!n.current&&!(!v||x!=="connected")){if(!s){n.current=!0,h();return}m.some(E=>E.id===s)&&(n.current=!0,ge.getState().setCurrentSession(s))}},[x,v,s,h,m,r]),i.useEffect(()=>{(async()=>{if(!v||x!=="connected"||o!=="chat"||p||!u)return;if(!(C.has(u)&&(C.get(u)?.length||0)>0))try{await S(u)}catch{}})()},[x,u,o,v,S,C,p]),i.useEffect(()=>{const E=d.current;if(!E)return;const I=new ResizeObserver(P=>{for(const F of P)c(F.contentRect.width)});return I.observe(E),c(E.clientWidth),()=>I.disconnect()},[]);const T=l>0&&l<Rk,A=l>=Lk;return i.useEffect(()=>{A&&o==="sessions"&&r==="sidebar"&&a("chat")},[A,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(ca,{title:m.find(E=>E.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(bs,{children:e.jsx(ko,{})})})]}):o==="settings"?e.jsx(Pl,{onClose:()=>a(A?"chat":"sessions"),forceMobile:T}):A?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:Ok},children:e.jsx(Ua,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(ca,{title:p&&!u?"New session":m.find(E=>E.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(bs,{children:e.jsx(ko,{})})})]})]}):o==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(ca,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ua,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>a("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(ca,{title:p&&!u?"New session":m.find(E=>E.id===u)?.title||"Chat",showBack:!0,onBack:N,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(bs,{children:e.jsx(ko,{})})})]})})},ca=({title:t,showBack:r,onBack:s,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:l,showContextUsage:c})=>{const{getCurrentModel:d}=et(),u=ge(g=>g.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,x=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($m,{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(cs,{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(Mo,{className:"h-5 w-5"})}),l&&e.jsx(wl,{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(wn,{className:"h-5 w-5"})}),c&&x&&x.totalTokens>0&&e.jsx(xl,{totalTokens:x.totalTokens,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit??0,size:"compact"})]})},Tl=".openchamber",da=t=>{const r=Wt.getState(),s=r.activeProjectId,n=s?r.projects.find(c=>c.id===s)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof t=="string"?Ut(t):"",a=`/${Tl}/`,l=o.indexOf(a);return l>0?o.slice(0,l):t?Ut(t):null},Ut=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Ju=t=>{const r=Ut(t);return!r||r==="/"?`/${Tl}`:`${r}/${Tl}`},_k=(t,r)=>{const s=Ut(t);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const l=Ut(o);if(l)return l}const a=typeof n.name=="string"?n.name.trim():"";return!a||!s?null:`${s}/${a}`}).filter(n=>!!n)},Bk=async t=>{const r=Ut(t);if(!r)return[];try{const n=(await Oe.listLocalDirectory(r)).filter(o=>o.isDirectory);return _k(r,n)}catch{return[]}},Vr=(t,r)=>{const s=Ut(t),n=Ut(r);if(!s||!n)return!1;if(s===n)return!0;const o=n==="/"?"/":`${n}/`;return s.startsWith(o)},qp=async(t,r)=>{const s=Ut(r);if(!s)return s;try{const n=await t.path.get({directory:s});return Ut(n.data?.directory??"")||s}catch{return s}},Kp=async(t,r)=>{const s=Ut(r);if(!s)return[];const n=await qp(t,s),o=l=>l.filter(c=>{const d=Ut(c.directory??"");return d?Vr(d,s)||n!==s&&Vr(d,n):!1}),a=async l=>{const c=await t.session.list({directory:l});return Array.isArray(c.data)?c.data:[]};try{const l=o(await a(s));if(l.length>0)return l}catch{}if(n&&n!==s)try{const l=o(await a(n));if(l.length>0)return l}catch{}try{const l=await t.session.list(void 0),c=Array.isArray(l.data)?l.data:[];return o(c)}catch{return[]}},zk=async(t,r)=>{const s=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&s.set(Ut(o.path),o.worktreeMetadata)});const n=Array.from(new Set(t.sessions.map(o=>Ut(o.path)))).filter(Boolean).filter(o=>!s.has(o));if(n.length===0)return s;try{const o=await Zn(r),a=new Map(o.map(l=>[Ut(l.worktree),l]));n.forEach(l=>{const c=a.get(l);c&&s.set(l,eo(r,c))})}catch{}return s},Xi=async t=>{const{apiClient:r,group:s,projectDirectory:n,worktreePaths:o}=t,a=await zk(s,n),l=ge.getState(),c=Array.from(new Set(o.map(p=>Ut(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<c.length;){const p=c[u];u+=1;const h=s.sessions.filter(w=>Ut(w.path)===p).map(w=>w.id),x=l.getSessionsByDirectory(p),g=Array.isArray(x)?x.map(w=>w.id):[];let b=[];if(g.length===0)try{b=(await Kp(r,p)).map(S=>S.id)}catch{b=[]}const y=Array.from(new Set([...g,...b,...h].filter(Boolean)));m.push({worktreePath:p,sessionIds:y,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,c.length)},f)),m};function Hk(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),l=r.length>=4&&!isNaN(a)&&String(a)===o,c=l?r.slice(2,-1):r.slice(2);if(c.length===0)return null;const d=c.join("/");return{groupSlug:s,provider:n,model:d,index:l?a:1}}const Kr=rs()(fs((t,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const s=wt.getState().currentDirectory,n=da(s);if(!n){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Ut(n),a=Ju(o),l=r().groups;t({isLoading:!0,error:null});try{const c=Oe.getApiClient(),d=await qp(c,o),u=Ju(d);let m=new Map,f=[];try{f=await Zn(o),m=new Map(f.map(S=>[Ut(S.worktree),S]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const C=await c.session.list({directory:o}),v=Array.isArray(C.data)?C.data:[];if(v.some(j=>{const M=Ut(j.directory??"");return Vr(M,a)||Vr(M,u)}))return v}catch{}const S=await c.session.list(void 0);return Array.isArray(S.data)?S.data:[]},h=async S=>{const C=new Map,v=5;let j=0;const M=async()=>{for(;j<S.length;){const k=S[j];j+=1;const D=Ut(k);if(D)try{(await Kp(c,D)).forEach(T=>C.set(T.id,T))}catch(N){console.debug("Failed to fetch sessions from worktree:",D,N)}}};return await Promise.all(Array.from({length:Math.min(v,S.length)},M)),Array.from(C.values())};let g=(await p()).filter(S=>{const C=Ut(S.directory??"");return C?Vr(C,a)||Vr(C,u):!1});if(g.length===0){const S=new Set;f.map(v=>Ut(v.worktree)).filter(v=>Vr(v,a)||Vr(v,u)).forEach(v=>S.add(v));const C=Array.from(new Set([a,u].map(v=>Ut(v)).filter(Boolean)));await Promise.all(C.map(async v=>{(await Bk(v)).forEach(M=>S.add(M))})),S.size>0&&(g=await h(Array.from(S)))}const b=new Map;for(const S of g){const C=S.time?.updated??0;b.set(S.id,typeof C=="number"?C:0)}const y=new Map;for(const S of g){const C=Hk(S.title);if(!C)continue;const v=Ut(S.directory),j=m.get(v),M={id:S.id,path:v,providerId:C.provider,modelId:C.model,instanceNumber:C.index,branch:j?.branch??"",displayLabel:`${C.provider}/${C.model}`,worktreeMetadata:j?eo(o,j):void 0},k=y.get(C.groupSlug);k?k.push(M):y.set(C.groupSlug,[M])}const w=Array.from(y.entries()).map(([S,C])=>{const v=C.reduce((j,M)=>{const k=b.get(M.id)??0;return Math.max(j,k)},0);return{name:S,sessions:C.sort((j,M)=>{const k=j.providerId.localeCompare(M.providerId);if(k!==0)return k;const D=j.modelId.localeCompare(M.modelId);return D!==0?D:j.instanceNumber-M.instanceNumber}),lastActive:v||Date.now(),sessionCount:C.length}});w.sort((S,C)=>S.name.localeCompare(C.name)),t({groups:w,isLoading:!1,error:null})}catch(c){console.error("Failed to load agent groups:",c),t({groups:l.length>0?l:[],isLoading:!1,error:c instanceof Error?c.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(l=>l.name===s);if(!n)return!1;const o=wt.getState().currentDirectory,a=da(o);if(!a)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const l=Oe.getApiClient(),c=await Xi({apiClient:l,group:n,projectDirectory:Ut(a),worktreePaths:n.sessions.map(f=>f.path)}),d=ge.getState(),u=new Set;c.forEach(({worktreePath:f,sessionIds:p,metadata:h})=>{p.forEach(x=>{u.add(x),h&&(d.setWorktreeMetadata(x,h),d.setSessionDirectory(x,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(l){return t({error:l instanceof Error?l.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=Ut(n);if(!a)return!1;const l=wt.getState().currentDirectory,c=da(l);if(!c)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const d=Oe.getApiClient(),u=await Xi({apiClient:d,group:o,projectDirectory:Ut(c),worktreePaths:[a]}),m=ge.getState(),f=new Set;u.forEach(({worktreePath:x,sessionIds:g,metadata:b})=>{g.forEach(y=>{f.add(y),b&&(m.setWorktreeMetadata(y,b),m.setSessionDirectory(y,x))})});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(x=>x.name===s);if(!h)return r().selectedGroupName===s&&t({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===s){const x=r().selectedSessionId,g=new Set(h.sessions.map(b=>b.id));(!x||!g.has(x))&&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=Ut(n);if(!a)return!1;const c=Array.from(new Set(o.sessions.map(m=>Ut(m.path)).filter(Boolean))).filter(m=>m!==a);if(c.length===0)return!0;const d=wt.getState().currentDirectory,u=da(d);if(!u)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const m=Oe.getApiClient(),f=await Xi({apiClient:m,group:o,projectDirectory:Ut(u),worktreePaths:c}),p=ge.getState(),h=new Set;f.forEach(({worktreePath:g,sessionIds:b,metadata:y})=>{b.forEach(w=>{h.add(w),y&&(p.setWorktreeMetadata(w,y),p.setSessionDirectory(w,g))})});const{failedIds:x}=await p.deleteSessions(Array.from(h),{archiveWorktree:!0,silent:!0});if(x.length>0&&t({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===s){const g=r().groups.find(y=>y.name===s),b=g?.sessions.find(y=>Ut(y.path)===a)??g?.sessions[0]??null;t({selectedSessionId:b?.id??null})}return x.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"})),Wk=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`},Uk=({group:t,isSelected:r,onSelect:s})=>{const[n,o]=i.useState(!1),[a,l]=i.useState(!1),[c,d]=i.useState(!1),u=Kr(f=>f.deleteGroup),m=i.useCallback(async()=>{if(c)return;if(d(!0),W.info(`Deleting "${t.name}"...`),await u(t.name))W.success(`Deleted "${t.name}"`);else{const p=Kr.getState().error;W.error(p||`Failed to delete "${t.name}"`)}d(!1),l(!1)},[u,t.name,c]);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(qt,{className:"h-3 w-3"}),t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:Wk(t.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(es,{open:n,onOpenChange:o,children:[e.jsx(ts,{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(Zr,{className:"h-3.5 w-3.5"})})}),e.jsx(ss,{align:"end",className:"min-w-[140px]",children:e.jsx(Ct,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),l(!0)},children:"Delete"})})]})})]})}),e.jsx(us,{open:a,onOpenChange:l,children:e.jsxs(ms,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Delete agent group"}),e.jsxs(Ns,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Vs,{children:[e.jsx(Se,{variant:"outline",onClick:()=>l(!1),disabled:c,children:"Cancel"}),e.jsx(Se,{variant:"destructive",onClick:()=>{m()},disabled:c,children:c?"Deleting…":"Delete"})]})]})})]})},Vk=({className:t,selectedGroupName:r,onGroupSelect:s,onNewAgent:n})=>{const[o,a]=i.useState(""),[l,c]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Kr(),f=wt(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]),x=l?h:h.slice(0,p),g=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(Us,{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(cs,{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(Gt,{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(jt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[x.map(b=>e.jsx(Uk,{group:b,isSelected:r===b.name,onSelect:()=>s?.(b.name)},b.name)),!l&&g>0&&e.jsxs("button",{type:"button",onClick:()=>c(!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 (",g,")"]}),l&&h.length>p&&e.jsx("button",{type:"button",onClick:()=>c(!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"})]})]})]})},Gk=10*1024*1024,qk=5,Kk=({className:t,onCreateGroup:r,isCreating:s=!1})=>{const[n,o]=i.useState(""),[a,l]=i.useState(""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState("HEAD"),[h,x]=i.useState([]),[g,b]=i.useState(!1),[y,w]=i.useState([]),[S,C]=i.useState(!1),[v,j]=i.useState(!1),M=i.useRef(null),k=i.useRef(null),D=wt(_=>_.currentDirectory??null),{isGitRepository:N,isLoading:T}=gc(D),A=i.useMemo(()=>{if(typeof window>"u")return null;const _=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof _=="string"&&_.trim().length>0?_.trim():null},[]),E=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),I=Wt(_=>_.activeProjectId),P=Wt(_=>_.projects),F=i.useMemo(()=>{if(E&&A)return A;if(I){const O=P.find(le=>le.id===I);if(O?.path)return O.path}const _=D??A;if(!_)return null;const H=_.replace(/\\/g,"/").replace(/\/+$/,"")||_,B=H.indexOf("/.openchamber/");return B>0?H.slice(0,B):H.endsWith("/.openchamber")?H.slice(0,H.length-13):H},[I,P,D,A,E]);i.useEffect(()=>{if(!F)return;let _=!1;return j(!0),(async()=>{try{const H=await En(F);_||w(H)}catch{}finally{_||j(!1)}})(),()=>{_=!0}},[F]);const $=i.useCallback(_=>{c.length>=qk||d(H=>[...H,_])},[c.length]),Q=i.useCallback(_=>{d(H=>H.filter((L,B)=>B!==_))},[]),ie=i.useCallback((_,H)=>{d(L=>L.map((B,O)=>O===_?H:B))},[]),K=async _=>{const H=_.target.files;if(!H)return;let L=0;for(let B=0;B<H.length;B++){const O=H[B];if(O.size>Gk){W.error(`File "${O.name}" is too large (max 10MB)`);continue}try{const le=await new Promise((pe,De)=>{const z=new FileReader;z.onload=()=>pe(z.result),z.onerror=De,z.readAsDataURL(O)}),we={id:Ga(),filename:O.name,mimeType:O.type||"application/octet-stream",size:O.size,dataUrl:le};x(pe=>[...pe,we]),L++}catch(le){console.error("File attach failed",le),W.error(`Failed to attach "${O.name}"`)}}L>0&&W.success(`Attached ${L} file${L>1?"s":""}`),M.current&&(M.current.value="")},ee=_=>{x(H=>H.filter(L=>L.id!==_))},V=g||s,ae=!!(n.trim()&&a.trim()&&c.length>=1&&N&&!T),G=async _=>{if(_.preventDefault(),!(!ae||V)){b(!0);try{const H=c.map(({providerID:O,modelID:le,displayName:we,variant:pe})=>({providerID:O,modelID:le,displayName:we,variant:pe})),L=h.length>0?h.map(O=>({mime:O.mimeType,filename:O.filename,url:O.dataUrl})):void 0,B=y.filter(O=>O.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:H,agent:u||void 0,worktreeBaseBranch:f,files:L,setupCommands:B.length>0?B:void 0}),o(""),l(""),d([]),m(""),x([]),p("HEAD")}catch(H){console.error("Failed to create agent group:",H),W.error("Failed to create agent group")}finally{b(!1)}}},q=_=>{pc(_)||_.key==="Enter"&&!_.shiftKey&&(_.preventDefault(),ae&&!V&&G(_))};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:G,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:_=>o(_.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(qt,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(Xf,{directory:D,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(co,{open:S,onOpenChange:C,children:[e.jsxs($o,{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(_=>_.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",y.filter(_=>_.trim()).length," configured)"]})]}),e.jsx(Gt,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",S&&"rotate-180")})]}),e.jsx(uo,{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_WORKTREE_PATH"})," for project root."]}),v?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[y.map((_,H)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(St,{value:_,onChange:L=>{const B=[...y];B[H]=L.target.value,w(B)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const L=y.filter((B,O)=>O!==H);w(L)},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(os,{className:"h-4 w-4"})})]},H)),e.jsxs("button",{type:"button",onClick:()=>w([...y,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(cs,{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(Zf,{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(Jf,{selectedModels:c,onAdd:$,onRemove:Q,onUpdate:ie,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(Rs,{ref:k,id:"prompt",value:a,onChange:_=>l(_.target.value),onKeyDown:q,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(_=>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:[_.mimeType.startsWith("image/")?e.jsx(kr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(wr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:_.filename,children:_.filename}),e.jsx("button",{type:"button",onClick:()=>ee(_.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(os,{className:"h-3.5 w-3.5"})})]},_.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:M,type:"file",multiple:!0,className:"hidden",onChange:K,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>M.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(jm,{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:[c.length," model",c.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!ae||V,className:R("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",ae?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:V?e.jsx(Cx,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Fo,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},Qk=({group:t,className:r})=>{const{selectedSessionId:s,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Kr(),{setCurrentSession:l,currentSessionId:c}=ge(),[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),l(S.id)},[n,l]);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!==c&&l(S.id),s||n(S.id))}},[t.name,t.sessions,s,c,n,l]);const x=p?.id===c,g=i.useCallback(()=>{if(!p?.path){W.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{W.success("Worktree path copied")}).catch(()=>{W.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]),w=i.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(W.info("Removing worktree..."),await o(t.name,d.path))W.success("Worktree removed");else{const C=Kr.getState().error;W.error(C||"Failed to remove worktree");return}else if(W.info("Removing other worktrees..."),await a(t.name,d.path))W.success("Removed other worktrees");else{const C=Kr.getState().error;W.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(qt,{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(es,{children:[e.jsx(ts,{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(Gt,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(ss,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:t.sessions.map(S=>e.jsxs(Ct,{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(qt,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:S.worktreeMetadata?.label||S.branch})]})]}),p?.id===S.id&&e.jsx($t,{className:"h-4 w-4 text-primary flex-shrink-0"})]},S.id))})]})}),e.jsxs(es,{children:[e.jsx(ts,{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(Zr,{className:"h-4 w-4"})})}),e.jsxs(ss,{align:"end",className:"min-w-[220px]",children:[e.jsx(Ct,{onSelect:S=>{S.preventDefault(),b()},variant:"destructive",children:"Remove this worktree"}),e.jsx(Ct,{onSelect:S=>{S.preventDefault(),y()},children:"Leave this one, remove others"}),e.jsxs(Ct,{onClick:S=>{S.stopPropagation(),g()},disabled:!p?.path,children:[e.jsx(sr,{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(Ns,{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(Vs,{children:[e.jsx(Se,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Se,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{w()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?x?e.jsx(Mp,{sessionId:p.id,children:e.jsx(Cp,{})}):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"})})})]})},Yk=({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=et(S=>S.isInitialized),a=et(S=>S.initializeApp),l=ge(S=>S.loadSessions),c=wt(S=>S.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Kr(),{createMultiRun:h,isLoading:x}=No();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=v=>{const M=v.detail?.status;(M==="connected"||M==="connecting"||M==="error"||M==="disconnected")&&n(M)};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{c(C,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const j=et.getState();if(!j.isInitialized||!j.isConnected||j.providers.length===0||j.agents.length===0)return;await l(),hs()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:j.providers.length,agents:j.agents.length,sessions:ge.getState().sessions.length})}catch{}})()},[s,o,a,r,l,c]);const g=i.useCallback(S=>{m(S)},[m]),b=i.useCallback(()=>{m(null)},[m]),y=i.useCallback(async S=>{W.info(`Creating agent group "${S.name}" with ${S.models.length} model(s)...`);const C=await h(S);if(C){W.success(`Agent group "${S.name}" created with ${C.sessionIds.length} session(s)`);const v=C.groupSlug,j=async(M=6)=>{for(let k=0;k<M;k+=1){if(await p(),Kr.getState().groups.some(N=>N.name===v))return!0;await new Promise(N=>setTimeout(N,500))}return!1};try{await ge.getState().loadSessions()}catch{}await j(),m(v)}else{const v=No.getState().error;W.error(v||"Failed to create agent group")}},[h,p,m]),w=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(Vk,{selectedGroupName:u,onGroupSelect:g,onNewAgent:b})}),e.jsx("div",{className:"flex-1 min-w-0",children:w?e.jsx(Qk,{group:w}):e.jsx(Kk,{onCreateGroup:y,isCreating:x})})]})},Jk=(t=5e3)=>{const[r,s]=_e.useState(null);return _e.useEffect(()=>{if(!ds())return;let n=!1,o=null;const a=async()=>{const l=await Qx();n||(s(l),o=setTimeout(a,t))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[t]),r},Xk=({onClose:t})=>{const{sessions:r,messages:s,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:l}=ge(),c=Jk(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(lc,{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(Mx,{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(os,{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," / ",Ar.MAX_SESSIONS]})]})]}),c&&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:c.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:[c.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:c.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:[Ar.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:[Ar.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:[Ar.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(jt,{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(Dx,{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>Ar.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsxs(Se,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Ks,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(ft,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Se,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{l()},children:"Evict LRU"})}),e.jsx(ft,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{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(ft,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},Zk="openchamber-message-cursors",oo="cursors",eC=1,Qp="openchamber.messageCursors",Sc=()=>typeof window<"u",Nc=()=>Sc()&&typeof indexedDB<"u",Yp=()=>Nc()?new Promise((t,r)=>{const s=indexedDB.open(Zk,eC);s.onupgradeneeded=()=>{const n=s.result;n.objectStoreNames.contains(oo)||n.createObjectStore(oo)},s.onerror=()=>{r(s.error??new Error("Failed to open IndexedDB"))},s.onsuccess=()=>{t(s.result)}}):Promise.reject(new Error("IndexedDB not supported")),Jp=()=>{if(!Sc())return{};try{const t=window.localStorage.getItem(Qp);if(!t)return{};const r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},tC=t=>{if(Sc())try{window.localStorage.setItem(Qp,JSON.stringify(t))}catch{}},sC=async(t,r,s)=>{if(!t||!r)return;if(Nc())try{const o=await Yp();await new Promise((a,l)=>{const c=o.transaction(oo,"readwrite");c.objectStore(oo).put({messageId:r,completedAt:s},t),c.oncomplete=()=>a(),c.onerror=()=>l(c.error??new Error("Cursor write failed")),c.onabort=()=>l(c.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=Jp();n[t]={messageId:r,completedAt:s},tC(n)},rC=async t=>{if(!t)return null;if(Nc())try{const s=await Yp(),n=await new Promise((o,a)=>{const l=s.transaction(oo,"readonly"),d=l.objectStore(oo).get(t);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),l.onerror=()=>a(l.error??new Error("Cursor read failed")),l.onabort=()=>a(l.error??new Error("Cursor read aborted"))});return s.close(),n}catch{}return Jp()[t]??null},nC=50,oC=750,Xu=new WeakMap,Zu=t=>{if(!t||!Array.isArray(t))return 0;const r=Xu.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 Xu.set(t,s),s},aC=10,em=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<aC?null:n},tm=(t,r)=>{const s=em(t),n=em(r);return!s||!n||s.length!==n.length?!0:s>n},Fl=new Map,Zi=(t,r)=>{const s=`${t}:${r}`,n=Fl.get(s);if(n&&n.sessionId===t)return n.message;const l=(ge.getState().messages.get(t)||[]).find(c=>c.info.id===r)||null;return Fl.set(s,{sessionId:t,message:l}),l},iC=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(" ")},lC=()=>{const{addStreamingPart:t,completeStreamingMessage:r,updateMessageInfo:s,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:l,currentSessionId:c,applySessionMetadata:d,getWorktreeMetadata:u,loadMessages:m,loadSessions:f,updateSession:p,removeSessionFromStore:h}=ge(),{checkConnection:x}=et(),g=je(Ne=>Ne.nativeNotificationsEnabled),b=je(Ne=>Ne.notificationMode),y=wt(Ne=>Ne.currentDirectory),w=i.useMemo(()=>{if(!c)return;try{const We=u?.(c);if(We?.path)return We.path}catch(We){console.warn("Failed to inspect worktree metadata for session directory:",We)}const ue=ge.getState().sessions.find(We=>We.id===c);if(ue&&typeof ue.directory=="string"&&ue.directory.trim().length>0)return ue.directory.trim()},[c,u]),S=i.useMemo(()=>{if(w&&w.length>0)return w;if(typeof y=="string"&&y.trim().length>0)return y.trim()},[w,y]);i.useEffect(()=>{let Ne=!1;const ue=async()=>{try{const ve=await Oe.listPendingPermissions();if(Ne||ve.length===0)return;for(const ke of ve)o(ke)}catch{}},We=async()=>{try{const ke=Wt.getState().projects.map(Ve=>Ve.path),ct=ge.getState().sessions.map(Ve=>Ve.directory),Ue=[S,...ke,...ct],Be=await Oe.listPendingQuestions({directories:Ue});if(Ne||Be.length===0)return;for(const Ve of Be)a(Ve)}catch{}};return ue(),We(),()=>{Ne=!0}},[o,a,S]);const C=i.useCallback(Ne=>{if(typeof Ne!="string")return null;const ue=Ne.trim();if(!ue)return null;const We=ue.replace(/\\/g,"/");return We.length>1?We.replace(/\/+$/,""):We},[]),v=i.useCallback(Ne=>{if(!Ne)return null;try{const ve=u?.(Ne),ke=C(ve?.path??null);if(ke)return ke}catch{}const We=ge.getState().sessions.find(ve=>ve.id===Ne);return C(We?.directory??null)},[u,C]),j=je(Ne=>Ne.setEventStreamStatus),M=i.useRef(null),k=i.useCallback((Ne,ue)=>{const We=ue??null,ve=M.current;if(!(ve&&ve.status===Ne&&ve.hint===We)){if(M.current={status:Ne,hint:We},hs()){const Ze={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[Ne]??"[INFO]",ct=We?`${Ze} SSE ${Ne}: ${We}`:`${Ze} SSE ${Ne}`;console.info(ct)}j(Ne,We)}},[j]),D=i.useCallback((Ne,ue,We)=>{if(!Ne)return Promise.resolve();const ve=Date.now();if(K.current)return K.current;if(ve-ee.current<oC)return Promise.resolve();const ke=m(Ne,We).catch(Ze=>{console.warn(`[useEventStream] Failed to resync messages (${ue}):`,Ze)}).finally(()=>{K.current=null,ee.current=Date.now()});return K.current=ke,ke},[m]),N=i.useCallback(async Ne=>{hs()&&console.info("[useEventStream] Bootstrapping state:",Ne);try{await Promise.all([f(),c?D(c,Ne,1/0):Promise.resolve()])}catch(ue){console.warn("[useEventStream] Bootstrap failed:",Ne,ue)}},[c,f,D]),T=i.useCallback((Ne,ue,We)=>{hs()&&console.debug(`[MessageTracker] ${Ne}: ${ue}`,We)},[]),A=i.useCallback(Ne=>{hs()&&console.debug(`[MessageTracker] ${Ne}: reported`)},[]),E=i.useRef(null),I=i.useRef(null),P=i.useRef(0);i.useRef(new Set);const F=i.useRef(new Set),$=i.useRef(new Map),Q=i.useRef(null),ie=i.useRef(!1),K=i.useRef(null),ee=i.useRef(0),V=i.useRef(new Set),ae=i.useRef(new Set),G=i.useRef(new Set),q=i.useRef(new Set),_=i.useRef(new Set),H=i.useRef(new Map),L=i.useCallback(()=>{if(typeof document>"u")return"visible";const Ne=document.visibilityState;return Ne==="hidden"&&document.hasFocus()?"visible":Ne},[]),B=i.useRef(L()),O=i.useRef(typeof navigator>"u"?!0:navigator.onLine),le=i.useRef(!1),we=i.useRef(null),pe=i.useRef(null),De=i.useRef(Date.now()),z=i.useRef(!1),he=i.useCallback(Ne=>{const ue=Date.now();ue-De.current>25e3&&(N(Ne),De.current=ue)},[N]);i.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(z.current=!0)},[]);const Z=i.useRef(new Map),de=i.useRef(new Map),Ee=i.useRef(0),ne=i.useRef(null),ye=i.useRef(c),te=i.useRef(null),ce=i.useRef(null);i.useEffect(()=>{ye.current=c},[c]);const X=i.useCallback((Ne,ue)=>{if(!Ne)return;const We=Date.now(),ve=$.current,ke=ve.get(Ne);if(ke&&We-ke<3e3)return;ve.set(Ne,We);const Ze=ct=>{if(typeof ue=="string"&&ue.trim().length>0)return ue.trim();try{const Ve=u?.(ct);if(Ve?.path)return Ve.path}catch{}const Be=ge.getState().sessions.find(Ve=>Ve.id===ct);return Be&&typeof Be.directory=="string"&&Be.directory.trim().length>0?Be.directory.trim():null};setTimeout(async()=>{try{const ct=Ze(Ne),Ue=ct?await Oe.withDirectory(ct,()=>Oe.getSession(Ne)):await Oe.getSession(Ne);if(Ue){const Be={};typeof Ue.title=="string"&&Ue.title.length>0&&(Be.title=Ue.title),Ue.summary!==void 0&&(Be.summary=Ue.summary),Object.keys(Be).length>0&&d(Ne,Be)}}catch(ct){console.warn("Failed to refresh session metadata:",ct)}},100)},[d,u]),U=i.useCallback((Ne,ue)=>{if(ge.getState().sessionActivityPhase?.get(Ne)===ue){de.current=new Map(ge.getState().sessionActivityPhase??new Map);return}const ve=Z.current.get(Ne);ve&&(clearTimeout(ve),Z.current.delete(Ne));const ke=new Map(ge.getState().sessionActivityPhase??new Map);if(ke.set(Ne,ue),de.current=ke,ge.setState({sessionActivityPhase:ke}),ue==="cooldown"){const Ze=setTimeout(()=>{if(Z.current.delete(Ne),ge.getState().sessionActivityPhase?.get(Ne)==="cooldown"){const Ue=new Map(ge.getState().sessionActivityPhase??new Map);Ue.set(Ne,"idle"),de.current=Ue,ge.setState({sessionActivityPhase:Ue})}},2e3);Z.current.set(Ne,Ze)}},[]),Y=i.useCallback(async()=>{const Ne=Date.now();if(ne.current)return ne.current;if(Ne-Ee.current<1500)return;Ee.current=Ne;const ue=ve=>{const ke=new Set,Ze=ge.getState().sessions,ct=new Set(Ze.map(Be=>Be.id));for(const[Be,Ve]of Object.entries(ve)){if(!Be||!Ve)continue;ke.add(Be);const dt=Ve.type==="busy"||Ve.type==="retry"?"busy":"idle";U(Be,dt)}const Ue=ge.getState().sessionActivityPhase;if(Ue)for(const[Be,Ve]of Ue.entries())ct.has(Be)&&(Ve==="busy"||Ve==="cooldown")&&!ke.has(Be)&&U(Be,"idle")},We=(async()=>{try{if(dr()){const dt=await Oe.getWebServerSessionActivity();if(dt&&Object.keys(dt).length>0){ue(dt);return}}const ve=await Oe.getGlobalSessionStatus();if(ve&&Object.keys(ve).length>0){ue(ve);return}const ke=new Set,Ze=ge.getState().sessions;for(const dt of Ze){const pt=v(dt.id);pt&&ke.add(pt)}const ct=C(S??null);ct&&ke.add(ct);const Ue=Array.from(ke);if(Ue.length===0){const dt=await Oe.getSessionStatus();dt&&ue(dt);return}const Be=await Promise.allSettled(Ue.map(dt=>Oe.getSessionStatusForDirectory(dt))),Ve={};for(const dt of Be)dt.status!=="fulfilled"||!dt.value||Object.assign(Ve,dt.value);if(Object.keys(Ve).length===0&&Array.from(ge.getState().sessionActivityPhase?.values?.()??[]).some(pt=>pt==="busy"||pt==="cooldown")&&!await Oe.checkHealth().catch(()=>!1))return;ue(Ve)}catch{}})().finally(()=>{ne.current=null});return ne.current=We,We},[S,C,v,U]);i.useEffect(()=>{const Ne=c??null,ue=te.current,We=v(Ne),ve=ce.current;ue&&Ne&&ue!==Ne&&ve&&We&&ve!==We&&Y(),te.current=Ne,ce.current=We},[c,Y,v]);const se=i.useCallback(Ne=>{if(De.current=Date.now(),hs()&&console.debug("[useEventStream] Received event:",Ne.type,Ne.properties),!Ne.properties)return;const ue=Ne.properties;if(!new Set(["session.abort","session.error"]).has(Ne.type)){const ve=(typeof ue.session=="object"&&ue.session!==null?ue.session:null)||(typeof ue.sessionInfo=="object"&&ue.sessionInfo!==null?ue.sessionInfo:null);if(ve){const ke=ve,Ze=typeof ke.id=="string"&&ke.id.length>0?ke.id:typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof ue.sessionID=="string"&&ue.sessionID.length>0?ue.sessionID:typeof ue.id=="string"&&ue.id.length>0?ue.id:void 0;if(Ze){const ct=typeof ke.title=="string"?ke.title:typeof ue.title=="string"?ue.title:void 0,Ue=typeof ke.summary=="object"&&ke.summary!==null?ke.summary:typeof ue.summary=="object"&&ue.summary!==null?ue.summary:void 0;if(ct!==void 0||Ue!==void 0){const Be={};ct!==void 0&&(Be.title=ct),Ue!==void 0&&(Be.summary=Ue),d(Ze,Be)}}}}switch(Ne.type){case"server.connected":x();break;case"global.disposed":case"server.instance.disposed":{N("server_disposed_event");break}case"openchamber:session-activity":{const ve=typeof ue.sessionId=="string"?ue.sessionId:null,ke=typeof ue.phase=="string"?ue.phase:null;ve&&(ke==="idle"||ke==="busy"||ke==="cooldown")&&(U(ve,ke),X(ve,typeof ue.directory=="string"?ue.directory:null));break}case"mcp.tools.changed":{const ve=typeof ue.directory=="string"?ue.directory:S;bo.getState().refresh({directory:ve??null,silent:!0});break}case"session.status":if(z.current)break;{const ve=typeof ue.sessionID=="string"?ue.sessionID:null,ke=typeof ue.status=="object"&&ue.status!==null?ue.status:null,Ze=typeof ke?.type=="string"?ke.type:null;ve&&Ze&&(U(ve,Ze==="busy"||Ze==="retry"?"busy":"idle"),X(ve,typeof ue.directory=="string"?ue.directory:null))}break;case"message.part.updated":{const ve=typeof ue.part=="object"&&ue.part!==null?ue.part:null;if(!ve)break;const ke=ve,Ze=typeof ue.info=="object"&&ue.info!==null?ue.info:ue,ct=typeof Ze.sessionID=="string"?Ze.sessionID:null,Ue=typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof ct=="string"&&ct.length>0?ct:typeof ue.sessionID=="string"&&ue.sessionID.length>0?ue.sessionID:null,Be=typeof Ze.id=="string"?Ze.id:null,Ve=typeof ke.messageID=="string"&&ke.messageID.length>0?ke.messageID:typeof Be=="string"&&Be.length>0?Be:typeof ue.messageID=="string"&&ue.messageID.length>0?ue.messageID:null;if(!Ue||!Ve){hs()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:ke.sessionID??ct??ue.sessionID,messageID:ke.messageID??Be??ue.messageID});break}const dt=Ue,pt=Ve,Ge=ge.getState().sessionMemoryState.get(dt)?.trimmedHeadMaxId;if(Ge&&!tm(pt,Ge)){hs()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:dt,messageId:pt,trimmedHeadMaxId:Ge});break}let ut="assistant";if(Ze&&typeof Ze.role=="string")ut=Ze.role;else{const kt=Zi(dt,pt);if(kt){const At=kt.info.role;typeof At=="string"&&(ut=At)}}if(T(pt,"part_received",{role:ut}),ut==="user"&&ke.synthetic===!0){T(pt,"skipped_synthetic_user_part");break}const xt={...ve,type:ve.type||"text"};T(pt,"addStreamingPart_called"),t(dt,pt,xt,ut);break}case"message.updated":{const ve=typeof ue.info=="object"&&ue.info!==null?ue.info:ue,ke=ve,Ze=typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof ue.sessionID=="string"&&ue.sessionID.length>0?ue.sessionID:null,ct=typeof ke.id=="string"&&ke.id.length>0?ke.id:typeof ue.messageID=="string"&&ue.messageID.length>0?ue.messageID:null;if(!Ze||!ct){hs()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:ke.sessionID??ue.sessionID,messageID:ke.id??ue.messageID});break}const Ue=Ze,Be=ct,Ve=ge.getState().sessionMemoryState.get(Ue)?.trimmedHeadMaxId;if(Ve&&!tm(Be,Ve)){hs()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Ue,messageId:Be,trimmedHeadMaxId:Ve});break}if(z.current&&hs())try{const Lt=ue.parts||ke.parts||[],$e=(Array.isArray(Lt)?Lt.filter(Le=>Le?.type==="text"):[]).map(Le=>{const ot=Le;return typeof ot?.text=="string"?ot.text:typeof ot?.content=="string"?ot.content:""}).join(`
233
- `);console.info("[STREAM-TRACE] message.updated",{messageId:Be,role:ke.role,status:ke.status,textLen:$e.length,textPreview:$e.slice(0,120),partsCount:Array.isArray(Lt)?Lt.length:0})}catch{}if(T(Be,"message_updated",{role:ke.role}),ke.role==="user"){const Lt=ue.parts||ke.parts,Me=Array.isArray(Lt)?Lt:[],$e=Zi(Ue,Be),Le=(()=>{const fe=ke.agent;if(typeof fe=="string"&&fe.trim().length>0)return fe.trim();const xe=ke.mode;return typeof xe=="string"&&xe.trim().length>0?xe.trim():""})(),ot=(()=>{const xe=ke.time?.created;return typeof xe=="number"?xe:null})(),oe=Me.length>0&&Me.every(fe=>fe?.synthetic===!0),Te=(()=>{if(!Le)return!1;if(oe&&(Le==="plan"||Le==="build"))return!0;const fe=H.current.get(Ue);return fe?ot===null?!1:Be===fe.messageId?!0:ot>=fe.created:!0})();if(Le&&Te)try{const fe=et.getState().agents;if(Array.isArray(fe)&&fe.some(xe=>xe?.name===Le)){const xe=nt.getState();if(xe.saveSessionAgentSelection(Ue,Le),H.current.set(Ue,{created:ot??Date.now(),messageId:Be}),ye.current===Ue)try{et.getState().setAgent(Le)}catch{}const Re=ke.model,st=typeof Re?.providerID=="string"?Re.providerID:null,mt=typeof Re?.modelID=="string"?Re.modelID:null;if(st&&mt){xe.saveSessionModelSelection(Ue,st,mt),xe.saveAgentModelForSession(Ue,Le,st,mt);const Ot=typeof ke.variant=="string"?ke.variant:void 0;if(Ot&&xe.saveAgentModelVariantForSession(Ue,Le,st,mt,Ot),ye.current===Ue)try{et.getState().setProvider(st),et.getState().setModel(mt)}catch{}}}}catch{}if(oe&&(Le==="plan"||Le==="build")&&ye.current===Ue){const fe=`${Ue}:${Be}:${Le}`;_.current.has(fe)||(_.current.add(fe),Ss(async()=>{const{toast:xe}=await import("./vendor-.bun-koHRsLHN.js").then(Re=>Re.df);return{toast:xe}},__vite__mapDeps([0,1])).then(({toast:xe})=>{xe.info(Le==="plan"?"Plan mode active":"Build mode active",{description:Le==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const Ie={...ve,userMessageMarker:!0,clientRole:"user",...Le?{mode:Le}:{}};if(s(Ue,Be,Ie),!$e&&Me.length===0){const fe=`${Ue}:${Be}`;F.current.has(fe)||(F.current.add(fe),Oe.getSessionMessages(Ue,50).then(xe=>{ge.getState().syncMessages(Ue,xe)}).catch(()=>{}))}if(Me.length>0)for(let fe=0;fe<Me.length;fe++){const xe=Me[fe];if(xe.synthetic===!0){const mt=xe.text,Ot=typeof mt=="string"?mt.trim():"";if(!(Ot.startsWith("User has requested to enter plan mode")||Ot.startsWith("The plan at ")))continue}const st={...xe,type:xe?.type||"text",sessionID:xe?.sessionID||Ue,messageID:xe?.messageID||Be};t(Ue,Be,st,"user")}T(Be,"user_message_created_from_event",{partsCount:Me.length});break}const dt=Zi(Ue,Be),pt=Zu(dt?.parts||[]),Ge=dt?.info?.finish==="stop",ut=ue.parts||ke.parts,xt=Array.isArray(ut)?ut:[],kt=xt.length>0,Xt=typeof(ke.time||{})?.completed=="number";if(!kt&&!Xt)break;const as=ve.finish,_t=typeof as=="string"?as:null,Mt=_t==="stop";if(ke.role==="assistant"&&kt){const Lt=Zu(xt);if(pt>0&&Lt+nC<pt&&!Mt){T(Be,"skipped_shrinking_update",{incomingLen:Lt,existingLen:pt});break}if(z.current){const $e=pt>0&&Lt<pt,Le=xt.some(oe=>{if(!oe||oe.type!=="text")return!1;const Te=oe;return typeof Te.text=="string"&&Te.text.length>0});if($e&&!(Mt&&Le)){T(Be,"desktop_shrinking_update_suppressed",{incomingLen:Lt,existingLen:pt});break}}}if(s(Ue,Be,ve),kt&&ke.role!=="user"){const $e=(ge.getState().messages.get(Ue)||[]).find(oe=>oe.info.id===Be),Le=!$e||$e.parts.length===0;T(Be,Le?"server_parts_injected":"server_parts_refreshed",{count:xt.length});const ot=z.current&&ke.role==="assistant"?xt.filter(oe=>oe?.type!=="text"):xt;for(let oe=0;oe<ot.length;oe++){const Te=ot[oe],Ie={...Te,type:Te?.type||"text",sessionID:Te?.sessionID||Ue,messageID:Te?.messageID||Be};t(Ue,Be,Ie,ke.role),T(Be,`server_part_${oe}`)}}const Rt=ve.time,Jt=Rt?.completed,Ft=typeof Jt=="number"&&Number.isFinite(Jt),Qt=_t==="stop"||Ge;if(ve.role==="assistant"&&(Ft||Qt)&&ve.role==="assistant"){const Me=ge.getState().messages.get(Ue)||[];let $e=null,Le="";for(let xe=0;xe<Me.length;xe++){const Re=Me[xe];Re.info.role==="assistant"&&Re.info.id>Le&&(Le=Re.info.id,$e=Re.info.id)}if(c===Ue&&Be!==$e)break;if(!Qt&&z.current){T(Be,"desktop_completion_without_stop");break}const oe=Ft?Jt:Date.now();if(Ft||s(Ue,Be,{...ve,time:{...Rt??{},completed:oe}}),T(Be,"completed",{timeCompleted:oe}),A(Be),sC(Ue,Be,oe),r(Ue,Be),_t==="stop"&&dr()&&g&&(b==="always"||B.current==="hidden")){const Re=G.current;if(!Re.has(Be)){Re.add(Be);const st=Ps();if(st?.notifications){const mt=ke.mode||"agent",Ot=ke.modelID||"assistant",Bt=`${mt.charAt(0).toUpperCase()+mt.slice(1)} agent is ready`,Ms=`${iC(Ot)} completed the task`;st.notifications.notifyAgentCompletion({title:Bt,body:Ms,tag:Be})}}}z.current||_t==="stop"&&ge.getState().sessionActivityPhase?.get(Ue)==="busy"&&U(Ue,"cooldown");const Te=ve.sessionID,Ie=typeof Te=="string"&&Te.length>0?Te:Ue;X(Ie,typeof ue.directory=="string"?ue.directory:null),ve.summary&&typeof Ie=="string"&&n(Ie,null)}break}case"session.created":case"session.updated":{const ve=typeof ue.info=="object"&&ue.info!==null?ue.info:typeof ue.sessionInfo=="object"&&ue.sessionInfo!==null?ue.sessionInfo:typeof ue.session=="object"&&ue.session!==null?ue.session:ue,ke=typeof ve.id=="string"&&ve.id.length>0?ve.id:typeof ve.sessionID=="string"&&ve.sessionID.length>0?ve.sessionID:typeof ue.sessionID=="string"&&ue.sessionID.length>0?ue.sessionID:typeof ue.id=="string"&&ue.id.length>0?ue.id:void 0;if(ke){const Ze=typeof ve.time=="object"&&ve.time!==null?ve.time:typeof ue.time=="object"&&ue.time!==null?ue.time:null,ct=Ze&&typeof Ze.compacting=="number"?Ze.compacting:null;n(ke,ct);const Ue=typeof ve.directory=="string"?ve.directory:typeof ue.directory=="string"?ue.directory:null,Be={...ve,id:ke,...Ue?{directory:Ue}:{}};p(Be)}break}case"session.deleted":{const ve=typeof ue.sessionID=="string"?ue.sessionID:typeof ue.id=="string"?ue.id:null;ve&&h(ve);break}case"session.abort":{const ve=typeof ue.sessionID=="string"&&ue.sessionID.length>0?ue.sessionID:null,ke=typeof ue.messageID=="string"&&ue.messageID.length>0?ue.messageID:null;ve&&ke&&r(ve,ke);break}case"permission.asked":{if(!("sessionID"in ue)||typeof ue.sessionID!="string")break;const ve=ue;o(ve);const ke=`${ve.sessionID}:${ve.id}`;V.current.has(ke)||setTimeout(()=>{if(ye.current===ve.sessionID||!ge.getState().permissions.get(ve.sessionID)?.some(Be=>Be.id===ve.id))return;V.current.add(ke);const Ue=ge.getState().sessions.find(Be=>Be.id===ve.sessionID)?.title||"Session";if(Ss(async()=>{const{toast:Be}=await import("./vendor-.bun-koHRsLHN.js").then(Ve=>Ve.df);return{toast:Be}},__vite__mapDeps([0,1])).then(({toast:Be})=>{Be.warning("Permission required",{description:Ue,action:{label:"Open",onClick:()=>{je.getState().setActiveMainTab("chat"),ge.getState().setCurrentSession(ve.sessionID)}}})}),dr()&&g&&(b==="always"||B.current==="hidden")){const Ve=Ps();Ve?.notifications&&Ve.notifications.notifyAgentCompletion({title:"Permission required",body:Ue,tag:`permission-${ke}`})}},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in ue)||typeof ue.sessionID!="string")break;const ve=ue;a(ve);const ke=`${ve.sessionID}:${ve.id}`;if(dr()&&g&&(b==="always"||B.current==="hidden")){const ct=q.current;if(!ct.has(ke)){ct.add(ke);const Ue=Ps();if(Ue?.notifications){const Be=Array.isArray(ve.questions)?ve.questions[0]:void 0,Ve=typeof Be?.header=="string"?Be.header.trim():"",dt=typeof Be?.question=="string"?Be.question.trim():"",pt=/plan\s*mode/i.test(Ve)?"Switch to plan mode":/build\s*agent/i.test(Ve)?"Switch to build mode":Ve||"Input needed",Ge=dt||"Agent is waiting for your response";Ue.notifications.notifyAgentCompletion({title:pt,body:Ge,tag:ke})}}}ae.current.has(ke)||setTimeout(()=>{if(ye.current===ve.sessionID||!ge.getState().questions.get(ve.sessionID)?.some(Be=>Be.id===ve.id))return;ae.current.add(ke);const Ue=ge.getState().sessions.find(Be=>Be.id===ve.sessionID)?.title||"Session";Ss(async()=>{const{toast:Be}=await import("./vendor-.bun-koHRsLHN.js").then(Ve=>Ve.df);return{toast:Be}},__vite__mapDeps([0,1])).then(({toast:Be})=>{Be.info("Input needed",{description:Ue,action:{label:"Open",onClick:()=>{je.getState().setActiveMainTab("chat"),ge.getState().setCurrentSession(ve.sessionID)}}})})},0);break}case"question.replied":{const ve=typeof ue.sessionID=="string"?ue.sessionID:null,ke=typeof ue.requestID=="string"?ue.requestID:null;ve&&ke&&l(ve,ke);break}case"question.rejected":{const ve=typeof ue.sessionID=="string"?ue.sessionID:null,ke=typeof ue.requestID=="string"?ue.requestID:null;ve&&ke&&l(ve,ke);break}case"todo.updated":{const ve=typeof ue.sessionID=="string"?ue.sessionID:null,ke=Array.isArray(ue.todos)?ue.todos:null;ve&&ke&&hj(ve,ke);break}}},[c,g,b,t,r,s,o,a,l,x,X,n,d,T,A,U,p,h,N,S]),me=i.useCallback(()=>{const Ne=L();return B.current=Ne,Ne==="visible"&&O.current},[L]),ze=i.useCallback(()=>{hs()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:z.current,hasUnsubscribe:!!E.current,currentSessionId:ye.current,effectiveDirectory:S,onlineStatus:O.current,visibilityState:B.current,lastEventTimestamp:De.current,reconnectAttempts:P.current})},[S]),qe=i.useCallback(async()=>!0,[]),tt=i.useCallback(()=>{if(ie.current){hs()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(ie.current=!0,I.current&&(clearTimeout(I.current),I.current=null),E.current){const Ne=E.current;E.current=null;try{Ne()}catch(ue){console.warn("[useEventStream] Error during unsubscribe:",ue)}}ie.current=!1},[]),Xe=i.useCallback(async Ne=>{if(ze(),!me()){le.current=!0,O.current?k("paused","Paused while hidden"):k("offline","Waiting for network");return}z.current&&(await qe()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),Ne?.resetAttempts&&(P.current=0),tt(),De.current=Date.now(),k("connecting",null),hs()&&console.info("[useEventStream] Starting event stream...");const ue=ve=>{console.warn("Event stream error:",ve)},We=()=>{const ve=le.current;if(P.current=0,le.current=!1,De.current=Date.now(),k("connected",null),x(),Y(),ve)N("sse_reconnected");else{const ke=ye.current;ke&&setTimeout(()=>{D(ke,"sse_reconnected",1/0).then(()=>X(ke)).catch(Ze=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Ze)})},0)}};if(hs()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:S,isCleaningUp:ie.current}),ie.current){hs()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const ve=Oe.subscribeToGlobalEvents(Ze=>{const ct=Ze.payload,Ue=Ze.payload,Be=typeof Ue.properties=="object"&&Ue.properties!==null?Ue.properties:{},Ve=Ze.directory&&Ze.directory!=="global"?{...Be,directory:Ze.directory}:Be;se({type:typeof ct.type=="string"?ct.type:"",properties:Ve})},ue,We),ke=()=>{try{ve()}catch(Ze){console.warn("[useEventStream] Error during unsubscribe:",Ze)}};ie.current?ke():E.current=ke}catch(ve){console.error("[useEventStream] Error during subscription:",ve),ue(ve)}},[me,tt,k,x,D,X,se,S,Y,qe,ze,N]),Nt=i.useCallback(Ne=>{if(!me()){le.current=!0,tt(),O.current?k("paused","Paused while hidden"):k("offline","Waiting for network");return}const ue=P.current+1;P.current=ue;const We=Ne??`Retrying (${ue})`;k("reconnecting",We);const ve=ue<=3?Math.min(1e3*Math.pow(2,ue-1),8e3):Math.min(2e3*Math.pow(2,ue-3),32e3),ke=Math.floor(Math.random()*250),Ze=ve+ke;I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{Xe({resetAttempts:!1})},Ze)},[me,tt,k,Xe]);i.useEffect(()=>{const Ne=Z.current;typeof window<"u"&&(window.__messageTracker=T);let ue=null;z.current&&typeof window<"u"&&(ue=Ve=>{const dt=typeof Ve.detail?.sessionId=="string"?Ve.detail.sessionId:null,pt=typeof Ve.detail?.phase=="string"?Ve.detail.phase:null;dt&&(pt==="idle"||pt==="busy"||pt==="cooldown")&&(U(dt,pt),X(dt))},window.addEventListener("openchamber:session-activity",ue));const We=()=>{we.current&&(clearTimeout(we.current),we.current=null)},ve=()=>{we.current||(we.current=setTimeout(()=>{const Ve=L();B.current=Ve,Ve!=="visible"?(tt(),le.current=!0,k("paused","Paused while hidden")):We()},5e3))},ke=()=>{if(B.current=L(),B.current==="visible"){if(We(),he("visibility_restore"),le.current||!E.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ve=ye.current;Ve&&(D(Ve,"visibility_restore",hl()).catch(()=>{}),X(Ve)),Y(),k("connecting","Resuming stream"),Xe({resetAttempts:!0})}}else k("paused","Paused while hidden"),ve()},Ze=()=>{if(B.current=L(),B.current==="visible"&&(We(),he("window_focus"),le.current||!E.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ve=ye.current;Ve&&(X(Ve),D(Ve,"window_focus",hl()).then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(dt=>console.warn("[useEventStream] Failed to refresh messages:",dt))),Y(),k("connecting","Resuming stream"),Xe({resetAttempts:!0})}},ct=()=>{O.current=!0,he("network_restored"),(le.current||!E.current)&&(k("connecting","Network restored"),Xe({resetAttempts:!0}))},Ue=()=>{O.current=!1,le.current=!0,k("offline","Waiting for network"),tt()};typeof document<"u"&&document.addEventListener("visibilitychange",ke),typeof window<"u"&&(window.addEventListener("online",ct),window.addEventListener("offline",Ue),window.addEventListener("focus",Ze));const Be=setTimeout(()=>{Xe({resetAttempts:!0})},100);return pe.current&&clearInterval(pe.current),pe.current=setInterval(()=>{if(!me())return;const Ve=Date.now();Array.from(ge.getState().sessionActivityPhase?.values?.()??[]).some(pt=>pt==="busy"||pt==="cooldown")&&Y(),Ve-De.current>45e3&&Promise.resolve().then(async()=>{try{await Oe.checkHealth()?De.current=Date.now():Nt("Refreshing stalled stream")}catch(pt){console.warn("Health check after stale stream failed:",pt),Nt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Be),ue&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",ue),typeof document<"u"&&document.removeEventListener("visibilitychange",ke),typeof window<"u"&&(window.removeEventListener("online",ct),window.removeEventListener("offline",Ue),window.removeEventListener("focus",Ze)),We(),pe.current&&(clearInterval(pe.current),pe.current=null),Ne.forEach(Ve=>clearTimeout(Ve)),Ne.clear(),Fl.clear(),G.current.clear(),q.current.clear(),le.current=!1,B.current=L(),O.current=typeof navigator>"u"?!0:navigator.onLine,tt(),Q.current&&(clearTimeout(Q.current),Q.current=null),k("idle",null)}},[S,T,L,tt,k,Xe,Nt,m,X,U,Y,me,f,he,D])},cC=()=>{const{openNewSessionDraft:t,abortCurrentOperation:r,armAbortPrompt:s,clearAbortPrompt:n,currentSessionId:o}=ge(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=je(),{themeMode:p,setThemeMode:h}=Br(),{working:x}=cp(),g=i.useRef(null),b=i.useRef(null),y=i.useRef(!1),w=i.useCallback(()=>{b.current&&(clearTimeout(b.current),b.current=null),g.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:M,content:k})=>{const D=M||"openchamber.log",N=new Blob([k],{type:"text/plain;charset=utf-8"}),T=URL.createObjectURL(N),A=document.createElement("a");A.href=T,A.download=D,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(T)}).finally(()=>{y.current=!1});return}if($s(C)&&C.key==="."&&(C.preventDefault(),l()),$s(C)&&C.key.toLowerCase()==="n"){C.preventDefault();const v=Vt(),j=et.getState().settingsAutoCreateWorktree;if(v?!1:j?!C.shiftKey:C.shiftKey){u("chat"),d(!1),ci();return}u("chat"),d(!1),t()}if($s(C)&&C.key==="/"){C.preventDefault();const v=["light","dark","system"],M=(v.indexOf(p)+1)%v.length;h(v[M])}if($s(C)&&!C.shiftKey&&C.key.toLowerCase()==="t"){C.preventDefault();const{isTimelineDialogOpen:v,setTimelineDialogOpen:j}=je.getState();j(!v);return}if($s(C)&&!C.shiftKey&&C.key===","){C.preventDefault();const{isSettingsDialogOpen:v}=je.getState();m(!v);return}if($s(C)&&!C.shiftKey&&C.key.toLowerCase()==="l"){C.preventDefault();const{isMobile:v,isSessionSwitcherOpen:j}=je.getState();v?d(!j):c();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:v,isCommandPaletteOpen:j,isHelpDialogOpen:M,isSessionSwitcherOpen:k,isAboutDialogOpen:D,activeMainTab:N,isModelSelectorOpen:T}=je.getState();if(v||j||M||k||D||!(N==="chat"))return;C.preventDefault(),f(!T);return}if($s(C)&&C.shiftKey&&C.key.toLowerCase()==="t"){const{isSettingsDialogOpen:v,isCommandPaletteOpen:j,isHelpDialogOpen:M,isSessionSwitcherOpen:k,isAboutDialogOpen:D,activeMainTab:N}=je.getState();if(v||j||M||k||D||!(N==="chat"))return;const E=et.getState();if(E.getCurrentModelVariants().length===0)return;C.preventDefault(),E.cycleCurrentVariant();const P=et.getState().currentVariant,F=ge.getState(),$=F.currentSessionId,Q=et.getState().currentAgentName,ie=et.getState().currentProviderId,K=et.getState().currentModelId;$&&Q&&ie&&K&&F.saveAgentModelVariantForSession($,Q,ie,K,P);return}if(C.key==="Escape"){const{isSettingsDialogOpen:v,isCommandPaletteOpen:j,isHelpDialogOpen:M,isSessionSwitcherOpen:k,isAboutDialogOpen:D,activeMainTab:N}=je.getState();if(v){C.preventDefault(),m(!1),w();return}if(j||M||k||D||!(N==="chat")){w();return}const E=o;if(!(x.canAbort&&!!E)){w();return}const P=Date.now(),F=g.current;if(F&&P<F){C.preventDefault(),w(),r();return}C.preventDefault();const $=s(3e3)??P+3e3;g.current=$,b.current&&clearTimeout(b.current);const Q=Math.max($-P,0);b.current=setTimeout(()=>{g.current&&Date.now()>=g.current&&w()},Q||0);return}};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[t,r,a,l,c,d,u,m,f,h,p,x,s,w,o]),i.useEffect(()=>()=>{w()},[w])},sm="openchamber:menu-action",dC=t=>{const{openNewSessionDraft:r}=ge(),{toggleCommandPalette:s,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=je(),{addProject:u}=Wt(),{requestAccess:m,startAccessing:f}=di(),{setThemeMode:p}=Br(),h=i.useRef(!1),x=i.useCallback(()=>{ds()?m("").then(async g=>{if(!g.success||!g.path){g.error&&g.error!=="Directory selection cancelled"&&W.error("Failed to select directory",{description:g.error});return}const b=await f(g.path);if(!b.success){W.error("Failed to open directory",{description:b.error||"Desktop could not grant file access."});return}u(g.path,{id:g.projectId})||W.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(g=>{console.error("Desktop: Error selecting directory:",g),W.error("Failed to select directory")}):so.requestDirectoryDialog()},[u,m,f]);i.useEffect(()=>{const g=b=>{switch(b.detail){case"about":d(!0);break;case"settings":c(!0);break;case"command-palette":s();break;case"new-session":l("chat"),a(!1),r();break;case"new-worktree-session":l("chat"),a(!1),ci();break;case"change-workspace":x();break;case"open-git-tab":{const{activeMainTab:w}=je.getState();l(w==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:w}=je.getState();l(w==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:w}=je.getState();l(w==="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:v})=>{const j=C||"openchamber.log",M=new Blob([v],{type:"text/plain;charset=utf-8"}),k=URL.createObjectURL(M),D=document.createElement("a");D.href=k,D.download=j,document.body.appendChild(D),D.click(),document.body.removeChild(D),URL.revokeObjectURL(k),W.success("Logs saved",{description:`Downloaded to ~/Downloads/${j}`})}).catch(()=>{W.error("Failed to download logs")}).finally(()=>{h.current=!1});break}}};return window.addEventListener(sm,g),()=>window.removeEventListener(sm,g)},[r,s,n,o,a,l,c,d,p,t,x])},uC=t=>t.role==="assistant",rm=t=>{const r=t.info;if(!uC(r))return;const s=r.time?.completed;return typeof s=="number"?s:void 0},Da=t=>{if(!t)return!1;if(t.role==="user")return!0;const r=t;return r.clientRole==="user"?!0:!!r.userMessageMarker},nm=t=>(Array.isArray(t?.parts)?t.parts:[]).map(n=>an(n)).join(" ").replace(/\s+/g," ").trim(),mC=(t,r)=>{if(!t||!Da(t.info))return-1;const s=nm(t),n=typeof t.info?.time?.created=="number"?t.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((l,c)=>{if(!Da(l.info))return;const d=nm(l),u=!!(s&&d&&d===s),m=typeof l.info?.time?.created=="number"?l.info.time.created:void 0,f=typeof n=="number"&&typeof m=="number"?Math.abs(m-n):null;if(u){const p=typeof f=="number"?f:0;p<a&&(o=c,a=p);return}!s&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=c,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(l=>{if(!Da(l.info))return!1;const c=typeof l.info?.time?.created=="number"?l.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},fC=()=>{const{currentSessionId:t,messages:r,streamingMessageIds:s}=ge(),n=i.useMemo(()=>t?s.get(t)??null:null,[t,s]),o=i.useRef(void 0),a=i.useRef(0),l=i.useCallback(async()=>{if(!t||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=r.get(t)||[],u=ge.getState().sessionMemoryState.get(t),m=$a(),f=u?.isStreaming?m.VIEWPORT_MESSAGES:m.HISTORICAL_MESSAGES,p=f+m.FETCH_BUFFER,h=await Oe.getSessionMessages(t,p),x=await rC(t);if(!h)return;const g=d[d.length-1];if(g){const b=h.findIndex(S=>S.info.id===g.info.id),w=b===-1?mC(g,h):b;if(w!==-1)if(w<h.length-1){const S=h.slice(w+1);console.log(`[SYNC] Found ${S.length} new messages to append`);const C=[...d,...S],{syncMessages:v}=ge.getState();v(t,C)}else{const S=h[w],C=d[d.length-1],v=rm(S),j=rm(C);if(v&&!j){console.log("[SYNC] Last message completed on server");const M=[...d.slice(0,-1),S],{syncMessages:k}=ge.getState();k(t,M)}}else if(Da(g.info)){const S=h.slice(-f);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:C}=ge.getState();C(t,S)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(x){const b=h.findIndex(y=>y.info.id===x.messageId);if(b!==-1){if(b<h.length-1){const w=h.slice(b+1).slice(-f);if(w.length>0){console.log(`[SYNC] Restoring ${w.length} messages after cursor`);const{syncMessages:S}=ge.getState();S(t,w)}}}else if(h.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const y=h.slice(-f),{syncMessages:w}=ge.getState();w(t,y)}}else if(h.length>0){const b=h.slice(-f);console.log(`[SYNC] Loading last ${b.length} messages`);const{syncMessages:y}=ge.getState();y(t,b)}}catch(d){console.debug("Background sync failed:",d)}}},[t,r,n]);i.useEffect(()=>{const c=()=>{console.log("[FOCUS] Window focused - checking for updates"),l()};return window.addEventListener("focus",c),()=>window.removeEventListener("focus",c)},[l]),i.useEffect(()=>{if(!t||n)return;const c=()=>{document.visibilityState==="visible"&&l(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[t,n,l]),i.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),l())};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[l])},pC=()=>{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 l=a,c=l.type==="busy"||l.type==="retry"?"busy":"idle";n.set(o,c)}),n.size>0&&ge.setState({sessionActivityPhase:n})}catch{}})(),()=>{t=!0}},[])},hC=["chat","git","diff","terminal","files"],gC=["settings","agents","commands","skills","providers","git-identities"],Zs={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function om(t){const r=xC();return{sessionId:yC(r),tab:bC(r),settingsSection:wC(r),diffFile:vC(r)}}function xC(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function yC(t){const r=t.get(Zs.SESSION);return!r||r.trim().length===0?null:r.trim()}function bC(t){const r=t.get(Zs.TAB);if(!r)return null;const s=r.toLowerCase().trim();return hC.includes(s)?s:null}function wC(t){const r=t.get(Zs.SETTINGS);if(!r)return null;const s=r.toLowerCase().trim();return gC.includes(s)?s:s==="openchamber"||s==="general"||s==="preferences"?"settings":null}function vC(t){const r=t.get(Zs.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(Zs.SESSION)||t.has(Zs.TAB)||t.has(Zs.SETTINGS)||t.has(Zs.FILE)}catch{return!1}}const jC="chat";function Xp(t){const r=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&r.set(Zs.SESSION,t.sessionId),t.isSettingsOpen){const s=t.settingsSection==="sessions"?"settings":t.settingsSection;return r.set(Zs.SETTINGS,s),r}return t.tab!==jC&&r.set(Zs.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&r.set(Zs.FILE,t.diffFile),r}function SC(t,r){const s=typeof window<"u"?window.location.pathname:"/",n=t.toString();return n?`${s}?${n}`:s}function NC(t){if(typeof window>"u")return!0;try{const r=new URLSearchParams(window.location.search),s=Xp(t),n=[...r.entries()].sort((a,l)=>a[0].localeCompare(l[0])),o=[...s.entries()].sort((a,l)=>a[0].localeCompare(l[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 kC(t,r={}){if(!(typeof window>"u")&&!CC()&&!(!r.force&&NC(t)))try{const s=Xp(t),n=SC(s);r.replace?window.history.replaceState({...window.history.state,route:t},"",n):window.history.pushState({route:t},"",n)}catch{}}function CC(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function MC(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function DC(){const t=i.useMemo(()=>MC(),[]),r=i.useRef(!1),s=i.useRef(!1),n=ge(f=>f.setCurrentSession),o=je(f=>f.setActiveMainTab),a=je(f=>f.setSettingsDialogOpen),l=je(f=>f.setSidebarSection),c=je(f=>f.navigateToDiff),d=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=ge.getState().currentSessionId;f.sessionId!==p&&await n(f.sessionId)}if(f.settingsSection){l(f.settingsSection),a(!0);return}je.getState().isSettingsDialogOpen&&a(!1),f.tab&&o(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&c(f.diffFile)}finally{s.current=!1}}},[n,o,a,l,c]),u=i.useCallback(()=>{const f=ge.getState(),p=je.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();kC(p,f)},[t,u]);i.useEffect(()=>{if(r.current||(r.current=!0,!am()))return;const f=om();(async()=>(await d(f),t||m({replace:!0})))()},[d,t,m]),i.useEffect(()=>{if(t)return;let f=ge.getState().currentSessionId;return ge.subscribe(h=>{const x=h.currentSessionId;x===f||s.current||(f=x,m())})},[t,m]),i.useEffect(()=>{if(t)return;let f=je.getState().activeMainTab,p=je.getState().isSettingsDialogOpen,h=je.getState().sidebarSection,x=je.getState().pendingDiffFile;return je.subscribe(b=>{if(s.current)return;const y=b.activeMainTab!==f,w=b.isSettingsDialogOpen!==p,S=b.sidebarSection!==h,C=b.pendingDiffFile!==x&&b.activeMainTab==="diff";f=b.activeMainTab,p=b.isSettingsDialogOpen,h=b.sidebarSection,x=b.pendingDiffFile,(y||w||S||C)&&m()})},[t,m]),i.useEffect(()=>{if(typeof window>"u"||t)return;const f=()=>{const p=om();if(am())d(p);else{const h=je.getState();h.isSettingsDialogOpen&&a(!1),h.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[d,t,o,a])}const AC=1e4,im=()=>{if(typeof document>"u")return"visible";const t=document.visibilityState;return t==="hidden"&&document.hasFocus()?"visible":t},lm=t=>{if(!dr())return;const r=Ps();r?.push?.setVisibility&&r.push.setVisibility({visible:t})},EC=()=>{i.useEffect(()=>{if(!dr()||typeof document>"u")return;const t=()=>{lm(im()==="visible")},r=()=>{im()==="visible"&&lm(!0)};t();const s=window.setInterval(r,AC);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 IC(){const{git:t}=Bs(),r=wt(m=>m.currentDirectory),{currentSessionId:s,sessions:n,worktreeMetadata:o}=ge(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=ls(),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){c();return}return a(u),d(u,t),l(t),()=>{c()}},[u,t,a,l,c,d])}function PC({children:t}){return IC(),e.jsx(e.Fragment,{children:t})}const TC=()=>{const[{isUpdating:t,message:r},s]=i.useState(()=>gy());return i.useEffect(()=>hy(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(yc,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Zp={getLastAssistantMessage(){const t=ge.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}),l=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),c=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!l&&!c&&(!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:l,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!l&&!c}),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&&!l&&!c&&(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=ge.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=wt.getState(),r=ge.getState(),s=Wt.getState(),n=t.currentDirectory||null,o=Oe.getDirectory()??null,a=r.sessions||[],l=new Set,c={};a.forEach(k=>{const D=k.directory;typeof D=="string"&&D.trim().length>0?(l.add(D),c[D]=(c[D]??0)+1):c["(none)"]=(c["(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}},x=async k=>{try{const D=await fetch(k);return D.ok?await p(D):{status:D.status}}catch(D){return{error:D instanceof Error?D.message:String(D)}}};let g=null,b=null,y=null,w=null;const S=n?`/api/path?directory=${encodeURIComponent(n)}`:"/api/path";g=await x(S);const C=n?`/api/project/current?directory=${encodeURIComponent(n)}`:"/api/project/current";b=await x(C),y=await x("/api/config/settings");try{const k=await fetch("/api/health"),D=k.headers.get("content-type")||"",N=await h(k);w={status:k.status,ok:k.ok,contentType:D,type:D.includes("application/json")?"json":"html",preview:N?N.slice(0,120):null}}catch(k){w={error:k instanceof Error?k.message:String(k)}}let v={isGitRepo:null};if(n)try{v.isGitRepo=await _r(n)}catch(k){v={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})),M={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:g?.directory||g?.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:l.size,directorySamples:Array.from(l).slice(0,5),directoryCounts:c},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:v,localStorage:d,opencode:{pathInfo:g,projectInfo:b,health:w},openchamber:{settingsInfo:y}};return console.log("[DEBUG] App status snapshot:",M),M},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=ge.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=ge.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||[],l=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),c=a.some(d=>d.type==="tool");return a.length===0||!l&&!c});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:
234
- `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
235
- `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
236
- `),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)
237
- `),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=ge.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const l=o.messages.get(a)||[],c=r?l:l.filter(p=>p.info.role==="assistant"),d={totalMessages:l.length,analyzedMessages:c.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(x=>typeof x=="number");return h.length>0?Math.max(...h):null},f=c.map((p,h)=>{const x=p.info??{},g=Array.isArray(p.parts)?p.parts:[],b=x.time??{},y=u(b.completed),w=y!==null,S=g.filter(A=>A.type==="tool"),C=g.filter(A=>A.type==="reasoning"),v=m(S.map(A=>u(A.state?.time?.end??A.state?.time?.start))),j=m(C.map(A=>u(A.time?.end??A.time?.start))),M=m([v,j].filter(A=>A!==null)),k=S.some(A=>["pending","running","started"].includes(A.state?.status)),D=C.some(A=>typeof A.time?.end!="number");S.length>0&&(d.withTools+=1),C.length>0&&(d.withReasoning+=1),w||(d.completedMissing+=1);const N=!!(w&&typeof v=="number"&&y<v);N&&(d.completedBeforeTool+=1);const T=!!(w&&typeof j=="number"&&y<j);return T&&(d.completedBeforeReasoning+=1),w&&k&&(d.runningToolsWhenCompleted+=1),w&&D&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:x.id,role:x.role,completedAt:y,latestToolTimestamp:v,latestReasoningTimestamp:j,latestPartTimestamp:M,completed_missing:!w,completed_before_tool:N,completed_before_reasoning:T,running_tools_when_completed:!!(w&&k),reasoning_open_when_completed:!!(w&&D),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=ge.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"),l=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&l),p=t.messageStreamStates,h=o.info.sessionID?t.streamingMessageIds.get(o.info.sessionID)??null:null,x=p.get(o.info.id),g=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:",l),console.log("messageIsComplete:",f),console.log("lifecycle phase:",x?.phase),console.log("isStreamingCandidate:",g),console.log("streamingMessageId:",h),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:m,hasStopReason:l,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Zp,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 FC=({open:t,onOpenChange:r})=>{const[s,n]=i.useState(null),[o,a]=i.useState(!1),[l,c]=i.useState(!1),d=i.useCallback(async()=>{if(!o){a(!0),c(!1);try{(await Zp.copyDiagnosticsReport()).ok?(c(!0),W.success("Diagnostics copied")):W.error("Copy failed")}catch(m){W.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 Ss(async()=>{const{getVersion:x}=await import("./vendor-.bun-koHRsLHN.js").then(g=>g.di);return{getVersion:x}},__vite__mapDeps([0,1])),h=await p();n(h)}catch{n("1.5.8")}})():n("1.5.8")},[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(yc,{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:l?"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(Hm,{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(il,{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 el({apis:t,children:r}){return e.jsx(Zl.Provider,{value:t,children:r})}const RC="curl -fsSL https://opencode.ai/install | bash",LC=3e3;function OC({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(sr,{className:"h-4 w-4"})})]})}const $C=3e4;function _C({onCliAvailable:t}){const[r,s]=i.useState(!1),[n,o]=i.useState(!1),[a,l]=i.useState(!1);i.useEffect(()=>{const m=setTimeout(()=>o(!0),$C);return()=>clearTimeout(m)},[]),i.useEffect(()=>{l(typeof window.opencodeDesktop<"u")},[]);const c=i.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await Ss(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-koHRsLHN.js").then(x=>x.dh);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(RC),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,LC);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:c,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(Xs,{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($t,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(OC,{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(Xs,{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 BC=()=>{const{isAboutDialogOpen:t,setAboutDialogOpen:r}=je();return e.jsx(FC,{open:t,onOpenChange:r})};function zC({apis:t}){const{initializeApp:r,isInitialized:s,isConnected:n}=et(),{error:o,clearError:a,loadSessions:l}=ge(),c=wt(j=>j.currentDirectory),d=wt(j=>j.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=Op(),h=_s(j=>j.refreshStatus),[x,g]=i.useState(()=>t.runtime.isDesktop),[b,y]=i.useState(()=>t.runtime.isVSCode),[w,S]=i.useState(()=>t.runtime.isDesktop?Yx():!0);i.useEffect(()=>{g(t.runtime.isDesktop),y(t.runtime.isVSCode)},[t.runtime.isDesktop,t.runtime.isVSCode]),i.useEffect(()=>(Hc(t),()=>Hc(null)),[t]),i.useEffect(()=>{h(t.github,{force:!0})},[t.github,h]),i.useEffect(()=>{if(typeof document>"u")return;const j=document.documentElement,M=Eu[f]?.stack??Eu[sN].stack,k=ln[p]?.stack??ln[Ca].stack;j.style.setProperty("--font-sans",M),j.style.setProperty("--font-heading",M),j.style.setProperty("--font-family-sans",M),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=M)},[f,p]),i.useEffect(()=>{if(s){const M=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},150);return()=>clearTimeout(M)}},[s]),i.useEffect(()=>{const j=setTimeout(()=>{const M=document.getElementById("initial-loading");M&&!s&&(M.classList.add("fade-out"),setTimeout(()=>{M.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(c),await l()))()},[c,d,l,n,b]),lC(),EC(),DC(),cC();const C=i.useCallback(()=>{m(j=>!j)},[]);dC(C),fC(),pC(),Up(),i.useEffect(()=>{const j=M=>{$s(M)&&M.shiftKey&&M.key==="D"&&(M.preventDefault(),m(k=>!k))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const v=i.useCallback(()=>{S(!0),window.location.reload()},[]);return x&&!w?e.jsx(bs,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(_C,{onCliAvailable:v})})}):b?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(bs,{children:e.jsx(el,{apis:t,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Yk,{}),e.jsx(Di,{})]})})}):e.jsx(bs,{children:e.jsx(el,{apis:t,children:e.jsx(vu,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx($k,{}),e.jsx(Di,{})]})})})}):e.jsx(bs,{children:e.jsx(el,{apis:t,children:e.jsx(PC,{children:e.jsx(vu,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Fk,{}),e.jsx(Di,{}),e.jsx(TC,{}),e.jsx(BC,{}),u&&e.jsx(Xk,{onClose:()=>m(!1)})]})})})})})}const eh=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=wt.getState();t&&s.homeDirectory!==t&&s.synchronizeHomeDirectory(t),r&&!Vt()&&s.setDirectory(r,{showOverlay:!1})},th="/auth/session",HC=async()=>fetch(th,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),cm=async t=>fetch(th,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:t})}),kc=({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})]}),WC=({message:t="Preparing workspace…"})=>e.jsx(kc,{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})})}),UC=({onRetry:t})=>e.jsx(kc,{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"})]})}),VC=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},GC=()=>{try{const t=new URL(window.location.href);t.searchParams.delete("token"),window.history.replaceState({},"",t.toString())}catch{}},qC=({children:t})=>{const r=i.useMemo(()=>ds(),[]),s=i.useMemo(()=>Vt(),[]),n=r||s,[o,a]=i.useState(()=>n?"authenticated":"pending"),[l,c]=i.useState(""),[d,u]=i.useState(!1),[m,f]=i.useState(""),p=i.useRef(null),h=i.useRef(n),x=i.useRef(!1),g=i.useCallback(async()=>{if(n){a("authenticated");return}a(y=>y==="authenticated"?y:"pending");try{const y=await HC();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||g()},[g,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"||x.current||d)return;const y=VC();y&&(x.current=!0,GC(),u(!0),f(""),cm(y).then(w=>{if(w.ok){c(""),a("authenticated");return}if(w.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(w=>{console.warn("Failed to submit URL token:",w),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 Zm(),await ef(),await eh()))())},[n,o]);const b=async y=>{if(y.preventDefault(),!(!l||d)){u(!0),f("");try{const w=await cm(l);if(w.ok){c(""),a("authenticated");return}if(w.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(w){console.warn("Failed to submit UI password:",w),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(WC,{}):o==="error"?e.jsx(UC,{onRetry:()=>{g()}}):o==="locked"?e.jsx(kc,{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(Ax,{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:l,onChange:y=>{c(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:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Tt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ex,{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})},tl=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(c=>c+c).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,l=n&255;return`${o} ${a} ${l}`};class KC{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(`
238
- `)}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=tl(r.colors.surface.muted),o=tl(r.colors.surface.subtle),a=tl(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 l=r.metadata.variant==="dark",c=l?.8:.95,d=l?.7:.9;if(n)s.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !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,c)} !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 {
239
- ${s}
240
- }
241
-
242
- .dark {
243
- ${s}
244
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
245
- ${s}
246
- }
247
-
248
- :root:not(.dark) {
249
- ${s}
250
- }`,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=Vt()?ay:Ul;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),l=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${l}, ${s})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),l=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${l}, ${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,l=(n>>8&255)-o,c=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c: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,l=(n>>8&255)+o,c=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c: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 Cc={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"}}},Mc={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"}}},To=[Cc,Mc];function qa(t){return To.find(r=>r.metadata.id===t)}const sh=Cc.metadata.id,rh=Mc.metadata.id,QC=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,nh=t=>t==="dark"?Mc:Cc,YC=t=>(To.find(s=>s.metadata.variant===t)??nh(t)).metadata.id,ua=(t,r)=>{const s=qa(t);return s&&s.metadata.variant===r?s:To.find(o=>o.metadata.variant===r)??nh(r)},JC=typeof window<"u"?i.useLayoutEffect:i.useEffect,Ka=(t,r)=>{if(!t)return r==="light"?sh:rh;const s=qa(t);return s&&s.metadata.variant===r?s.metadata.id:YC(r)},XC=t=>{let r=sh,s=rh,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),l=localStorage.getItem("darkThemeId"),c=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(c!==null){if(c==="true")n="system";else if(d){const f=qa(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=Ka(a,"light"),s=Ka(l,"dark")}if(t){const o=qa(t);o&&(o.metadata.variant==="light"?r=o.metadata.id:s=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:s}};function ZC({children:t,defaultThemeId:r}){const s=_e.useMemo(()=>new KC,[]),[n,o]=_e.useState(()=>XC(r)),[a,l]=_e.useState(()=>QC()),[c,d]=_e.useState(()=>typeof window>"u"||!Vt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=_e.useMemo(()=>Vt(),[]),m=_e.useMemo(()=>u&&c?c:n.themeMode==="light"?ua(n.lightThemeId,"light"):n.themeMode==="dark"||a?ua(n.darkThemeId,"dark"):ua(n.lightThemeId,"light"),[u,n,a,c]),f=_e.useMemo(()=>u&&c?[c,...To]:To,[u,c]);_e.useEffect(()=>{if(!u)return;const C=M=>{d(M);const k=M.metadata.variant==="dark"?"dark":"light",D=je.getState();D.theme!==k&&D.setTheme(k)},v=M=>{const k=M.detail;k?.theme&&C(k.theme)},j=window.__OPENCHAMBER_VSCODE_THEME__;return j&&C(j),window.addEventListener("openchamber:vscode-theme",v),()=>window.removeEventListener("openchamber:vscode-theme",v)},[u]);const p=_e.useCallback(C=>{if(typeof document>"u")return;const v=C.colors.surface.background;document.body.style.backgroundColor=v;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",v);const M=C.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let k=document.querySelector(`meta[name="theme-color"][media="${M}"]`);k||(k=document.createElement("meta"),k.setAttribute("name","theme-color"),k.setAttribute("media",M),document.head.appendChild(k)),k.setAttribute("content",v)},[]),h=_e.useCallback(C=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",C)},[]);JC(()=>{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]),_e.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const C=window.matchMedia("(prefers-color-scheme: dark)"),v=j=>{l(j.matches)};return l(C.matches),C.addEventListener("change",v),()=>C.removeEventListener("change",v)},[n.themeMode]),_e.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]),_e.useEffect(()=>{is({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]),_e.useEffect(()=>{if(typeof window>"u")return;const C=v=>{const j=v.detail;j&&o(M=>{let k=M.themeMode;j.useSystemTheme===!0?k="system":j.useSystemTheme===!1&&(j.themeVariant==="dark"||j.themeVariant==="light")&&(k=j.themeVariant);let D=M.lightThemeId;typeof j.lightThemeId=="string"&&j.lightThemeId.length>0&&(D=Ka(j.lightThemeId,"light"));let N=M.darkThemeId;return typeof j.darkThemeId=="string"&&j.darkThemeId.length>0&&(N=Ka(j.darkThemeId,"dark")),k===M.themeMode&&D===M.lightThemeId&&N===M.darkThemeId?M:{themeMode:k,lightThemeId:D,darkThemeId:N}})};return window.addEventListener("openchamber:settings-synced",C),()=>window.removeEventListener("openchamber:settings-synced",C)},[]);const x=_e.useCallback(C=>{const v=f.find(j=>j.metadata.id===C);v&&o(j=>v.metadata.variant==="dark"?j.darkThemeId===v.metadata.id&&j.themeMode==="dark"?j:{...j,darkThemeId:v.metadata.id,themeMode:"dark"}:j.lightThemeId===v.metadata.id&&j.themeMode==="light"?j:{...j,lightThemeId:v.metadata.id,themeMode:"light"})},[f]),g=_e.useCallback(C=>{o(v=>v.themeMode===C?v:{...v,themeMode:C})},[]),b=_e.useCallback(C=>{if(C){o(j=>j.themeMode==="system"?j:{...j,themeMode:"system"});return}const v=m.metadata.variant==="dark"?"dark":"light";o(j=>j.themeMode===v?j:{...j,themeMode:v})},[m.metadata.variant]),y=_e.useCallback(C=>{const v=f.find(j=>j.metadata.id===C&&j.metadata.variant==="light");v&&o(j=>j.lightThemeId===v.metadata.id?j:{...j,lightThemeId:v.metadata.id})},[f]),w=_e.useCallback(C=>{const v=f.find(j=>j.metadata.id===C&&j.metadata.variant==="dark");v&&o(j=>j.darkThemeId===v.metadata.id?j:{...j,darkThemeId:v.metadata.id})},[f]),S={currentTheme:m,availableThemes:f,setTheme:x,isSystemPreference:n.themeMode==="system",setSystemPreference:b,themeMode:n.themeMode,setThemeMode:g,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:y,setDarkThemePreference:w};return e.jsx(rc.Provider,{value:S,children:t})}const eM=({children:t})=>{const{theme:r,applyTheme:s,fontSize:n,applyTypography:o,padding:a,applyPadding:l}=je();return i.useLayoutEffect(()=>{s(),o(),l()},[r,s,n,o,a,l]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&s()};return c.addEventListener("change",d),()=>{c.removeEventListener("change",d)}},[r,s]),e.jsx(e.Fragment,{children:t})};let dm=!1;const tM=()=>{if(dm||typeof window>"u")return;dm=!0;let t={showReasoningTraces:je.getState().showReasoningTraces,showTextJustificationActivity:je.getState().showTextJustificationActivity,nativeNotificationsEnabled:je.getState().nativeNotificationsEnabled,notificationMode:je.getState().notificationMode,autoDeleteEnabled:je.getState().autoDeleteEnabled,autoDeleteAfterDays:je.getState().autoDeleteAfterDays,toolCallExpansion:je.getState().toolCallExpansion,fontSize:je.getState().fontSize,padding:je.getState().padding,cornerRadius:je.getState().cornerRadius,inputBarOffset:je.getState().inputBarOffset,diffLayoutPreference:je.getState().diffLayoutPreference,diffViewMode:je.getState().diffViewMode},r=null,s=null;const n=()=>{const a=r;r=null,s=null,a&&Object.keys(a).length>0&&is(a)},o=a=>{r={...r??{},...a},!s&&(s=setTimeout(n,150))};je.subscribe(a=>{const l={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},c={};l.showReasoningTraces!==t.showReasoningTraces&&(c.showReasoningTraces=l.showReasoningTraces),l.showTextJustificationActivity!==t.showTextJustificationActivity&&(c.showTextJustificationActivity=l.showTextJustificationActivity),l.nativeNotificationsEnabled!==t.nativeNotificationsEnabled&&(c.nativeNotificationsEnabled=l.nativeNotificationsEnabled),l.notificationMode!==t.notificationMode&&(c.notificationMode=l.notificationMode),l.autoDeleteEnabled!==t.autoDeleteEnabled&&(c.autoDeleteEnabled=l.autoDeleteEnabled),l.autoDeleteAfterDays!==t.autoDeleteAfterDays&&(c.autoDeleteAfterDays=l.autoDeleteAfterDays),l.toolCallExpansion!==t.toolCallExpansion&&(c.toolCallExpansion=l.toolCallExpansion),l.fontSize!==t.fontSize&&(c.fontSize=l.fontSize),l.padding!==t.padding&&(c.padding=l.padding),l.cornerRadius!==t.cornerRadius&&(c.cornerRadius=l.cornerRadius),l.inputBarOffset!==t.inputBarOffset&&(c.inputBarOffset=l.inputBarOffset),l.diffLayoutPreference!==t.diffLayoutPreference&&(c.diffLayoutPreference=l.diffLayoutPreference),l.diffViewMode!==t.diffViewMode&&(c.diffViewMode=l.diffViewMode),t=l,Object.keys(c).length>0&&o(c)})};let um=!1;const mm="openchamber-typography-base",sM=()=>{if(typeof document>"u")return;const r=`:root {
251
- ${Object.entries(Ul).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
252
- `)}
253
- }
254
- `,s=document.getElementById(mm);if(s){s.textContent=r;return}const n=document.createElement("style");n.id=mm,n.textContent=r,document.head.appendChild(n)},rM=()=>{um||typeof window>"u"||(um=!0,sM())},nM=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await Zm();await ef();tM();rM();await eh();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 l=o[o.length-1].info.tokens;l&&typeof l=="object"&&console.debug("Token breakdown:",{base:(l.input||0)+(l.output||0)+(l.reasoning||0),cache:l.cache?(l.cache.read||0)+(l.cache.write||0):0}),r.sessionContextUsage.get(s);const c=window.__zustand_config_store__;if(c){const d=c.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 oh=document.getElementById("root");if(!oh)throw new Error("Root element not found");Ix.createRoot(oh).render(e.jsx(_e.StrictMode,{children:e.jsx(ZC,{children:e.jsx(eM,{children:e.jsx(qC,{children:e.jsx(zC,{apis:nM})})})})}));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 iM=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{us as D,bn as S,ms as a,Pf as b,R as c,Zj as d,e0 as e,iu as f,Cr as g,t0 as h,r0 as i,iM as m,mp as p,s0 as r,pa as t};