@openchamber/web 1.5.5 → 1.5.7

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,158 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-BrcdMJ39.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-CLg_YFoi.js","assets/index-DCvGkY6V.js","assets/index-DMDb0aQz.css"])))=>i.map(i=>d[i]);
2
- import{t as Lp,c as Op,F as _p,j as e,R as $p,T as Bp,P as zp,C as Wp,A as Hp,a as Up,b as ns,d as cs,p as Ws,e as Hs,f as Vp,_ as bs,g as i,r as Ju,i as Zt,I as Gp,k as qp,l as Kp,m as Qp,n as Yp,L as Xp,o as Jp,q as Zp,s as eh,u as Gt,S as th,v as sh,w as Zu,x as rh,y as nh,z as oh,B as ah,D as ih,E as lh,G as Te,H as yc,J as ch,K as dh,M as Yn,N as qi,O as bc,Q as Oa,U as Ot,V as Bs,W as Jt,X as Nl,Y as em,Z as tm,$ as uh,a0 as Wr,a1 as mh,a2 as Qs,a3 as sr,a4 as Vr,a5 as Ht,a6 as Cl,a7 as fh,a8 as un,a9 as Ml,aa as gn,ab as mn,ac as Ki,ad as Is,ae as sm,af as ph,ag as hh,ah as gh,ai as xh,aj as yh,ak as bh,al as wh,am as Zo,an as vh,ao as rm,ap as ga,aq as Hr,ar as ps,as as xn,at as lr,au as So,av as is,aw as br,ax as jh,ay as Sh,az as nm,aA as Dl,aB as fn,aC as om,aD as wr,aE as am,aF as Ln,aG as kh,aH as _a,aI as cr,aJ as ai,aK as Nh,aL as Gr,aM as Nr,aN as Xs,aO as Ch,aP as Us,aQ as Mh,aR as wc,aS as Qi,aT as Dh,aU as Ah,aV as Eh,aW as Ih,aX as Ph,aY as Th,aZ as Fh,a_ as Rh,a$ as Lh,b0 as im,b1 as ii,b2 as Oh,b3 as Al,b4 as El,b5 as _h,b6 as $h,b7 as Bh,b8 as zh,b9 as Wh,ba as Hh,bb as Uh,bc as Vh,bd as Gh,be as qh,bf as Kh,bg as Qh,bh as Yh,bi as Xh,bj as Jh,bk as Zh,bl as Cr,bm as xa,bn as vr,bo as hr,bp as eg,bq as tg,br as $a,bs as sg,bt as Il,bu as rg,bv as ng,bw as og,bx as On,by as ag,bz as ig,bA as lg,bB as cg,bC as dg,bD as ho,bE as ea,bF as Ba,bG as ug,bH as mg,bI as In,bJ as Nn,bK as lm,bL as fg,bM as pg,bN as Ys,bO as hg,bP as gg,bQ as cm,bR as xg,bS as yg,bT as Yi,bU as dm,bV as um,bW as bg,bX as Dr,bY as _n,bZ as wg,b_ as vc,b$ as vg,c0 as Xi,c1 as Gn,c2 as qn,c3 as jg,c4 as mm,c5 as Pl,c6 as Tl,c7 as Fl,c8 as Sg,c9 as kg,ca as Ng,cb as Cg,cc as jc,cd as fm,ce as Mg,cf as Dg,cg as Ag,ch as za,ci as Eg,cj as Ig,ck as Pg,cl as Cn,cm as Sc,cn as Tg,co as Fg,cp as Rg,cq as Lg,cr as Og,cs as _g,ct as Kn,cu as $g,cv as Bg,cw as zg,cx as Wg,cy as Hg,cz as Ug,cA as pm,cB as hm,cC as gm,cD as xm,cE as ym,cF as Vg,cG as bm,cH as wm,cI as vm,cJ as Mn,cK as Gg,cL as qg,cM as Kg,cN as Ze,cO as Qg,cP as Yg,cQ as Xg,cR as Jg,cS as kc,cT as Zg,cU as ex,cV as go,cW as jm,cX as Sm,cY as li,cZ as Wa,c_ as km,c$ as tx,d0 as sx,d1 as Ji,d2 as Nm,d3 as Zi,d4 as rx,d5 as nx,d6 as ox,d7 as ax,d8 as ix,d9 as lx}from"./vendor-.bun-BrcdMJ39.js";import{c as cx,l as dx,g as ux,r as mx,d as fx,a as px,b as hx,e as gx,u as xx,f as yx,h as bx,i as wx,j as vx,k as jx,m as Sx}from"./index-DCvGkY6V.js";const ls=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Wt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,gr=()=>typeof window>"u"?!1:!ls()&&!Wt(),qr=()=>ls()?window.opencodeDesktop??null:null,Cm=()=>{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},Mm=async()=>{const t=qr();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},kx=async()=>{const t=qr();if(!t)return null;try{return await t.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},Nx=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Pr=async()=>{const t=Cm();if(!t)return null;try{return await t.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},Cx=async t=>{const r=Cm();if(!r)return null;try{return await r.updateSettings(t)}catch(s){return console.warn("[desktop] Failed to update desktop settings",s),null}},Mx=async t=>{const r=qr();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)}}},Dx=async t=>{const r=qr();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)}}},Ax=async t=>{const r=qr();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)}}},Ex=async()=>{const t=qr();if(!t||!t.checkForUpdates)return null;try{return await t.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},Ix=async t=>{const r=qr();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(t),!0}catch(s){return console.warn("Failed to download update",s),!1}},Px=async()=>{const t=qr();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 F(...t){return Lp(Op(t))}const Dm=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Ts=t=>Dm()&&ls()?t.metaKey:t.ctrlKey,Xt=()=>Dm()&&ls()?"⌘":"Ctrl",Am=(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}`},ya=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function on(t,r){if(!t)return"";const s=ya(t);if(s==="/")return"/";const n=r?ya(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 Nc(t,r){if(!t)return"/";const s=ya(t);if(!s||s==="/")return"/";const n=r?ya(r):void 0;return n&&n!=="/"&&s===n?"~":s.split("/").pop()||s||"/"}function Gs(t,r){return r?t?t.toLowerCase().includes(r.toLowerCase())?!0:new _p([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function Tx({delayDuration:t=0,...r}){return e.jsx(Up,{"data-slot":"tooltip-provider",delayDuration:t,...r})}function lt({delayDuration:t=0,...r}){return e.jsx(Tx,{delayDuration:t,children:e.jsx($p,{"data-slot":"tooltip",...r})})}function ct({...t}){return e.jsx(Bp,{"data-slot":"tooltip-trigger",...t})}function it({className:t,sideOffset:r=0,children:s,...n}){return e.jsx(zp,{children:e.jsxs(Wp,{"data-slot":"tooltip-content",sideOffset:r,className:F("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(Hp,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let ci=null;const Cc=()=>{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}}},Fx=()=>{if(typeof window>"u"||!window.localStorage)return Cc();const t=window.localStorage,r=Cc();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}}},hs=()=>(ci||(ci=Fx()),ci),Rl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Rx={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Mc(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Mr={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)"}}},ta={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Mr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:ta.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Mr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:ta.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Mr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:ta.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Mr.tool.inline})},Ce=ns()(cs(Ws((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:!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:"dynamic",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"single",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})},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(Rl);if(o===1){for(const[l]of a)n.style.removeProperty(Mc(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Mc(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:Hs(()=>hs()),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,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 Lx(){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 Ox(){return ls()?"desktop":gr()?"web":null}const Dc={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Ha=ns()((t,r)=>({...Dc,checkForUpdates:async()=>{const s=Ox();if(s){t({checking:!0,error:null,runtimeType:s});try{let n=null;s==="desktop"?n=await Ex():s==="web"&&(n=await Lx()),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 Ix(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 Px()}catch(o){t({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{t({available:!1,downloaded:!1,info:null})},reset:()=>{t(Dc)}})),_x="/api",$x=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Bx=t=>{const r=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if($x.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}},zx=()=>{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},Ao=t=>t.replace(/\\/g,"/"),di=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class Wx{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=_x){const n=zx()||r;this.baseUrl=Bx(n),this.client=Vp({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 bs(async()=>{const{default:f}=await import("./vendor-.bun-BrcdMJ39.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}),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.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 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:v=>{v instanceof Error&&v.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",v),s&&!u.signal.aborted&&s(v))},onSseEvent:v=>{if(u.signal.aborted)return;v.id&&typeof v.id=="string"&&(m=v.id);const S=v.data,N=f(S);N&&r(N)}};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 v 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=di();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=di();if(n)try{const o=await n.listDirectory(r||"",s);return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:Ao(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=di(),o=typeof s?.directory=="string"&&s.directory.trim().length>0?s.directory.trim():this.currentDirectory,a=o?Ao(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=Ao(f.path),h=p.split("/").filter(Boolean).pop()||p,x=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?Ao(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 Mm();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 Fe=new Wx,Hx=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:Fe},Symbol.toStringTag,{value:"Module"})),el=new Set;function Ua(t){return el.add(t),()=>{el.delete(t)}}function xr(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 el)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 xo(t,r){return t.scopes.includes("all")||t.scopes.includes(r)}const Ll="Updating OpenCode configuration...";let yr=0,Ur=Ll;const tl=new Set;function ba(){const t={isUpdating:yr>0,message:Ur};tl.forEach(r=>r(t))}function Ks(t){yr+=1,yr===1?(Ur=t||Ll,ba()):t&&(Ur=t,ba())}function Fs(){yr!==0&&(yr-=1,yr===0&&(Ur=Ll,ba()))}function Ar(t){Ur===t&&yr>0||(Ur=t,yr>0&&ba())}function Ux(t){return tl.add(t),t({isUpdating:yr>0,message:Ur}),()=>{tl.delete(t)}}function Vx(){return{isUpdating:yr>0,message:Ur}}const pr=ns()(cs(Ws((t,r)=>({queuedMessages:{},queueModeEnabled:!1,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}),us({queueModeEnabled:s})},getQueueForSession:s=>r().queuedMessages[s]??[]}),{name:"message-queue-store",storage:Hs(()=>hs()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),Ac=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},Gx=t=>!t||typeof t!="object"?null:{showReasoningTraces:t.showReasoningTraces},qx=t=>{const r=Ce.getState();typeof t.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(t.showReasoningTraces)},Kx=async()=>{if(typeof window>"u")return null;if(ls()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const s=await r.load();return Ac(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=Gx(r);return Ac(s)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let Em=null;const Ec=t=>{Em=t},As=()=>Em,sa=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"))},Qx=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},Yx=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},Im=()=>{const t=Ce.persist;if(t&&typeof t=="object")return t},Pm=()=>As()?.settings??null,ra=t=>{const r=Ce.getState(),s=pr.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)},Ic=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=Yx(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.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=Qx(r.skillCatalogs);return o&&(s.skillCatalogs=o),s},Xx=async()=>{const t=Pm();if(t)try{const r=await t.load();return Ic(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 Ic(s)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},Tm=async()=>{if(typeof window>"u")return;const t=Im(),r=s=>{sa(s);const n=()=>ra(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=ls()?await Pr():await Xx();s&&r(s)}catch(s){console.warn("Failed to synchronise settings:",s)}},us=async t=>{if(typeof window>"u")return;if(ls()){try{const s=await Cx(t);s&&(sa(s),ra(s))}catch(s){console.warn("Failed to update desktop settings:",s)}return}const r=Pm();if(r)try{const s=await r.save(t);s&&(sa(s),ra(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&&(sa(n),ra(n))}catch(s){console.warn("Failed to update shared settings via API:",s)}},Fm=async()=>{if(typeof window>"u")return;const t=Im();try{const r=await Kx();if(!r)return;const s=()=>qx(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)}},Jx=3e4,Zx=40,ey=60,ty=(t,r,s,n,o)=>{const a=t.trim(),l=r.trim().toLowerCase();return`${a}::${l}::${s}::${n?"1":"0"}::${o?"1":"0"}`},Va=ns()(cs((t,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,n,o=ey,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=ty(l,c,o,d,u),f=Date.now(),p=r().cache[m];if(p&&f-p.timestamp<Jx)return p.files;const h=r().inFlight[m];if(h)return h;const x=Fe.searchFiles(c,{directory:l,limit:o,includeHidden:d,respectGitignore:u}).then(g=>(t(b=>{const y={...b.cache,[m]:{files:g,timestamp:Date.now()}},v=b.cacheKeys.filter(S=>S!==m);for(v.push(m);v.length>Zx;){const S=v.shift();S&&delete y[S]}return{cache:y,cacheKeys:v}}),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"})),ds=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var sy={};let nr=null;const rr=hs(),Pc=rr.getItem("lastDirectory"),ry=typeof Pc=="string"&&Pc.length>0,Eo=t=>{try{Va.getState().invalidateDirectory(t)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},Rm=t=>{const r=t.trim();if(!r)return r;const s=r.replace(/\\/g,"/");return s.length>1?s.replace(/\/+$/,""):s},ny=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},na=(t,r)=>{const s=ny(t,r);return Rm(s)},wa=()=>{if(typeof window<"u"){const r=rr.getItem("homeDirectory")||nr||null,s=rr.getItem("lastDirectory");if(s&&!Wt())return na(s,r);if(nr)return nr;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 nr=n,rr.setItem("homeDirectory",n),n;if(r&&!Wt())return nr=r,r}const t=typeof process<"u"&&sy?.HOME;return t||process?.cwd?.()||"/"},oy=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},ay=t=>(nr=t,typeof window<"u"&&rr.setItem("homeDirectory",t),us({homeDirectory:t}),t),Lm=async()=>{const t=n=>{const o=oy(n);return o?ay(o):null};try{const n=await Fe.getFilesystemHome(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Fe.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 Mm(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=wa(),s=t(r);return s||r},iy=()=>{if(!Wt())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const r=Rm(t);return r.length>0?r:null},an=iy()||wa();an&&Fe.setDirectory(an);const ly=!!(an&&an!=="/"),bt=ns()(cs((t,r)=>({currentDirectory:an,directoryHistory:[an],historyIndex:0,homeDirectory:an,hasPersistedDirectory:ry,isHomeReady:ly,isSwitchingDirectory:!1,setDirectory:(s,n)=>{const o=nr||r().homeDirectory||rr.getItem("homeDirectory"),a=na(s,o);ds()&&console.log("[DirectoryStore] setDirectory called with path:",a),Fe.setDirectory(a),Eo(),t(l=>{const c=[...l.directoryHistory.slice(0,l.historyIndex+1),a];return rr.setItem("lastDirectory",a),us({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];Fe.setDirectory(o),Eo(),rr.setItem("lastDirectory",o),us({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];Fe.setDirectory(o),Eo(),rr.setItem("lastDirectory",o),us({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:s,setDirectory:n}=r(),o=nr||r().homeDirectory||wa();if(s===o||s==="/")return;const a=s.endsWith("/")?s.slice(0,-1):s,l=a.lastIndexOf("/");if(l===-1){const c=nr||wa();n(c)}else n(l===0?"/":a.substring(0,l))},goHome:async()=>{const s=nr||r().homeDirectory||await Lm();r().setDirectory(s)},synchronizeHomeDirectory:s=>{const n=r(),o=s;nr=o;const a=n.homeDirectory!==o,l=rr.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?na(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(g=>na(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;Fe.setDirectory(g),Eo(),rr.setItem("lastDirectory",g),us({lastDirectory:g})}us({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Lm().then(t=>{bt.getState().synchronizeHomeDirectory(t)});const Pn=hs(),Om="projects",sl="activeProjectId",cy=(t,r)=>{const s=t.trim();return!s.startsWith("~")||!r?s:s==="~"?r:s.startsWith("~/")||s.startsWith("~\\")?`${r}${s.slice(1)}`:s},Ga=t=>{const r=t.trim();if(!r)return"";const s=Pn.getItem("homeDirectory")||bt.getState().homeDirectory||"",o=cy(r,s).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},_m=t=>{const r=Ga(t);if(!r||r==="/")return"Root";const s=r.split("/").filter(Boolean);return s[s.length-1]||r},dy=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,$m=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=Ga(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},uy=()=>{try{const t=Pn.getItem(Om);return t?$m(JSON.parse(t)):[]}catch{return[]}},my=()=>{try{const t=Pn.getItem(sl);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},Ol=(t,r)=>{try{Pn.setItem(Om,JSON.stringify(t))}catch{}try{r?Pn.setItem(sl,r):Pn.removeItem(sl)}catch{}},bn=(t,r)=>{Ol(t,r),us({projects:t,activeProjectId:r??void 0})},fy=uy(),py=()=>{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=Ga(r);if(!s)return null;const n=`vscode:${s}`,o={id:n,path:s,label:_m(s),addedAt:Date.now(),lastOpenedAt:Date.now()};return ds()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},tr=py(),_l=tr?.projects??fy,Bm=tr?.activeProjectId??my()??_l[0]?.id??null;tr&&Ol(_l,Bm);const Vt=ns()(cs((t,r)=>({projects:_l,activeProjectId:Bm,validateProjectPath:s=>{if(typeof s!="string"||s.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=Ga(s);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(s,n)=>{if(tr)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()||_m(l),m=n?.id?.trim(),p={id:m&&!r().projects.some(x=>x.id===m)?m:dy(),path:l,label:u,addedAt:d,lastOpenedAt:d},h=[...r().projects,p];return t({projects:h}),ds()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:s=>{if(tr)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}),bn(o,a),a){const l=o.find(c=>c.id===a);l&&(Fe.setDirectory(l.path),bt.getState().setDirectory(l.path,{showOverlay:!1}))}else bt.getState().goHome()},setActiveProject:s=>{if(tr)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}),bn(c,s),Fe.setDirectory(a.path),bt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:s=>{if(tr)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}),bn(c,s)},renameProject:(s,n)=>{if(tr)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}),bn(c,l)},reorderProjects:(s,n)=>{if(tr)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}),bn(l,a)},synchronizeFromSettings:s=>{if(tr)return;const n=$m(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}),Ol(n,o),o)){const d=n.find(u=>u.id===o);d&&(Fe.setDirectory(d.path),bt.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(tr)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}),bn(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",t=>{const r=t.detail;r&&typeof r=="object"&&Vt.getState().synchronizeFromSettings(r)});const hy=new Set(["init","review"]),Dn=t=>hy.has(t.name),ao="useCommandsStore",rl=t=>new Promise(r=>setTimeout(r,t)),Io=()=>{try{const r=Vt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const s=Fe.getDirectory();if(s?.trim())return s.trim()}catch(t){console.warn("[CommandsStore] Error resolving config directory:",t)}return null},gy=2e4,Tc=300,Fc=4,xy=800,yy=200,by=2e3,Kr=ns()(cs(Ws((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=Io(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await Fe.withDirectory(a,()=>Fe.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=>{Ks("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=Io(),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 ui({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&xr("commands",{source:ao}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Fs()}},updateCommand:async(s,n)=>{Ks("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=Io(),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 ui({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&xr("commands",{source:ao}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Fs()}},deleteCommand:async s=>{Ks("Deleting command configuration…");let n=!1;try{const o=Io(),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 ui({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&xr("commands",{source:ao}),r().selectedCommandName===s&&t({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||Fs()}},getCommandByName:s=>{const{commands:n}=r();return n.find(o=>o.name===s)}}),{name:"commands-store",storage:Hs(()=>hs()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Kr);async function wy(t){const r=typeof t=="number"&&t>0?Math.min(t,Tc):0;r>0&&await rl(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<gy;){n+=1,Ar(`Waiting for OpenCode… (attempt ${n})`);try{if(await Fe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-s,l=n<=Fc&&a<1200?Tc:Math.min(xy+Math.max(0,n-Fc)*yy,by);await rl(l)}throw o||new Error("OpenCode did not become ready in time")}async function ui(t={}){const{message:r,delayMs:s}=t;try{Ar(r||"Refreshing commands…")}catch{}try{await wy(s),Ar("Refreshing commands…"),await Kr.getState().loadCommands(),xr("commands",{source:ao})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Ar("OpenCode refresh failed. Please retry refreshing configuration manually."),await rl(1500)}finally{Fs()}}let Rc=null;Rc||(Rc=Ua(t=>{if(t.source!==ao&&xo(t,"commands")){const{loadCommands:r}=Kr.getState();r()}}));const Rr=()=>{const t=Fe.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},oa="useSkillsStore",or=ns()(cs(Ws((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=Rr(),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=Rr(),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=>{Ks("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=Rr(),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&&xr("skills",{source:oa}),d}catch{return!1}finally{Fs()}},updateSkill:async(s,n)=>{Ks("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=Rr(),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&&xr("skills",{source:oa}),u}catch{return!1}finally{Fs()}},deleteSkill:async s=>{Ks("Deleting skill...");try{const n=Rr(),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&&xr("skills",{source:oa}),r().selectedSkillName===s&&t({selectedSkillName:null}),c}catch{return!1}finally{Fs()}},getSkillByName:s=>{const{skills:n}=r();return n.find(o=>o.name===s)},readSupportingFile:async(s,n)=>{try{const o=Rr(),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=Rr(),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=Rr(),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:Hs(()=>hs()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=or);let Lc=null;Lc||(Lc=Ua(t=>{if(t.source!==oa&&xo(t,"skills")){const{loadSkills:r}=or.getState();r()}}));const mi=()=>{const t=Fe.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},ko=ns()(cs((t,r)=>({sources:[],itemsBySource:{},selectedSourceId:null,isLoadingCatalog:!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};let o=null;try{for(let a=0;a<3;a++)try{const l=mi(),c=s?.refresh?"&refresh=true":"",d=l?`?directory=${encodeURIComponent(l)}${c}`:c?"?refresh=true":"",u=await fetch(`/api/config/skills/catalog${d}`,{method:"GET",headers:{Accept:"application/json"}}),m=await u.json().catch(()=>null);if(!u.ok||!m?.ok){o=m?.error||{kind:"unknown",message:`Failed to load catalog (${u.status})`};const g=200*(a+1);await new Promise(b=>setTimeout(b,g));continue}const f=m.sources||[],p=m.itemsBySource||{},h=r().selectedSourceId,x=h&&f.some(g=>g.id===h)?h:f[0]?.id??null;return t({sources:f,itemsBySource:p,selectedSourceId:x}),!0}catch(l){o={kind:"unknown",message:l instanceof Error?l.message:String(l)};const c=200*(a+1);await new Promise(d=>setTimeout(d,c))}return t({sources:n.sources,itemsBySource:n.itemsBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{t({isLoadingCatalog:!1})}},scanRepo:async s=>{t({isScanning:!0,lastScanError:null,scanResults:null});try{const n=mi(),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=mi(),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 or.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"})),vy=()=>{const t=Fe.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},Po=()=>{try{const r=Vt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const s=Fe.getDirectory();if(s?.trim())return s.trim()}catch(t){console.warn("[AgentsStore] Error resolving config directory:",t)}return null},sn=t=>{const r=t;return r.native===!0||r.builtIn===!0},zm=t=>{const r=t;return r.hidden===!0||r.options?.hidden===!0},Wm=t=>t.filter(r=>!zm(r)),aa="useAgentsStore",va=t=>new Promise(r=>setTimeout(r,t)),jy=2e4,Oc=300,_c=4,Sy=800,ky=200,Ny=2e3,Qr=ns()(cs(Ws((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=Po(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await Fe.withDirectory(o,()=>Fe.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=>{Ks("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=Po(),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 io({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&xr("agents",{source:aa}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||Fs()}},updateAgent:async(s,n)=>{Ks("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=Po(),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 io({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&xr("agents",{source:aa}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||Fs()}},deleteAgent:async s=>{Ks("Deleting agent configuration…");let n=!1;try{const o=Po(),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 io({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&xr("agents",{source:aa}),r().selectedAgentName===s&&t({selectedAgentName:null}),u}catch{return!1}finally{n||Fs()}},getAgentByName:s=>{const{agents:n}=r();return n.find(o=>o.name===s)},getVisibleAgents:()=>{const{agents:s}=r();return Wm(s)}}),{name:"agents-store",storage:Hs(()=>hs()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Qr);async function Cy(t){const r=typeof t=="number"&&t>0?Math.min(t,Oc):0;r>0&&await va(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<jy;){n+=1,Ar(`Waiting for OpenCode… (attempt ${n})`);try{if(await Fe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-s,l=n<=_c&&a<1200?Oc:Math.min(Sy+Math.max(0,n-_c)*ky,Ny);await va(l)}throw o||new Error("OpenCode did not become ready in time")}const My=t=>{if(!t||t.length===0)return["all"];const r=Array.from(new Set(t));return r.includes("all")?["all"]:r};async function Dy(t={}){const{message:r,delayMs:s}=t,n=My(t.scopes),o=t.mode??(n.includes("all")?"projects":"active");try{Ar(r||"Refreshing configuration…")}catch{}try{await Cy(s);const a=at.getState(),l=Qr.getState(),c=Kr.getState(),d=or.getState(),u=ko.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=vy(),b=o==="projects"?Vt.getState().projects:[],y=Array.from(new Set([...g?[g]:[],...b.map(N=>N.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&at.setState({directoryScoped:{}});const v=[];for(const N of y)m&&v.push(a.loadProviders({directory:N}).then(()=>{})),f&&v.push(a.loadAgents({directory:N}).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(()=>{}))),Ar("Refreshing configuration…"),await Promise.all([...v,...S])}catch{Ar("OpenCode refresh failed. Please retry."),await va(1500)}finally{Fs()}}async function io(t){await Dy(t)}async function lo(t){Ks(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 io({...n,message:s.message,delayMs:s.reloadDelayMs}):await io(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),Ar("Failed to reload configuration. Please try again."),await va(2e3),Fs(),r}}let $c=null;$c||($c=Ua(t=>{if(t.source!==aa&&xo(t,"agents")){const{loadAgents:r}=Qr.getState();r()}}));const Ay="https://models.dev/api.json",Ey="/api/openchamber/models-metadata",Bc="opencode",zc="big-pickle",Iy=async()=>{try{if(ls()){const c=await Pr();return{defaultModel:c?.defaultModel,defaultVariant:c?.defaultVariant,defaultAgent:c?.defaultAgent,autoCreateWorktree:c?.autoCreateWorktree,gitmojiEnabled:c?.gitmojiEnabled}}const t=As()?.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{}}},To=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]}},Py=t=>t?.toLowerCase?.()??"",Ty=t=>t==="primary"||t==="all"||t===void 0||t===null,yo=t=>typeof t=="object"&&t!==null,ja=t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),Fy=t=>{if(!yo(t))return!1;const r=t;if(r.modalities){const{input:s,output:n}=r.modalities;if(s&&!ja(s)||n&&!ja(n))return!1}return!0},Ry=t=>{if(!yo(t))return!1;const r=t;return r.models===void 0||yo(r.models)},Hm=(t,r)=>{const s=Py(t);return!s||!r?"":`${s}/${r}`},Ly=t=>{const r=new Map;if(!yo(t))return r;for(const[s,n]of Object.entries(t)){if(!Ry(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:s,a=n.models;if(!(!a||!yo(a)))for(const[l,c]of Object.entries(a)){if(!Fy(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:ja(c.modalities.input)?c.modalities.input:void 0,output:ja(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=Hm(o,d);m&&r.set(m,u)}}return r},Oy=async()=>{if(typeof fetch!="function")return new Map;const t=[Ey,Ay];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 Ly(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 fi=null;const _y=(t,r)=>{t().size>0||fi||(fi=Oy().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{fi=null}))},$y=t=>new Promise(r=>setTimeout(r,t)),$l="__global__",Tn=t=>{const r=typeof t=="string"?t.trim():"";return r.length>0?r:$l},wn=t=>t===$l?null:t,By=()=>{if(typeof window>"u")return $l;const t=Fe.getDirectory()??bt.getState().currentDirectory;return Tn(t)},at=ns()(cs(Ws((t,r)=>({activeDirectoryKey:By(),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=Tn(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:wn(n)}),await r().loadAgents({directory:wn(n)}))},loadProviders:async s=>{const n=Tn(s?.directory??wn(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{_y(()=>r().modelsMetadata,h=>t({modelsMetadata:h}));const u=await Fe.withDirectory(wn(n),()=>Fe.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=To(h.settingsDefaultModel);if(y){const v=p.find(S=>S.id===y.providerId);if(v?.models.some(S=>S.id===y.modelId)){const S=v.models.find(w=>w.id===y.modelId),N=h.settingsDefaultVariant&&S?.variants?.[h.settingsDefaultVariant]?h.settingsDefaultVariant:void 0;b.currentProviderId=y.providerId,b.currentModelId=y.modelId,b.currentVariant=N,b.selectedProviderId=y.providerId,g.currentProviderId=y.providerId,g.currentModelId=y.modelId,g.currentVariant=N,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=To(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=Tn(s?.directory??wn(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([Fe.withDirectory(wn(n),()=>Fe.listAgents()),Iy()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(t(w=>{const A={...w.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},j={settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsGitmojiEnabled:u.gitmojiEnabled??!1,directoryScoped:{...w.directoryScoped,[n]:A}};return w.activeDirectoryKey===n&&(j.agents=m),j}),m.length===0)return t(w=>{const A={...w.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},j={directoryScoped:{...w.directoryScoped,[n]:A}};return w.activeDirectoryKey===n&&(j.currentAgentName=void 0),j}),!0;const p=(w,k)=>{const A=f.find(j=>j.id===w);return A?A.models.some(j=>j.id===k):!1},h=m.filter(w=>Ty(w.mode));let b=h.find(w=>w.name==="build")||h[0]||m[0];const y={};if(u.defaultAgent){const w=m.find(k=>k.name===u.defaultAgent);w?b=w:y.defaultAgent=""}let v,S,N;if(u.defaultModel){const w=To(u.defaultModel);if(w&&p(w.providerId,w.modelId)){if(v=w.providerId,S=w.modelId,u.defaultVariant){const j=f.find(M=>M.id===w.providerId)?.models.find(M=>M.id===w.modelId)?.variants;j&&Object.prototype.hasOwnProperty.call(j,u.defaultVariant)?N=u.defaultVariant:y.defaultVariant=""}}else y.defaultModel=""}if(!v&&b?.model?.providerID&&b?.model?.modelID){const{providerID:w,modelID:k}=b.model;p(w,k)&&(v=w,S=k)}if(!v)if(p(Bc,zc))v=Bc,S=zc;else{const w=f[0],k=w?.models[0];w&&k&&(v=w.id,S=k.id)}return t(w=>{const k=w.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},A={...k,providers:f,agents:m,currentAgentName:b.name,currentProviderId:v??k.currentProviderId,currentModelId:S??k.currentModelId,currentVariant:N},j={directoryScoped:{...w.directoryScoped,[n]:A}};return w.activeDirectoryKey===n&&(j.currentAgentName=b.name,v&&S&&(j.currentProviderId=v,j.currentModelId=S,j.currentVariant=N)),j}),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}),us(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=To(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(N=>N.id===m.providerId)?.models.find(N=>N.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 Fe.checkHealth();return t({isConnected:a}),a}catch(a){o=a,n+=1;const l=400*n;await $y(l)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),t({isConnected:!1}),!1},initializeApp:async()=>{try{const s=ds();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 Fe.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=Hm(s,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:s}=r();return Wm(s)}}),{name:"config-store",storage:Hs(()=>hs()),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__=at);let Wc=null;Wc||(Wc=Ua(async t=>{const r=[];if(xo(t,"agents")){const{loadAgents:s}=at.getState();r.push(s().then(()=>{}))}if(xo(t,"providers")){const{loadProviders:s}=at.getState();r.push(s())}r.length>0&&await Promise.all(r)}));let Hc=null;typeof window<"u"&&!Hc&&(Hc=bt.subscribe((t,r)=>{const s=Tn(t.currentDirectory),n=Tn(r.currentDirectory);s!==n&&at.getState().activateDirectory(t.currentDirectory)}));const rn={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,HISTORICAL_MESSAGES:90,FETCH_BUFFER:20,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},nl=180,Sa=()=>{const t=Ce.getState?.();return t?{...rn,HISTORICAL_MESSAGES:t.memoryLimitHistorical??rn.HISTORICAL_MESSAGES,VIEWPORT_MESSAGES:t.memoryLimitViewport??rn.VIEWPORT_MESSAGES}:rn},ol=()=>{const t=Ce.getState?.();return t?t.memoryLimitActiveSession??nl:nl},kr=rn,Ps=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function Yr(t){const r=Ps();return r?r.checkIsGitRepository(t):cx(t)}async function zy(t){const r=Ps();return r?r.getGitStatus(t):ux(t)}async function qa(t){const r=Ps();return r?r.getGitBranches(t):Sx(t)}async function Wy(t,r){const s=Ps();return s?s.deleteGitBranch(t,r):fx(t,r)}async function Hy(t,r){const s=Ps();return s?s.deleteRemoteBranch(t,r):px(t,r)}async function Um(t){const r=Ps();return r?r.listGitWorktrees(t):dx(t)}async function Uy(t,r){const s=Ps();return s?s.addGitWorktree(t,r):hx(t,r)}async function Vm(t,r){const s=Ps();return s?s.removeGitWorktree(t,r):mx(t,r)}async function Vy(t){const r=Ps();return r?r.ensureOpenChamberIgnored(t):jx(t)}async function Gy(){const t=Ps();return t?t.getGitIdentities():vx()}async function qy(t){const r=Ps();return r?r.createGitIdentity(t):yx(t)}async function Ky(t,r){const s=Ps();return s?s.updateGitIdentity(t,r):xx(t,r)}async function Qy(t){const r=Ps();return r?r.deleteGitIdentity(t):gx(t)}async function Yy(){const t=Ps();return t?.discoverGitCredentials?t.discoverGitCredentials():bx()}async function Xy(){const t=Ps();return t?.getGlobalGitIdentity?t.getGlobalGitIdentity():wx()}const Jy="openchamber.json",Gm=".openchamber";function qm(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Zy=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},al=(t,r)=>{const s=Zy(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},Km=t=>al(al(t,Gm),Jy);async function Qm(t){const r=Km(t);try{const s=qm();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(`${Xm()}/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 eb(t,r){const s=Km(t),n=al(t,Gm);try{await Fe.createDirectory(n);const o=qm();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(`${Xm()}/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 tb(t,r){const n={...await Qm(t)||{},...r};return eb(t,n)}async function Qn(t){return(await Qm(t))?.["setup-worktree"]??[]}async function Ym(t,r){const s=r.filter(n=>n.trim().length>0);return tb(t,{"setup-worktree":s})}function sb(t,r){return t.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function Xm(){const t="/api";return t.startsWith("/"),t}const rb=".openchamber",Uc="/api";function nb(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Ir=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Vc=(t,r)=>{const s=Ir(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},Jm=t=>t?t.startsWith("refs/heads/")?t.substring(11):t.startsWith("heads/")?t.substring(6):t.startsWith("refs/")?t.substring(5):t:"",ob=async t=>{try{await Fe.createDirectory(t)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function ab(t,r){const s=Ir(t),n=Vc(s,rb);return await ob(n),Vc(n,r)}async function Bl(t){const{projectDirectory:r,worktreeSlug:s,branch:n,createBranch:o,startPoint:a}=t,l=Ir(r),c=await ab(l,s),d={path:c,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await Uy(l,d),{path:c,branch:n,label:Jm(n),projectDirectory:l,relativePath:c.startsWith(`${l}/`)?c.slice(l.length+1):c}}async function Zm(t){const{projectDirectory:r,path:s,force:n}=t,o=Ir(r);await Vm(o,{path:s,force:n})}async function ef(t){const{projectDirectory:r,path:s,branch:n,force:o,deleteRemote:a,remote:l}=t,c=Ir(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await Vm(c,{path:s,force:o}),d&&(await Wy(c,{branch:d,force:!0}),a))try{await Hy(c,{branch:d,remote:l})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function $n(t){const r=Ir(t);return Um(r)}async function Ka(t){const r=Ir(t),s=await zy(r);return{isDirty:!s.isClean,ahead:s.ahead,behind:s.behind,upstream:s.tracking}}function Bn(t,r){const s=Ir(t),n=Ir(r.worktree);return{path:n,branch:r.branch??"",label:Jm(r.branch??""),projectDirectory:s,relativePath:n.startsWith(`${s}/`)?n.slice(s.length+1):n}}async function zl(t,r,s){const n=s??await Qn(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>sb(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:t,projectDirectory:r,commands:o});try{const a=nb();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(`${Uc}/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(`${Uc}/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 tf=hs(),sf="oc.sessionSelectionByDirectory",pi=".openchamber",ib=()=>{try{const t=tf.getItem(sf);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 ia=null;const Wl=()=>(ia||(ia=ib()),ia),rf=t=>{ia=t;try{tf.setItem(sf,JSON.stringify(t))}catch{}},nf=t=>{if(!t)return null;const s=Wl()[t];return typeof s=="string"?s:null},jr=(t,r)=>{if(!t)return;const s={...Wl()};r?s[t]=r:delete s[t],rf(s)},lb=(t,r)=>{if(!t)return;const s=nf(t);if(!s)return;if(!new Set(r).has(s)){const o={...Wl()};delete o[t],rf(o)}},Gc=async(t,r)=>{const s=t.status??await Ka(t.path).catch(()=>{});await ef({projectDirectory:t.projectDirectory,path:t.path,branch:t.branch,force:!!s?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},At=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},qc=()=>{if(typeof window>"u")return null;const t=window.__VSCODE_CONFIG__,r=typeof t?.workspaceFolder=="string"?t.workspaceFolder:null;return At(r)},cb=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,Fo=(...t)=>{ds()&&cb()&&console.log("[OpenChamber][VSCode][sessions]",...t)},Lr=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())},Js=t=>{const r=new Map;t.forEach(s=>{const n=At(s.directory??null);if(!n)return;const o=r.get(n);o?o.push(s):r.set(n,[s])});for(const[s,n]of r.entries())r.set(s,Lr(n));return r},vn=(t,r)=>{const s=t.find(n=>n.id===r);return s?At(s.directory??null):null},db=async(t,r,s)=>{const n=At(r);if(!n||t.length===0)return null;const o=t.map(u=>({id:u.id,directory:At(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await $n(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=Bn(n,u),f=At(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},ft=ns()(cs(Ws((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=bt.getState(),n=Vt.getState(),o=Fe.getApiClient(),a=qc(),l=!!a;Fo("loadSessions:start",{workspace:a,currentDirectory:s.currentDirectory,clientDirectory:Fe.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const c=new Map,d=async R=>{const V=At(R)??R,G=V,O=c.get(G);if(O)return O;try{const Y=await o.path.get({directory:R}),U=At(Y.data?.directory??null)??V;return c.set(G,U),U}catch{return c.set(G,V),V}},u=(R,V,G)=>{const O=At(V);if(!O)return R;const K=G?.includeDescendants===!0?`${O}/`:null,U=G?.includeMissingDirectory===!0;return R.filter(Q=>{const W=At(Q.directory??null);return W?!!(W===O||K&&W.startsWith(K)):U})},m=(R,V,G)=>{const O=At(V);if(!O)return R;const Y=At(G??null);if(!Y||Y===O)return R.map(Q=>At(Q.directory??null)?Q:{...Q,directory:O});const K=Y==="/"?"/":`${Y}/`,U=O==="/"?"/":`${O}/`;return R.map(Q=>{const W=At(Q.directory??null);if(!W)return{...Q,directory:O};if(W===Y)return{...Q,directory:O};if(K!=="/"&&W.startsWith(K)){const se=W.slice(K.length);return{...Q,directory:`${U}${se}`}}return Q})},f=async R=>{const V=At(R);if(!V)try{const W=await o.session.list(void 0);return Array.isArray(W.data)?W.data:[]}catch(W){throw console.debug("Failed to list sessions (global):",W),W}const G=await d(V),O=async()=>{const W=await o.session.list({directory:V});return Array.isArray(W.data)?W.data:[]};let Y=[],K=null,U=!1;try{Y=await O()}catch(W){console.debug("Failed to list sessions for directory:",V,W),K=W,Y=[]}if(Y.length===0){U=!0;try{const W=await o.session.list(void 0),se=Array.isArray(W.data)?W.data:[];Y=u(se,G,{includeDescendants:l,includeMissingDirectory:!1})}catch(W){throw console.debug("Failed to list sessions (global fallback):",W),K||W}}const Q=u(Y,G,{includeDescendants:l,includeMissingDirectory:!U});return Fo("fetchSessionsForDirectory",{requestedDirectory:V,canonicalDirectory:G,fetched:Y.length,filtered:Q.length}),m(Q,V,G)},p=At(s.currentDirectory??Fe.getDirectory()??null),h=n.projects.find(R=>R.id===n.activeProjectId)??null,x=At(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 R=>{const V=At(R.path);if(!V)return{projectId:R.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const G=await Yr(V).catch(()=>!1),O=await f(V||null);Fo("projectSessions",{projectId:R.id,projectPath:V,isGitRepo:G,parentSessions:O.length});const Y=[];let K=[];const U=new Set;if(U.add(V),G){const W=`${V}/${pi}`;try{const se=new Set;(await Fe.listLocalDirectory(V)).some(oe=>oe.isDirectory&&oe.name===pi)&&(await Fe.listLocalDirectory(W)).filter(_=>_.isDirectory).forEach(_=>{const X=/^([A-Za-z]:)?\//.test(_.path)?_.path:`${W}/${_.name}`,re=At(X)??X;se.add(re)});const $=await $n(V);Array.isArray($)&&(K=$.map(oe=>Bn(V,oe)).filter(oe=>oe.path.includes(`/${pi}/`)),K.forEach(oe=>se.add(oe.path))),se.forEach(oe=>{const _=At(oe)??oe;U.add(_)}),se.size>0&&(await Promise.allSettled(Array.from(se).map(_=>f(_)))).forEach(_=>{_.status==="fulfilled"&&Array.isArray(_.value)&&Y.push(..._.value)})}catch{K=[]}}const Q=Lr([...O,...Y]);return{projectId:R.id,projectPath:V,sessions:Q,discoveredWorktrees:K,validPaths:U}})),v=new Map;y.forEach(R=>{R.projectPath&&R.validPaths.forEach(V=>{const G=At(V)??V,O=R.sessions.filter(Y=>(At(Y.directory??null)??G)===G);v.set(G,Lr(O))})});const S=Lr(Array.from(v.values()).flat()),N=r();let w=N.worktreeMetadata;for(const R of y)if(R.projectPath)try{const V=await db(R.sessions,R.projectPath,w);V&&(w=V)}catch(V){console.debug("Failed to refresh worktree metadata during session load:",V)}const k=new Map;y.forEach(R=>{R.projectPath&&k.set(R.projectPath,R.discoveredWorktrees)});const A=new Set;y.forEach(R=>{R.validPaths.forEach(V=>{const G=At(V)??V;G&&A.add(G)})});const j=p??x??null,M=j&&A.has(j)?j:x??j,C=M?v.get(M)??[]:S,I=new Set(S.map(R=>R.id));for(const[R,V]of v.entries())lb(R,V.map(G=>G.id));const E=(M??null)!==(N.lastLoadedDirectory??null);let P=N.currentSessionId;if((!P||!I.has(P)||E)&&(P=C[0]?.id??S[0]?.id??null),M){const R=nf(M);R&&I.has(R)&&(P=R)}const D=(()=>{if(!P)return M??null;const R=w.get(P)?.path;if(R)return At(R)??R;const V=vn(S,P);return V||(M??null)})();try{Fe.setDirectory(D??void 0)}catch(R){console.warn("Failed to sync OpenCode directory after session load:",R)}const T=x?y.find(R=>R.projectPath===x)?.discoveredWorktrees??[]:[];t({sessions:S,sessionsByDirectory:v,currentSessionId:P,lastLoadedDirectory:M??null,isLoading:!1,worktreeMetadata:w,availableWorktrees:T,availableWorktreesByProject:k}),M&&jr(M,P),D&&D!==M&&jr(D,P)}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=bt.getState(),l=At(a.currentDirectory),c=qc(),d=c??At(n??Fe.getDirectory()??l);Fo("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 v=y.get(d)??[];y.set(d,Lr([p,...v]))}return{sessions:b,sessionsByDirectory:y,currentSessionId:u,webUICreatedSessions:new Set([...g.webUICreatedSessions,u]),isLoading:!1}}),d)try{Fe.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(v=>{const S=v.sessions.map(w=>w.id===u?y:w),N=new Map(v.sessionsByDirectory);if(d){const k=(N.get(d)??[]).map(A=>A.id===u?y:A);N.set(d,Lr(k))}return{sessions:S,sessionsByDirectory:Js(S),currentSessionId:y.id,webUICreatedSessions:new Set([...Array.from(v.webUICreatedSessions).filter(w=>w!==u),y.id])}}),jr(d??null,y.id)},x=async()=>{const g=Fe.getApiClient(),b=20;for(let y=0;y<b;y+=1){try{const v=await g.session.list(d?{directory:d}:void 0),N=(Array.isArray(v.data)?v.data:[]).find(w=>!(f.has(w.id)||s&&w.title&&w.title!==s));if(N)return N}catch(v){console.debug("Session poll attempt failed:",v)}await new Promise(v=>setTimeout(v,2e3))}return null};try{const g=()=>Fe.createSession({title:s,parentID:o??void 0});let b=null;try{b=d?await Fe.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(v=>v.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(v=>v!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(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=vn(r().sessions,s),l=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await Gc(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Fe.deleteSession(s);if(!(l?await Fe.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=>At(y.path)!==At(o.path)):p.availableWorktrees,b=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const y=At(o.projectDirectory)??o.projectDirectory,v=b.get(y)??[];b.set(y,v.filter(S=>At(S.path)!==At(o.path)))}return{sessions:h,sessionsByDirectory:Js(h),currentSessionId:m,isLoading:!1,worktreeMetadata:x,availableWorktrees:g,availableWorktreesByProject:b}});const f=l??Fe.getDirectory()??null;return jr(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),v=vn(r().sessions,b),S=y?.path??v;y&&n?.archiveWorktree&&!m.has(y.path)&&(await Gc(y,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(b),u.push({path:y.path,projectDirectory:y.projectDirectory}),m.add(y.path));const N=()=>Fe.deleteSession(b);(S?await Fe.withDirectory(S,N):await N())?(l.push(b),y?.path&&!u.some(k=>k.path===y.path)&&u.push({path:y.path,projectDirectory:y.projectDirectory})):c.push(b)}catch{c.push(b)}const f=bt.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(k=>!p.has(k.id));b.currentSessionId&&p.has(b.currentSessionId)?x=null:x=b.currentSessionId;const v=new Map(b.worktreeMetadata);for(const k of p)v.delete(k);for(const k of d)v.delete(k);const S=new Set(u.map(k=>At(k.path)).filter(k=>!!k)),N=S.size>0?b.availableWorktrees.filter(k=>!S.has(At(k.path)??k.path)):b.availableWorktrees,w=new Map(b.availableWorktreesByProject);return u.length>0&&u.reduce((A,j)=>{const M=At(j.projectDirectory)??j.projectDirectory,C=At(j.path)??j.path;return A.has(M)||A.set(M,new Set),A.get(M)?.add(C),A},new Map).forEach((A,j)=>{const C=(w.get(j)??[]).filter(I=>!A.has(At(I.path)??I.path));w.set(j,C)}),{sessions:y,sessionsByDirectory:Js(y),currentSessionId:x,...a?{}:{isLoading:!1,error:h},worktreeMetadata:v,availableWorktrees:N,availableWorktreesByProject:w}});const g=Fe.getDirectory()??null;return jr(g,x),{deletedIds:l,failedIds:c}},updateSessionTitle:async(s,n)=>{try{const o=vn(r().sessions,s),a=r().worktreeMetadata.get(s),l=()=>Fe.updateSession(s,n),c=a?.path??o,d=c?await Fe.withDirectory(c,l):await l();t(u=>{const m=u.sessions.map(f=>f.id===s?d:f);return{sessions:m,sessionsByDirectory:Js(m)}})}catch(o){t({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async s=>{try{const n=vn(r().sessions,s),o=Fe.getApiClient(),l=r().worktreeMetadata.get(s)?.path??n,c=async()=>{const u=n??Fe.getDirectory();return o.session.share({sessionID:s,...u?{directory:u}:{}})},d=l?await Fe.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:Js(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=vn(r().sessions,s),o=Fe.getApiClient(),l=r().worktreeMetadata.get(s)?.path??n,c=async()=>{const u=n??Fe.getDirectory();return o.session.unshare({sessionID:s,...u?{directory:u}:{}})},d=l?await Fe.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:Js(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=Fe.getDirectory()??null;jr(n,s)},clearError:()=>{t({error:null})},getSessionsByDirectory:s=>{const n=At(s)??s,{sessionsByDirectory:o,sessions:a}=r(),l=o.get(n);return l||a.filter(c=>(At(c.directory??null)??n)===n)},getDirectoryForSession:s=>{if(!s)return null;const n=r().worktreeMetadata.get(s);if(n?.path)return At(n.path)??n.path;const o=r().sessions.find(l=>l.id===s);return At(o?.directory??null)},applySessionMetadata:(s,n)=>{!s||!n||t(o=>{const a=o.sessions.findIndex(h=>h.id===s);if(a===-1)return o;const 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:Js(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:Js(m)}}),c&&jr(c,null),n&&jr(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=Lr(a);return{sessions:l,sessionsByDirectory:Js(l)}})},removeSessionFromStore:s=>{s&&t(n=>{const o=n.sessions.find(u=>u.id===s),a=At(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&&jr(a,null),{sessions:l,sessionsByDirectory:Js(l),currentSessionId:d,worktreeMetadata:c}})}}),{name:"session-store",storage:Hs(()=>hs()),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=Lr(n);return{...r,...t,sessions:f,sessionsByDirectory:Js(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"})),of="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.",ub="This message bellow comes from an AI agent in another session. I want you to act according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed; if it is a bug description, find the root cause and fix it. Proceed with actions right away based on your understanding of the task. Here is the content of the message: ",hi=t=>typeof t=="string"&&t.trim()===of.trim(),gi=(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},Xn=(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},Kc=new Map,af=t=>{const r=Kc.get(t);r&&(clearTimeout(r),Kc.delete(t))},Jr=t=>{for(const r of t)af(r)},bo=t=>{if(!t)return"";if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>bo(r)).join("");if(typeof t=="object"){if(typeof t.text=="string")return t.text;if(Array.isArray(t.content))return t.content.map(r=>bo(r)).join("")}return""},co=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:co(n)).join("");const s=bo(r.delta);return s||(typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||bo(o.delta)||""}return""}).join(""):"")},Jn=(t,r)=>{const s={...t};if(s.type=s.type||"text",s.type==="text"){const n=r&&typeof r.text=="string"?r.text:"",o=typeof s.text=="string"?s.text:"",a=bo(t.delta);o?s.text=o:a?s.text=n?`${n}${a}`:a:n?s.text=n:s.text="",delete s.delta}return s},Qc=50*1024*1024,mb=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"}},fb=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"}},pb=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},hb=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},ar=ns()(cs(Ws((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=Qc;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=fb(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=Fe.getApiClient(),v=s.lastIndexOf("/"),S=v>0?s.substring(0,v):"/",N=v>0?s.substring(v+1):s,w=await y.file.read({path:N,directory:S});w.data&&"content"in w.data?(c=w.data.content,d=w.data.encoding??void 0,u=w.data.mimeType??void 0):c=""}catch(y){console.error("Failed to read server file:",y),c=`[File: ${n}]`}const m=u||mb(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const v=new TextEncoder().encode(c||"");return hb(v)})(),h=d==="base64"?pb(p):new TextEncoder().encode(c||"").length;if(h>Qc)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:Hs(()=>hs()),partialize:t=>({attachedFiles:t.attachedFiles})}),{name:"file-store"})),gb=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),xb=t=>t?gb.has(t.toLowerCase()):!1,yb=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},bb=t=>{if(t)try{const r=yb();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===t)}catch{}},wb=(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"},la=t=>{const r=bb(t);return r?wb(r.permission,"edit"):"ask"},Yc=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},xi=t=>{const r=t.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return Yc(r);const s=t.parts.find(n=>typeof n.tokens<"u");return!s||typeof s.tokens>"u"?0:typeof s.tokens=="number"?s.tokens:Yc(s.tokens)},yi=(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}},Zn=["ask","allow","full"],ht=ns()(cs(Ws((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);return a.set(s,n),{sessionAgentSelections:a}})},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(x.providerID&&x.modelID){const v=n.find(S=>S.model?.providerID===x.providerID&&S.model?.modelID===x.modelID);if(v)return v.name}const{currentAgentContext:b}=r(),y=b.get(s);if(y&&n.find(v=>v.name===y))return y;if(g>0&&x.providerID&&x.modelID){const S=(o.get(s)||[]).filter(N=>N.info.role==="assistant").sort((N,w)=>N.info.time.created-w.info.time.created);for(let N=g-1;N>=0;N--){const k=S[N].info;if(k.providerID===x.providerID&&k.modelID===x.modelID){if(k.mode&&typeof k.mode=="string"&&n.find(M=>M.name===k.mode))return k.mode;const A=n.find(j=>j.model?.providerID===k.providerID&&j.model?.modelID===k.modelID);if(A)return A.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"){p=typeof y.variant=="string"&&y.variant.trim().length>0?y.variant:void 0,h=y.model?.providerID&&y.model?.modelID?{providerID:y.model.providerID,modelID:y.model.modelID}:void 0;continue}if(y.providerID&&y.modelID){const v=d(y,f.indexOf(g));if(v&&n.find(S=>S.name===v)){p&&h&&h.providerID===y.providerID&&h.modelID===y.modelID&&l(s,v,y.providerID,y.modelID,p);const S={providerId:y.providerID,modelId:y.modelID,timestamp:b.time.created},N=c.get(v);(!N||S.timestamp>N.timestamp)&&c.set(v,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=yi(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 N=()=>{t(w=>{const k=w.sessionContextUsage.get(s);if(k&&k.totalTokens===S.totalTokens&&k.percentage===S.percentage&&k.contextLimit===S.contextLimit&&(k.outputLimit??0)===(S.outputLimit??0)&&(k.normalizedOutput??0)===(S.normalizedOutput??0)&&k.thresholdLimit===S.thresholdLimit&&k.lastMessageId===S.lastMessageId)return w;const A=new Map(w.sessionContextUsage);return A.set(s,S),{sessionContextUsage:A}})};typeof queueMicrotask=="function"?queueMicrotask(N):typeof window<"u"?window.setTimeout(N,0):setTimeout(N,0)},g=r().sessionContextUsage.get(s);if(g&&g.lastMessageId===h){const S=g.normalizedOutput??g.outputLimit??0,N=g.contextLimit!==c||S!==d||g.thresholdLimit!==u;if(N&&g.totalTokens>0){const w=g.totalTokens/u*100,k={totalTokens:g.totalTokens,percentage:Math.min(w,100),contextLimit:c,outputLimit:l.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return x(k),k}if(!N&&g.totalTokens>0)return g}const b=xi(p);if(b===0)return g||null;const y=yi(b,n,o),v={totalTokens:b,percentage:y.percentage,contextLimit:y.contextLimit,outputLimit:y.outputLimit,normalizedOutput:y.normalizedOutput,thresholdLimit:y.thresholdLimit,lastMessageId:h};return x(v),v},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=xi(d);if(u===0)return;const m=yi(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"&&xi(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=la(n))=>!s||!n?o:r().sessionAgentEditModes.get(s)?.get(n)??o,setSessionAgentEditMode:(s,n,o,a=la(n))=>{if(!s||!n)return;const l=a??"ask";l==="deny"||o==="deny"||Zn.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=la(n))=>{if(!s||!n)return;const a=o??"ask";if(a==="deny")return;const l=r().getSessionAgentEditMode(s,n,a),c=Zn.indexOf(l),d=Zn.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%Zn.length,f=Zn[m];r().setSessionAgentEditMode(s,n,f,a)}}),{name:"context-store",storage:Hs(()=>hs()),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"})),Xc=(t,r)=>{const s=new Map(t);return s.delete(r),s};let bi=[],wi=null;const vb=50,jb=3e4,Zr=new Map,Ro=new Map,jn=new Map,Sb=10,ka=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<Sb?null:n},Lo=(t,r)=>{const s=ka(t),n=ka(r);return!s||!n||s.length!==n.length?!0:s>n},kb=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},An=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),Na=t=>t?.finish==="stop",Jc=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??""}`}}},Zc=new Set,Ca=(t=[],r=[])=>{if(!r.length)return[...t];const s=[...t],n=new Set(t.map(Jc).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=Jc(o);a&&n.has(a)||(s.push(o),a&&n.add(a))}),s},Nb=(t,r)=>{const s=Array.isArray(t.parts)?t.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=An(s),a=An(n),l=Na(t.info),c=Na(r.info);let d=n;return l&&o>=a?d=Ca(s,n):c&&a>=o?d=Ca(n,s):o>=a&&(d=s),{...r,info:{...t.info,...r.info},parts:d}},Oo=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]=Nb(r[a],n)}return r},Cb=(t,r)=>{let s=r,n=r?ka(r):null;for(const o of t){const a=o?.info?.id,l=ka(a);!a||!l||(!n||l>n)&&(n=l,s=a)}return s},dr=(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},Sn=(t,r,s)=>{if(t.get(r)===s)return t;const o=new Map(t);return o.set(r,s),o},_o=(t,r)=>{const s=new Map(t);let n=!1;for(const o of r)s.delete(o)&&(n=!0);return n?s:t},Mb=(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},ed=(t,r,s)=>t.streamingMessageIds.get(r)===s?!0:t.messageSessionIndex.get(s)===r&&t.messageStreamStates.has(s),Db=async t=>{if(t)try{return ft.getState().getDirectoryForSession(t)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},td=t=>{if(!t)return null;try{return ft.getState().sessions.find(n=>n.id===t)?.revert?.messageID??null}catch{return null}},sd=(t,r)=>{if(!r)return t;const s=t.findIndex(n=>n.info.id===r);return s===-1?t:t.slice(0,s)},vi=async(t,r)=>{const s=await Db(t);return s?Fe.withDirectory(s,r):r()},Et=ns()(cs(Ws((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=Sa(),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 vi(s,()=>Fe.getSessionMessages(s,u)),f=td(s),p=sd(m,f),h=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,g=(h?p.filter(b=>{const y=b?.info?.id;return y?Lo(y,h):!0}):p).slice(-d);t(b=>{const y=new Map(b.messages),v=b.messages.get(s)||[],S=new Map(v.filter(T=>typeof T.info?.id=="string").map(T=>[T.info.id,T])),N=g.map(T=>{const R={...T.info,clientRole:T.info?.clientRole??T.info.role,userMessageMarker:T.info.role==="user"?!0:T.info?.userMessageMarker},V=(Array.isArray(T.parts)?T.parts:[]).map(O=>{if(O?.type==="text"){const Y=O.text??O.content??"";if(hi(Y))return{...O,synthetic:!0}}return O}),G=R?.id?S.get(R.id):void 0;if(G&&G.info.role==="assistant"){const O=Array.isArray(G.parts)?G.parts:[],Y=An(O),K=An(V);if(Na(G.info)&&Y>K){const Q=Ca(O,V);return{...T,info:R,parts:Q}}}return{...T,info:R,parts:V}}),w=Oo(N),k=new Set(v.map(T=>T.info.id)),A=new Set(w.map(T=>T.info.id)),j=[];k.forEach(T=>{A.has(T)||j.push(T)}),y.set(s,w);const M=new Map(b.sessionMemoryState),C=b.sessionMemoryState.get(s);M.set(s,{...C,viewportAnchor:w.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:m.length,hasMoreAbove:m.length>g.length,trimmedHeadMaxId:C?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const I={messages:y,sessionMemoryState:M};Jr(j);const E=Xn(b.messageStreamStates,j);if(E!==b.messageStreamStates&&(I.messageStreamStates=E),j.length>0){const T=b.streamingMessageIds.get(s);T&&j.includes(T)&&(I.streamingMessageIds=dr(I.streamingMessageIds??b.streamingMessageIds,s,null))}if(j.length>0){const T=_o(I.messageSessionIndex??b.messageSessionIndex,j);T!==(I.messageSessionIndex??b.messageSessionIndex)&&(I.messageSessionIndex=T)}if(j.length>0){const T=new Map(b.pendingAssistantParts);let R=!1;j.forEach(V=>{T.delete(V)&&(R=!0)}),R&&(I.pendingAssistantParts=T)}const P=I.messageSessionIndex??b.messageSessionIndex;let D=P;return w.forEach(T=>{const R=T?.info?.id;typeof R=="string"&&R.length>0&&(D=Sn(D,R,s))}),D!==P&&(I.messageSessionIndex=D),I})},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 vi(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=Fe.getApiClient(),v=Fe.getDirectory();if(g==="init"){const S=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await y.session.init({sessionID:f,...v?{directory:v}:{},messageID:S,providerID:n,modelID:o});return}if(g==="summarize"){await y.session.summarize({sessionID:f,...v?{directory:v}:{},providerID:n,modelID:o});return}try{const S=await Fe.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=jn.get(f);b&&(clearTimeout(b),jn.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 v=new Map(y.abortControllers);return v.set(f,x),{abortControllers:v}});const g=(c??[]).map(y=>({type:"file",mime:y.mimeType,filename:y.filename,url:y.dataUrl}));t(y=>{const v=new Set(y.pendingAssistantHeaderSessions);v.add(f);const S=new Map(y.pendingUserMessageMetaBySession);return S.set(f,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o,variant:typeof m=="string"&&m.trim().length>0?m:void 0}),{pendingAssistantHeaderSessions:v,pendingUserMessageMetaBySession:S}});const b=u?.map(y=>({text:y.text,files:y.attachments?.map(v=>({type:"file",mime:v.mimeType,filename:v.filename,url:v.dataUrl}))}));if(await Fe.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:g.length>0?g:void 0,additionalParts:b,agentMentions:d?[{name:d}]:void 0}),g.length>0)try{ar.getState().clearAttachedFiles()}catch(y){console.error("Failed to clear attached files after send",y)}t(y=>{const v=new Map(y.abortControllers);return v.delete(f),{abortControllers:v}})}catch(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 v=new Set(b.pendingAssistantHeaderSessions);v.delete(f);const S=new Map(b.pendingUserMessageMetaBySession);return S.delete(f),{abortControllers:y,pendingAssistantHeaderSessions:v,pendingUserMessageMetaBySession:S}}),new Error(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=Mb(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=Zr.get(u);m&&(clearTimeout(m),Zr.delete(u),Ro.delete(u))}c.size>0&&Jr(c);const d=Date.now();t(u=>{const m=Xn(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(v=>{if(!c.has(v.info.id)&&c.size>0)return v;const S=(v.parts??[]).map(N=>{if(N.type==="reasoning"){const w=N,k={...w.time??{}};return typeof k.end!="number"&&(k.end=d),{...w,time:k}}if(N.type==="tool"){const w=N,k={...w.state??{}};return(k.status==="running"||k.status==="pending")&&(k.status="aborted"),{...w,state:k}}return N.type==="step-start"?{...N,type:"step-finish",aborted:!0}:N});return p=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:S}});p&&(h=new Map(u.messages),h.set(s,y))}const 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:dr(u.streamingMessageIds,s,null),...p?{messages:h}:{}}}),Fe.abortSession(s).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(s,n,o,a,l)=>{const c=r();if(Zc.has(n))return;const d=c.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!Lo(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>kr.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=Sn(h.messageSessionIndex,n,s);y!==h.messageSessionIndex&&(b.messageSessionIndex=y);const v=M=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(s)))return M;const I=new Map(h.sessionAbortFlags);return I.delete(s),{...M,sessionAbortFlags:I}},S=M=>{const C=M||"",I=Ro.get(n);if(C&&I===C){const D=r();if(ed(D,s,n)){const T=Zr.get(n);T&&(clearTimeout(T),Zr.delete(n)),setTimeout(()=>{const R=r();typeof R.forceCompleteMessage=="function"&&R.forceCompleteMessage(s,n,"timeout"),R.completeStreamingMessage(s,n)},100)}}Ro.set(n,C);const E=Zr.get(n);E&&clearTimeout(E);const P=setTimeout(()=>{const D=r();typeof D.forceCompleteMessage=="function"&&D.forceCompleteMessage(s,n,"timeout"),ed(D,s,n)&&D.completeStreamingMessage(s,n),Zr.delete(n),Ro.delete(n)},8e3);Zr.set(n,P)},N=s!==l,w=h.sessionMemoryState.get(s);if(N&&w?.isStreaming){g.length>=kr.BACKGROUND_STREAMING_BUFFER&&g.shift();const M=new Map(h.sessionMemoryState);M.set(s,{...w,backgroundMessageCount:(w.backgroundMessageCount||0)+1}),h.sessionMemoryState=M}if(f==="assistant"){const M=h.sessionMemoryState.get(s);if(M){const C=Date.now(),I=new Map(h.sessionMemoryState);I.set(s,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??C,lastAccessedAt:C,isZombie:!1}),h.sessionMemoryState=I}}const k=co(o);if(hi(k)&&(o.synthetic=!0),kb()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:k.length,snapshotParts:u.length})}catch{}const A=b.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const M=dr(A,s,n);M!==A&&(b.streamingMessageIds=M,window.__messageTracker?.(n,"streamingId_set_latest"))}const j=g.findIndex(M=>M.info.id===n);if(j!==-1&&f==="user"){const M=g[j],C=M.parts.findIndex(T=>T.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const I=Jn(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(n,`user_part_type:${I.type||"unknown"}`);const E={...M};C!==-1?E.parts=E.parts.map((T,R)=>R===C?I:T):E.parts=[...E.parts,I];const P=[...g];P[j]=E;const D=new Map(h.messages);return D.set(s,P),v({messages:D})}if(f==="assistant"&&j!==-1){const M=g[j],C=M.parts.findIndex(R=>R.id===o.id),I=Jn(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(n,`part_type:${I.type||"unknown"}`);const E={...M};C!==-1?E.parts=E.parts.map((R,V)=>V===C?I:R):E.parts=[...E.parts,I];const P=[...g];P[j]=E;const D=new Map(h.messages);D.set(s,P),b.messageStreamStates=gi(h.messageStreamStates,n);const T=dr(b.streamingMessageIds??h.streamingMessageIds,s,n);return T!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=T,window.__messageTracker?.(n,"streamingId_set")),I.type==="text"?S(I.text||""):S(""),v({messages:D,...b})}if(j===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const ee=Jn(o);window.__messageTracker?.(n,`new_user_part_type:${ee.type||"unknown"}`);const pe=h.pendingUserMessageMetaBySession.get(s),$=ht.getState(),oe=pe?.mode??$.getSessionAgentSelection(s)??$.getCurrentAgent(s),_=typeof oe=="string"&&oe.trim().length>0?oe.trim():void 0,z=pe?.providerID??(h.lastUsedProvider?.providerID||void 0),X=pe?.modelID??(h.lastUsedProvider?.modelID||void 0);pe&&(b.pendingUserMessageMetaBySession=Xc(h.pendingUserMessageMetaBySession,s));const re={info:{id:n,sessionID:s,role:"user",clientRole:"user",userMessageMarker:!0,..._?{mode:_}:{},...z?{providerID:z}:{},...X?{modelID:X}:{},time:{created:Date.now()}},parts:[ee]},ge=[...g,re];ge.sort((fe,we)=>{const he=fe.info?.time?.created||0,_e=we.info?.time?.created||0;return he-_e});const H=new Map(h.messages);return H.set(s,ge),v({messages:H})}if(o?.type==="text"){const ee=co(o).trim();if(ee.length>0){const pe=[...g].reverse().find($=>$.info.role==="user");if(pe){const $=pe.parts.map(oe=>co(oe)).join("").trim();if($.length>0&&$===ee)return Zc.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const M=Jn(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?S(M.text||""):S("");const C=h.pendingAssistantParts.get(n),I=C?[...C.parts]:[],E=I.findIndex(ee=>ee.id===M.id);E!==-1?I[E]=M:I.push(M);const P=new Map(h.pendingAssistantParts);P.set(n,{sessionId:s,parts:I});const D=h.lastUsedProvider?.providerID||"",T=h.lastUsedProvider?.modelID||"",R=Date.now(),V=Fe.getDirectory()??"/",G=ht.getState(),O=G.getSessionAgentSelection(s)??G.getCurrentAgent(s),Y=typeof O=="string"&&O.trim().length>0?O.trim():void 0,K=h.pendingAssistantHeaderSessions.has(s);if(K){const ee=new Set(h.pendingAssistantHeaderSessions);ee.delete(s),b.pendingAssistantHeaderSessions=ee}const Q={info:f==="user"?{id:n,sessionID:s,role:"user",time:{created:R},agent:Y||"default",model:{providerID:D,modelID:T},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:s,role:"assistant",time:{created:R},parentID:n,modelID:T,providerID:D,mode:Y||"default",...K?{openchamberHeaderAnchor:!0}:{},path:{cwd:V,root:V},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:I},W=[...g,Q],se=new Map(h.messages);if(se.set(s,W),f==="assistant"){b.messageStreamStates=gi(h.messageStreamStates,n);const ee=dr(b.streamingMessageIds??h.streamingMessageIds,s,n);ee!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=ee,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:se,pendingAssistantParts:P,...b})}else{const M=g[j],C=M.parts.findIndex(T=>T.id===o.id),I=Jn(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(n,`part_type:${I.type||"unknown"}`);const E={...M};C!==-1?E.parts=E.parts.map((T,R)=>R===C?I:T):E.parts=[...E.parts,I];const P=[...g];P[j]=E;const D=new Map(h.messages);if(D.set(s,P),E.info.role==="assistant"){b.messageStreamStates=gi(h.messageStreamStates,n);const T=dr(b.streamingMessageIds??h.streamingMessageIds,s,n);T!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=T,window.__messageTracker?.(n,"streamingId_set"))}return I.type==="text"?S(I.text||""):S(""),v({messages:D,...b})}})},addStreamingPart:(s,n,o,a,l)=>{if(a!=="user"){r()._addStreamingPartImmediate(s,n,o,a,l);return}bi.push({sessionId:s,messageId:n,part:o,role:a,currentSessionId:l}),wi||(wi=setTimeout(()=>{const c=[...bi];bi=[],wi=null;const d=r();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},vb))},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(w=>w.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(w=>{if(!w)return w;if(w.type==="tool"){const k=w.state;if(!k)return w;const A=k.status,j=A==="running"||A==="pending"||A==="started",M=!k.time||typeof k.time?.end!="number";if(j||M){const C={...k};return j&&(C.status="completed"),M&&(C.time={...k.time??{},end:f}),b=!0,{...w,state:C}}return w}if(w.type==="reasoning"){const k=w.time;return!k||typeof k.end!="number"?(b=!0,{...w,time:{...k??{},end:f}}):w}if(w.type==="text"){const k=w.time;return k&&typeof k.end!="number"?(b=!0,{...w,time:{...k,end:f}}):w}return w});if(!x&&!b)return l;window.__messageTracker?.(n,`force_complete:${o}`);const v={...m,info:g,parts:b?y:m.parts},S=[...d];S[u]=v;const N=new Map(l.messages);return N.set(c,S),{messages:N}})},markMessageStreamSettled:s=>{t(n=>{af(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}:{}}}),Jr([s])},updateMessageInfo:(s,n,o)=>{t(c=>{const d=c.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!Lo(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(s)??[]],f=m.findIndex(j=>j.info.id===n),p=c.pendingAssistantParts.get(n),h=(j=[],M=[])=>{if(!M.length)return j;const C=[...j];return M.forEach(I=>{const E=C.findIndex(P=>P.id===I.id);E===-1?C.push(I):C[E]=I}),C},x=j=>{if(!j)return j;const M=j.clientRole??j.role,C=M==="user"?!0:j.userMessageMarker;return{...j,clientRole:M,...C?{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 V=m[0]?.info,G=typeof V?.time?.created=="number"?V.time.created:null,O=typeof V?.id=="string"?V.id:null,Y=o,K=typeof Y?.time?.created=="number"?Y.time.created:null,U=typeof Y?.id=="string"?Y.id:n;let Q=!1;if(K!==null&&G!==null&&(Q=K<G),!Q&&U&&O&&(Q=U.localeCompare(O)<0),Q)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const j=x(o);if(j&&j.role==="user"){const R=p?.parts??[],V=c.pendingUserMessageMetaBySession.get(s),G={info:{...j,userMessageMarker:!0,clientRole:"user",...V?.mode?{mode:V.mode}:{},...V?.providerID?{providerID:V.providerID}:{},...V?.modelID?{modelID:V.modelID}:{}},parts:R.length>0?[...R]:[]},O=new Map(c.messages),Y=[...m,G];Y.sort((Q,W)=>{const se=Q.info?.time?.created||0,ee=W.info?.time?.created||0;return se-ee}),O.set(s,Y);const K={messages:O,...V?{pendingUserMessageMetaBySession:Xc(c.pendingUserMessageMetaBySession,s)}:{}},U=Sn(K.messageSessionIndex??c.messageSessionIndex,n,s);if(U!==(K.messageSessionIndex??c.messageSessionIndex)&&(K.messageSessionIndex=U),p){const Q=new Map(c.pendingAssistantParts);Q.delete(n),K.pendingAssistantParts=Q}return K}if(!j||j.role!=="assistant")return c;const M=p?.parts??[],C=c.pendingAssistantHeaderSessions.has(s),I={info:{...j,animationSettled:j?.animationSettled??!1,...C?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},E=new Map(c.messages),P=[...m,I];E.set(s,P);const D={messages:E,...C?{pendingAssistantHeaderSessions:(()=>{const R=new Set(c.pendingAssistantHeaderSessions);return R.delete(s),R})()}:{}},T=Sn(D.messageSessionIndex??c.messageSessionIndex,n,s);if(T!==(D.messageSessionIndex??c.messageSessionIndex)&&(D.messageSessionIndex=T),p){const R=new Map(c.pendingAssistantParts);R.delete(n),D.pendingAssistantParts=R}return D}const g=m[f],b=g.info;if(b.userMessageMarker===!0||b.clientRole==="user"||b.role==="user"){const j={...g.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:b.providerID||void 0,modelID:b.modelID||void 0},M=c.pendingUserMessageMetaBySession.get(s);M&&!j.mode&&M.mode&&(j.mode=M.mode);const C={...g,info:j},I=new Map(c.messages),E=[...m];if(E[f]=C,I.set(s,E),M){const P=new Map(c.pendingUserMessageMetaBySession);return P.delete(s),{messages:I,pendingUserMessageMetaBySession:P}}return{messages:I}}const v={...g.info,...o};o.role&&o.role!==g.info.role&&(v.role=g.info.role),v.clientRole=v.clientRole??g.info.clientRole??g.info.role,v.clientRole==="user"&&(v.userMessageMarker=!0);const S=p?.parts?h(g.parts,p.parts):g.parts,N={...g,info:v,parts:S},w=new Map(c.messages),k=[...m];k[f]=N,w.set(s,k);const A={messages:w};if(p){const j=new Map(c.pendingAssistantParts);j.delete(n),A.pendingAssistantParts=j}return A});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=dr(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}}),Jr([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=jn.get(s);d&&(clearTimeout(d),jn.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}}),jn.delete(s)},2e3);jn.set(s,u)}},syncMessages:(s,n)=>{const o=td(s),a=sd(n,o),l=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,c=l?a.filter(d=>{const u=d?.info?.id;return u?Lo(u,l):!0}):a;t(d=>{const u=new Map(d.messages),m=d.messages.get(s)||[],f=new Map(m.filter(w=>typeof w.info?.id=="string").map(w=>[w.info.id,w])),p=c.map(w=>{const k={...w.info,clientRole:w.info?.clientRole??w.info.role,userMessageMarker:w.info.role==="user"?!0:w.info?.userMessageMarker,animationSettled:w.info.role==="assistant"?w.info?.animationSettled??!0:w.info?.animationSettled},A=(Array.isArray(w.parts)?w.parts:[]).map(C=>{if(C?.type==="text"){const I=C.text??C.content??"";if(hi(I))return{...C,synthetic:!0}}return C}),j=typeof k?.id=="string"?k.id:void 0,M=j?f.get(j):void 0;if(M&&M.info.role==="assistant"){const C=Array.isArray(M.parts)?M.parts:[],I=An(C),E=An(A);if(Na(M.info)&&I>E){const D=Ca(C,A);return{...w,info:k,parts:D}}}return{...w,info:k,parts:A}}),h=Oo(p),x=new Set(m.map(w=>w.info.id)),g=new Set(h.map(w=>w.info.id)),b=[];x.forEach(w=>{g.has(w)||b.push(w)}),u.set(s,h);const y={messages:u,isSyncing:!0};Jr(b);const v=Xn(d.messageStreamStates,b);if(v!==d.messageStreamStates&&(y.messageStreamStates=v),b.length>0){const w=d.streamingMessageIds.get(s);w&&b.includes(w)&&(y.streamingMessageIds=dr(y.streamingMessageIds??d.streamingMessageIds,s,null))}if(b.length>0){const w=_o(y.messageSessionIndex??d.messageSessionIndex,b);w!==(y.messageSessionIndex??d.messageSessionIndex)&&(y.messageSessionIndex=w)}if(b.length>0){const w=new Map(d.pendingAssistantParts);let k=!1;b.forEach(A=>{w.delete(A)&&(k=!0)}),k&&(y.pendingAssistantParts=w)}const S=y.messageSessionIndex??d.messageSessionIndex;let N=S;return h.forEach(w=>{const k=w?.info?.id;typeof k=="string"&&k.length>0&&(N=Sn(N,k,s))}),N!==S&&(y.messageSessionIndex=N),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??Sa().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 v=new Map(b.sessionMemoryState),S={...d,viewportAnchor:u-m,trimmedHeadMaxId:Cb(h,d.trimmedHeadMaxId)};v.set(s,S);const N={messages:y,sessionMemoryState:v};Jr(g);const w=Xn(b.messageStreamStates,g);if(w!==b.messageStreamStates&&(N.messageStreamStates=w),g.length>0){const j=b.streamingMessageIds.get(s);j&&g.includes(j)&&(N.streamingMessageIds=dr(N.streamingMessageIds??b.streamingMessageIds,s,null))}if(g.length>0){const j=_o(N.messageSessionIndex??b.messageSessionIndex,g);j!==(N.messageSessionIndex??b.messageSessionIndex)&&(N.messageSessionIndex=j)}const k=N.messageSessionIndex??b.messageSessionIndex;let A=k;return p.forEach(j=>{const M=j?.info?.id;typeof M=="string"&&M.length>0&&(A=Sn(A,M,s))}),A!==k&&(N.messageSessionIndex=A),N})},evictLeastRecentlyUsed:s=>{const n=r();if(n.messages.size<=kr.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(N=>N.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((N,w)=>{N.sessionId===c&&(x.delete(w),g=!0)}),g&&(h.pendingAssistantParts=x);const b=new Map(d.sessionCompactionUntil);b.delete(c)&&(h.sessionCompactionUntil=b),Jr(m);const y=Xn(d.messageStreamStates,m);y!==d.messageStreamStates&&(h.messageStreamStates=y);const v=_o(h.messageSessionIndex??d.messageSessionIndex,m);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const S=dr(d.streamingMessageIds,c,null);if(S!==d.streamingMessageIds&&(h.streamingMessageIds=S),d.abortControllers.has(c)){const N=new Map(d.abortControllers);N.delete(c),h.abortControllers=N}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 vi(s,()=>Fe.getSessionMessages(s));if(n==="up"&&a.length>0){const d=Oo(c),u=a[0],m=d.findIndex(f=>f.info.id===u.info.id);if(m>0){const f=Math.min(kr.VIEWPORT_MESSAGES,m),p=d.slice(m-f,m);t(h=>{const x=[...p,...a],g=Oo(x),b=Math.max(0,g.length-a.length),y=new Map(h.messages);y.set(s,g);const v=new Map(h.sessionMemoryState);return v.set(s,{...l,viewportAnchor:l.viewportAnchor+b,hasMoreAbove:m-f>0,totalAvailableMessages:d.length}),{messages:y,sessionMemoryState:v}})}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:Hs(()=>hs()),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"})),Ab=t=>typeof t=="object"&&t!==null,Eb=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},Ib=async(t,r)=>{try{const n=ft.getState().getDirectoryForSession(t);if(n)return Fe.withDirectory(n,r)}catch(s){console.warn("Failed to resolve session directory for permission handling:",s)}return r()},wo=ns()(cs(Ws((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=la(c),u=n?.getSessionAgentEditMode?.(o,c)??d;if(u==="full"||u==="allow"&&xb(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 Ib(s,()=>Fe.replyToPermission(n,o)),o==="reject"&&await Et.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:Hs(()=>hs()),partialize:t=>({permissions:Array.from(t.permissions.entries())}),merge:(t,r)=>{if(!Ab(t))return r;const s=Eb(t.permissions);return{...r,permissions:new Map(s)}}}),{name:"permission-store"})),Pb=t=>typeof t=="object"&&t!==null,Tb=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},rd=async(t,r)=>{try{const n=ft.getState().getDirectoryForSession(t);if(n)return Fe.withDirectory(n,r)}catch(s){console.warn("Failed to resolve session directory for question handling:",s)}return r()},En=ns()(cs(Ws((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 rd(s,()=>Fe.replyToQuestion(n,o)),r().dismissQuestion(s,n)},rejectQuestion:async(s,n)=>{await rd(s,()=>Fe.rejectQuestion(n)),r().dismissQuestion(s,n)}}),{name:"question-store",storage:Hs(()=>hs()),partialize:t=>({questions:Array.from(t.questions.entries())}),merge:(t,r)=>{if(!Pb(t))return r;const s=Tb(t.questions);return{...r,questions:new Map(s)}}}),{name:"question-store"})),Hl=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
- `),uo=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},nd=(t,r,s)=>{if(!r)return null;const n=s(r)?.path;if(typeof n=="string"&&n.trim().length>0)return uo(n);const o=t.find(a=>a.id===r);return o?uo(o.directory??null):null},me=ns()(cs((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)=>ht.getState().getSessionAgentEditMode(s,n,o),toggleSessionAgentEditMode:(s,n,o)=>ht.getState().toggleSessionAgentEditMode(s,n,o),setSessionAgentEditMode:(s,n,o,a)=>ht.getState().setSessionAgentEditMode(s,n,o,a),loadSessions:()=>ft.getState().loadSessions(),openNewSessionDraft:s=>{let n=null;s?.directoryOverride!==void 0?n=s.directoryOverride:n=Vt.getState().getActiveProject()?.path??null,t({newSessionDraft:{open:!0,directoryOverride:n,parentID:s?.parentID??null,title:s?.title},currentSessionId:null,error:null});try{const o=at.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=ft.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 ft.getState().createSession(s,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async s=>{if(!s)return;const n=Et.getState(),{messages:o,lastUsedProvider:a}=n;let l,c;if(o.forEach((y,v)=>{const S=y.find(N=>N.info?.id===s);S&&!l&&(l=S,c=v)}),!l||l.info.role!=="assistant")return;const d=Hl(l.parts);if(!d.trim())return;const u=ft.getState(),m=nd(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}=at.getState(),g=p||a?.providerID,b=h||a?.modelID;!g||!b||await Fe.sendMessage({id:f.id,providerID:g,modelID:b,text:d,prefaceText:of,agent:x??void 0})},deleteSession:(s,n)=>ft.getState().deleteSession(s,n),deleteSessions:(s,n)=>ft.getState().deleteSessions(s,n),updateSessionTitle:(s,n)=>ft.getState().updateSessionTitle(s,n),shareSession:s=>ft.getState().shareSession(s),unshareSession:s=>ft.getState().unshareSession(s),setCurrentSession:async s=>{s&&r().closeNewSessionDraft();const n=ft.getState().currentSessionId,o=nd(ft.getState().sessions,s,ft.getState().getWorktreeMetadata),a=Fe.getDirectory()??bt.getState().currentDirectory??null,l=o??a;try{Fe.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,Sa().VIEWPORT_MESSAGES)}if(ft.getState().setCurrentSession(s),s){r().messages.get(s)||await r().loadMessages(s),r().trimToViewportWindow(s,ol());const d=r().messages.get(s);if(d&&d.length>0){const u=at.getState().agents;if(u.length>0)try{await ht.getState().analyzeAndSaveExternalSessionChoices(s,u,r().messages)}catch(m){console.warn("Failed to analyze session choices:",m)}}}r().evictLeastRecentlyUsed()},loadMessages:(s,n)=>Et.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=v=>{t(S=>{const N=new Map(S.sessionActivityPhase??new Map);return N.set(v,"busy"),{sessionActivityPhase:N}})},h=v=>{t(S=>{const N=new Map(S.sessionActivityPhase??new Map);return N.set(v,"idle"),{sessionActivityPhase:N}})};if(m?.open){const v=await ft.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!v?.id)throw new Error("Failed to create session");const S=at.getState(),N=S.currentAgentName,w=f??N,k=S.currentProviderId,A=S.currentModelId;if(k&&A)try{ht.getState().saveSessionModelSelection(v.id,k,A)}catch{}if(w){try{ht.getState().saveSessionAgentSelection(v.id,w)}catch{}if(k&&A){try{ht.getState().saveAgentModelForSession(v.id,w,k,A)}catch{}if(u!==void 0)try{ht.getState().saveAgentModelVariantForSession(v.id,w,k,A,u)}catch{}}}try{ft.getState().initializeNewOpenChamberSession(v.id,S.agents)}catch{}r().closeNewSessionDraft(),p(v.id);try{return await Et.getState().sendMessage(s,n,o,w,v.id,l,c,d,u)}catch(j){throw h(v.id),j}}const x=ft.getState().currentSessionId,g=x?ht.getState().getSessionAgentSelection(x):null,b=at.getState().currentAgentName,y=f||g||b||void 0;if(x&&y){try{ht.getState().saveSessionAgentSelection(x,y)}catch{}if(u!==void 0)try{ht.getState().saveAgentModelVariantForSession(x,y,n,o,u)}catch{}}x&&p(x);try{return await Et.getState().sendMessage(s,n,o,y,x||void 0,l,c,d,u)}catch(v){throw x&&h(x),v}},abortCurrentOperation:()=>{const s=ft.getState().currentSessionId;return Et.getState().abortCurrentOperation(s||void 0)},armAbortPrompt:(s=3e3)=>{const n=ft.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&&Et.getState().acknowledgeSessionAbort(s)},addStreamingPart:(s,n,o,a)=>{const c=ft.getState().currentSessionId||s;return Et.getState().addStreamingPart(s,n,o,a,c)},completeStreamingMessage:(s,n)=>Et.getState().completeStreamingMessage(s,n),markMessageStreamSettled:s=>Et.getState().markMessageStreamSettled(s),updateMessageInfo:(s,n,o)=>Et.getState().updateMessageInfo(s,n,o),updateSessionCompaction:(s,n)=>Et.getState().updateSessionCompaction(s,n??null),addPermission:s=>{const n={currentAgentContext:ht.getState().currentAgentContext,sessionAgentSelections:ht.getState().sessionAgentSelections,getSessionAgentEditMode:ht.getState().getSessionAgentEditMode};return wo.getState().addPermission(s,n)},respondToPermission:(s,n,o)=>wo.getState().respondToPermission(s,n,o),addQuestion:s=>En.getState().addQuestion(s),dismissQuestion:(s,n)=>En.getState().dismissQuestion(s,n),respondToQuestion:(s,n,o)=>En.getState().respondToQuestion(s,n,o),rejectQuestion:(s,n)=>En.getState().rejectQuestion(s,n),clearError:()=>ft.getState().clearError(),getSessionsByDirectory:s=>ft.getState().getSessionsByDirectory(s),getDirectoryForSession:s=>ft.getState().getDirectoryForSession(s),getLastMessageModel:s=>Et.getState().getLastMessageModel(s),getCurrentAgent:s=>ht.getState().getCurrentAgent(s),syncMessages:(s,n)=>Et.getState().syncMessages(s,n),applySessionMetadata:(s,n)=>ft.getState().applySessionMetadata(s,n),addAttachedFile:s=>ar.getState().addAttachedFile(s),addServerFile:(s,n,o)=>ar.getState().addServerFile(s,n,o),removeAttachedFile:s=>ar.getState().removeAttachedFile(s),clearAttachedFiles:()=>ar.getState().clearAttachedFiles(),updateViewportAnchor:(s,n)=>Et.getState().updateViewportAnchor(s,n),trimToViewportWindow:(s,n)=>{const o=ft.getState().currentSessionId,a=r().sessionActivityPhase?.get(s);if(!(a==="busy"||a==="cooldown"))return Et.getState().trimToViewportWindow(s,n,o||void 0)},evictLeastRecentlyUsed:()=>{const s=ft.getState().currentSessionId;return Et.getState().evictLeastRecentlyUsed(s||void 0)},loadMoreMessages:(s,n)=>Et.getState().loadMoreMessages(s,n),saveSessionModelSelection:(s,n,o)=>ht.getState().saveSessionModelSelection(s,n,o),getSessionModelSelection:s=>ht.getState().getSessionModelSelection(s),saveSessionAgentSelection:(s,n)=>ht.getState().saveSessionAgentSelection(s,n),getSessionAgentSelection:s=>ht.getState().getSessionAgentSelection(s),saveAgentModelForSession:(s,n,o,a)=>ht.getState().saveAgentModelForSession(s,n,o,a),getAgentModelForSession:(s,n)=>ht.getState().getAgentModelForSession(s,n),saveAgentModelVariantForSession:(s,n,o,a,l)=>ht.getState().saveAgentModelVariantForSession(s,n,o,a,l),getAgentModelVariantForSession:(s,n,o,a)=>ht.getState().getAgentModelVariantForSession(s,n,o,a),analyzeAndSaveExternalSessionChoices:(s,n)=>{const o=Et.getState().messages;return ht.getState().analyzeAndSaveExternalSessionChoices(s,n,o)},isOpenChamberCreatedSession:s=>ft.getState().isOpenChamberCreatedSession(s),markSessionAsOpenChamberCreated:s=>ft.getState().markSessionAsOpenChamberCreated(s),initializeNewOpenChamberSession:(s,n)=>ft.getState().initializeNewOpenChamberSession(s,n),setWorktreeMetadata:(s,n)=>ft.getState().setWorktreeMetadata(s,n),setSessionDirectory:(s,n)=>ft.getState().setSessionDirectory(s,n),getWorktreeMetadata:s=>ft.getState().getWorktreeMetadata(s),getContextUsage:(s,n)=>{if(r().newSessionDraft?.open)return null;const o=ft.getState().currentSessionId;if(!o)return null;const a=Et.getState().messages;return ht.getState().getContextUsage(o,s,n,a)},updateSessionContextUsage:(s,n,o)=>{const a=Et.getState().messages;return ht.getState().updateSessionContextUsage(s,n,o,a)},initializeSessionContextUsage:(s,n,o)=>{const a=Et.getState().messages;return ht.getState().initializeSessionContextUsage(s,n,o,a)},debugSessionMessages:async s=>{const n=Et.getState().messages.get(s)||[],o=ft.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=Et.getState().messages;return ht.getState().pollForTokenUpdates(s,n,a,o)},updateSession:s=>ft.getState().updateSession(s),removeSessionFromStore:s=>ft.getState().removeSessionFromStore(s),revertToMessage:async(s,n)=>{const a=(Et.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 Fe.revertSession(s,n);ft.getState().updateSession(c);const d=Et.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);Et.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 bs(async()=>{const{toast:p}=await import("./vendor-.bun-BrcdMJ39.js").then(h=>h.db);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 bs(async()=>{const{toast:h}=await import("./vendor-.bun-BrcdMJ39.js").then(x=>x.db);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await Fe.unrevertSession(s);await ft.getState().updateSession(m),await r().loadMessages(s);const{toast:f}=await bs(async()=>{const{toast:p}=await import("./vendor-.bun-BrcdMJ39.js").then(h=>h.db);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 Fe.forkSession(s,n);if(!l||!l.id){const{toast:f}=await bs(async()=>{const{toast:p}=await import("./vendor-.bun-BrcdMJ39.js").then(h=>h.db);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 bs(async()=>{const{toast:p}=await import("./vendor-.bun-BrcdMJ39.js").then(h=>h.db);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 bs(async()=>{const{toast:f}=await import("./vendor-.bun-BrcdMJ39.js").then(p=>p.db);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 bs(async()=>{const{toast:d}=await import("./vendor-.bun-BrcdMJ39.js").then(u=>u.db);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"}));ft.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=me.getState().newSessionDraft?.open;me.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})});Et.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}}}}}),me.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})});ar.subscribe((t,r)=>{t.attachedFiles!==r.attachedFiles&&me.setState({attachedFiles:t.attachedFiles})});ht.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||me.setState({sessionModelSelections:t.sessionModelSelections,sessionAgentSelections:t.sessionAgentSelections,sessionAgentModelSelections:t.sessionAgentModelSelections,currentAgentContext:t.currentAgentContext,sessionContextUsage:t.sessionContextUsage,sessionAgentEditModes:t.sessionAgentEditModes})});wo.subscribe((t,r)=>{t.permissions!==r.permissions&&me.setState({permissions:t.permissions})});En.subscribe((t,r)=>{t.questions!==r.questions&&me.setState({questions:t.questions})});bt.subscribe((t,r)=>{const s=uo(t.currentDirectory??null),n=uo(r.currentDirectory??null);if(s===n)return;const o=me.getState().newSessionDraft;if(!o?.open)return;const a=uo(o.directoryOverride);a&&a!==n||me.setState(l=>({newSessionDraft:{...l.newSessionDraft,directoryOverride:s,parentID:null}}))});const Fb=me.getState().newSessionDraft?.open;me.setState({sessions:ft.getState().sessions,currentSessionId:Fb?null:ft.getState().currentSessionId,lastLoadedDirectory:ft.getState().lastLoadedDirectory,isLoading:ft.getState().isLoading,error:ft.getState().error,webUICreatedSessions:ft.getState().webUICreatedSessions,worktreeMetadata:ft.getState().worktreeMetadata,availableWorktrees:ft.getState().availableWorktrees,availableWorktreesByProject:ft.getState().availableWorktreesByProject,messages:Et.getState().messages,sessionMemoryState:Et.getState().sessionMemoryState,messageStreamStates:Et.getState().messageStreamStates,sessionCompactionUntil:Et.getState().sessionCompactionUntil,sessionAbortFlags:Et.getState().sessionAbortFlags,streamingMessageIds:Et.getState().streamingMessageIds,abortControllers:Et.getState().abortControllers,lastUsedProvider:Et.getState().lastUsedProvider,isSyncing:Et.getState().isSyncing,permissions:wo.getState().permissions,questions:En.getState().questions,attachedFiles:ar.getState().attachedFiles,sessionModelSelections:ht.getState().sessionModelSelections,sessionAgentSelections:ht.getState().sessionAgentSelections,sessionAgentModelSelections:ht.getState().sessionAgentModelSelections,currentAgentContext:ht.getState().currentAgentContext,sessionContextUsage:ht.getState().sessionContextUsage,sessionAgentEditModes:ht.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=me);const Ul=({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 M=t.current;if(!M)return;const{scrollHeight:C,clientHeight:I,scrollTop:E,scrollWidth:P,clientWidth:D,scrollLeft:T}=M,R=8;if(C>I){const V=Math.max(I-R*2,0),G=I/C*V,O=Math.max(r,Math.min(V,G)),Y=Math.max(V-O,0),K=Math.max(C-I,1),U=E/K*Y;d({length:O,offset:U})}else d({length:0,offset:0});if(!o&&P>D){const V=Math.max(D-R*2,0),G=D/P*V,O=Math.max(r,Math.min(V,G)),Y=Math.max(V-O,0),K=Math.max(P-D,1),U=T/K*Y;m({length:O,offset:U})}else m({length:0,offset:0})},[t,r,o]),y=i.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),s)},[s]),v=i.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{b(),l(!0),y()})},[y,b]);i.useEffect(()=>{const M=t.current;if(!M)return;b(),l(!0),y(),M.addEventListener("scroll",v,{passive:!0});const C=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null;C?.observe(M);const I=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return I?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",v),C?.disconnect(),I?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[t,v,y,b]);const S=(M,C)=>{const I=t.current;I&&(h.current=!0,x.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:I.scrollTop,scrollLeft:I.scrollLeft},g.current=C,l(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},N=M=>{if(!h.current)return;const C=t.current;if(!C)return;const I=g.current;if(I==="vertical"){const{pointerY:E,scrollTop:P}=x.current,D=M.clientY-E,T=C.clientHeight,R=Math.max(T-c.length,1),V=Math.max(C.scrollHeight-C.clientHeight,1),G=D/R*V;C.scrollTop=P+G}else if(I==="horizontal"){const{pointerX:E,scrollLeft:P}=x.current,D=M.clientX-E,T=C.clientWidth,R=Math.max(T-u.length,1),V=Math.max(C.scrollWidth-C.clientWidth,1),G=D/R*V;C.scrollLeft=P+G}},w=M=>{h.current&&(h.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),y())},k=c.length>0,A=u.length>0;if(!k&&!A)return null;const j=8;return e.jsxs("div",{className:F("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[k&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${j+c.offset}px`,right:`${j/2}px`},onPointerDown:M=>S(M,"vertical"),onPointerMove:N,onPointerUp:w,onPointerCancel:w}),A&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${j+u.offset}px`,bottom:`${j/2}px`},onPointerDown:M=>S(M,"horizontal"),onPointerMove:N,onPointerUp:w,onPointerCancel:w})]})},gt=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:F("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-none",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(l,{ref:h,className:F("overlay-scrollbar-target overlay-scrollbar-container overscroll-none",u?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",t),style:n,...f,children:s}),e.jsx(Ul,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});gt.displayName="ScrollableOverlay";const od="mobile-overlay-root",Rb=()=>{if(typeof document>"u")return null;let t=document.getElementById(od);return t||(t=document.createElement("div"),t.id=od,document.body.appendChild(t)),t},$s=({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=Rb()),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:F("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(Zt,{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(gt,{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 Ju.createPortal(m,d.current)},il=({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:F("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(Gp,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:F(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[g,e.jsx($s,{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:F("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:g}),e.jsx(it,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(b=>e.jsx("p",{className:"typography-micro leading-tight",children:b},b))})})]})},eo={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},lf=(t,r,s)=>{if(typeof window>"u")return;const n=document.documentElement,o=r==="mobile",a=r==="tablet";n.classList.remove("device-mobile","device-tablet","device-desktop"),n.classList.add(r==="mobile"?"device-mobile":r==="tablet"?"device-tablet":"device-desktop"),t?(n.classList.add("desktop-runtime"),n.style.setProperty("--is-mobile","0"),n.style.setProperty("--device-type","desktop"),n.style.setProperty("--font-scale","1"),n.style.setProperty("--has-coarse-pointer","0"),n.style.setProperty("--has-touch-input","0"),n.classList.remove("mobile-pointer")):(n.classList.remove("desktop-runtime"),n.style.setProperty("--is-mobile",o?"1":"0"),n.style.setProperty("--device-type",r),n.style.setProperty("--font-scale",o?"0.9":a?"0.95":"1"),n.style.setProperty("--has-coarse-pointer",s?"1":"0"),n.style.setProperty("--has-touch-input",s?"1":"0"),s?n.classList.add("mobile-pointer"):n.classList.remove("mobile-pointer"))};function ji(){const t=window.innerWidth,r=typeof window.matchMedia=="function",s=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=s?.matches??!1,a=n?.matches??!1,l=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||l>0,u=t>eo.md&&t<=eo.lg,m=t<=eo.md;let f=d&&m,p=d&&!f&&u,h=!d||t>eo.lg,x="desktop";c?(f=!1,p=!1,h=!0,x="desktop"):f?x="mobile":p?x="tablet":(h=!0,x="desktop"),lf(c,x,d);let g="xs";for(const[b,y]of Object.entries(eo))t>=y&&(g=b);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:x,screenWidth:t,breakpoint:g,hasTouchInput:d}}function Qt(){const[t,r]=i.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:ji());return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(ji())};return window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[]),i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const s=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(ji())},a=[],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;lf(s,t.deviceType,u)},[t.deviceType,t.hasTouchInput]),t}const $o=5e3,Lb=1e4,Ob=5e3,_b=1e4,$b=25,Bb=4,ad=15e3,ur=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),zb=(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},Wb=(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!!zb(t.diffStats,r.diffStats)},Hb=(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},as=ns()(cs((t,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:$o,setActiveDirectory:s=>{const{activeDirectory:n,directories:o}=r();if(n!==s)if(s&&!o.has(s)){const a=new Map(o);a.set(s,ur()),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=ur()),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(Wb(c.status,m)){d=!0;const f=new Map(r().directories),p=f.get(s)??ur(),h=Hb(p.status,m),x=new Set((p.status?.files??[]).map(v=>v.path)),g=new Set((m.files??[]).map(v=>v.path)),b=new Map(p.diffCache);for(const v of x)g.has(v)||b.delete(v);for(const v of h)b.delete(v);const y=h.size>0;f.set(s,{...p,isGitRepo:!0,status:m,diffCache:b,lastStatusFetch:Date.now(),lastStatusChange:y?Date.now():p.lastStatusChange}),t({directories:f})}else{const f=new Map(r().directories),p=f.get(s)??ur();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)??ur();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)??ur();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)??ur();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=ur();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>_b||!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)??ur(),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(v=>!o.diffCache.has(v.path)).slice(0,$b);if(c.length===0)return;let d=0;const u=[],m=()=>{const v=d;return d+=1,v<c.length?c[v]:null},f=async v=>{const S=n.getGitFileDiff(s,{path:v}),N=new Promise((k,A)=>{setTimeout(()=>A(new Error(`Timed out after ${ad}ms`)),ad)}),w=await Promise.race([S,N]);return{path:v,diff:{original:w.original??"",modified:w.modified??""}}},p=async()=>{for(;;){const v=m();if(!v)return;try{u.push(await f(v.path))}catch{}}},h=Math.min(Bb,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(v=>{b.set(v.path,{...v.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)??ur();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:$o});else{const m=Math.min(a+Ob,Lb);t({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&t({pollIntervalId:o()})},a)};t({pollIntervalId:o(),currentPollInterval:$o})},stopPolling:()=>{const{pollIntervalId:s}=r();s&&(clearTimeout(s),t({pollIntervalId:null,currentPollInterval:$o}))},refresh:async(s,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,s,n)}}),{name:"git-store"})),cf=t=>as(r=>t?r.directories.get(t)?.status??null:null),df=t=>as(r=>t?r.directories.get(t)?.branches??null:null),Ub=t=>as(r=>t?r.directories.get(t)?.log??null:null),Vb=t=>as(r=>t?r.directories.get(t)?.identity??null:null),Vl=t=>as(r=>t?r.directories.get(t)?.isGitRepo??null:null),Gb=t=>as(r=>t?r.directories.get(t)?.status?.files?.length??0:0);function es({...t}){return e.jsx(qp,{"data-slot":"dropdown-menu",...t})}function ts({...t}){return e.jsx(Kp,{"data-slot":"dropdown-menu-trigger",...t})}function ss({className:t,sideOffset:r=4,...s}){return e.jsx(Qp,{children:e.jsx(Yp,{"data-slot":"dropdown-menu-content",sideOffset:r,className:F("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 Nt({className:t,inset:r,variant:s="default",...n}){return e.jsx(sh,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":s,className:F("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 Ma({...t}){return e.jsx(Jp,{"data-slot":"dropdown-menu-radio-group",...t})}function Da({className:t,children:r,...s}){return e.jsxs(Zp,{"data-slot":"dropdown-menu-radio-item",className:F("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(eh,{children:e.jsx(Gt,{className:"size-3"})})}),r]})}function $r({className:t,inset:r,...s}){return e.jsx(Xp,{"data-slot":"dropdown-menu-label","data-inset":r,className:F("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",t),...s})}function Ds({className:t,...r}){return e.jsx(th,{"data-slot":"dropdown-menu-separator",className:F("bg-border -mx-1 my-0.5 h-px",t),...r})}const qb=rh("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 De({className:t,variant:r,size:s,asChild:n=!1,...o}){const a=n?Zu:"button";return e.jsx(a,{"data-slot":"button",className:F(qb({variant:r,size:s,className:t})),...o})}const No=nh,Qa=({className:t,...r})=>e.jsx(oh,{className:F("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}),Co=({className:t,...r})=>e.jsx(ah,{className:F("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",t),...r}),Kb={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"}]}};function Gl(t){return Kb[t]||{displayName:t.charAt(0).toUpperCase()+t.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Qb(t,r,s){const n=Gl(t);if(n.outputLanguage==="auto"){if(s?.filePath||s?.file_path||s?.sourcePath){const o=s.filePath||s.file_path||s.sourcePath,a=Tr(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 Tr(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 Yb=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function vo(t){const r=t.split(".").pop()?.toLowerCase();return Yb.includes(r||"")}function ll(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 Xb(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 ql=i.createContext(null),Fr=()=>{const t=i.useContext(ql);if(!t)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return t},uf=t=>{const r=Fr();return t(r)},Jb=()=>uf(t=>t.runtime.isDesktop),mf=()=>uf(t=>t.runtime.isVSCode),ff=({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(De,{size:"sm",variant:"ghost",className:F("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(lh,{className:"h-3 w-3"})})},Kl=Te.createContext(void 0);function Xr(){const t=Te.useContext(Kl);if(!t)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return t}function Ya(){return Te.useContext(Kl)}const Zb="Flexoki",ew="dark",tw={"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"},sw=[{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"}}],rw={name:Zb,type:ew,colors:tw,tokenColors:sw},nw="Flexoki",ow="light",aw={"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"},iw=[{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"}}],lw={name:nw,type:ow,colors:aw,tokenColors:iw},Ql="flexoki-dark",Yl="flexoki-light",cw=rw,dw=lw;function pf(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 hf(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 Xl=hf(cw,Ql,"dark"),Jl=hf(dw,Yl,"light");pf(Xl,Ql);pf(Jl,Yl);const zn={dark:Ql,light:Yl},id=[Jl,Xl];let ld=!1;function gf(){ld||(yc(zn.dark,async()=>Xl),yc(zn.light,async()=>Jl),ld=!0)}const Si=({...t})=>{const{theme:r="system"}=ch();return e.jsx(dh,{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})},cd=async t=>{try{await navigator.clipboard.writeText(t)}catch(r){console.error("Failed to copy to clipboard:",r)}},q={...Yn,success:(t,r)=>Yn.success(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),info:(t,r)=>Yn.info(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),error:(t,r)=>Yn.error(t,{...r,action:r?.action||{label:"Copy",onClick:()=>cd(String(t))}}),warning:(t,r)=>Yn.warning(t,{...r,action:r?.action||{label:"Copy",onClick:()=>cd(String(t))}})},Rs=Te.forwardRef(({className:t,...r},s)=>e.jsx(gt,{as:"textarea",ref:s,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:F("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 uw=`
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 mw(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 fw=(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
- `)},cl=({original:t,modified:r,language:s,fileName:n="file",renderSideBySide:o,wrapLines:a=!1,layout:l="fill"})=>{const{isMobile:c}=Qt(),{inputBarOffset:d,isKeyboardOpen:u}=Ce(),f=Ya()?.currentTheme?.metadata?.variant==="dark",p=Ce(K=>K.setActiveMainTab),[h,x]=Te.useState(null),[g,b]=Te.useState(""),y=Te.useRef(null),v=Te.useCallback(()=>{if(c)return"50%";const K=document.querySelector("main.flex-1");if(K){const U=K.getBoundingClientRect();return`${U.left+U.width/2}px`}return"50%"},[c]),[S,N]=Te.useState(v),w=me(K=>K.sendMessage),k=me(K=>K.currentSessionId),{currentProviderId:A,currentModelId:j,currentAgentName:M,currentVariant:C}=at(),I=ht(K=>K.getSessionAgentSelection),E=ht(K=>K.getAgentModelForSession),P=ht(K=>K.getAgentModelVariantForSession);Te.useEffect(()=>{if(c)return;const K=()=>{N(v())};return window.addEventListener("resize",K),()=>window.removeEventListener("resize",K)},[c,v]);const D=Te.useCallback(K=>{if(c&&K&&h&&K.start===K.end){const U=K.start,Q=h.start,W=h.end,se=Math.min(Q,W,U),ee=Math.max(Q,W,U);if(U<Q||U>W){x({...K,start:se,end:ee});return}}x(K),K||b("")},[c,h]);Te.useEffect(()=>{if(!h)return;const K=Q=>{const W=Q.target;if(y.current?.contains(W)||W.closest("[data-sonner-toast]")||W.closest("[data-sonner-toaster]"))return;Q.composedPath().some(pe=>pe instanceof HTMLElement?pe.hasAttribute("data-line-number")||pe.closest?.("[data-line-number]"):!1)||(x(null),b(""))},U=setTimeout(()=>{document.addEventListener("click",K)},100);return()=>{clearTimeout(U),document.removeEventListener("click",K)}},[h]);const T=Te.useCallback(async()=>{if(!h||!g.trim())return;if(!k){q.error("Select a session to send comment");return}const K=I(k)||M,U=K?E(k,K):null,Q=U?.providerId||A,W=U?.modelId||j;if(!Q||!W){q.error("Select a model to send comment");return}const se=K&&Q&&W?P(k,K,Q,W)??C:C,ee=fw(t,r,h),pe=h.start,$=h.end,oe=h.side==="deletions"?"original":"modified",_=`Comment on \`${n}\` lines ${pe}-${$} (${oe}):
77
- \`\`\`${s}
78
- ${ee}
79
- \`\`\`
80
-
81
- ${g}`;b(""),x(null),p("chat");try{await w(_,Q,W,K,void 0,void 0,void 0,se)}catch(z){console.error("Failed to send comment",z)}},[h,g,t,r,n,s,w,k,A,j,M,C,p,I,E,P]);gf();const R=Te.useRef(null),V=Te.useMemo(()=>{const K=mw(n,t,r);if(R.current?.key===K)return R.current.fileDiff;const U={name:n,contents:t,cacheKey:`old-${K}`},Q={name:n,contents:r,cacheKey:`new-${K}`},W=qi(U,Q);return R.current={key:K,fileDiff:W},W},[n,t,r,s]),G=Te.useMemo(()=>({theme:{dark:zn.dark,light:zn.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:D,unsafeCSS:uw}),[f,o,a,D]);if(typeof window>"u")return null;const Y=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:K=>{b(K.target.value);const U=K.target;U.style.height="auto";const W=20*5+8;U.style.height=`${Math.min(U.scrollHeight,W)}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:K=>{K.key==="Enter"&&(K.metaKey||K.ctrlKey)&&(K.preventDefault(),T()),K.key==="Escape"&&(K.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:[Xt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:K=>{g.trim()&&(K.preventDefault(),T())},onClick:()=>{c||T()},disabled:!g.trim(),className:F("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(Oa,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return l==="fill"?e.jsxs("div",{className:F("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(gt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,children:e.jsx(bc,{fileDiff:V,options:G,selectedLines:h})})}),h&&e.jsx("div",{className:F("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:Y})]}):e.jsxs("div",{className:F("relative","w-full"),children:[e.jsx(gt,{outerClassName:"pierre-diff-wrapper w-full",disableHorizontal:!1,fillContainer:!1,children:e.jsx(bc,{fileDiff:V,options:G,selectedLines:h})}),h&&Ju.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:F("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:Y})}),document.body)]})},pw=1100,xf=15e3,yf={"?":{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"}},hw=yf.M,ca=[{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"},bf=t=>{const r=gw(t);return yf[r]??hw},xw=t=>{const{index:r,working_dir:s}=t;return r==="A"||s==="A"||r==="?"||s==="?"},Aa=(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]})},yw=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)}),Aa(s.insertions,s.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Ot,{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($r,{className:"typography-meta text-muted-foreground",children:"View mode"}),e.jsx(Ma,{value:l,onValueChange:u=>c(u),children:ca.map(u=>e.jsx(Da,{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(Ma,{value:r??"",onValueChange:n,children:t.map(u=>e.jsx(Da,{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:Aa(u.insertions,u.deletions)})]})},u.path))})]})]})}),bw=i.memo(({mode:t,onModeChange:r})=>{const s=ca.find(n=>n.value===t)??ca[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(Ot,{className:"size-4 opacity-50"})]})}),e.jsx(ss,{className:"min-w-[220px]",children:e.jsx(Ma,{value:t,onValueChange:n=>r(n),children:ca.map(n=>e.jsx(Da,{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))})})]})}),ww=i.memo(({changedFiles:t,selectedFile:r,onSelectFile:s})=>t.length===0?null:e.jsx(gt,{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=bf(n),a=r===n.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(n.path),className:F("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}),Aa(n.insertions,n.deletions)]})},n.path)})})})),vw=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"}})]})]})})}),jw=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"}})]})]})})}),Sw=i.memo(({filePath:t,diff:r,renderSideBySide:s,wrapLines:n})=>{const o=i.useMemo(()=>Tr(t)||"text",[t]);return vo(t)?e.jsx(jw,{filePath:t,diff:r,renderSideBySide:s}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(cl,{original:r.original,modified:r.modified,language:o,fileName:t,renderSideBySide:s,wrapLines:n,layout:"inline"})})}),kw=i.memo(({filePath:t,diff:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=i.useMemo(()=>Tr(t)||"text",[t]);return vo(t)?e.jsx(vw,{filePath:t,diff:r,isVisible:s,renderSideBySide:n}):s?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(cl,{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(cl,{original:r.original,modified:r.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})})}),Nw=i.memo(({directory:t,filePath:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=as(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(kw,{filePath:r,diff:l,isVisible:s,renderSideBySide:n,wrapLines:o}):null}),Cw=i.memo(({directory:t,file:r,layout:s,wrapLines:n,scrollRootRef:o,isSelected:a,onSelect:l,registerSectionRef:c})=>{const{git:d}=Fr(),u=as(i.useCallback(D=>D.directories.get(t)?.diffCache.get(r.path)??null,[t,r.path])),m=as(D=>D.setDiff),f=Ce(D=>D.setDiffFileLayout),[p,h]=i.useState(!0),[x,g]=i.useState(!1),[b,y]=i.useState(0),[v,S]=i.useState(null),[N,w]=i.useState(!1),k=i.useRef(null),A=i.useRef(null),j=i.useMemo(()=>bf(r),[r]),M=s==="side-by-side",C=i.useMemo(()=>u?{original:u.original,modified:u.modified}:null,[u]),I=i.useCallback(D=>{A.current=D,c(r.path,D)},[r.path,c]),E=i.useCallback(D=>{h(D),D&&g(!0)},[]),P=i.useCallback(()=>{l(r.path)},[r.path,l]);return i.useEffect(()=>{if(!p||x)return;const D=A.current;if(!D)return;if(!o.current||typeof IntersectionObserver>"u"){g(!0);return}const T=new IntersectionObserver(R=>{R.some(V=>V.isIntersecting)&&(g(!0),T.disconnect())},{root:o.current,rootMargin:"200px 0px",threshold:.1});return T.observe(D),()=>T.disconnect()},[x,p,o]),i.useEffect(()=>{if(!p||!x)return;if(!t||C){k.current=null,w(!1);return}const D=`${t}::${r.path}::${b}`;if(k.current===D)return;k.current=D,S(null),w(!0);let T=!1;return(async()=>{try{const R=d.getGitFileDiff(t,{path:r.path}),V=xf,G=new Promise((Y,K)=>{setTimeout(()=>K(new Error(`Timed out after ${V}ms`)),V)}),O=await Promise.race([R,G]);if(T)return;m(t,r.path,{original:O.original??"",modified:O.modified??""}),w(!1)}catch(R){if(T)return;const V=R instanceof Error?R.message:String(R);S(V),w(!1)}})(),()=>{T=!0,k.current===D&&(k.current=null)}},[t,C,b,r.path,d,x,p,m]),e.jsx("div",{ref:I,className:"scroll-mt-4",children:e.jsxs(No,{open:p,onOpenChange:E,className:"group/collapsible",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background",children:e.jsxs(Qa,{onClick:P,className:F("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:F("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(Ot,{className:"size-4"}):e.jsx(Bs,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:j.color},title:j.description,"aria-label":j.description,children:j.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:[Aa(r.insertions,r.deletions),e.jsx(ff,{mode:M?"side-by-side":"unified",onModeChange:D=>{const T=D==="side-by-side"?"side-by-side":"inline";f(r.path,T)},className:"opacity-70"})]})]})}),e.jsx(Co,{children:e.jsxs("div",{className:"relative border border-t-0 border-border/60 bg-background rounded-b-xl overflow-hidden",children:[v?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:v}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>y(D=>D+1),children:"Retry"})]}):null,N&&!C&&!v?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(Jt,{size:16,className:"animate-spin"}),"Loading diff…"]}):null,C?e.jsx(Sw,{filePath:r.path,diff:C,renderSideBySide:M,wrapLines:n}):null]})})]})})}),Mw=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=me(),{currentDirectory:n}=bt(),o=t?s.get(t)??void 0:void 0,l=r.find(c=>c.id===t)?.directory;return o?.path??l??n??void 0},Dw=()=>{const{git:t}=Fr(),r=Mw(),{screenWidth:s,isMobile:n}=Qt(),o=Vl(r??null),a=cf(r??null),l=as(H=>H.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=as(),[m,f]=i.useState(null),[p,h]=i.useState(0),[x,g]=i.useState(null),b=i.useRef(null),y=Ce(H=>H.pendingDiffFile),v=Ce(H=>H.setPendingDiffFile),S=Ce(H=>H.diffLayoutPreference),N=Ce(H=>H.diffFileLayout),w=Ce(H=>H.setDiffFileLayout),k=Ce(H=>H.diffWrapLines),A=Ce(H=>H.setDiffWrapLines),j=Ce(H=>H.diffViewMode),M=Ce(H=>H.setDiffViewMode),C=n||k,I=j==="stacked",E=n||s<=768,P=!E&&s>=1024,D=i.useRef(null),T=i.useRef(new Map),R=i.useRef(null),V=i.useMemo(()=>{if(!a?.files)return[];const H=a.diffStats??{};return a.files.map(fe=>({...fe,insertions:H[fe.path]?.insertions??0,deletions:H[fe.path]?.deletions??0,isNew:xw(fe)})).sort((fe,we)=>fe.path.localeCompare(we.path))},[a]),G=i.useMemo(()=>m?V.find(H=>H.path===m)??null:null,[V,m]),O=i.useCallback(H=>{const fe=N[H.path];if(fe)return fe;if(S==="inline")return"inline";if(S==="side-by-side")return"side-by-side";const we=s<pw;return H.isNew||we?"inline":"side-by-side"},[N,S,s]),Y=i.useMemo(()=>G?O(G):null,[O,G]);i.useEffect(()=>{r&&(c(r),as.getState().directories.get(r)?.status||d(r,t))},[r,c,d,t]),i.useEffect(()=>{y&&(f(y),v(null),I&&(R.current=y))},[I,y,v]),i.useEffect(()=>{!m&&!y&&V.length>0&&f(V[0].path)},[V,m,y]),i.useEffect(()=>{if(!I){R.current=null;return}const H=R.current;if(!H)return;const fe=T.current.get(H);fe&&(fe.scrollIntoView({behavior:"smooth",block:"start"}),R.current=null)},[V,I]),i.useEffect(()=>{m&&V.length>0&&(V.some(fe=>fe.path===m)||f(V[0]?.path??null))},[V,m]);const K=i.useCallback((H,fe)=>{const we=T.current;fe?we.set(H,fe):we.delete(H)},[]),U=i.useCallback((H,fe="smooth")=>{const we=T.current.get(H);return we?(we.scrollIntoView({behavior:fe,block:"start"}),!0):!1},[]),Q=i.useCallback(H=>{f(H)},[]),W=i.useCallback(H=>{f(H),I&&!U(H)&&(R.current=H)},[I,U]),se=i.useCallback(H=>{M(H),H==="stacked"&&m&&!U(m,"auto")&&(R.current=m)},[U,m,M]),ee=i.useCallback(H=>{const fe=H==="side-by-side"?"side-by-side":"inline";if(I){V.forEach(we=>{w(we.path,fe)});return}G&&w(G.path,fe)},[V,I,G,w]),pe=(Y??"side-by-side")==="side-by-side",$=!I||!P,oe=as(i.useCallback(H=>!r||!m?null:H.directories.get(r)?.diffCache.get(m)??null,[r,m])),_=!!oe,z=!I&&!!m&&!_;i.useEffect(()=>{if(I)return;if(g(null),!r||!m){b.current=null;return}if(oe){b.current=null;return}const H=`${r}::${m}::${p}`;if(b.current===H)return;b.current=H;let fe=!1;return(async()=>{try{const we=t.getGitFileDiff(r,{path:m}),he=xf,_e=new Promise((J,ne)=>{setTimeout(()=>ne(new Error(`Timed out after ${he}ms`)),he)}),te=await Promise.race([we,_e]);if(fe)return;u(r,m,{original:te.original??"",modified:te.modified??""})}catch(we){if(fe)return;const he=we instanceof Error?we.message:String(we);g(he)}})(),()=>{fe=!0,b.current===H&&(b.current=null)}},[r,I,m,oe,t,u,p]);const X=()=>!r||V.length===0?null:V.map(H=>e.jsx(Nw,{directory:r,filePath:H.path,isVisible:H.path===m,renderSideBySide:pe,wrapLines:C},H.path)),re=()=>r?e.jsxs("div",{className:"flex flex-1 min-h-0 gap-3 px-3 pb-3 pt-2",children:[P&&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:V.length})]}),e.jsx(ww,{changedFiles:V,selectedFile:m,onSelectFile:W})]}),e.jsx(gt,{ref:D,outerClassName:"flex-1 min-h-0",className:"pr-2",children:e.jsx("div",{className:"flex flex-col gap-3",children:V.map(H=>e.jsx(Cw,{directory:r,file:H,layout:O(H),wrapLines:C,scrollRootRef:D,isSelected:H.path===m,onSelect:Q,registerSectionRef:K},H.path))})})]}):null,ge=()=>r?l&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Jt,{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."}):V.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"}):I?re():e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[X(),z&&!_&&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(H=>H+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Jt,{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(Nl,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:l&&!a?"Loading changes…":`${V.length} ${V.length===1?"file":"files"} changed`})]}),!E&&e.jsx(bw,{mode:j,onModeChange:se}),$&&e.jsx(yw,{changedFiles:V,selectedFile:m,selectedFileEntry:G,onSelectFile:W,isMobile:E,showModeSelector:E,mode:j,onModeChange:se}),e.jsx("div",{className:"flex-1"}),G&&e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>A(!k),className:F("h-5 w-5 p-0 transition-opacity",C?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:C?"Disable line wrap":"Enable line wrap",children:e.jsx(em,{className:"size-4"})}),G&&Y&&e.jsx(ff,{mode:Y==="side-by-side"?"side-by-side":"unified",onModeChange:ee})]}),ge()]})},Aw=()=>{const{git:t}=Fr(),{currentSessionId:r,sessions:s,worktreeMetadata:n}=me(),{currentDirectory:o}=bt(),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}=as(),f=Gb(d??null);return i.useEffect(()=>{d&&(u(d),as.getState().directories.get(d)?.status||m(d,t))},[d,u,m,t]),f},mo=Te.forwardRef(({className:t,...r},s)=>e.jsx(tm,{className:F("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(uh,{className:F("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"}})}));mo.displayName=tm.displayName;const Ew={},da=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},dd=t=>da(t)??"__global__",Iw=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}},no=ns()(cs((t,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:s=>{const n=dd(s??bt.getState().currentDirectory);return r().byDirectory[n]??Ew},refresh:async s=>{const n=da(s?.directory??bt.getState().currentDirectory),o=dd(n);s?.silent||t(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const c=(await Fe.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=da(n??bt.getState().currentDirectory);await Fe.getApiClient().mcp.connect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(s,n)=>{const o=da(n??bt.getState().currentDirectory);await Fe.getApiClient().mcp.disconnect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function Pw(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 Tw=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}},Fw=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},dl=({headerIconButtonClass:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(!1),{isMobile:l}=Qt(),d=bt(j=>j.currentDirectory)??null,u=no(j=>j.getStatusForDirectory(d)),m=no(j=>j.refresh),f=no(j=>j.connect),p=no(j=>j.disconnect),h=i.useCallback(j=>{j||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),s(j)},[]),x=i.useCallback(j=>{a.current||o(j)},[]),[g,b]=i.useState(!1),[y,v]=i.useState(null);i.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),i.useEffect(()=>{r&&m({directory:d,silent:!0})},[r,m,d]);const S=i.useMemo(()=>Iw(u),[u]),N=i.useMemo(()=>Object.keys(u).sort((j,M)=>j.localeCompare(M)),[u]),w=i.useCallback(j=>{if(j?.preventDefault(),g)return;b(!0);const M=new Promise(C=>setTimeout(C,500));Promise.all([m({directory:d}),M]).finally(()=>{b(!1)})},[g,m,d]),k=()=>e.jsxs(e.Fragment,{children:[N.map(j=>{const M=u[j],C=Fw(M),I=M?.status==="connected",E=y===j,P=Tw(M);return e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-muted/50",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l?e.jsx("span",{className:F("h-2 w-2 rounded-full flex-shrink-0",C==="success"&&"bg-status-success",C==="error"&&"bg-status-error",C==="warning"&&"bg-status-warning",C==="default"&&"bg-muted-foreground/40"),"aria-label":P}):e.jsxs(lt,{delayDuration:300,children:[e.jsx(ct,{asChild:!0,children:e.jsx("span",{className:F("h-2 w-2 rounded-full flex-shrink-0",C==="success"&&"bg-status-success",C==="error"&&"bg-status-error",C==="warning"&&"bg-status-warning",C==="default"&&"bg-muted-foreground/40"),"aria-label":P})}),e.jsx(it,{side:"left",children:e.jsx("p",{children:P})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:j})]})}),e.jsx(mo,{checked:I,disabled:E,className:"data-[state=checked]:bg-status-info",onCheckedChange:async D=>{v(j);try{D?await f(j,d):await p(j,d)}finally{v(null)}}})]},j)}),N.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."})]}),A=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:F(t,"relative"),onClick:l?()=>s(!0):void 0,children:[e.jsx(Pw,{className:"h-[1.0625rem] w-[1.0625rem]"}),S.total>0&&e.jsx("span",{className:F("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:[A,e.jsxs($s,{open:r,title:"MCP Servers",onClose:()=>s(!1),renderHeader:j=>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:w,"aria-label":"Refresh",children:e.jsx(Wr,{className:F("h-4 w-4",g&&"animate-spin")})}),j]})]}),children:[e.jsx("div",{className:"py-1",children:k()}),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(lt,{delayDuration:1e3,open:r?!1:n,onOpenChange:x,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:A})}),e.jsx(it,{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:w,"aria-label":"Refresh",children:e.jsx(Wr,{className:F("h-4 w-4",g&&"animate-spin")})})]}),e.jsx(Ds,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:k()}),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})})]})]})]})},ud=()=>{const t=Ce(O=>O.setSessionSwitcherOpen),r=Ce(O=>O.toggleSidebar),s=Ce(O=>O.setSettingsDialogOpen),n=Ce(O=>O.toggleCommandPalette),o=Ce(O=>O.toggleHelpDialog),a=Ce(O=>O.activeMainTab),l=Ce(O=>O.setActiveMainTab),{getCurrentModel:c}=at(),d=me(O=>O.getContextUsage),{isMobile:u}=Qt(),m=Aw(),f=Ha(O=>O.available),p=i.useRef(null),[h,x]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),g=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Te.useEffect(()=>{if(typeof window>"u")return;const O=typeof window.opencodeDesktop<"u";x(O)},[]);const b=c(),y=b&&typeof b.limit=="object"&&b.limit!==null?b.limit:null,v=y&&typeof y.context=="number"?y.context:0,S=y&&typeof y.output=="number"?y.output:0,N=d(v,S),w=Ce(O=>O.isSessionSwitcherOpen),k=i.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const Y=O.tagName;(Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||O.isContentEditable)&&O.blur()},[]),A=i.useCallback(()=>{if(u){k(),t(!w);return}r()},[k,u,w,t,r]),j=i.useCallback(()=>{u&&k(),t(!1),s(!0)},[k,u,t,s]),M="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",C=i.useMemo(()=>h&&g?"pl-[5.75rem]":"pl-3",[h,g]),I=i.useCallback(()=>{if(typeof document>"u")return;const O=p.current?.getBoundingClientRect().height;O&&document.documentElement.style.setProperty("--oc-header-height",`${O}px`)},[]);Te.useEffect(()=>{if(typeof window>"u")return;I();const O=p.current;if(!O||typeof ResizeObserver>"u")return()=>{};const Y=new ResizeObserver(()=>{I()});return Y.observe(O),window.addEventListener("resize",I),window.addEventListener("orientationchange",I),()=>{Y.disconnect(),window.removeEventListener("resize",I),window.removeEventListener("orientationchange",I)}},[I]),Te.useEffect(()=>{I()},[I,u]);const E=i.useCallback(async O=>{if(!O.target.closest("button, a, input, select, textarea")&&O.button===0&&h)try{const{getCurrentWindow:Y}=await bs(async()=>{const{getCurrentWindow:U}=await import("./vendor-.bun-BrcdMJ39.js").then(Q=>Q.dd);return{getCurrentWindow:U}},__vite__mapDeps([0,1]));await Y().startDragging()}catch(Y){console.error("Failed to start window dragging:",Y)}},[h]),P=i.useCallback(async O=>{if(O.button===0&&h)try{const{getCurrentWindow:Y}=await bs(async()=>{const{getCurrentWindow:U}=await import("./vendor-.bun-BrcdMJ39.js").then(Q=>Q.dd);return{getCurrentWindow:U}},__vite__mapDeps([0,1]));await Y().startDragging()}catch(Y){console.error("Failed to start window dragging:",Y)}},[h]),D=i.useMemo(()=>[{id:"chat",label:"Chat",icon:mh},{id:"diff",label:"Diff",icon:Qs,badge:!u&&m>0?m:void 0},{id:"files",label:"Files",icon:sr},{id:"terminal",label:"Terminal",icon:Vr},{id:"git",label:"Git",icon:Ht,showDot:u&&m>0}],[m,u]);Te.useEffect(()=>{const O=Y=>{if(Ts(Y)&&!Y.shiftKey&&!Y.altKey){const K=parseInt(Y.key,10);K>=1&&K<=D.length&&(Y.preventDefault(),l(D[K-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[D,l]);const T=O=>{const Y=a===O.id,K=O.icon,U=O.id==="chat";return e.jsxs("button",{type:"button",onClick:()=>l(O.id),onMouseDown:Y?P:void 0,className:F("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",Y?"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",U&&!u&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":Y,role:"tab",children:[u?e.jsx(K,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(K,{size:16}),e.jsx("span",{className:"header-tab-label",children:O.label})]}),U&&!u&&N&&N.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(il,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact"})}),O.badge!==void 0&&O.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:O.badge})]},O.id)},R=()=>e.jsxs("div",{onMouseDown:E,className:F("app-region-drag relative flex h-12 select-none items-center",C),role:"tablist","aria-label":"Main navigation",children:[e.jsx("button",{type:"button",onClick:A,"aria-label":"Open sessions",className:`${M} mr-2`,children:e.jsx(Ml,{className:"h-5 w-5"})}),e.jsx("div",{className:"flex items-center gap-1 p-1 bg-background/50 rounded-lg",children:D.map(O=>T(O))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:M,children:e.jsx(gn,{className:"h-5 w-5"})})}),e.jsx(it,{children:e.jsxs("p",{children:["Command Palette (",Xt(),"+K)"]})})]}),e.jsx(dl,{headerIconButtonClass:M}),e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:M,children:e.jsx(mn,{className:"h-5 w-5"})})}),e.jsx(it,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Xt(),"+.)"]})})]})]})]}),V=()=>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:[w?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(Cl,{className:"h-5 w-5"})}):e.jsx("button",{onClick:A,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(fh,{className:"h-5 w-5"})}),!w&&N&&N.totalTokens>0&&a==="chat"&&e.jsx(il,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact",isMobile:!0}),w&&e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),!w&&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:D.map(O=>{const Y=a===O.id,K=O.icon;return e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{u&&k(),l(O.id)},"aria-label":O.label,"aria-selected":Y,role:"tab",className:F(M,"relative",Y&&"text-foreground bg-secondary"),children:[e.jsx(K,{className:"h-5 w-5"}),O.badge!==void 0&&O.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.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(it,{children:e.jsx("p",{children:O.label})})]},O.id)})}),e.jsx(dl,{headerIconButtonClass:M}),e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:j,"aria-label":"Open settings",className:F(M,"relative"),children:[e.jsx(un,{className:"h-5 w-5"}),f&&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(it,{children:e.jsx("p",{children:f?"Settings (Update available)":"Settings"})})]})]})]}),G=F("header-safe-area border-b border-border/50 relative z-10",h?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:p,className:G,style:{"--padding-scale":"1"},children:u?V():R()})};function Zl({className:t,...r}){return e.jsx("div",{"data-slot":"card",className:F("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",t),...r})}function wf({className:t,...r}){return e.jsx("div",{"data-slot":"card-header",className:F("@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 vf({className:t,...r}){return e.jsx("div",{"data-slot":"card-title",className:F("leading-none font-semibold",t),...r})}function jf({className:t,...r}){return e.jsx("div",{"data-slot":"card-content",className:F("px-6",t),...r})}class fs 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(Zl,{className:"w-full max-w-md",children:[e.jsx(wf,{className:"text-center",children:e.jsxs(vf,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Ki,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(jf,{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(De,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let Bo=0;function xs({...t}){return e.jsx(ph,{"data-slot":"dialog",...t})}function Rw({...t}){return e.jsx(xh,{"data-slot":"dialog-portal",...t})}const Sf=Te.forwardRef(({className:t,...r},s)=>(Te.useEffect(()=>(Bo+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Bo=Math.max(0,Bo-1),Bo===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(sm,{ref:s,"data-slot":"dialog-overlay",className:F("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",t),...r})));Sf.displayName=sm.displayName;function ys({className:t,children:r,showCloseButton:s=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Rw,{"data-slot":"dialog-portal",children:[e.jsx(Sf,{className:"rounded-none"}),e.jsxs(hh,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:F("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(gh,{"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(Zt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function vs({className:t,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:F("flex flex-col gap-2 text-center sm:text-left",t),...r})}function zs({className:t,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:F("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",t),...r})}function js({className:t,...r}){return e.jsx(yh,{"data-slot":"dialog-title",className:F("typography-markdown leading-none font-semibold text-foreground",t),...r})}function Ns({className:t,...r}){return e.jsx(bh,{"data-slot":"dialog-description",className:F("text-muted-foreground typography-ui-label",t),...r})}const md="https://github.com/btriapitsyn/openchamber/releases";async function Lw(){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 Ow(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 ul=({open:t,onOpenChange:r,info:s,downloading:n,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Te.useState(!1),[p,h]=Te.useState("idle"),[x,g]=Te.useState(null),b=s?.version?`${md}/tag/v${s.version}`:md,y=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",S=s?.updateCommand||"openchamber update";Te.useEffect(()=>{t||(h("idle"),g(null))},[t]);const N=async()=>{try{await navigator.clipboard.writeText(S),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},w=Te.useCallback(async()=>{h("updating"),g(null);const A=await Lw();if(!A.success){h("error"),g(A.error||"Update failed");return}h("restarting"),await new Promise(M=>setTimeout(M,2e3)),h("reconnecting"),await Ow()?window.location.reload():(h("error"),g("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),k=p!=="idle"&&p!=="error";return e.jsx(xs,{open:t,onOpenChange:k?void 0:r,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(vs,{children:e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(wh,{className:"h-5 w-5 text-primary"}),p==="restarting"||p==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(s?.currentVersion||s?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s?.currentVersion&&e.jsx("span",{className:"font-mono",children:s.currentVersion}),s?.currentVersion&&s?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),s?.version&&e.jsx("span",{className:"font-mono text-primary",children:s.version})]}),v&&k&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zo,{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&&!k&&e.jsx(gt,{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((A,j)=>/^\d+\.\d+\.\d+$/.test(A.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",A.trim(),`
82
- `]},j):A.replace(/^- /gm,"• ").trim()+`
83
-
84
- `)})}),v&&p==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(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:N,className:F("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(Gt,{className:"h-4 w-4"}):e.jsx(rm,{className:"h-4 w-4"})})]})]}),!v&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[y,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${y}%`}})})]}),(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:F("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(ga,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!n&&e.jsxs("button",{onClick:c,className:F("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(Hr,{className:"h-4 w-4"}),"Download Update"]}),!v&&n&&e.jsxs("button",{disabled:!0,className:F("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(Zo,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&o&&e.jsxs("button",{onClick:d,className:F("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(Is,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!k&&e.jsxs("button",{onClick:w,className:F("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(Hr,{className:"h-4 w-4"}),"Update Now"]}),v&&k&&e.jsxs("button",{disabled:!0,className:F("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(Zo,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},fd=264,pd=200,hd=500,gd="openchamber:check-for-updates",_w=({isOpen:t,isMobile:r,children:s})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:l}=Ce(),[c,d]=i.useState(!1),u=i.useRef(0),m=i.useRef(n||fd),[f,p]=i.useState(!1),h=Ha(),x=i.useRef(!1),g=h.checkForUpdates,{available:b,downloaded:y,checking:v}=h,[S,N]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");if(i.useEffect(()=>{if(typeof window>"u")return;const A=typeof window.opencodeDesktop<"u";N(A)},[]),i.useEffect(()=>{if(typeof window>"u")return;const A=()=>{typeof window.opencodeDesktop<"u"&&(x.current=!0,g())};return window.addEventListener(gd,A),()=>{window.removeEventListener(gd,A)}},[g]),i.useEffect(()=>{x.current&&(v||(b||y?p(!0):q.success("No updates available",{description:"You are running the latest version."}),x.current=!1))},[b,y,v]),i.useEffect(()=>{if(r||!c)return;const A=M=>{const C=M.clientX-u.current,I=Math.min(hd,Math.max(pd,m.current+C));o(I)},j=()=>{d(!1)};return window.addEventListener("pointermove",A),window.addEventListener("pointerup",j,{once:!0}),()=>{window.removeEventListener("pointermove",A),window.removeEventListener("pointerup",j)}},[r,c,o]),i.useEffect(()=>{r&&c&&d(!1)},[r,c]),r)return null;const w=t?Math.min(hd,Math.max(pd,n||fd)):0,k=A=>{t&&(d(!0),u.current=A.clientX,m.current=w,A.preventDefault())};return e.jsxs("aside",{className:F("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:`${w}px`,minWidth:`${w}px`,maxWidth:`${w}px`,overflowX:"clip"},"aria-hidden":!t||w===0,children:[t&&e.jsx("div",{className:F("absolute right-0 top-0 z-20 h-full w-[4px] cursor-col-resize hover:bg-primary/50 transition-colors",c&&"bg-primary"),onPointerDown:k,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:F("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:`${w}px`,overflowX:"hidden"},"aria-hidden":!t,children:[e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(fs,{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:F("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(un,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),b||y?e.jsxs("button",{onClick:()=>p(!0),className:F("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(Hr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!S&&e.jsxs(lt,{children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{onClick:()=>l(!0),className:F("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(ps,{className:"h-4 w-4"})})}),e.jsx(it,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(ul,{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 ec({className:t,...r}){return e.jsx(xn,{"data-slot":"command",className:F("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",t),...r})}function $w({title:t="Command Palette",description:r="Search for a command to run...",children:s,className:n,showCloseButton:o=!0,...a}){return e.jsxs(xs,{...a,children:[e.jsxs(vs,{className:"sr-only",children:[e.jsx(js,{children:t}),e.jsx(Ns,{children:r})]}),e.jsx(ys,{className:F("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(ec,{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 tc({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(lr,{className:"size-4 shrink-0 opacity-50"}),e.jsx(xn.Input,{"data-slot":"command-input",className:F("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 sc({className:t,children:r,scrollbarClassName:s,disableHorizontal:n,...o}){return e.jsx(gt,{as:xn.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:F("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 rc({...t}){return e.jsx(xn.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...t})}function ln({className:t,...r}){return e.jsx(xn.Group,{"data-slot":"command-group",className:F("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 Ea({className:t,...r}){return e.jsx(xn.Separator,{"data-slot":"command-separator",className:F("bg-border -mx-1 h-px",t),...r})}function gs({className:t,...r}){return e.jsx(xn.Item,{"data-slot":"command-item",className:F("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 Sr({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(gn,{className:"size-3.5"}):l==="shift"||l==="⇧"?e.jsx(So,{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:F("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",t),...r,children:o.length>0?o.map((a,l)=>e.jsxs(Te.Fragment,{children:[l>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),s(a)]},`${a}-${l}`)):r.children})}const xd=["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"],yd=["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 Bw(){const t=xd[Math.floor(Math.random()*xd.length)],r=yd[Math.floor(Math.random()*yd.length)];return`${t}-${r}`}function bd(t){const r=Bw();return t&&t.trim()?`${t.trim().replace(/\/+$/,"")}/${r}`:r}async function zw(t,r,s=10){let n;try{const o=await qa(t);n=new Set(o?.all??[])}catch{return bd(r)}for(let o=0;o<s;o++){const a=bd(r);if(!n.has(a))return a}return null}const kf=t=>t.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let Fn=!1;async function Xa(){if(Fn)return null;const t=Vt.getState().getActiveProject();if(!t?.path)return q.error("No active project",{description:"Please select a project first."}),null;const r=t.path;let s=!1;try{s=await Yr(r)}catch{}if(!s)return q.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Fn=!0,Ks("Creating new worktree session...");try{const n=t.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,l=await zw(r,o);if(!l)return q.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const c=kf(l),u=await Bl({projectDirectory:r,worktreeSlug:c,branch:l,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await Ka(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=me.getState(),h=await p.createSession(void 0,u.path);if(!h)return await Zm({projectDirectory:r,path:u.path,force:!0}).catch(()=>{}),q.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const x=at.getState(),g=x.agents;p.initializeNewOpenChamberSession(h.id,g),p.setSessionDirectory(h.id,u.path),p.setWorktreeMetadata(h.id,f);try{const v=x.getVisibleAgents();let S;if(x.settingsDefaultAgent){const N=v.find(w=>w.name===x.settingsDefaultAgent);N&&(S=N.name)}if(S||(S=v.find(N=>N.name==="build")?.name||v[0]?.name),S){x.setAgent(S),ht.getState().saveSessionAgentSelection(h.id,S);const N=x.settingsDefaultModel;if(N){const w=N.split("/");if(w.length===2){const[k,A]=w;if(x.getModelMetadata(k,A)){ht.getState().saveSessionModelSelection(h.id,k,A),ht.getState().saveAgentModelForSession(h.id,S,k,A);const M=x.settingsDefaultVariant;if(M){const E=x.providers.find(P=>P.id===k)?.models.find(P=>P.id===A)?.variants;E&&Object.prototype.hasOwnProperty.call(E,M)&&(x.setCurrentVariant(M),ht.getState().saveAgentModelVariantForSession(h.id,S,k,A,M))}}}}}}catch{}bt.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const y=(await Qn(r)).filter(v=>v.trim().length>0);return y.length>0?(q.success("Worktree created",{description:`Branch: ${l}. Running ${y.length} setup command${y.length===1?"":"s"}...`}),zl(u.path,r,y).then(v=>{if(v.success)q.success("Setup commands completed",{description:`All ${v.results.length} command${v.results.length===1?"":"s"} succeeded.`});else{const S=v.results.filter(w=>!w.success),N=v.results.filter(w=>w.success);q.error("Setup commands failed",{description:`${S.length} of ${v.results.length} command${v.results.length===1?"":"s"} failed.`+(N.length>0?` ${N.length} succeeded.`:"")})}}).catch(()=>{q.error("Setup commands failed",{description:"Could not execute setup commands."})})):q.success("Worktree created",{description:`Branch: ${l}`}),h}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return q.error("Failed to create worktree",{description:o}),null}finally{Fs(),Fn=!1}}async function Ww(t,r){if(Fn)return null;let s=!1;try{s=await Yr(t)}catch{}if(!s)return q.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Fn=!0,Ks("Creating worktree session...");try{const n=kf(r),o=await Bl({projectDirectory:t,worktreeSlug:n,branch:r,createBranch:!1}),a=await Ka(o.path).catch(()=>{}),l=a?{...o,status:a}:o,c=me.getState(),d=await c.createSession(void 0,o.path);if(!d)return await Zm({projectDirectory:t,path:o.path,force:!0}).catch(()=>{}),q.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const u=at.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),ht.getState().saveSessionAgentSelection(d.id,x);const g=u.settingsDefaultModel;if(g){const b=g.split("/");if(b.length===2){const[y,v]=b;if(u.getModelMetadata(y,v)){ht.getState().saveSessionModelSelection(d.id,y,v),ht.getState().saveAgentModelForSession(d.id,x,y,v);const N=u.settingsDefaultVariant;if(N){const A=u.providers.find(j=>j.id===y)?.models.find(j=>j.id===v)?.variants;A&&Object.prototype.hasOwnProperty.call(A,N)&&(u.setCurrentVariant(N),ht.getState().saveAgentModelVariantForSession(d.id,x,y,v,N))}}}}}}catch{}bt.getState().setDirectory(o.path,{showOverlay:!1});try{await c.loadSessions()}catch{}const p=(await Qn(t)).filter(h=>h.trim().length>0);return p.length>0?(q.success("Worktree created",{description:`Branch: ${r}. Running ${p.length} setup command${p.length===1?"":"s"}...`}),zl(o.path,t,p).then(h=>{if(h.success)q.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);q.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(()=>{q.error("Setup commands failed",{description:"Could not execute setup commands."})})):q.success("Worktree created",{description:`Branch: ${r}`}),d}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return q.error("Failed to create worktree",{description:o}),null}finally{Fs(),Fn=!1}}const Hw=()=>{const{isCommandPaletteOpen:t,setCommandPaletteOpen:r,setHelpDialogOpen:s,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:l,toggleSidebar:c}=Ce(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=me(),f=at(T=>T.settingsAutoCreateWorktree),{currentDirectory:p}=bt(),{themeMode:h,setThemeMode:x}=Xr(),g=()=>{r(!1)},b=async()=>{n("chat"),a(!1),d(),g()},y=T=>{u(T),g()},v=T=>{x(T),g()},S=()=>{s(!0),g()},N=()=>{g(),Xa()},{isMobile:w}=Qt(),k=()=>{if(w){const{isSessionSwitcherOpen:T}=Ce.getState();a(!T)}else c();g()},A=()=>{n("diff"),g()},j=()=>{n("git"),g()},M=()=>{n("terminal"),g()},C=()=>{o(!0),g()},I=()=>{lo(),g()},E=()=>{l(!0),g()},P=m(p??""),D=i.useMemo(()=>P.slice(0,5),[P]);return e.jsxs($w,{open:t,onOpenChange:r,children:[e.jsx(tc,{placeholder:"Type a command or search..."}),e.jsxs(sc,{children:[e.jsx(rc,{children:"No results found."}),e.jsxs(ln,{heading:"Actions",children:[e.jsxs(gs,{onSelect:k,children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(Sr,{children:[Xt()," + L"]})]}),e.jsxs(gs,{onSelect:b,children:[e.jsx(is,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Sr,{children:f?`Shift + ${Xt()} + N`:`${Xt()} + N`})]}),e.jsxs(gs,{onSelect:N,children:[e.jsx(Ht,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Sr,{children:f?`${Xt()} + N`:`Shift + ${Xt()} + N`})]}),e.jsxs(gs,{onSelect:S,children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(Sr,{children:[Xt()," + ."]})]}),e.jsxs(gs,{onSelect:A,children:[e.jsx(Qs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(Sr,{children:[Xt()," + 2"]})]}),e.jsxs(gs,{onSelect:M,children:[e.jsx(Vr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(Sr,{children:[Xt()," + 3"]})]}),e.jsxs(gs,{onSelect:j,children:[e.jsx(Ht,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(Sr,{children:[Xt()," + 4"]})]}),e.jsxs(gs,{onSelect:E,children:[e.jsx(br,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(Sr,{children:[Xt()," + T"]})]}),e.jsxs(gs,{onSelect:C,children:[e.jsx(un,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(Sr,{children:[Xt()," + ,"]})]}),e.jsxs(gs,{onSelect:I,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Ea,{}),e.jsxs(ln,{heading:"Theme",children:[e.jsxs(gs,{onSelect:()=>v("light"),children:[e.jsx(jh,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx(Gt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(gs,{onSelect:()=>v("dark"),children:[e.jsx(Sh,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx(Gt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(gs,{onSelect:()=>v("system"),children:[e.jsx(nm,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx(Gt,{className:"ml-auto h-4 w-4"})]})]}),D.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ea,{}),e.jsx(ln,{heading:"Recent Sessions",children:D.map(T=>e.jsxs(gs,{onSelect:()=>y(T.id),children:[e.jsx(Dl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:T.title||"Untitled Session"})]},T.id))})]})]})]})},Uw=(t,r)=>{const s=t.trim().toLowerCase();return s==="ctrl"||s==="control"?e.jsx(_a,{className:"h-3.5 w-3.5"},`ctrl-${r}`):s==="⌘"||s==="cmd"||s==="command"||s==="meta"?e.jsx(gn,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:t.trim()},`key-${r}`)},Vw=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:"+"}),Uw(s,n)]},`${s}-${n}`))},Gw=()=>{const{isHelpDialogOpen:t,setHelpDialogOpen:r}=Ce(),s=at(a=>a.settingsAutoCreateWorktree),n=Xt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:gn},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:mn},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:Ml},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:fn},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:om},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:wr}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:s?"Create New Session in Worktree":"Create New Session",icon:s?Ht:is},{keys:[`Shift + ${n} + N`],description:s?"Create New Session":"Create New Session in Worktree",icon:s?is:Ht},{keys:[`${n} + I`],description:"Focus Chat Input",icon:am},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Ln}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:kh},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:Qs},{keys:[`${n} + 3`],description:"Open Files",icon:sr},{keys:[`${n} + 4`],description:"Open Terminal",icon:Vr},{keys:[`${n} + 5`],description:"Open Git Panel",icon:Ht},{keys:[`${n} + T`],description:"Open Timeline",icon:br},{keys:[`${n} + ,`],description:"Open Settings",icon:un}]}];return e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(vs,{children:[e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(un,{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:Vw(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(mn,{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"})]})]})]})})]})]})})},qw={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"}},Nf=({className:t,size:r="md"})=>{const s=qw[r];return e.jsx("div",{className:F("grid grid-cols-3",s.container,t),"aria-label":"Loading",children:Array.from({length:9},(n,o)=>e.jsx("div",{className:F("rounded-full bg-current animate-grid-pulse",s.dot),style:{animationDelay:`${(o%3+Math.floor(o/3))*150}ms`}},o))})},ki=new Set,Ni=new Set,Ci=new Set,Wn={onDeleteRequest(t){return ki.add(t),()=>{ki.delete(t)}},requestDelete(t){!t.sessions.length&&t.mode!=="worktree"||ki.forEach(r=>r(t))},onCreateRequest(t){return Ni.add(t),()=>{Ni.delete(t)}},requestCreate(t){const r=t??{};Ni.forEach(s=>s(r))},onDirectoryRequest(t){return Ci.add(t),()=>{Ci.delete(t)}},requestDirectoryDialog(){Ci.forEach(t=>t())}};function Cf(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 jt({className:t,type:r,...s}){return e.jsx("input",{type:r,"data-slot":"input",className:F("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 Kw({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(v=>{const S=new Map(v);return S.set(y.id,{branches:null,worktrees:[],loading:!0,error:null}),S});try{const[v,S]=await Promise.all([qa(y.path),Um(y.path)]);c(N=>{const w=new Map(N);return w.set(y.id,{branches:v,worktrees:S,loading:!1,error:null}),w})}catch(v){c(S=>{const N=new Map(S);return N.set(y.id,{branches:null,worktrees:[],loading:!1,error:v instanceof Error?v.message:"Failed to load"}),N})}})},[t,s,n]);const p=b=>{u(y=>{const v=new Set(y);return v.has(b)?v.delete(b):v.add(b),v})},h=async(b,y)=>{const v=`${b.id}:${y}`;f(v);try{await Ww(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 v=y.toLowerCase();return b.filter(S=>S.toLowerCase().includes(v))},g=s.filter(b=>{const y=l.get(b.id);return y&&!y.error&&(y.loading||y.branches)});return e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl max-h-[70vh] flex flex-col overflow-hidden gap-3",children:[e.jsxs(vs,{className:"flex-shrink-0",children:[e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(Ht,{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(lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{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),v=d.has(b.id),S=y?.branches,N=y?.worktrees||[],w=new Set(N.map(M=>M.branch).filter(Boolean)),k=S?.all||[],j=x(k,o).filter(M=>!M.startsWith("remotes/")).filter(M=>!w.has(M));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(Bs,{className:F("h-4 w-4 text-muted-foreground transition-transform",v&&"rotate-90")}),e.jsx(cr,{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(Jt,{className:"h-4 w-4 text-muted-foreground animate-spin"}),S&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[j.length," branches"]})]}),v&&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}):j.length===0?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:o?"No matching branches":"No branches found"}):j.map(M=>{const C=S?.branches[M],I=C?.current,E=m===`${b.id}:${M}`;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(Ht,{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:F("text-sm truncate",I&&"font-medium text-primary"),children:M}),I&&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:[C?.commit&&e.jsx("span",{className:"font-mono",children:C.commit.slice(0,7)}),C?.ahead!==void 0&&C.ahead>0&&e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["↑",C.ahead]}),C?.behind!==void 0&&C.behind>0&&e.jsxs("span",{className:"text-[color:var(--status-warning)]",children:["↓",C.behind]})]})]}),e.jsxs(lt,{children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>h(b,M),disabled:E,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:E?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-3.5 w-3.5 mr-1"}),"Worktree"]})})}),e.jsx(it,{side:"left",children:"Create worktree for this branch"})]})]},M)})})]},b.id)})})})]})})}const wd="oc.sessions.projectCollapse",vd="oc.sessions.expandedParents",jd=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(",","")},mr=t=>{if(!t)return null;const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},Sd=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),Qw=({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,onOpenMultiRunLauncher:b,onClose:y,sentinelRef:v,children:S,settingsAutoCreateWorktree:N})=>{const{attributes:w,listeners:k,setNodeRef:A,isDragging:j}=Lh({id:t}),[M,C]=i.useState(!1);return e.jsxs("div",{ref:A,className:F("relative",j&&"opacity-40"),children:[c&&e.jsx("div",{ref:v,"data-project-id":t,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("div",{className:F("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:I=>{I.preventDefault(),C(!0)},children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...w,children:[e.jsxs(lt,{delayDuration:1500,children:[e.jsx(ct,{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:F("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(it,{side:"right",sideOffset:8,children:s})]}),e.jsxs(es,{open:M,onOpenChange:C,children:[e.jsx(ts,{asChild:!0,children:e.jsx("button",{type:"button",className:F("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",m?"opacity-70":"opacity-0 group-hover/project:opacity-100"),"aria-label":"Project menu",onClick:I=>I.stopPropagation(),children:e.jsx(Gr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"min-w-[180px]",children:[a&&!u&&N&&h&&e.jsxs(Nt,{onClick:h,children:[e.jsx(is,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),a&&!u&&!N&&x&&e.jsxs(Nt,{onClick:x,children:[e.jsx(Ht,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),a&&!u&&g&&e.jsxs(Nt,{onClick:g,children:[e.jsx(im,{className:"mr-1.5 h-4 w-4"}),"Browse Branches"]}),a&&!u&&e.jsxs(Nt,{onClick:b,children:[e.jsx(Cf,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(Nt,{onClick:y,className:"text-destructive focus:text-destructive",children:[e.jsx(Zt,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),a&&!u&&x&&N&&e.jsxs(lt,{children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),x()},className:F("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(Ht,{className:"h-4 w-4"})})}),e.jsx(it,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session in worktree"})})]}),(!N||!a)&&e.jsxs(lt,{children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),h()},className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground flex-shrink-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"New session",children:e.jsx(is,{className:"h-4 w-4"})})}),e.jsx(it,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session"})})]})]})}),S]})},Yw=({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:F("typography-ui font-semibold truncate",r?"text-primary":"text-foreground"),children:t})})}),Ia=({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(()=>hs(),[]),[v,S]=i.useState(new Set),[N,w]=i.useState(new Map),[k,A]=i.useState(new Set),[j,M]=i.useState(null),[C,I]=i.useState(!1),[E,P]=i.useState(null),[D,T]=i.useState(new Set),[R,V]=i.useState(null),G=i.useRef(new Map),O=i.useRef(0),Y=bt(B=>B.homeDirectory),K=bt(B=>B.currentDirectory),U=bt(B=>B.setDirectory),Q=Vt(B=>B.projects),W=Vt(B=>B.activeProjectId),se=Vt(B=>B.addProject),ee=Vt(B=>B.removeProject),pe=Vt(B=>B.setActiveProject),$=Vt(B=>B.setActiveProjectIdOnly),oe=Vt(B=>B.reorderProjects),_=Ce(B=>B.setActiveMainTab),z=Ce(B=>B.setSessionSwitcherOpen),X=Ce(B=>B.openMultiRunLauncher),re=at(B=>B.settingsAutoCreateWorktree),ge=me(B=>B.sessions),H=me(B=>B.sessionsByDirectory),fe=me(B=>B.currentSessionId),we=me(B=>B.setCurrentSession),he=me(B=>B.updateSessionTitle),_e=me(B=>B.shareSession),te=me(B=>B.unshareSession),J=me(B=>B.sessionMemoryState),ne=me(B=>B.sessionActivityPhase),ke=me(B=>B.permissions),Z=me(B=>B.worktreeMetadata),ye=me(B=>B.availableWorktreesByProject),de=me(B=>B.getSessionsByDirectory),je=me(B=>B.openNewSessionDraft),[ie,Xe]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),mt=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{try{const B=y.getItem(vd);if(B){const ve=JSON.parse(B);Array.isArray(ve)&&h(new Set(ve.filter(Be=>typeof Be=="string")))}const ue=y.getItem(wd);if(ue){const ve=JSON.parse(ue);Array.isArray(ve)&&S(new Set(ve.filter(Be=>typeof Be=="string")))}}catch{}},[y]),i.useEffect(()=>{typeof window>"u"||Xe(typeof window.opencodeDesktop<"u")},[]);const Ae=i.useMemo(()=>[...ge].sort((B,ue)=>(ue.time?.updated||0)-(B.time?.updated||0)),[ge]);i.useEffect(()=>{let B=!1;const ue=Q.map(ve=>({id:ve.id,path:mr(ve.path)})).filter(ve=>!!ve.path);return w(new Map),ue.length===0?()=>{B=!0}:(ue.forEach(ve=>{Yr(ve.path).then(Be=>{B||w(ze=>{const tt=new Map(ze);return tt.set(ve.id,Be),tt})}).catch(()=>{B||w(Be=>{const ze=new Map(Be);return ze.set(ve.id,null),ze})})}),()=>{B=!0})},[Q]);const ae=i.useMemo(()=>{const B=new Map;return Ae.forEach(ue=>{const ve=ue.parentID;ve&&B.set(ue.id,ve)}),B},[Ae]),Ue=i.useMemo(()=>{const B=new Map;return Ae.forEach(ue=>{const ve=ue.parentID;if(!ve)return;const Be=B.get(ve)??[];Be.push(ue),B.set(ve,Be)}),B.forEach(ue=>ue.sort((ve,Be)=>(Be.time?.updated||0)-(ve.time?.updated||0))),B},[Ae]);i.useEffect(()=>{fe&&h(B=>{const ue=new Set(B);let ve=ae.get(fe)||null,Be=!1;for(;ve;)ue.has(ve)||(ue.add(ve),Be=!0),ve=ae.get(ve)||null;return Be?ue:B})},[fe,ae]),i.useEffect(()=>{const B=new Set;Ae.forEach(ue=>{const ve=mr(ue.directory??null);ve&&B.add(ve)}),Q.forEach(ue=>{const ve=mr(ue.path);ve&&B.add(ve)}),B.forEach(ue=>{const ve=x.get(ue);ve&&ve!=="unknown"||b.current.has(ue)||(b.current.add(ue),Fe.listLocalDirectory(ue).then(()=>{g(Be=>{const ze=new Map(Be);return ze.get(ue)==="exists"?Be:(ze.set(ue,"exists"),ze)})}).catch(()=>{g(Be=>{const ze=new Map(Be);return ze.get(ue)==="missing"?Be:(ze.set(ue,"missing"),ze)})}).finally(()=>{b.current.delete(ue)}))})},[Ae,Q,x]),i.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const Se=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."})]}),Ne=i.useCallback((B,ue,ve,Be)=>{if(!ve){if(Be&&Be!==W&&$(Be),ue&&ue!==K&&U(ue,{showOverlay:!1}),t&&(_("chat"),z(!1)),!s&&B===fe){r?.(B);return}we(B),r?.(B)}},[W,s,K,fe,t,r,_,$,we,U,z]),Ge=i.useCallback(async()=>{a&&c.trim()&&(await he(a,c.trim()),l(null),d(""))},[a,c,he]),rt=i.useCallback(()=>{l(null),d("")},[]),Ke=i.useCallback(async B=>{const ue=await _e(B.id);ue&&ue.share?.url?q.success("Session shared",{description:"You can copy the link from the menu."}):q.error("Unable to share session")},[_e]),Le=i.useCallback((B,ue)=>{navigator.clipboard.writeText(B).then(()=>{m(ue),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{q.error("Failed to copy URL")})},[]),Ye=i.useCallback(async B=>{await te(B)?q.success("Session unshared"):q.error("Unable to unshare session")},[te]),xt=i.useCallback(B=>{const ue=[],ve=Be=>{(Ue.get(Be)??[]).forEach(tt=>{ue.push(tt),ve(tt.id)})};return ve(B),ue},[Ue]),nt=me(B=>B.deleteSession),It=me(B=>B.deleteSessions),Pt=i.useCallback(async B=>{const ue=xt(B.id),ve=Z.get(B.id);if(ve){const Be=ve.path,ze=[],tt=new Set;ge.forEach(Me=>{const qe=Z.get(Me.id);qe&&qe.path===Be&&!tt.has(Me.id)&&(ze.push(Me),tt.add(Me.id),xt(Me.id).forEach(ot=>{tt.has(ot.id)||(ze.push(ot),tt.add(ot.id))}))}),Wn.requestDelete({sessions:ze,mode:"worktree",worktree:ve});return}if(ue.length===0)await nt(B.id)?q.success("Session deleted",{action:{label:"OK",onClick:()=>{}}}):q.error("Failed to delete session");else{const Be=[B.id,...ue.map(Me=>Me.id)],{deletedIds:ze,failedIds:tt}=await It(Be);ze.length>0&&q.success(`Deleted ${ze.length} session${ze.length===1?"":"s"}`,{action:{label:"OK",onClick:()=>{}}}),tt.length>0&&q.error(`Failed to delete ${tt.length} session${tt.length===1?"":"s"}`)}},[xt,nt,It,Z,ge]),zt=i.useCallback(()=>{ie&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(B=>{B.success&&B.path?se(B.path,{id:B.projectId})||q.error("Failed to add project",{description:"Please select a valid directory."}):B.error&&B.error!=="Directory selection cancelled"&&q.error("Failed to select directory",{description:B.error})}).catch(B=>{console.error("Desktop: Error selecting directory:",B),q.error("Failed to select directory")}):Wn.requestDirectoryDialog()},[se,ie]),We=i.useCallback(B=>{h(ue=>{const ve=new Set(ue);ve.has(B)?ve.delete(B):ve.add(B);try{y.setItem(vd,JSON.stringify(Array.from(ve)))}catch{}return ve})},[y]),ut=i.useCallback(B=>{const ue=Ue.get(B.id)??[];return{session:B,children:ue.map(ve=>ut(ve)),worktree:Z.get(B.id)??null}},[Ue,Z]),vt=i.useCallback((B,ue,ve)=>{const Be=mr(ue??null),ze=[...B].sort((wt,xe)=>(xe.time?.updated||0)-(wt.time?.updated||0)),tt=new Map(ze.map(wt=>[wt.id,wt])),Me=new Map;ze.forEach(wt=>{const xe=wt.parentID;if(!xe)return;const Ie=Me.get(xe)??[];Ie.push(wt),Me.set(xe,Ie)}),Me.forEach(wt=>wt.sort((xe,Ie)=>(Ie.time?.updated||0)-(xe.time?.updated||0)));const qe=new Map;ve.forEach(wt=>{if(wt.path){const xe=mr(wt.path)??wt.path;qe.set(xe,wt)}});const et=wt=>{const xe=mr(wt.directory??null),Ie=Z.get(wt.id)??null;if(Ie)return Ie;if(xe){const st=qe.get(xe)??null;if(st&&xe!==Be)return st}return null},ot=wt=>{const xe=Me.get(wt.id)??[];return{session:wt,children:xe.map(Ie=>ot(Ie)),worktree:et(wt)}},$t=ze.filter(wt=>{const xe=wt.parentID;return xe?!tt.has(xe):!0}).map(wt=>ot(wt));return[{id:"all",label:"All sessions",description:Be?on(Be,Y):null,isMain:!0,worktree:null,directory:Be,sessions:$t}]},[Y,Z]),dt=i.useCallback(B=>{A(ue=>{const ve=new Set(ue);return ve.has(B)?ve.delete(B):ve.add(B),ve})},[]),Tt=i.useCallback(B=>{O.current=Date.now()+150,S(ue=>{const ve=new Set(ue);ve.has(B)?ve.delete(B):ve.add(B);try{y.setItem(wd,JSON.stringify(Array.from(ve)))}catch{}return ve})},[y]),Ct=i.useMemo(()=>Q.map(B=>({...B,normalizedPath:mr(B.path)})).filter(B=>!!B.normalizedPath),[Q]),os=i.useCallback(B=>{const ue=mt?[]:ye.get(B.normalizedPath)??[],ve=[B.normalizedPath,...ue.map(tt=>mr(tt.path)??tt.path).filter(tt=>!!tt)],Be=new Set,ze=[];return ve.forEach(tt=>{(H.get(tt)??de(tt)).forEach(qe=>{Be.has(qe.id)||(Be.add(qe.id),ze.push(qe))})}),ze},[ye,de,H,mt]),St=i.useMemo(()=>Ct.map(B=>{const ue=os(B),ve=ye.get(B.normalizedPath)??[],Be=vt(ue,B.normalizedPath,ve);return{project:B,groups:Be}}),[Ct,os,vt,ye]);i.useEffect(()=>{if(!ie)return;const B=new IntersectionObserver(ue=>{ue.forEach(ve=>{const Be=ve.target.dataset.projectId;Be&&T(ze=>{const tt=new Set(ze);return ve.isIntersecting?tt.delete(Be):tt.add(Be),tt})})},{threshold:0});return G.current.forEach(ue=>{ue&&B.observe(ue)}),()=>B.disconnect()},[ie,St]);const Lt=i.useCallback((B,ue=0,ve,Be)=>{const ze=B.session,tt=mr(ze.directory??null)??mr(ve??null),qe=(tt?x.get(tt):null)==="missing",et=J.get(ze.id),ot=fe===ze.id,_t=ze.title||"Untitled Session",$t=B.children.length>0,wt=p.has(ze.id),xe=ze.summary?.additions,Ie=ze.summary?.deletions,st=typeof xe=="number"||typeof Ie=="number";if(a===ze.id)return e.jsx("div",{className:F("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",ue>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:pt=>{pt.preventDefault(),Ge()},children:[e.jsx("input",{value:c,onChange:pt=>d(pt.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:pt=>{pt.key==="Escape"&&rt()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Gt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:rt,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Zt,{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:[$t?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:wt?e.jsx(Ot,{className:"h-3 w-3"}):e.jsx(Bs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:jd(ze.time?.created||Date.now())}),ze.share?e.jsx(ai,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,st&&((xe??0)!==0||(Ie??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,xe??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Ie??0)]})]}):null,$t?e.jsxs("span",{className:"truncate",children:[B.children.length," ",B.children.length===1?"task":"tasks"]}):null]})]})},ze.id);const $e=ne?.get(ze.id)??"idle",kt=$e==="busy"||$e==="cooldown",Mt=ke.get(ze.id)?.length??0,Kt=et&&et.isZombie?e.jsx(Ki,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(i.Fragment,{children:[e.jsx("div",{className:F("group relative flex items-center rounded-md px-1.5 py-1",ot?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",qe?"opacity-75":"",ue>0&&"pl-[20px]"),onContextMenu:pt=>{pt.preventDefault(),V(ze.id)},children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:qe,onClick:()=>Ne(ze.id,tt,qe,Be),className:F("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:[kt?e.jsx(Nf,{size:"xs",className:"text-primary flex-shrink-0"}):null,e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:_t}),Mt>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(Nh,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:Mt})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[$t?e.jsx("span",{role:"button",tabIndex:0,onClick:pt=>{pt.stopPropagation(),We(ze.id)},onKeyDown:pt=>{(pt.key==="Enter"||pt.key===" ")&&(pt.preventDefault(),pt.stopPropagation(),We(ze.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":wt?"Collapse subsessions":"Expand subsessions",children:wt?e.jsx(Ot,{className:"h-3 w-3"}):e.jsx(Bs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:jd(ze.time?.created||Date.now())}),ze.share?e.jsx(ai,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,B.worktree?e.jsxs(lt,{delayDuration:700,children:[e.jsx(ct,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(Ht,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(it,{side:"top",className:"text-xs",children:B.worktree.branch||B.worktree.label||"Worktree"})]}):null,st&&((xe??0)!==0||(Ie??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,xe??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Ie??0)]})]}):null,$t?e.jsxs("span",{className:"truncate",children:[B.children.length," ",B.children.length===1?"task":"tasks"]}):null,qe?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(Ki,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Kt,e.jsxs(es,{open:R===ze.id,onOpenChange:pt=>V(pt?ze.id:null),children:[e.jsx(ts,{asChild:!0,children:e.jsx("button",{type:"button",className:F("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:pt=>pt.stopPropagation(),onKeyDown:pt=>pt.stopPropagation(),children:e.jsx(Gr,{className:t?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"min-w-[180px]",children:[e.jsxs(Nt,{onClick:()=>{l(ze.id),d(_t)},className:"[&>svg]:mr-1",children:[e.jsx(Nr,{className:"mr-1 h-4 w-4"}),"Rename"]}),ze.share?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{onClick:()=>{ze.share?.url&&Le(ze.share.url,ze.id)},className:"[&>svg]:mr-1",children:u===ze.id?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xs,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(Nt,{onClick:()=>Ye(ze.id),className:"[&>svg]:mr-1",children:[e.jsx(Ch,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(Nt,{onClick:()=>Ke(ze),className:"[&>svg]:mr-1",children:[e.jsx(ai,{className:"mr-1 h-4 w-4"}),"Share"]}),B.worktree?e.jsxs(Nt,{onClick:()=>{Be&&Be!==W&&pe(Be),_("chat"),t&&z(!1),je({directoryOverride:B.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(Ht,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(Nt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Pt(ze),children:[e.jsx(Us,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),$t&&wt?B.children.map(pt=>Lt(pt,ue+1,tt??ve,Be)):null]},ze.id)},[x,J,ne,ke,fe,p,a,c,Ge,rt,We,Ne,Ke,Le,Ye,Pt,u,t,W,pe,_,z,je,R]),Ft=i.useCallback((B,ue,ve)=>{const Be=k.has(ue),ze=n?10:5,tt=B.sessions.length,Me=Be?B.sessions:B.sessions.slice(0,ze),qe=tt-Me.length;return e.jsxs(e.Fragment,{children:[Me.map(et=>Lt(et,0,B.directory,ve)),tt===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,qe>0&&!Be?e.jsxs("button",{type:"button",onClick:()=>dt(ue),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 ",qe," more ",qe===1?"session":"sessions"]}):null,Be&&tt>ze?e.jsx("button",{type:"button",onClick:()=>dt(ue),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]})},[k,n,Lt,dt]),Ut=Mh(wc(Rh,{activationConstraint:{distance:8}}),wc(Fh,{coordinateGetter:Th})),Rt=i.useCallback(B=>{P(B.active.id)},[]),qt=i.useCallback(B=>{const{active:ue,over:ve}=B;if(P(null),!ve||ue.id===ve.id)return;const Be=Ct.findIndex(tt=>tt.id===ue.id),ze=Ct.findIndex(tt=>tt.id===ve.id);Be!==-1&&ze!==-1&&oe(Be,ze)},[Ct,oe]),be=i.useCallback(()=>{P(null)},[]),Ee=i.useMemo(()=>{if(!E)return null;const B=St.find(ve=>ve.project.id===E);if(!B)return null;const ue=B.project;return{id:ue.id,label:Sd(ue.label?.trim()||Nc(ue.normalizedPath,Y)||ue.normalizedPath),isActive:ue.id===W}},[E,St,Y,W]);return e.jsxs("div",{className:F("flex h-full flex-col text-foreground overflow-x-hidden",t?"":ie?"bg-transparent":"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:Q.length})]}),e.jsx("button",{type:"button",onClick:zt,className:F("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",!ie&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(Qi,{className:"h-4.5 w-4.5"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:F("space-y-1 pb-1 pl-2.5 pr-1",""),children:St.length===0?Se:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const B=St.find(Be=>Be.project.id===W)??St[0];if(!B)return Se;const ue=B.groups.find(Be=>Be.isMain&&Be.sessions.length>0)??B.groups.find(Be=>Be.sessions.length>0)??B.groups.find(Be=>Be.isMain)??B.groups[0];if(!ue)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const ve=`${B.project.id}:${ue.id}`;return Ft(ue,ve,B.project.id)})()}):e.jsxs(Dh,{sensors:Ut,collisionDetection:Ah,onDragStart:Rt,onDragEnd:qt,onDragCancel:be,children:[e.jsx(Eh,{items:Ct.map(B=>B.id),strategy:Ih,children:St.map(B=>{const ue=B.project,ve=ue.id,Be=Sd(ue.label?.trim()||Nc(ue.normalizedPath,Y)||ue.normalizedPath),ze=on(ue.normalizedPath,Y),tt=v.has(ve),Me=ve===W,qe=N.get(ve),et=j===ve;return e.jsx(Qw,{id:ve,projectLabel:Be,projectDescription:ze,isCollapsed:tt,isActiveProject:Me,isRepo:!!qe,isHovered:et,isDesktopRuntime:ie,isStuck:D.has(ve),hideDirectoryControls:n,mobileVariant:t,onToggle:()=>Tt(ve),onHoverChange:ot=>M(ot?ve:null),onNewSession:()=>{ve!==W&&pe(ve),_("chat"),t&&z(!1),je({directoryOverride:ue.normalizedPath})},onNewWorktreeSession:()=>{ve!==W&&pe(ve),_("chat"),t&&z(!1),Xa()},onOpenBranchPicker:()=>I(!0),onOpenMultiRunLauncher:()=>{ve!==W&&pe(ve),X()},onClose:()=>ee(ve),sentinelRef:ot=>{G.current.set(ve,ot)},settingsAutoCreateWorktree:re,children:tt?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:B.groups[0]?Ft(B.groups[0],`${ve}:all`,ve):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},ve)})}),e.jsx(Ph,{children:Ee?e.jsx(Yw,{projectLabel:Ee.label,isActiveProject:Ee.isActive}):null})]})}),e.jsx(Kw,{open:C,onOpenChange:I,projects:Ct,activeProjectId:W})]})},Ja=()=>{const[t,r]=Te.useState(!1);Te.useEffect(()=>{r(ls())},[]);const s=Te.useCallback(async a=>t?await Mx(a):{success:!0,path:a},[t]),n=Te.useCallback(async a=>t?await Dx(a):{success:!0},[t]),o=Te.useCallback(async a=>t?await Ax(a):{success:!0},[t]);return{isDesktop:t,requestAccess:s,startAccessing:n,stopAccessing:o}},kd=({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(()=>ls(),[]),{isMobile:p}=Qt(),[h,x]=i.useState([]),[g,b]=i.useState(new Set),[y,v]=i.useState(!0),[S,N]=i.useState(!1),[w,k]=i.useState(""),[A,j]=i.useState(new Set),[M,C]=i.useState(null),[I,E]=i.useState(""),[P,D]=i.useState(!0),T=i.useRef(null),{requestAccess:R,startAccessing:V,isDesktop:G}=Ja(),O=i.useRef(c),Y=i.useCallback(te=>{if(!te)return te;if(te==="/"||te.length===0)return"/";let J=te;for(;J.length>1&&J.endsWith("/");)J=J.slice(0,-1);return J.length===0?"/":J},[]),K=i.useMemo(()=>{if(!w)return null;const te=w.replace(/\\/g,"/");return Y(te)},[w,Y]),U=i.useMemo(()=>{if(typeof d=="string"&&d.length>0){const te=d.replace(/\\/g,"/"),J=Y(te);if(J&&J!=="/")return J}return K&&K!=="/"?K:null},[d,K,Y]),Q=i.useMemo(()=>typeof u=="boolean"?!!(u&&U):!!U,[u,U]);i.useEffect(()=>{Q||(v(!0),x([]))},[Q]);const W=i.useCallback(te=>{if(!te||!Q||!U)return!1;const J=te.replace(/\\/g,"/"),ne=Y(J)??J;if(ne===U)return!0;const ke=`${U}/`;return ne.startsWith(ke)},[Q,U,Y]),se=async te=>{if(Q){if(a==="deferred"){r(te);return}if(G){const J=await R(te);J.success&&J.path?(await V(J.path),r(J.path)):(console.error("Failed to get directory access:",J.error),r(te))}else r(te)}};i.useEffect(()=>{let te=!1;const J=Z=>{if(!Z)return!1;const ye=Y(Z.replace(/\\/g,"/"));return!ye||ye==="/"?!1:(k(typeof ye=="string"?ye:Z.replace(/\\/g,"/")),!0)};return d&&J(d)||(async()=>{try{const Z=await Fe.getFilesystemHome();if(!te&&J(Z))return}catch(Z){console.warn("Failed to resolve filesystem home directory:",Z)}try{const Z=await Fe.getSystemInfo();if(!te&&J(Z?.homeDirectory))return}catch(Z){console.warn("Failed to resolve home directory from system info:",Z)}})(),()=>{te=!0}},[d,Y]),i.useEffect(()=>{let te=!1;const J=ye=>{if(te)return;const de=ye.filter(je=>typeof je=="string"&&je.length>0).map(je=>{const ie=je.replace(/\\/g,"/");return Y(ie)??ie});j(new Set(de))},ne=()=>{try{const ye=localStorage.getItem("pinnedDirectories");if(!ye)return;const de=JSON.parse(ye);Array.isArray(de)&&J(de)}catch(ye){console.warn("Failed to load pinned directories from local storage:",ye)}},ke=async()=>{try{let ye=[];if(f){const de=await Pr();ye=Array.isArray(de?.pinnedDirectories)?de.pinnedDirectories:[]}else{const de=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(de.ok){const je=await de.json();ye=Array.isArray(je?.pinnedDirectories)?je.pinnedDirectories:[]}}if(te)return;J(ye)}catch(ye){console.warn("Failed to load pinned directories:",ye)}};ne();const Z=ye=>{const de=ye.detail;de&&Array.isArray(de.pinnedDirectories)&&J(de.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",Z),ke(),()=>{te=!0,window.removeEventListener("openchamber:settings-synced",Z)}},[f,Y]);const ee=i.useRef(!0);i.useEffect(()=>{if(ee.current){ee.current=!1;return}const te={pinnedDirectories:Array.from(A)};us(te)},[A]),i.useEffect(()=>{U&&j(te=>{const J=Array.from(te).map(ne=>Y(ne.replace(/\\/g,"/"))??ne).filter(ne=>W(ne));return new Set(J)})},[U,W,Y]),i.useEffect(()=>{O.current!==c&&(O.current=c)},[c]);const pe=te=>{j(J=>{if(!W(te))return J;const ne=Y(te.replace(/\\/g,"/"))??te.replace(/\\/g,"/"),ke=new Set(J);return ke.has(ne)?ke.delete(ne):ke.add(ne),ke})},$=i.useMemo(()=>Array.from(A).map(te=>Y(te.replace(/\\/g,"/"))??te).filter(te=>W(te)).map(te=>({path:te,name:te.split("/").pop()||te})).sort((te,J)=>te.name.localeCompare(J.name)),[A,W,Y]),oe=i.useCallback(async te=>{const J=de=>c||!de.startsWith("."),ne=U;if(!Q||!ne)return[];const ke=te&&te.length>0?te:ne,Z=ke?ke.replace(/\\/g,"/"):null,ye=Z?Y(Z)??Z:null;if(ye){const de=`${ne}/`;if(!(ye===ne||ye.startsWith(de)))return[]}try{return(await Fe.listLocalDirectory(te)).filter(je=>{if(!je.isDirectory||!J(je.name))return!1;const ie=je.path.replace(/\\/g,"/"),Xe=Y(ie)??ie,mt=Xe===ne?ne:`${ne}/`;return Xe===ne||Xe.startsWith(mt)}).map(je=>({name:je.name,path:je.path.replace(/\\/g,"/"),isDirectory:!0})).sort((je,ie)=>je.name.localeCompare(ie.name))}catch{try{const je=await Fe.getApiClient().file.list({path:".",directory:te});return je.data?je.data.filter(ie=>{if(ie.type!=="directory"||!ie.name||!J(ie.name))return!1;const Xe=String(ie.absolute||ie.path||ie.name).replace(/\\/g,"/"),mt=Y(Xe)??Xe,Ae=mt===ne?ne:`${ne}/`;return mt===ne||mt.startsWith(Ae)}).map(ie=>({name:ie.name||"",path:String(ie.absolute||ie.path||ie.name).replace(/\\/g,"/"),isDirectory:!0})).filter(ie=>ie.name!=="").sort((ie,Xe)=>ie.name.localeCompare(Xe.name)):[]}catch{return[]}}},[c,U,Y,Q]),_=i.useRef(!1),z=i.useCallback(async()=>{if(!Q||!U){v(!0),x([]);return}_.current||v(!0);try{const te=await oe(U);x(te),_.current=!0}catch{}finally{v(!1)}},[Q,U,oe]);i.useEffect(()=>{Q&&(n==="inline"||S)&&z()},[n,S,Q,z]);const X=async te=>{if(!Q)return;const J=g.has(te.path),ne=new Set(g);if(J){ne.delete(te.path),b(ne);return}ne.add(te.path),b(ne);const ke=await oe(te.path),Z=ye=>ye.map(de=>de.path===te.path?{...de,children:ke}:de.children?{...de,children:Z(de.children)}:de);x(ye=>Z(ye))};i.useEffect(()=>{M&&T.current&&(T.current.focus(),T.current.select())},[M]);const re=(te,J=[])=>{const ne="new_directory",ke=J.map(je=>je.name);if(!ke.includes(ne))return ne;let Z=1;const ye=new RegExp(`^${ne}(\\d+)$`);for(const je of ke){const ie=je.match(ye);if(ie){const Xe=parseInt(ie[1],10);Xe>Z&&(Z=Xe)}}let de=2;for(;ke.includes(`${ne}${de}`);)de++;return`${ne}${Math.max(de,Z+1)}`},ge=async te=>{if(Q){if(g.has(te.path)){const J=re(te.path,te.children);E(J)}else{const J=new Set(g);if(J.add(te.path),b(J),te.children){const ne=re(te.path,te.children);E(ne)}else{const ne=await oe(te.path),ke=ye=>ye.map(de=>de.path===te.path?{...de,children:ne}:de.children?{...de,children:ke(de.children)}:de);x(ye=>ke(ye));const Z=re(te.path,ne);E(Z)}}C(te.path)}},H=async()=>{if(!M||!Q)return;const te=I.trim()||"new_directory",J=`${M}/${te}`;try{await Fe.createDirectory(J);const ne=await oe(M),ke=Z=>Z.map(ye=>ye.path===M?{...ye,children:ne}:ye.children?{...ye,children:ke(ye.children)}:ye);x(Z=>ke(Z)),C(null),E("")}catch(ne){console.error("Failed to create directory:",ne)}},fe=()=>{C(null),E("")},we=(te,J=0)=>{const ne=g.has(te.path),ke=te.isDirectory,Z=A.has(te.path),ye=t===te.path,de=n==="inline",je=e.jsxs(e.Fragment,{children:[ke&&e.jsx("button",{onClick:ie=>{ie.stopPropagation(),X(te)},className:F("hover:bg-accent rounded","p-0.5"),children:ne?e.jsx(Ot,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Bs,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!ke&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:ie=>{ie.stopPropagation(),se(te.path),n==="dropdown"&&a==="immediate"&&N(!1)},onDoubleClick:ie=>{ie.stopPropagation(),l&&l(te.path)},className:F("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",de&&ye?"text-primary":"text-foreground"),children:[e.jsx(sr,{className:F("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",de&&ye&&"text-primary")}),e.jsx("span",{className:F("font-medium truncate","typography-ui-label",de&&ye?"text-primary":"text-foreground"),children:te.name})]}),e.jsx("button",{onClick:ie=>{ie.stopPropagation(),ge(te)},className:F("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(is,{className:F("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:ie=>{ie.stopPropagation(),pe(te.path)},className:F("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:Z?"Unpin directory":"Pin directory",children:Z?e.jsx(ii,{className:F("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(Oh,{className:F("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:F("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",ye?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${J*(p?12:14)+(p?4:6)}px`},children:je}),ne&&e.jsxs(e.Fragment,{children:[M===te.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(J+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(sr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{ref:T,value:I,onChange:ie=>E(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"?(ie.preventDefault(),ie.stopPropagation(),H()):ie.key==="Escape"&&(ie.preventDefault(),ie.stopPropagation(),fe())},onBlur:H,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),H()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Gt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),fe()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Zt,{className:"h-3 w-3 text-muted-foreground"})})]}),te.children&&te.children.map(ie=>we(ie,J+1))]})]},te.path):e.jsxs("div",{children:[e.jsxs(Nt,{className:F("flex items-center gap-1 cursor-pointer group",t===te.path&&"bg-accent"),style:{paddingLeft:`${J*12+8}px`},onSelect:ie=>{ie.preventDefault()},children:[ke&&e.jsx("button",{onClick:ie=>{ie.stopPropagation(),X(te)},className:"p-0.5 hover:bg-accent rounded",children:ne?e.jsx(Ot,{className:"h-3 w-3"}):e.jsx(Bs,{className:"h-3 w-3"})}),!ke&&e.jsx("div",{className:"w-4"}),je]}),ne&&e.jsxs("div",{children:[M===te.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(J+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(sr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{ref:T,value:I,onChange:ie=>E(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"?(ie.preventDefault(),ie.stopPropagation(),H()):ie.key==="Escape"&&(ie.preventDefault(),ie.stopPropagation(),fe())},onBlur:H,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),H()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Gt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),fe()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Zt,{className:"h-3 w-3 text-muted-foreground"})})]}),te.children&&te.children.map(ie=>we(ie,J+1))]})]},te.path)},he=(te,J)=>{if(n==="inline"){const ne=t===J;return e.jsxs("div",{className:F("group flex items-center gap-2 mx-1 rounded-lg transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",ne?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>se(J),onDoubleClick:ke=>{ke.stopPropagation(),l&&l(J)},className:F("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",ne?"text-primary":"text-foreground"),children:[e.jsx(sr,{className:F("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",ne?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:F("typography-ui-label font-medium truncate flex-shrink-0",ne?"text-primary":"text-foreground"),children:te}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:on(J,w)})]}),e.jsx("button",{onClick:()=>pe(J),className:F("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(ii,{className:F("text-primary","h-3.5 w-3.5")})})]},J)}return e.jsxs(Nt,{onSelect:ne=>{ne.preventDefault(),se(J),a==="immediate"&&N(!1)},className:F("flex items-start gap-2 cursor-pointer group py-2",t===J&&"bg-accent"),children:[e.jsx(sr,{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:te}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:on(J,w)})]}),e.jsx("button",{onClick:ne=>{ne.stopPropagation(),ne.preventDefault(),pe(J)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(ii,{className:"h-3 w-3 text-primary"})})]},J)},_e=e.jsx(e.Fragment,{children:Q?e.jsxs(e.Fragment,{children:[$.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>D(te=>!te),className:F("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:[P?e.jsx(Ot,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Bs,{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:$.length})]}),P&&$.map(({name:te,path:J})=>he(te,J)),n==="dropdown"&&e.jsx(Ds,{}),n==="inline"&&P&&e.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),e.jsx("div",{className:F("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(te=>we(te)),!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:F("overflow-hidden flex flex-col",o),children:e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:_e})}):e.jsxs(es,{open:S,onOpenChange:N,children:[e.jsx(ts,{asChild:!0,children:e.jsxs(De,{variant:"ghost",className:F("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(sr,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:t,children:on(t,w)})]}),e.jsx(Ot,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(ss,{align:"start",className:"w-[350px]",children:e.jsx(gt,{outerClassName:"h-full",className:"w-full",children:_e})})]})},Za=(t,r=200)=>{const[s,n]=Te.useState(t);return Te.useEffect(()=>{const o=window.setTimeout(()=>{n(t)},r);return()=>{window.clearTimeout(o)}},[t,r]),s},Mf=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((w,k)=>{const A=w.trim().toLowerCase();if(!A)return 0;const j=k.toLowerCase();let M=0,C=-1,I=0;for(let E=0;E<A.length;E+=1){const P=A[E];if(!P||P===" ")continue;const D=j.indexOf(P,C+1);if(D===-1)return null;const T=D-C-1;if(T===0?I+=1:I=0,M+=10,M+=Math.max(0,18-D),M-=Math.max(0,T),D===0)M+=12;else{const R=j[D-1];(R==="/"||R==="_"||R==="-"||R==="."||R===" ")&&(M+=10)}M+=I>0?12:0,C=D}return M+=Math.max(0,24-Math.round(j.length/3)),M},[]),b=i.useCallback(w=>w.startsWith("~")&&r?w.replace(/^~/,r):w,[r]),y=i.useCallback(w=>{const k=b(w);if(k.endsWith("/"))return k;const A=k.lastIndexOf("/");return A===-1?"":A===0?"/":k.substring(0,A+1)},[b]),v=i.useCallback(w=>{const k=b(w);if(k.endsWith("/"))return"";const A=k.lastIndexOf("/");return A===-1?k:k.substring(A+1)},[b]),S=Za(t,150);i.useEffect(()=>{if(!n||!S){d([]);return}const w=y(S),k=v(S).toLowerCase();if(!w){d([]);return}let A=!1;return m(!0),Fe.listLocalDirectory(w).then(j=>{if(A)return;const M=j.filter(I=>!(!I.isDirectory||!a&&I.name.startsWith("."))),C=k?M.map(I=>{const E=g(k,I.name);return E!==null?{entry:I,score:E}:null}).filter(I=>I!==null).sort((I,E)=>E.score-I.score||I.entry.name.localeCompare(E.entry.name)).map(I=>I.entry):M.sort((I,E)=>I.name.localeCompare(E.name));d(C.slice(0,10)),p(0)}).catch(()=>{A||d([])}).finally(()=>{A||m(!1)}),()=>{A=!0}},[n,S,y,v,a,g]),i.useEffect(()=>{x.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),i.useEffect(()=>{if(!n)return;const w=k=>{const A=k.target;!A||!h.current||h.current.contains(A)||o()};return document.addEventListener("pointerdown",w,!0),()=>{document.removeEventListener("pointerdown",w,!0)}},[n,o]);const N=i.useCallback(w=>{const k=w.path.endsWith("/")?w.path:w.path+"/";s(k)},[s]);return i.useImperativeHandle(l,()=>({handleKeyDown:w=>{if(!n||c.length===0)return!1;const k=c.length;if(w.key==="Tab"){if(w.preventDefault(),w.shiftKey)p(A=>(A-1+k)%k);else if(k===1){const A=c[0];A&&N(A)}else p(A=>(A+1)%k);return!0}if(w.key==="ArrowDown")return w.preventDefault(),p(A=>(A+1)%k),!0;if(w.key==="ArrowUp")return w.preventDefault(),p(A=>(A-1+k)%k),!0;if(w.key==="Enter"){w.preventDefault();const A=(f%k+k)%k,j=c[A];return j&&N(j),o(),!0}return w.key==="Escape"?(w.preventDefault(),o(),!0):!1}}),[n,c,f,N,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(Wr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:c.map((w,k)=>{const A=f===k;return e.jsxs("div",{ref:j=>{x.current[k]=j},className:F("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",A&&"bg-muted"),onClick:()=>{N(w),o()},onMouseEnter:()=>p(k),children:[e.jsx(cr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w.name})]},w.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"})]})});Mf.displayName="DirectoryAutocomplete";const Df="directoryTreeShowHidden",ml="directory-show-hidden-change",Nd=()=>{if(typeof window>"u")return!1;try{return hs().getItem(Df)==="true"}catch{return!1}},Xw=()=>{typeof window>"u"||window.dispatchEvent(new Event(ml))},Af=t=>{if(!(typeof window>"u"))try{hs().setItem(Df,t?"true":"false"),Xw()}catch{}},Mo=()=>{const[t,r]=i.useState(Nd);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(Nd())};return window.addEventListener("storage",s),window.addEventListener(ml,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(ml,s)}},[]),t},Jw=({open:t,onOpenChange:r})=>{const{currentDirectory:s,homeDirectory:n,isHomeReady:o}=bt(),{addProject:a,getActiveProject:l}=Vt(),[c,d]=i.useState(null),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,x]=i.useState(!1),g=Mo(),{isDesktop:b,requestAccess:y,startAccessing:v}=Ja(),{isMobile:S}=Qt(),[N,w]=i.useState(!1),k=i.useRef(null),A=i.useCallback(se=>se?on(se,n):"",[n]);i.useEffect(()=>{if(t){p(!1),x(!1),w(!1);const ee=l()?.path||s||n||"";d(ee),m(A(ee))}},[t,s,n,A,l]),i.useEffect(()=>{!t||f||c||n&&o&&(d(n),p(!0),m("~"))},[t,f,c,n,o]);const j=i.useCallback(()=>{r(!1)},[r]),M=i.useCallback(async se=>{if(!(!se||h)){x(!0);try{let ee=se,pe;if(b){const oe=await y(se);if(!oe.success){q.error("Unable to access directory",{description:oe.error||"Desktop denied directory access."});return}ee=oe.path??se,pe=oe.projectId;const _=await v(ee);if(!_.success){q.error("Failed to open directory",{description:_.error||"Desktop could not grant file access."});return}}if(!a(ee,{id:pe})){q.error("Failed to add project",{description:"Please select a valid directory path."});return}j()}catch(ee){q.error("Failed to select directory",{description:ee instanceof Error?ee.message:"Unknown error occurred."})}finally{x(!1)}}},[a,j,b,y,v,h]),C=i.useCallback(async()=>{const se=u.trim()||c;se&&await M(se)},[M,u,c]),I=i.useCallback(se=>{d(se),p(!0),m(A(se))},[A]),E=i.useCallback(async se=>{d(se),p(!0),m(A(se)),await M(se)},[M,A]),P=i.useCallback(se=>{const ee=se.target.value;if(m(ee),p(!0),w(ee.startsWith("/")||ee.startsWith("~")),ee.startsWith("/")||ee.startsWith("~")){const pe=ee.startsWith("~")&&n?ee.replace(/^~/,n):ee;d(pe)}},[n]),D=i.useCallback(se=>{k.current?.handleKeyDown(se)||se.key==="Enter"&&(se.preventDefault(),C())},[C]),T=i.useCallback(se=>{d(se),p(!0),m(A(se))},[A]),R=i.useCallback(()=>{w(!1)},[]),V=i.useCallback(()=>{Af(!g)},[g]),G=e.jsxs("button",{type:"button",onClick:V,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(Al,{className:"h-4 w-4 text-primary"}):e.jsx(El,{className:"h-4 w-4"}),"Show hidden"]}),O=e.jsxs(vs,{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(js,{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."}),G]})]}),Y=e.jsxs("div",{className:"relative",children:[e.jsx(jt,{value:u,onChange:P,onKeyDown:D,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(Mf,{ref:k,inputValue:u,homeDirectory:n,onSelectSuggestion:T,visible:N,onClose:R,showHidden:g})]}),K=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(kd,{variant:"inline",currentPath:c??s,onSelectPath:I,onDoubleClickPath:E,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o})}),U=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:Y}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:G}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(kd,{variant:"inline",currentPath:c??s,onSelectPath:I,onDoubleClickPath:E,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),Q=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[Y,K]}),W=()=>e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",onClick:j,disabled:h,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(De,{onClick:C,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($s,{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:W()}),children:U}):e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:F("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:se=>{se.preventDefault()},children:[O,Q,e.jsx(zs,{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:W()})]})})},zo=t=>t?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,Zw=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},ev=()=>{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}=me(),{currentDirectory:y,homeDirectory:v,isHomeReady:S}=bt(),{projects:N,addProject:w,activeProjectId:k}=Vt(),{requestAccess:A,startAccessing:j}=Ja(),{isMobile:M,isTablet:C,hasTouchInput:I}=Qt(),E=M||C||I,P=i.useMemo(()=>{const z=(k?N.find(X=>X.id===k)??null:null)?.path??y;return Zw(z)},[k,y,N]),D=i.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||c.some(_=>_.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,c]),T=i.useMemo(()=>{const _=a?.worktree;return _&&typeof _.branch=="string"&&_.branch.trim().length>0?!0:c.length>0&&c.every(({metadata:z})=>typeof z.branch=="string"&&z.branch.trim().length>0)},[a?.worktree,c]),R=a?.mode==="worktree",V=R,G=f||!R||!T;i.useEffect(()=>{P&&(o.current.has(P)||Vy(P).then(()=>o.current.add(P)).catch(_=>{console.warn("Failed to ensure .openchamber directory is ignored:",_),o.current.delete(P)}))},[P]),i.useEffect(()=>{g()},[g,y]);const O=i.useMemo(()=>N.map(_=>`${_.id}:${_.path}`).join("|"),[N]),Y=i.useRef(O);i.useEffect(()=>{O!==Y.current&&(Y.current=O,g())},[g,O]),i.useEffect(()=>{if(!(s||!S||N.length>0)){if(n(!0),ls()){A("").then(async _=>{if(!_.success||!_.path){_.error&&_.error!=="Directory selection cancelled"&&q.error("Failed to select directory",{description:_.error});return}const z=await j(_.path);if(!z.success){q.error("Failed to open directory",{description:z.error||"Desktop could not grant file access."});return}w(_.path,{id:_.projectId})||q.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(_=>{console.error("Desktop: Error selecting directory:",_),q.error("Failed to select directory")});return}r(!0)}},[w,s,S,N.length,A,j]);const K=i.useCallback(_=>{l({sessions:_.sessions,dateLabel:_.dateLabel,mode:_.mode??"session",worktree:_.worktree??null})},[]),U=i.useCallback(()=>{l(null),d([]),m(!1),p(!1)},[]);i.useEffect(()=>Wn.onDeleteRequest(_=>{K(_)}),[K]),i.useEffect(()=>Wn.onDirectoryRequest(()=>{r(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1);return}const _=a.sessions.map(X=>{const re=b(X.id);return re?{session:X,metadata:re}:null}).filter(X=>!!X);if(d(_),m(!1),_.length===0)return;let z=!1;return(async()=>{const X=await Promise.all(_.map(async({metadata:re})=>{if(re.status&&typeof re.status.isDirty=="boolean")return re.status;try{return await Ka(re.path)}catch{return re.status}})).catch(re=>(console.warn("Failed to inspect worktree status before deletion:",re),_.map(({metadata:ge})=>ge.status)));z||!Array.isArray(X)||d(re=>re.map((ge,H)=>({session:ge.session,metadata:{...ge.metadata,status:X[H]??ge.metadata.status}})))})(),()=>{z=!0}},[a,b]),i.useEffect(()=>{T||m(!1)},[T]);const Q=i.useCallback(async()=>{if(a){p(!0);try{const _=V,z=_&&u;if(a.sessions.length===0&&R&&a.worktree){const X=u&&T;await ef({projectDirectory:P,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:X});const re=X?"Worktree and remote branch removed.":"Worktree removed.";q.success("Worktree removed",{description:zo(re)}),U(),g();return}if(a.sessions.length===1){const X=a.sessions[0];if(!await h(X.id,{archiveWorktree:_,deleteRemoteBranch:z})){q.error("Failed to delete session"),p(!1);return}const ge=_?z?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;q.success("Session deleted",{description:zo(ge),action:{label:"OK",onClick:()=>{}}})}else{const X=a.sessions.map(H=>H.id),{deletedIds:re,failedIds:ge}=await x(X,{archiveWorktree:_,deleteRemoteBranch:z});if(re.length>0){const H=_?z?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,we=[ge.length>0?`${ge.length} session${ge.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,H].filter(Boolean).join(" ");q.success(`Deleted ${re.length} session${re.length===1?"":"s"}`,{description:zo(we||void 0),action:{label:"OK",onClick:()=>{}}})}if(ge.length>0&&(q.error(`Failed to delete ${ge.length} session${ge.length===1?"":"s"}`,{description:zo("Please try again in a moment.")}),re.length===0)){p(!1);return}}U()}finally{p(!1)}}},[a,u,h,x,U,V,R,T,P,g]),W=a?.worktree??c[0]?.metadata??null,se=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}`:""}.`:"",ee=a?e.jsxs("div",{className:F(R?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&e.jsxs("div",{className:F(R?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[R&&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:F(R?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(_=>e.jsxs("li",{className:F(R?"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:F(!R&&"hidden"),children:"•"}),e.jsx("span",{className:"truncate",children:_.title||"Untitled Session"})]},_.id)),a.sessions.length>5&&e.jsxs("li",{className:F(R?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",a.sessions.length-5," more"]})]})]}),R?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(Ht,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),W?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:W.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:W?on(W.path,v):"Worktree path unavailable."}),D&&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,pe=R?T?e.jsxs("button",{type:"button",onClick:()=>{G||m(_=>!_)},disabled:G,className:F("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",G?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?e.jsx(Al,{className:"size-4 text-primary"}):e.jsx(El,{className:"size-4"}),"Delete remote branch"]}):e.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,$=R?e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[pe,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{variant:"ghost",onClick:U,disabled:f,children:"Cancel"}),e.jsx(De,{variant:"destructive",onClick:Q,disabled:f,children:f?"Deleting…":"Delete worktree"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",onClick:U,disabled:f,children:"Cancel"}),e.jsx(De,{variant:"destructive",onClick:Q,disabled:f,children:f?"Deleting…":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),oe=R?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[E?e.jsx($s,{open:!!a,onClose:()=>{f||U()},title:oe,footer:e.jsx("div",{className:"flex justify-end gap-2",children:$}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[se&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:se}),ee]})}):e.jsx(xs,{open:!!a,onOpenChange:_=>{if(!_){if(f)return;U()}},children:e.jsxs(ys,{className:F(R?"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(vs,{children:[e.jsxs(js,{className:F(R&&"flex items-center gap-2"),children:[R&&e.jsx(Us,{className:"h-5 w-5"}),oe]}),se&&e.jsx(Ns,{children:se})]}),e.jsx("div",{className:F(R&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:ee}),e.jsx(zs,{className:"mt-2 gap-2 pt-1 pb-1",children:$})]})}),e.jsx(Jw,{open:t,onOpenChange:r})]})};function tv(){return new Worker(_h,{type:"module"})}const sv=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function rv(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 Cd(t){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>t(void 0),0);return()=>window.clearTimeout(r)}const nv=({children:t})=>{const r=Bh(),s=as(c=>c.activeDirectory),n=as(c=>s?c.directories.get(s)?.lastStatusChange??0:0),o=as(c=>s?c.directories.get(s)?.diffCache.size??0:0),a=Te.useRef(!1),l=Te.useRef(new Map);return Te.useEffect(()=>{if(!r||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=qi(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Te.useEffect(()=>{if(!r||!s||!n||o===0)return;const c=as.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,Tr(b);const v=rv(b,y.original,y.modified),S={name:b,contents:y.original,cacheKey:`old-${v}`},N={name:b,contents:y.modified,cacheKey:`new-${v}`},w=qi(S,N),k={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(k,w)}p<f.length&&(m=Cd(h))};return h(void 0),p<f.length&&(m=Cd(h)),()=>{u=!0,m?.()}},[r,s,n,o]),e.jsx(e.Fragment,{children:t})},ov=({children:t})=>{const s=Ya()?.currentTheme?.metadata?.variant==="dark";gf();const n=Te.useMemo(()=>({theme:{dark:zn.dark,light:zn.light},themeType:s?"dark":"light",langs:sv}),[s]);return e.jsx($h,{poolOptions:{workerFactory:tv,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(nv,{children:t})})},fl=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),av=(t,r)=>{const s=fl(t),n=fl(r);return`${s}-${n}`.substring(0,60)},Md=(t,r)=>`${t}/${r}`,iv=t=>t.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),lv=()=>{const t=Vt.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=bt.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},fo=ns()(cs(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=lv();if(!d)return t({error:"No directory selected",isLoading:!1}),null;if(!await Yr(d))return t({error:"Not in a git repository",isLoading:!1}),null;const m=fl(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(w=>w.trim().length>0)??[],g=new Map;for(const w of o){const k=`${w.providerID}:${w.modelID}`;g.set(k,(g.get(k)||0)+1)}const b=new Map;for(const w of o){const k=`${w.providerID}:${w.modelID}`,A=g.get(k)||1,j=(b.get(k)||0)+1;b.set(k,j);const M=av(w.providerID,w.modelID),C=A>1?Md(m,`${M}/${j}`):Md(m,M);if(!C)return t({error:"Branch name is required for worktree creation",isLoading:!1}),null;const I=iv(C);if(!I)return t({error:`Invalid branch name: ${C}`,isLoading:!1}),null;try{const E=await Bl({projectDirectory:d,worktreeSlug:I,branch:C,createBranch:!0,startPoint:p}),P=A>1?`${m}/${w.providerID}/${w.modelID}/${j}`:`${m}/${w.providerID}/${w.modelID}`,D=await Fe.withDirectory(E.path,()=>Fe.createSession({title:P}));ft.getState().setWorktreeMetadata(D.id,E),h.push({sessionId:D.id,worktreePath:E.path,providerID:w.providerID,modelID:w.modelID,variant:w.variant})}catch(E){console.warn("[MultiRun] Failed to create session:",E)}}const y=c?.filter(w=>w.trim().length>0)??[];y.length>0&&Ym(d,y).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const v=h.map(w=>w.sessionId),S=h[0]?.sessionId??null;if(v.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const N=l?.map(w=>({type:"file",mime:w.mime,filename:w.filename,url:w.url}));try{await ft.getState().loadSessions()}catch{}if(x.length>0)for(const w of h)zl(w.worktreePath,d,x).then(k=>{if(!k.success){const A=k.results.filter(j=>!j.success);console.warn(`[MultiRun] Setup commands failed for ${w.worktreePath}:`,A)}}).catch(k=>{console.warn(`[MultiRun] Setup commands error for ${w.worktreePath}:`,k)});return(async()=>{try{await Promise.allSettled(h.map(async w=>{try{await Fe.withDirectory(w.worktreePath,()=>Fe.sendMessage({id:w.sessionId,providerID:w.providerID,modelID:w.modelID,variant:w.variant,text:n,agent:a,files:N}))}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}catch(w){console.warn("[MultiRun] Failed to start runs:",w)}})(),t({isLoading:!1}),{groupSlug:m,sessionIds:v,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 Ls({...t}){return e.jsx(zh,{"data-slot":"select",...t})}function cn({...t}){return e.jsx(Kh,{"data-slot":"select-group",...t})}function pn({...t}){return e.jsx(Uh,{"data-slot":"select-value",...t})}function Os({className:t,size:r="default",children:s,...n}){return e.jsxs(Wh,{"data-slot":"select-trigger","data-size":r,className:F("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(Hh,{asChild:!0,children:e.jsx(Ot,{className:"size-4 opacity-50"})})]})}function _s({className:t,children:r,position:s="popper",fitContent:n=!1,...o}){return e.jsx(Vh,{children:e.jsx(Gh,{"data-slot":"select-content",className:F("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(gt,{as:qh,outerClassName:F("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:F("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 Rn({className:t,...r}){return e.jsx(Qh,{"data-slot":"select-label",className:F("text-muted-foreground px-2 py-1.5 typography-meta",t),...r})}function rs({className:t,children:r,...s}){return e.jsxs(Yh,{"data-slot":"select-item",className:F("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(Xh,{children:e.jsx(Gt,{className:"size-4"})})}),e.jsx(Jh,{children:r})]})}function Pa({className:t,...r}){return e.jsx(Zh,{"data-slot":"select-separator",className:F("bg-border pointer-events-none -mx-1 my-1 h-px",t),...r})}const cv="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",dv=Object.assign({"../assets/provider-logos/gocode.svg":cv}),pl=new Map;for(const[t,r]of Object.entries(dv)){const s=t.match(/provider-logos\/([^/]+)\.svg$/i);s?.[1]&&r&&pl.set(s[1].toLowerCase(),r)}function Ef(t){const r=t?.toLowerCase()??null,s=r?pl.has(r):!1,n=r?pl.get(r)??null:null,[o,a]=Te.useState(s?"local":"remote");Te.useEffect(()=>{a(s?"local":"remote")},[s,r]);const l=Te.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 ws=({providerId:t,alt:r,className:s,onError:n})=>{const{src:o,onError:a,hasLogo:l}=Ef(t),c=i.useCallback(()=>{a(),n?.()},[a,n]);return!l||!o?null:e.jsx("img",{src:o,alt:r||`${t} logo`,className:F("dark:invert",s),onError:c})},nc=t=>t.nativeEvent.isComposing||t.nativeEvent.keyCode===229,oc=()=>{const{providers:t}=at(),{favoriteModels:r,recentModels:s}=Ce(),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}},If="h-7",Ta=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,uv=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),mv=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=uv.format(t);return r.endsWith(".0")?r.slice(0,-2):r},fv=({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:F("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",If),children:[e.jsx(ws,{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(Zt,{className:"h-3.5 w-3.5"})})]})},Pf=({selectedModels:t,onAdd:r,onRemove:s,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:l=!0,maxModels:c})=>{const{providers:d,modelsMetadata:u}=at(),{favoriteModelsList:m,recentModelsList:f}=oc(),[p,h]=i.useState(!1),[x,g]=i.useState(""),[b,y]=i.useState(0),[v,S]=i.useState(null),N=i.useRef(null),w=i.useRef(null),k=i.useRef(null),A=i.useRef([]),j=i.useMemo(()=>{const G=new Map;for(const O of t){const Y=`${O.providerID}:${O.modelID}`;G.set(Y,(G.get(Y)||0)+1)}return G},[t]),M=i.useCallback(G=>t.filter(Y=>Y.providerID===G.providerID&&Y.modelID===G.modelID).findIndex(Y=>Y.instanceId===G.instanceId)+1,[t]),C=(G,O)=>{const Y=`${G}/${O}`;return u.get(Y)},I=G=>{const O=G?.name||G?.id||"",Y=String(O);return Y.length>40?Y.substring(0,37)+"...":Y},E=i.useCallback((G,O)=>{if(!x.trim())return!0;const Y=x.toLowerCase();return G.toLowerCase().includes(Y)||O.toLowerCase().includes(Y)},[x]),P=i.useMemo(()=>m.filter(({model:G,providerID:O})=>{const K=d.find(Q=>Q.id===O)?.name||O,U=I(G);return E(U,K)}),[m,d,E]),D=i.useMemo(()=>f.filter(({model:G,providerID:O})=>{const K=d.find(Q=>Q.id===O)?.name||O,U=I(G);return E(U,K)}),[f,d,E]),T=i.useMemo(()=>d.map(G=>{const Y=(Array.isArray(G.models)?G.models:[]).filter(K=>{const U=I(K);return E(U,G.name||G.id||"")});return{...G,models:Y}}).filter(G=>G.models.length>0),[d,E]),R=P.length>0||D.length>0||T.length>0;i.useEffect(()=>{if(p&&k.current){const O=k.current.getBoundingClientRect().top-100;S(Math.max(150,Math.min(400,O)))}},[p]),i.useEffect(()=>{p&&N.current&&N.current.focus()},[p]),i.useEffect(()=>{if(!p)return;const G=O=>{w.current&&!w.current.contains(O.target)&&(h(!1),g(""),y(0))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[p]),i.useEffect(()=>{y(0)},[x]);const V=(G,O,Y,K,U,Q)=>{const W=`${O}:${Y}`,se=j.get(W)||0,ee=C(O,Y),pe=mv(ee?.limit?.context);return e.jsxs("button",{ref:$=>{A.current[U]=$},type:"button",onClick:()=>{r({providerID:O,modelID:Y,displayName:G.name||Y,instanceId:Ta()})},onMouseEnter:()=>y(U),className:F("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",Q?"bg-accent":"hover:bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:I(G)}),pe&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:pe})]}),se>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",se]})]},`${K}-${W}`)};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:w,children:[e.jsxs(De,{ref:k,type:"button",variant:"outline",size:"sm",className:If,onClick:()=>h(!p),children:[e.jsx(is,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const G=[];P.forEach(({model:U,providerID:Q,modelID:W})=>{G.push({model:U,providerID:Q,modelID:W,section:"fav"})}),D.forEach(({model:U,providerID:Q,modelID:W})=>{G.push({model:U,providerID:Q,modelID:W,section:"recent"})}),T.forEach(U=>{U.models.forEach(Q=>{G.push({model:Q,providerID:U.id,modelID:Q.id,section:"provider"})})});const O=G.length,Y=U=>{if(!nc(U))if(U.key==="ArrowDown"){U.preventDefault(),U.stopPropagation();const Q=(b+1)%Math.max(1,O);y(Q),setTimeout(()=>{A.current[Q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(U.key==="ArrowUp"){U.preventDefault(),U.stopPropagation();const Q=(b-1+Math.max(1,O))%Math.max(1,O);y(Q),setTimeout(()=>{A.current[Q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(U.key==="Enter"){U.preventDefault(),U.stopPropagation();const Q=G[b];Q&&r({providerID:Q.providerID,modelID:Q.modelID,displayName:Q.model.name||Q.modelID,instanceId:Ta()})}else U.key==="Escape"&&(U.preventDefault(),U.stopPropagation(),h(!1),g(""),y(0))};let K=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(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{ref:N,type:"text",placeholder:"Search models",value:x,onChange:U=>g(U.target.value),onKeyDown:Y,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(gt,{outerClassName:"flex-1",style:{maxHeight:v?`${v}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!R&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),P.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(Cr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),P.map(({model:U,providerID:Q,modelID:W})=>{const se=K++;return V(U,Q,W,"fav",se,b===se)})]}),D.length>0&&e.jsxs(e.Fragment,{children:[P.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(br,{className:"h-4 w-4"}),"Recent"]}),D.map(({model:U,providerID:Q,modelID:W})=>{const se=K++;return V(U,Q,W,"recent",se,b===se)})]}),(P.length>0||D.length>0)&&T.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),T.map((U,Q)=>e.jsxs(i.Fragment,{children:[Q>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(ws,{providerId:U.id,className:"h-4 w-4 flex-shrink-0"}),U.name]}),U.models.map(W=>{const se=K++;return V(W,U.id,W.id,"provider",se,b===se)})]},U.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((G,O)=>{const Y=`${G.providerID}:${G.modelID}`,K=j.get(Y)||1,U=M(G),W=d.find(oe=>oe.id===G.providerID)?.models.find(oe=>oe.id===G.modelID),se=W?.variants?Object.keys(W.variants):[],ee=se.length>0,pe="__default__",$=G.variant??pe;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(fv,{model:G,instanceIndex:U,totalSameModel:K,onRemove:()=>s(O)}),ee&&e.jsxs(Ls,{value:$,onValueChange:oe=>{if(!n)return;n(O,{...G,variant:oe===pe?void 0:oe})},children:[e.jsxs(Os,{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(wr,{className:F("h-3.5 w-3.5 flex-shrink-0",$===pe?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(pn,{placeholder:"Thinking"})]}),e.jsxs(_s,{fitContent:!0,children:[e.jsx(rs,{value:pe,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),se.map(oe=>e.jsx(rs,{value:oe,className:"pr-2 [&>span:first-child]:hidden",children:oe},oe))]})]})]},G.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 ac(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 Yr(t);if(c)return;if(l(d),!d){s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await qa(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 Tf=({directory:t,value:r,onChange:s,className:n,disabled:o,id:a})=>{const{branches:l,isLoading:c,isGitRepository:d}=ac(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(Ls,{value:r,onValueChange:s,disabled:m,children:[e.jsx(Os,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(pn,{children:u}):e.jsx(pn,{placeholder:c?"Loading branches…":"Select a branch"})}),e.jsxs(_s,{fitContent:!0,children:[e.jsxs(cn,{children:[e.jsx(Rn,{children:"Default"}),l.filter(f=>f.group==="special").map(f=>e.jsx(rs,{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(Pa,{}),e.jsxs(cn,{children:[e.jsx(Rn,{children:"Local branches"}),l.filter(f=>f.group==="local").map(f=>e.jsx(rs,{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(Pa,{}),e.jsxs(cn,{children:[e.jsx(Rn,{children:"Remote branches"}),l.filter(f=>f.group==="remote").map(f=>e.jsx(rs,{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."})]})},Ff=({value:t,onChange:r,className:s,disabled:n,id:o})=>{const a=at(f=>f.getVisibleAgents),l=at(f=>f.loadAgents),c=at(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(Ls,{value:m,onValueChange:r,disabled:n,children:[e.jsx(Os,{id:o,size:"lg",className:s??"max-w-full typography-meta text-foreground",children:e.jsx(pn,{placeholder:"Select an agent"})}),e.jsx(_s,{fitContent:!0,children:u.length>0&&e.jsx(cn,{children:u.map(f=>e.jsx(rs,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},pv=10*1024*1024,Dd=5,Ad=({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,v]=i.useState(!1),[S,N]=i.useState(!1),w=i.useRef(null),k=bt(_=>_.currentDirectory??null),A=i.useMemo(()=>{if(typeof window>"u")return null;const _=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof _=="string"&&_.trim().length>0?_.trim():null},[]),j=Vt(_=>_.activeProjectId),M=Vt(_=>_.projects),C=i.useMemo(()=>{if(j){const ge=M.find(H=>H.id===j);if(ge?.path)return ge.path}const _=k??A;if(!_)return null;const z=_.replace(/\\/g,"/").replace(/\/+$/,"")||_,re=z.indexOf("/.openchamber/");return re>0?z.slice(0,re):z.endsWith("/.openchamber")?z.slice(0,z.length-13):z},[j,M,k,A]),I=Ce(_=>_.isSidebarOpen),[E,P]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),D=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const _=typeof window.opencodeDesktop<"u";P(_)},[]);const T=i.useMemo(()=>E&&D?I?"pl-0":"pl-[8.0rem]":"pl-3",[E,D,I]),[R,V]=i.useState("HEAD"),{isLoading:G,isGitRepository:O}=ac(k),Y=fo(_=>_.createMultiRun),K=fo(_=>_.error),U=fo(_=>_.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&l(_=>_.trim().length>0?_:t)},[t]),i.useEffect(()=>{if(!C)return;let _=!1;return N(!0),(async()=>{try{const z=await Qn(C);_||b(z)}catch{}finally{_||N(!1)}})(),()=>{_=!0}},[C]);const Q=_=>{c.length>=Dd||(d(z=>[...z,_]),U())},W=_=>{d(z=>z.filter((X,re)=>re!==_)),U()},se=i.useCallback((_,z)=>{d(X=>X.map((re,ge)=>ge===_?z:re))},[]),ee=async _=>{const z=_.target.files;if(!z)return;let X=0;for(let re=0;re<z.length;re++){const ge=z[re];if(ge.size>pv){q.error(`File "${ge.name}" is too large (max 10MB)`);continue}try{const H=await new Promise((we,he)=>{const _e=new FileReader;_e.onload=()=>we(_e.result),_e.onerror=he,_e.readAsDataURL(ge)}),fe={id:Ta(),filename:ge.name,mimeType:ge.type||"application/octet-stream",size:ge.size,dataUrl:H};p(we=>[...we,fe]),X++}catch(H){console.error("File attach failed",H),q.error(`Failed to attach "${ge.name}"`)}}X>0&&q.success(`Attached ${X} file${X>1?"s":""}`),w.current&&(w.current.value="")},pe=_=>{p(z=>z.filter(X=>X.id!==_))},$=async _=>{if(_.preventDefault(),!!a.trim()&&!(c.length<2)){x(!0),U();try{const z=c.map(({instanceId:fe,...we})=>we),X=f.map(fe=>({mime:fe.mimeType,filename:fe.filename,url:fe.dataUrl})),re=g.filter(fe=>fe.trim().length>0),ge={name:n.trim(),prompt:a.trim(),models:z,agent:u||void 0,worktreeBaseBranch:R,files:X.length>0?X:void 0,setupCommands:re.length>0?re:void 0},H=await Y(ge);H&&(H.firstSessionId&&me.getState().setCurrentSession(H.firstSessionId),r?.())}finally{x(!1)}}},oe=!!(n.trim()&&a.trim()&&c.length>=2&&O&&!G);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:F("flex h-12 items-center justify-between border-b app-region-drag",T),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:F("flex items-center gap-3",E&&D&&I&&"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(lt,{delayDuration:500,children:[e.jsx(ct,{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(Zt,{className:"h-5 w-5"})})}),e.jsx(it,{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:$,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(jt,{id:"group-name",value:n,onChange:_=>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(Tf,{directory:k,value:R,onChange:V,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:R||"HEAD"}),"."]})]}),e.jsxs(No,{open:y,onOpenChange:v,children:[e.jsxs(Qa,{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(_=>_.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",g.filter(_=>_.trim()).length," configured)"]})]}),e.jsx(Ot,{className:F("h-4 w-4 text-muted-foreground transition-transform duration-200",y&&"rotate-180")})]}),e.jsx(Co,{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((_,z)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:_,onChange:X=>{const re=[...g];re[z]=X.target.value,b(re)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const X=g.filter((re,ge)=>ge!==z);b(X)},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(Zt,{className:"h-4 w-4"})})]},z)),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(is,{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(Ff,{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:_=>l(_.target.value),placeholder:"Enter the prompt to send to all models...",className:"typography-body min-h-[120px] max-h-[400px] resize-none overflow-y-auto field-sizing-content",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Attachments"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"(optional, same files for all runs)"})]}),e.jsx("input",{ref:w,type:"file",multiple:!0,className:"hidden",onChange:ee,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(De,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>w.current?.click(),children:[e.jsx(xa,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.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(vr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(hr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:_.filename,children:_.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",_.size<1024?`${_.size}B`:_.size<1024*1024?`${(_.size/1024).toFixed(1)}KB`:`${(_.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>pe(_.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Zt,{className:"h-3.5 w-3.5"})})]},_.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(Pf,{selectedModels:c,onAdd:Q,onRemove:W,onUpdate:se,minModels:2,maxModels:Dd})]}),K&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:K}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(De,{type:"button",variant:"outline",onClick:s,children:"Cancel"}),e.jsx(De,{type:"submit",disabled:!oe||h,children:h?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(eg,{className:"h-4 w-4 mr-2"}),"Start (",c.length," models)"]})})]})]})})})]})},hv=(t={})=>{const{edgeThreshold:r=30,minSwipeDistance:s=50,maxSwipeTime:n=300,enabled:o=!0}=t,{isMobile:a,setSessionSwitcherOpen:l,isSessionSwitcherOpen:c}=Ce(),d=Te.useRef(null),u=Te.useRef(null);return Te.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:v}=d.current,{x:S,y:N,time:w}=u.current,k=S-b,A=N-y,j=w-v,M=Math.abs(A)<Math.abs(k),C=j<=n,I=Math.abs(A)<s;k>=s&&M&&C&&I&&!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},oo=t=>t==="full"?{text:"var(--status-info)",border:"var(--status-info-border)",background:"var(--status-info-background)",borderWidth:1.5}:t==="allow"?{text:"var(--status-success)",border:"var(--status-success-border)",background:"var(--status-success-background)",borderWidth:1.5}:null;Te.memo(()=>{const t=Te.useRef(null),{addAttachedFile:r}=me(),{isMobile:s}=Ce(),n=mf(),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=me.getState().attachedFiles.length;try{await r(p),me.getState().attachedFiles.length>h&&m++}catch(x){console.error("File attach failed",x),q.error(x instanceof Error?x.message:"Failed to attach file")}}m>0&&q.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(`
85
- `);q.error(`Some files were skipped:
86
- ${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 v=atob(b),S=new Uint8Array(v.length);for(let w=0;w<v.length;w++)S[w]=v.charCodeAt(w);const N=new Blob([S],{type:y});return new File([N],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),q.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:F(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(xa,{className:F(a,"text-current")})})]})});const gv=Te.memo(({file:t,onRemove:r})=>{const s=()=>t.mimeType.startsWith("image/")?e.jsx(vr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("text")||t.mimeType.includes("code")?e.jsx(hr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("json")||t.mimeType.includes("xml")?e.jsx($a,{className:"h-3.5 w-3.5"}):e.jsx(hr,{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:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[e.jsx("div",{title:t.source==="server"?"Server file":"Local file",children:t.source==="server"?e.jsx(tg,{className:"h-3 w-3 text-primary"}):e.jsx(nm,{className:"h-3 w-3 text-muted-foreground"})}),s(),e.jsx("div",{className:"overflow-hidden max-w-[200px]",children:e.jsx("span",{className:"marquee-text",title:t.serverPath||a,children:a})}),e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["(",n(t.size),")"]}),e.jsx("button",{onClick:r,className:"ml-1 hover:text-destructive p-0.5",title:"Remove file",children:e.jsx(Zt,{className:"h-3 w-3"})})]})}),xv=Te.memo(()=>{const{attachedFiles:t,removeAttachedFile:r}=me();return t.length===0?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:"Attached:"}),t.map(s=>e.jsx(gv,{file:s,onRemove:()=>r(s.id)},s.id))]})})}),Rf=Te.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(vr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(hr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx($a,{className:"h-3.5 w-3.5"}):e.jsx(hr,{className:"h-3.5 w-3.5"}):e.jsx(hr,{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:"marquee-text",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(lt,{delayDuration:1e3,children:[e.jsx(ct,{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(vr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(it,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Lf=Te.memo(({message:t,sessionId:r,onEdit:s})=>{const n=pr(l=>l.removeFromQueue),o=i.useMemo(()=>{const l=t.content.split(`
87
- `),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(sg,{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(Zt,{className:"h-3 w-3"})})]})});Lf.displayName="QueuedMessageChip";const Ed=[],Of=Te.memo(({onEditMessage:t})=>{const r=me(a=>a.currentSessionId),s=pr(i.useCallback(a=>r?a.queuedMessages[r]??Ed:Ed,[r])),n=pr(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=ar.getState().attachedFiles;ar.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(Lf,{message:a,sessionId:r,onEdit:o},a.id))]})})});Of.displayName="QueuedMessageChips";const _f="filesViewShowGitignored",hl="files-view-show-gitignored-change",Id=()=>{if(typeof window>"u")return!1;try{return hs().getItem(_f)==="true"}catch{return!1}},yv=()=>{typeof window>"u"||window.dispatchEvent(new Event(hl))},bv=t=>{if(!(typeof window>"u"))try{hs().setItem(_f,t?"true":"false"),yv()}catch{}},ei=()=>{const[t,r]=i.useState(Id);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(Id())};return window.addEventListener("storage",s),window.addEventListener(hl,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(hl,s)}},[]),t},wv=i.forwardRef(({searchQuery:t,onFileSelect:r,onClose:s},n)=>{const{currentDirectory:o}=bt(),{addServerFile:a}=me(),l=Va(P=>P.searchFiles),c=Za(t,180),d=Mo(),u=ei(),[m,f]=i.useState([]),[p,h]=i.useState(!1),[x,g]=i.useState(0),[b,y]=i.useState(360),[v,S]=i.useState({}),[N,w]=i.useState({}),k=i.useRef([]),A=i.useRef([]),j=i.useRef([]),M=i.useRef(null),C=i.useCallback((P,D)=>{const T=P.trim().toLowerCase();if(!T)return 0;const R=D.toLowerCase();let V=0,G=-1,O=0;for(let Y=0;Y<T.length;Y+=1){const K=T[Y];if(!K||K===" ")continue;const U=R.indexOf(K,G+1);if(U===-1)return null;const Q=U-G-1;if(Q===0?O+=1:O=0,V+=10,V+=Math.max(0,18-U),V-=Math.max(0,Q),U===0)V+=12;else{const W=R[U-1];(W==="/"||W==="_"||W==="-"||W==="."||W===" ")&&(V+=10)}V+=O>0?12:0,G=U}return V+=Math.max(0,24-Math.round(R.length/3)),V},[]);i.useEffect(()=>{const P=D=>{const T=D.target;!T||!M.current||M.current.contains(T)||s()};return document.addEventListener("pointerdown",P,!0),()=>{document.removeEventListener("pointerdown",P,!0)}},[s]),i.useEffect(()=>{if(!o){f([]);return}const D=(c??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();let T=!1;return h(!0),l(o,D,80,{includeHidden:d,respectGitignore:!u}).then(R=>{if(T)return;const V=D?R.map(G=>{const O=G.relativePath||G.name||G.path,Y=C(D,O);return Y===null?null:{file:G,score:Y,labelLength:O.length}}).filter(Boolean):R.map(G=>({file:G,score:0,labelLength:(G.relativePath||G.name||G.path).length}));V.sort((G,O)=>O.score-G.score||G.labelLength-O.labelLength||G.file.path.localeCompare(O.file.path)),f(V.slice(0,15).map(G=>G.file))}).catch(()=>{T||f([])}).finally(()=>{T||h(!1)}),()=>{T=!0}},[o,c,C,l,d,u]),i.useEffect(()=>{g(0),S({}),w({})},[m]),i.useEffect(()=>{k.current[x]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[x]),i.useEffect(()=>{let P=null;const D=()=>{P!==null&&cancelAnimationFrame(P),P=requestAnimationFrame(()=>{const T={},R={};A.current.forEach((V,G)=>{if(!V)return;const Y=j.current[G]?.offsetWidth??V.scrollWidth,K=Math.max(0,Y-V.clientWidth),U=K>8;if(T[G]=U,U){const Q=Math.max(.6,K/110);R[G]=Q}}),S(T),w(R)})};return D(),window.addEventListener("resize",D),()=>{P!==null&&cancelAnimationFrame(P),window.removeEventListener("resize",D)}},[m]),i.useEffect(()=>{const P=A.current[x];if(!P)return;const D=()=>{const R=P.clientWidth;R>0&&y(R)};if(D(),typeof ResizeObserver>"u")return;const T=new ResizeObserver(D);return T.observe(P),()=>{T.disconnect()}},[x]);const I=i.useCallback(async P=>{await a(P.path,P.name),r(P)},[a,r]);i.useImperativeHandle(n,()=>({handleKeyDown:P=>{if(P==="Escape"){s();return}const D=m.length;if(D!==0){if(P==="ArrowDown"){g(T=>(T+1)%D);return}if(P==="ArrowUp"){g(T=>(T-1+D)%D);return}if(P==="Enter"||P==="Tab"){const T=(x%D+D)%D,R=m[T];R&&I(R)}}}}),[m,x,s,I]);const E=P=>{switch(P.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(hr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(vr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx($a,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:M,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(gt,{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(Wr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[m.map((P,D)=>{const T=P.relativePath||P.name,R=Am(T,{maxLength:45}),V=x===D,G=v[D]??!1,O=N[D]??2.6,Y=e.jsxs("div",{ref:K=>{k.current[D]=K},className:F("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",V&&"bg-muted"),onClick:()=>I(P),onMouseEnter:()=>g(D),children:[E(P),e.jsxs("span",{ref:K=>{A.current[D]=K},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:V?{"--file-mention-marquee-width":`${b}px`,"--file-mention-marquee-duration":`${O}s`}:void 0,"aria-label":T,children:[e.jsx("span",{ref:K=>{j.current[D]=K},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:T}),G&&V?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:T}):e.jsx("span",{className:"block truncate",children:R})]})]});return e.jsx(i.Fragment,{children:Y},P.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"})]})}),$f=i.forwardRef(({searchQuery:t,onCommandSelect:r,onClose:s},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=me(Il(v=>{const S=v.currentSessionId;return{hasMessagesInCurrentSession:(S?v.messages.get(S)?.length??0:0)>0,currentSessionId:S}})),l=!!a,[c,d]=i.useState([]),[u,m]=i.useState(!1),{commands:f,loadCommands:p}=Kr(),[h,x]=i.useState(0),g=i.useRef([]),b=i.useRef(null);i.useEffect(()=>{const v=S=>{const N=S.target;!N||!b.current||b.current.contains(N)||s()};return document.addEventListener("pointerdown",v,!0),()=>{document.removeEventListener("pointerdown",v,!0)}},[s]),i.useEffect(()=>{p()},[p]),i.useEffect(()=>{(async()=>{m(!0);try{const S=f.map(M=>({name:M.name,description:M.description,agent:M.agent??void 0,model:M.model??void 0,isBuiltIn:M.name==="init"||M.name==="review",scope:M.scope})),N=[...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}],w=new Map;N.forEach(M=>w.set(M.name,M)),S.forEach(M=>w.set(M.name,M));const k=Array.from(w.values()),A=!o,j=(t?k.filter(M=>Gs(M.name,t)||M.description&&Gs(M.description,t)):k).filter(M=>A||M.name!=="init");j.sort((M,C)=>{const I=M.name.toLowerCase().startsWith(t.toLowerCase()),E=C.name.toLowerCase().startsWith(t.toLowerCase());return I&&!E?-1:!I&&E?1:M.name.localeCompare(C.name)}),d(j)}catch{const S=!o,N=[...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}],w=(t?N.filter(k=>Gs(k.name,t)||k.description&&Gs(k.description,t)):N).filter(k=>S||k.name!=="init");d(w)}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:v=>{const S=c.length;if(v==="Escape"){s();return}if(S!==0){if(v==="ArrowDown"){x(N=>(N+1)%S);return}if(v==="ArrowUp"){x(N=>(N-1+S)%S);return}if(v==="Enter"||v==="Tab"){const N=(h%S+S)%S,w=c[N];w&&r(w)}}}}),[c,h,s,r]);const y=v=>{switch(v.name){case"init":return e.jsx(hr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(On,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(og,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(br,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(ng,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Vr,{className:"h-3.5 w-3.5 text-cyan-500"});default:return v.isBuiltIn?e.jsx(rg,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(gn,{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(gt,{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(Wr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[c.map((v,S)=>{const N=v.isBuiltIn,w=v.scope==="project";return e.jsxs("div",{ref:k=>{g.current[S]=k},className:F("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",S===h&&"bg-muted"),onClick:()=>r(v),onMouseEnter:()=>x(S),children:[e.jsx("div",{className:"mt-0.5",children:y(v)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-medium",children:["/",v.name]}),N?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):v.scope?e.jsx("span",{className:F("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",w?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:v.scope}):null,v.agent&&e.jsx("span",{className:"text-[10px] leading-none font-bold tracking-tight bg-[var(--surface-subtle)] text-[var(--surface-foreground)] border-[var(--interactive-border)] px-1.5 py-1 rounded border flex-shrink-0",children:v.agent})]}),v.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:v.description})]})]},v.name)}),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"})]})});$f.displayName="CommandAutocomplete";const vv=t=>t?t!=="primary":!1,Bf=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}=at(),{agents:f,loadAgents:p}=Qr();i.useEffect(()=>{f.length===0&&p()},[p,f.length]),i.useEffect(()=>{const g=m().filter(v=>vv(v.mode)).map(v=>{const S=f.find(N=>N.name===v.name);return{name:v.name,description:v.description,mode:v.mode??void 0,scope:S?.scope,isBuiltIn:S?sn(S):!1}}),b=t.trim(),y=b.length?g.filter(v=>Gs(v.name,b)):g;y.sort((v,S)=>v.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:v=>{u.current[g]=v},className:F("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:F("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(gt,{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"})]})});Bf.displayName="AgentMentionAutocomplete";const zf=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}=or();i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const h=t.trim(),g=[...h.length?m.filter(b=>Gs(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:F("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:F("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(gt,{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"})]})});zf.displayName="SkillAutocomplete";function jv({className:t,children:r,...s}){return e.jsxs(ag,{"data-slot":"scroll-area",className:F("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(Sv,{}),e.jsx(lg,{})]})}function Sv({className:t,orientation:r="vertical",...s}){return e.jsx(cg,{"data-slot":"scroll-area-scrollbar",orientation:r,className:F("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(dg,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const kv=({onFilesSelected:t,multiSelect:r=!1,children:s,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:l}=Qt(),c=l,{currentDirectory:d}=bt(),u=Va(Z=>Z.searchFiles),m=Mo(),f=ei(),[p,h]=i.useState(!1),[x,g]=i.useState(0),[b,y]=i.useState(!1),[v,S]=i.useState(""),N=Za(v,200),[w,k]=i.useState(new Set),[A,j]=i.useState(new Set),[M,C]=i.useState({}),I=i.useRef(new Set),E=i.useRef(new Set),[P,D]=i.useState([]),[T,R]=i.useState(!1),[V,G]=i.useState(!1),[O,Y]=i.useState(!1),[K,U]=i.useState(null),Q=n??p,W=o??h,se=i.useCallback(Z=>Z.slice().sort((ye,de)=>ye.type!==de.type?ye.type==="directory"?-1:1:ye.name.localeCompare(de.name)),[]),ee=i.useCallback((Z,ye)=>se(ye.filter(de=>m||!de.name.startsWith(".")).map(de=>{const je=de.name,ie=!de.isDirectory&&je.includes(".")?je.split(".").pop()?.toLowerCase():void 0;return{name:je,path:de.path||`${Z}/${je}`,type:de.isDirectory?"directory":"file",size:0,extension:ie}})),[se,m]),pe=i.useCallback(async Z=>{G(!0),U(null);try{const ye=await Fe.listLocalDirectory(Z,{respectGitignore:!f}),de=ee(Z,ye.map(je=>({name:je.name,path:je.path,isDirectory:je.isDirectory})));I.current=new Set([Z]),E.current=new Set,C({[Z]:de}),j(new Set)}catch{U("Failed to load directory contents"),I.current=new Set([Z]),E.current=new Set,C({[Z]:[]}),j(new Set)}finally{G(!1)}},[ee,f]),$=i.useCallback(async Z=>{const ye=Z.trim();if(!ye)return;const de=`${ye}::${x}`;if(!I.current.has(de)&&!E.current.has(de)){E.current=new Set(E.current),E.current.add(de);try{const je=await Fe.listLocalDirectory(ye,{respectGitignore:!f}),ie=ee(ye,je.map(Xe=>({name:Xe.name,path:Xe.path,isDirectory:Xe.isDirectory})));I.current=new Set(I.current),I.current.add(de),C(Xe=>({...Xe,[ye]:ie}))}catch{C(je=>je[ye]?je:{...je,[ye]:[]})}finally{E.current=new Set(E.current),E.current.delete(de)}}},[ee,f,x]);i.useEffect(()=>{(Q||b)&&d&&pe(d)},[Q,b,d,pe]),i.useEffect(()=>{g(Z=>Z+1)},[m,f]),i.useEffect(()=>{if(!(Q||b)||!d){D([]),R(!1);return}const Z=N.trim().replace(/^\.\//,"").replace(/^\/+/,"");if(!Z){D([]),R(!1);return}const ye=Z.toLowerCase();let de=!1;return R(!0),u(d,ye,150,{includeHidden:m,respectGitignore:!f}).then(je=>{if(de)return;const ie=je.map(Xe=>({name:Xe.name,path:Xe.path,type:"file",extension:Xe.extension,relativePath:Xe.relativePath,size:0}));D(ie)}).catch(()=>{de||D([])}).finally(()=>{de||R(!1)}),()=>{de=!0}},[Q,b,d,N,u,m,f]),i.useEffect(()=>{!Q&&!b&&(k(new Set),S(""),D([]),R(!1),I.current=new Set,E.current=new Set,C({}),j(new Set))},[Q,b]);const oe=Z=>{if(Z.type==="directory")return A.has(Z.path)?e.jsx(sr,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(sr,{className:"h-3.5 w-3.5 text-primary/60"});switch(Z.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(ho,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(vr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(ho,{className:"h-3.5 w-3.5 text-muted-foreground"})}},_=async Z=>{A.has(Z)?j(de=>{const je=new Set(de);return je.delete(Z),je}):(j(de=>{const je=new Set(de);return je.add(Z),je}),await $(Z))},z=Z=>{k(r?ye=>{const de=new Set(ye);return de.has(Z)?de.delete(Z):de.add(Z),de}:new Set([Z]))},X=async()=>{const Z=new Map;Object.values(M).forEach(je=>{je.forEach(ie=>{ie.type==="file"&&Z.set(ie.path,ie)})});const ye=new Map(P.map(je=>[je.path,je])),de=Array.from(w).map(je=>Z.get(je)??ye.get(je)).filter(je=>!!je);Y(!0);try{await t(de),k(new Set),W(!1),y(!1)}finally{Y(!1)}},re=i.useMemo(()=>d?M[d]??[]:[],[M,d]),ge=v.trim().length>0,H=Z=>M[Z]??[],fe=Z=>{if(d&&Z.startsWith(d)){const ye=Z.substring(d.length);return ye.startsWith("/")?ye.substring(1):ye}return Z.split("/").pop()||Z},we=(Z,ye)=>{const de=ge?Z.relativePath||fe(Z.path):Z.name,je=ge&&de.includes("/")&&de.length>45,ie=je?Am(de,{maxLength:c?42:48}):de,Xe=e.jsxs("div",{className:F("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",Z.type==="file"&&w.has(Z.path)&&"bg-primary/10"),style:{paddingLeft:`${ye*12}px`},onClick:mt=>{mt.preventDefault(),mt.stopPropagation(),Z.type==="file"&&z(Z.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:oe(Z)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":de,children:ie})]}),Z.type==="file"&&w.has(Z.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return je?e.jsxs(lt,{delayDuration:120,children:[e.jsx(ct,{asChild:!0,children:Xe}),e.jsx(it,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:de})})]},Z.path):i.cloneElement(Xe,{key:Z.path})},he=(Z,ye)=>{const de=Z.type==="directory",je=de?H(Z.path):[],ie=A.has(Z.path),Xe=de&&ie&&E.current.has(Z.path)&&je.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:F("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!de&&w.has(Z.path)&&"bg-primary/10"),style:{paddingLeft:`${ye*12}px`},onClick:mt=>{mt.preventDefault(),mt.stopPropagation(),de?_(Z.path):z(Z.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:oe(Z)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:Z.name}),!de&&w.has(Z.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),de&&ie&&je.length>0&&e.jsx("div",{children:je.map(mt=>he(mt,ye+1))}),de&&ie&&Xe&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(ye+1)*12}px`},children:"Loading…"})]},Z.path)},_e=w.size>0?`${w.size} file${w.size!==1?"s":""} selected`:"No files selected",te=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:_e}),e.jsx(De,{size:"sm",onClick:X,disabled:w.size===0||O,className:"h-6 typography-meta",children:O?"Attaching...":"Attach Files"})]}),J=c?"flex-1 min-h-[240px]":"h-[300px]",ne=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(lr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{value:v,onChange:Z=>S(Z.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:Z=>Z.stopPropagation()}),v&&e.jsx("button",{onClick:Z=>{Z.stopPropagation(),S("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(Zt,{className:"h-3 w-3"})})]})}),e.jsxs(jv,{className:J,children:[V&&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..."})}),K&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:K})}),!V&&!K&&e.jsxs("div",{className:"py-1 px-2",children:[ge?T?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):P.map(Z=>we(Z,0)):re.map(Z=>he(Z,0)),!ge&&re.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),ge&&!T&&P.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),ke=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),y(!0)},children:s});return a==="modal"?e.jsxs(e.Fragment,{children:[s?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),W(!0)},children:s}):null,e.jsx($s,{open:Q,onClose:()=>W(!1),title:"Select Project Files",footer:te,children:e.jsx("div",{className:"flex flex-col gap-0",children:ne})})]}):c?e.jsxs(e.Fragment,{children:[ke,e.jsx($s,{open:b,onClose:()=>y(!1),title:"Select Project Files",footer:te,children:e.jsx("div",{className:"flex flex-col gap-0",children:ne})})]}):e.jsxs(es,{open:Q,onOpenChange:W,children:[e.jsx(ts,{asChild:!0,children:s}),e.jsxs(ss,{className:F("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[ne,e.jsx(Ds,{}),te]})]})},Wo=[{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 Or(t){if(!t||t==="build")return Wo[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)%(Wo.length-1);return Wo[s]}const Nv=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Wf=t=>Nv(t),Cv=t=>t?typeof t=="string"?t==="ask":Wf(t)?Object.values(t).some(r=>r==="ask"):!1:!1,Mv=t=>t?typeof t=="string"?t==="deny":Wf(t)?Object.values(t).some(r=>r==="deny"):!1:!1,Hf=({agentDefaultEditMode:t,webfetchPermission:r,bashPermission:s})=>{const n=Cv(s),o=Mv(s),a=!n&&!o,l=r==="allow",c=r!=="deny",d=t==="allow"||t==="full",u=t==="ask";let m=t;d&&l&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:t!=="deny"&&c&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:l,webfetchNotDeny:c}},Ho=t=>t==="primary"||t==="all"||t===void 0||t===null,Fa=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},Uo=(t,r)=>{const s=Fa(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}}},Dv=(t,r)=>{const s=Fa(t);if(!s||s.length===0)return;const n={};for(const o of s)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},Av=[{key:"tool_call",icon:Ba,label:"Tool calling",isActive:t=>t?.tool_call===!0},{key:"reasoning",icon:wr,label:"Reasoning",isActive:t=>t?.reasoning===!0}],Ev={text:{icon:am,label:"Text"},image:{icon:vr,label:"Image"},video:{icon:mg,label:"Video"},audio:{icon:ug,label:"Audio"},pdf:{icon:$a,label:"PDF"}},Iv=t=>t.trim().toLowerCase(),to=(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=>Iv(o)))).map(o=>{const a=Ev[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Pv=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Tv=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Zs=t=>{if(typeof t!="number"||Number.isNaN(t))return"—";if(t===0)return"0";const r=Pv.format(t);return r.endsWith(".0")?r.slice(0,-2):r},Vo=t=>typeof t!="number"||!Number.isFinite(t)?"—":Tv.format(t),Mi=t=>Av.filter(r=>r.isActive(t)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Pd=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},Td=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)},Fd=({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}=at(),b=g(),{currentSessionId:y,messages:v,saveSessionAgentSelection:S,getSessionAgentSelection:N,saveAgentModelForSession:w,getAgentModelForSession:k,saveAgentModelVariantForSession:A,getAgentModelVariantForSession:j,analyzeAndSaveExternalSessionChoices:M,getSessionAgentEditMode:C,setSessionAgentEditMode:I}=me(),E=ht(L=>L.hasHydrated),{toggleFavoriteModel:P,isFavoriteModel:D,addRecentModel:T,isModelSelectorOpen:R,setModelSelectorOpen:V}=Ce(),{favoriteModelsList:G,recentModelsList:O}=oc(),{isMobile:Y}=Qt(),K=Jb(),U=mf(),Q=Y,[W,se]=i.useState(null),[ee,pe]=i.useState(null),[$,oe]=i.useState(""),_=i.useCallback(()=>se(null),[]),z=i.useCallback(()=>pe(null),[]),X=i.useRef(void 0),[re,ge]=i.useState(()=>{const L=new Set;return s&&L.add(s),L}),[H,fe]=i.useState(!1),we=R,he=V,[_e,te]=i.useState(!1),J=i.useId(),[ne,ke]=i.useState(""),[Z,ye]=i.useState(0),de=i.useRef([]);i.useEffect(()=>{W==="model"&&ge(()=>{const L=new Set;return s&&L.add(s),L})},[W,s]),i.useEffect(()=>{W!=="agent"&&fe(!1),W!=="model"&&oe("")},[W]);const je=i.useRef(we);i.useEffect(()=>{const L=je.current;je.current=we,we||(te(!1),ke(""),ye(0),L&&!Q&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[we,Q]),i.useEffect(()=>{ye(0)},[ne]);const ie=x?.(),Xe=i.useMemo(()=>ie?Uo(ie.permission,"edit")??"ask":"deny",[ie]),mt=i.useMemo(()=>{if(ie)return Uo(ie.permission,"webfetch")},[ie]),Ae=i.useMemo(()=>{if(!ie)return;const L=Dv(ie.permission,"bash");return L||void 0},[ie]),ae=i.useMemo(()=>Hf({agentDefaultEditMode:Xe,webfetchPermission:mt,bashPermission:Ae}),[Xe,mt,Ae]),{cascadeDefaultMode:Ue,modeAvailability:Se,autoApproveAvailable:Ne}=ae,Ge=!!(y&&a),rt=Ge&&y&&a?C(y,a,Ue):Ue,Ke={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},Le=i.useCallback(L=>!Se[L],[Se]),Ye=i.useMemo(()=>!Ge||Le(rt)&&rt!==Ue?Ue:rt,[Ue,Le,Ge,rt]),xt=[{mode:"ask",label:Ke.ask,disabled:Le("ask")},{mode:"allow",label:Ke.allow,disabled:Le("allow")},{mode:"full",label:Ke.full,disabled:Le("full")}],nt=i.useMemo(()=>oo(Ye),[Ye]),It=!Ge||!Ne;i.useEffect(()=>{It&&(fe(!1),te(!1))},[It]);const Pt=Y?"mobile":U?"vscode":"default",zt=Pt==="mobile"?"h-9":Pt==="vscode"?"h-6":"h-8",We=Pt==="mobile"?"h-5 w-5":"h-4 w-4",ut=Pt==="mobile"?"h-5 w-5":"h-4 w-4",vt=Q?"typography-micro":"typography-meta",dt=Pt==="mobile"||Pt==="vscode"?"gap-x-1":"gap-x-3",Tt=Ke[Ye],Ct=i.useCallback((L,ce=We)=>{const le=F(ce,"flex-shrink-0"),Re=oo(L),Qe={color:Re?Re.text:"var(--foreground)"};return L==="full"?e.jsx(Nr,{className:le,style:Qe}):L==="allow"?e.jsx(ea,{className:le,style:Qe}):L==="deny"?e.jsx(Ln,{className:le,style:Qe}):e.jsx(mn,{className:le,style:Qe})},[We]),os=i.useCallback(L=>{It||!y||!a||Le(L)||(I(y,a,L,Ue),he(!1),fe(!1),te(!1))},[Ue,It,y,a,I,he,te,Le]),St=p(),Lt=Array.isArray(St?.models)?St.models:[],Ft=s&&n?h(s,n):void 0,Ut=Mi(Ft),Rt=to(Ft,"input"),qt=to(Ft,"output"),be=i.useMemo(()=>`${s}/${n}`?m():[],[m,s,n]),Ee=be.length>0,B=[{label:"Input",value:Vo(Ft?.cost?.input)},{label:"Output",value:Vo(Ft?.cost?.output)},{label:"Cache read",value:Vo(Ft?.cost?.cache_read)},{label:"Cache write",value:Vo(Ft?.cost?.cache_write)}],ue=[{label:"Context",value:Zs(Ft?.limit?.context)},{label:"Output",value:Zs(Ft?.limit?.output)}],ve=i.useRef(void 0),Be=y?v.get(y)?.length??-1:-1,ze=i.useRef(null),tt=i.useCallback((L,ce,le)=>{if(!L||!ce)return"model-missing";const Re=r.find(Pe=>Pe.id===L);return Re?(Array.isArray(Re.models)?Re.models:[]).find(Pe=>Pe.id===ce)?(c(L),d(ce),y&&le&&w(y,le,L,ce),"applied"):"model-missing":"provider-missing"},[r,c,d,y,w]);i.useEffect(()=>{if(!y){ze.current=null;return}if(!E||r.length===0||b.length===0)return;(!ze.current||ze.current.sessionId!==y)&&(ze.current={sessionId:y,resolved:!1,inFlight:!1});const L=ze.current;if(!L||L.resolved||L.inFlight)return;let ce=!1;const le=()=>{if(ce)return;const Pe=ze.current;Pe&&Pe.sessionId===y&&(Pe.resolved=!0,Pe.inFlight=!1)},Re=()=>{const Pe=N(y);if(Pe){a!==Pe&&f(Pe);const Ve=k(y,Pe);if(Ve){const Oe=tt(Ve.providerId,Ve.modelId,Pe);if(Oe==="applied")return"resolved";if(Oe==="provider-missing")return"waiting"}else return"resolved"}for(const Ve of b){const Oe=k(y,Ve.name);if(!Oe)continue;a!==Ve.name&&f(Ve.name),S(y,Ve.name);const Je=tt(Oe.providerId,Oe.modelId,Ve.name);if(Je==="applied")return"resolved";if(Je==="provider-missing")return"waiting"}return"continue"},He=()=>{if(b.length===0)return;const Pe=b.filter(Oe=>Ho(Oe.mode)),Ve=b.find(Oe=>Oe.name==="build")||Pe[0]||b[0];Ve&&(S(y,Ve.name),a!==Ve.name&&f(Ve.name),Ve.model?.providerID&&Ve.model?.modelID&&tt(Ve.model.providerID,Ve.model.modelID,Ve.name))};return(async()=>{try{const Pe=Re();if(Pe==="resolved"){le();return}if(Pe==="waiting"||Be===-1)return;if(Be>0){L.inFlight=!0;try{const Ve=await M(y,b);if(ce)return;if(Ve.size>0){let Oe=null,Je=-1/0;for(const[yt,Dt]of Ve)Dt.timestamp>Je&&(Je=Dt.timestamp,Oe=yt);if(Oe){S(y,Oe),a!==Oe&&f(Oe);const yt=Ve.get(Oe);if(yt){const Dt=tt(yt.providerId,yt.modelId,Oe);if(Dt==="applied"){le();return}if(Dt==="provider-missing")return}else{le();return}}}}catch(Ve){ce||console.error("[ModelControls] Error resolving session from messages:",Ve)}finally{const Ve=ze.current;!ce&&Ve&&Ve.sessionId===y&&(Ve.inFlight=!1)}}He(),le()}catch(Pe){ce||console.error("[ModelControls] Error in session switch:",Pe)}})(),()=>{ce=!0}},[y,Be,b,a,N,k,f,tt,M,S,E,r]),i.useEffect(()=>{if(!E||!y||r.length===0||b.length===0)return;const ce=N(y)||a;if(!ce)return;const le=k(y,ce);if(!le)return;const Re=r.find(Ve=>Ve.id===le.providerId);if(!Re||!(Array.isArray(Re.models)?Re.models.some(Ve=>Ve.id===le.modelId):!1))return;const Qe=s===le.providerId,Pe=n===le.modelId;Qe&&Pe||(ce!==a&&f(ce),tt(le.providerId,le.modelId,ce))},[E,y,a,s,n,r,b,N,k,tt,f]),i.useEffect(()=>{if(!E)return;(async()=>{try{if(a!==ve.current&&(ve.current=a,a&&y)){await new Promise(Re=>setTimeout(Re,50));const ce=k(y,a);if(ce){const Re=tt(ce.providerId,ce.modelId,a);if(Re==="applied"||Re==="provider-missing")return}const le=b.find(Re=>Re.name===a);if(le?.model?.providerID&&le?.model?.modelID&&tt(le.model.providerID,le.model.modelID,a)==="provider-missing")return}}catch(ce){console.error("[ModelControls] Agent change error:",ce)}})()},[a,y,k,tt,b,E]),i.useEffect(()=>{if(!E||!a){u(void 0);return}if(!s||!n){u(void 0);return}if(be.length===0){u(void 0);return}if(o&&!be.includes(o)){u(void 0);return}if(!y){if(!o){const le=l&&be.includes(l)?l:void 0;u(le)}return}const L=j(y,a,s,n),ce=L&&be.includes(L)?L:void 0;u(ce)},[be,E,y,a,s,n,o,j,u,l]);const Me=i.useCallback(L=>{u(L),y&&a&&s&&n&&A(y,a,s,n,L)},[a,n,s,y,A,u]),qe=L=>{try{f(L),he(!1),y&&S(y,L),Q&&_()}catch(ce){console.error("[ModelControls] Handle agent change error:",ce)}},et=(L,ce)=>{try{const le=tt(L,ce,a||void 0);if(le!=="applied"){le==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",L):le==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:L,modelId:ce});return}T(L,ce),he(!1),Q&&_(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(le){console.error("[ModelControls] Handle model change error:",le)}},ot=L=>{const ce=typeof L?.name=="string"?L.name:typeof L?.id=="string"?L.id:"";return ce.length>40?ce.substring(0,37)+"...":ce},_t=()=>r.find(ce=>ce.id===s)?.name||s,$t=()=>{if(!s||!n||Lt.length===0)return"Not selected";const L=Lt.find(ce=>ce.id===n);return ot(L)},wt=()=>{if(!a){const ce=b.filter(He=>Ho(He.mode)),Re=ce.find(He=>He.name==="build")||ce[0];return Re?xe(Re.name):"Select Agent"}const L=b.find(ce=>ce.name===a);return xe(L?L.name:a)},xe=L=>L.charAt(0).toUpperCase()+L.slice(1),Ie=(L,ce,le)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:ce,"aria-label":ce,role:"img",children:e.jsx(L,{className:"h-3.5 w-3.5"})},le),st=i.useCallback(L=>{ge(ce=>{const le=new Set(ce);return le.has(L)?le.delete(L):le.add(L),le})},[]),$e=i.useCallback(L=>{X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{pe(L)},500)},[]),kt=i.useCallback(()=>{X.current&&clearTimeout(X.current)},[]);i.useEffect(()=>()=>{X.current&&clearTimeout(X.current)},[]);const Mt=()=>!Q||ee!=="model"?null:e.jsx($s,{open:!0,onClose:z,title:Ft?.name||$t(),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:_t()})]}),Ut.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:Ut.map(({key:L,icon:ce,label:le})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ie(ce,le,`cap-${L}`),e.jsx("span",{className:"typography-meta text-foreground",children:le})]},L))})]}),(Rt.length>0||qt.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:[Rt.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:Rt.map(({key:L,icon:ce,label:le})=>Ie(ce,`${le} input`,`input-${L}`))})]}),qt.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:qt.map(({key:L,icon:ce,label:le})=>Ie(ce,`${le} output`,`output-${L}`))})]})]})]}),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:Zs(Ft?.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:Zs(Ft?.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:Pd(Ft?.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:Td(Ft?.release_date)})]})]})]})]})}),Kt=()=>{if(!Q||ee!=="agent"||!ie)return null;const L=!!(ie.prompt&&ie.prompt.trim().length>0),ce=ie.model?.providerID&&ie.model?.modelID,le=ie.temperature!==void 0||ie.topP!==void 0,Re=Ve=>{const Oe=Fa(ie.permission)??[],Je=Oe.some(Dt=>Dt.permission===Ve&&Dt.pattern!=="*"),yt=Uo(Oe,Ve)??"ask";return Je?{mode:"ask",label:"Custom"}:yt==="allow"?{mode:"allow",label:"Allow"}:yt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},He=Re("edit"),Qe=Re("bash"),Pe=Re("webfetch");return e.jsx($s,{open:!0,onClose:z,title:xe(ie.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[ie.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:ie.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:ie.mode==="primary"?"Primary":ie.mode==="subagent"?"Subagent":ie.mode==="all"?"All":"—"})]}),(ce||le)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Model"}),ce&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[ie.model.providerID," / ",ie.model.modelID]}),le&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[ie.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:ie.temperature})]}),ie.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:ie.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:[Ct(He.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:He.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:[Ct(Qe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Qe.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:[Ct(Pe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Pe.label})]})]})]})]}),L&&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(ea,{className:"h-4 w-4 text-foreground"})]})})]})})},pt=()=>{if(!Q)return null;const L=$.trim(),ce=r.map(le=>{const Re=Array.isArray(le.models)?le.models:[],He=L.length===0?!0:Gs(le.name,L)||Gs(le.id,L),Qe=L.length===0?Re:Re.filter(Pe=>{const Ve=ot(Pe),Oe=typeof Pe.id=="string"?Pe.id:"";return Gs(Ve,L)||Gs(Oe,L)});return{provider:le,providerModels:Qe,matchesProvider:He}}).filter(({matchesProvider:le,providerModels:Re})=>le||Re.length>0);return e.jsx($s,{open:W==="model",onClose:_,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(lr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{value:$,onChange:le=>oe(le.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),$&&e.jsx("button",{type:"button",onClick:()=>oe(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Ln,{className:"h-4 w-4"})})]})}),ce.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."}),!$&&G.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(Cr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:G.map(({model:le,providerID:Re,modelID:He})=>{const Qe=Re===s&&He===n,Pe=h(Re,He);return e.jsxs("button",{type:"button",onClick:()=>et(Re,He),className:F("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",Qe?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ws,{providerId:Re,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:ot(le)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Pe?.limit?.context||Pe?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Pe?.limit?.context?`${Zs(Pe?.limit?.context)} ctx`:"",Pe?.limit?.context&&Pe?.limit?.output?" • ":"",Pe?.limit?.output?`${Zs(Pe?.limit?.output)} out`:""]})})]},`fav-mobile-${Re}-${He}`)})})]}),!$&&O.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(br,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:O.map(({model:le,providerID:Re,modelID:He})=>{const Qe=Re===s&&He===n,Pe=h(Re,He);return e.jsxs("button",{type:"button",onClick:()=>et(Re,He),className:F("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",Qe?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ws,{providerId:Re,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:ot(le)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Pe?.limit?.context||Pe?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Pe?.limit?.context?`${Zs(Pe?.limit?.context)} ctx`:"",Pe?.limit?.context&&Pe?.limit?.output?" • ":"",Pe?.limit?.output?`${Zs(Pe?.limit?.output)} out`:""]})})]},`recent-mobile-${Re}-${He}`)})})]}),ce.map(({provider:le,providerModels:Re})=>{if(Re.length===0&&!L.length)return null;const He=le.id===s,Qe=re.has(le.id)||L.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:()=>st(le.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Qe,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{providerId:le.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:le.name}),He&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Qe?e.jsx(Ot,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Bs,{className:"h-3 w-3 text-muted-foreground"})]}),Qe&&Re.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Re.map(Pe=>{const Ve=He&&Pe.id===n,Oe=h(le.id,Pe.id),Je=Mi(Oe).slice(0,3),yt=to(Oe,"input");return e.jsxs("div",{className:F("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",!Ve&&"hover:bg-muted",Ve?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>et(le.id,Pe.id),className:F("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:ot(Pe)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Oe?.limit?.context||Oe?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Oe?.limit?.context?e.jsxs("span",{children:[Zs(Oe?.limit?.context)," ctx"]}):null,Oe?.limit?.context&&Oe?.limit?.output?e.jsx("span",{children:"•"}):null,Oe?.limit?.output?e.jsxs("span",{children:[Zs(Oe?.limit?.output)," out"]}):null]}),(Je.length>0||yt.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Je,...yt].map(({key:Dt,icon:ks,label:Cs})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Cs,"aria-label":Cs,children:e.jsx(ks,{className:"h-3 w-3"})},`meta-${le.id}-${Pe.id}-${Dt}`))})]})]}),e.jsx("button",{type:"button",onClick:Dt=>{Dt.preventDefault(),Dt.stopPropagation(),P(le.id,Pe.id)},className:F("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",D(le.id,Pe.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":D(le.id,Pe.id)?"Unfavorite":"Favorite",title:D(le.id,Pe.id)?"Remove from favorites":"Add to favorites",children:D(le.id,Pe.id)?e.jsx(Cr,{className:"h-4 w-4"}):e.jsx(In,{className:"h-4 w-4"})})]},Pe.id)})})]},le.id)})]})})},Ss=()=>{if(!Q||!Ee)return null;const L=!o,ce=le=>{Me(le),_(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx($s,{open:W==="variant",onClose:_,title:"Thinking",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{type:"button",className:F("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",L?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ce(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),L&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),be.map(le=>{const Re=o===le,He=le.charAt(0).toUpperCase()+le.slice(1);return e.jsxs("button",{type:"button",className:F("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:()=>ce(le),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:He}),Re&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},le)})]})})},ms=()=>{if(!Q)return null;const L=b.filter(ce=>Ho(ce.mode));return e.jsx($s,{open:W==="agent",onClose:_,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[L.map(ce=>{const le=ce.name===a,Re=Or(ce.name);return e.jsxs("button",{type:"button",className:F("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",Re.class,le?"active":"border-border/40"),onClick:()=>qe(ce.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:F("h-2 w-2 rounded-full",Re.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:le?{color:`var(${Re.var})`}:void 0,children:xe(ce.name)})]}),ce.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:ce.description})]},ce.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:It,onClick:()=>{It||fe(ce=>!ce)},className:F("flex w-full items-center justify-between gap-2 px-2 py-1.5 text-left bg-transparent","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-t-xl",It?"cursor-not-allowed opacity-60":void 0),children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:nt?nt.text:"var(--foreground)",mixBlendMode:"normal"},children:Tt})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:F("flex items-center justify-center p-1",!nt&&"text-muted-foreground"),style:nt?{color:nt.text}:void 0,children:Ct(Ye,We)}),e.jsx(Ot,{className:F("h-4 w-4 text-muted-foreground transition-transform",H?"rotate-180":"")})]})]}),H&&!It&&e.jsx("div",{className:"border-t border-border/40 bg-transparent px-2 py-1.5",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:xt.map(ce=>{const le=ce.mode===Ye,Re=oo(ce.mode);return e.jsxs("button",{type:"button",disabled:ce.disabled,onClick:()=>os(ce.mode),className:F("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",ce.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",le?"bg-primary/10":void 0),style:le&&Re?{backgroundColor:Re.background??void 0}:void 0,children:[Ct(ce.mode,We),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:Re?Re.text:"var(--foreground)"},children:ce.label})})]},ce.mode)})})})]})]})})},Yt=()=>e.jsx(it,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ft?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:Ft.name||$t()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:_t()})]}),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:Ut.length>0?Ut.map(({key:L,icon:ce,label:le})=>Ie(ce,le,`cap-${L}`)):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:Rt.length>0?Rt.map(({key:L,icon:ce,label:le})=>Ie(ce,`${le} input`,`input-${L}`)):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:qt.length>0?qt.map(({key:L,icon:ce,label:le})=>Ie(ce,`${le} output`,`output-${L}`)):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)"}),B.map(L=>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:L.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:L.value})]},L.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"}),ue.map(L=>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:L.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:L.value})]},L.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:Pd(Ft.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:Td(Ft.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),Vs=(L,ce,le,Re,He,Qe)=>{const Pe=h(ce,le),Ve=Mi(Pe).map(Es=>({...Es,id:`cap-${Es.key}`})),Oe=[...to(Pe,"input"),...to(Pe,"output")],Je=Array.from(new Map(Oe.map(Es=>[Es.key,Es])).values()).map(Es=>({...Es,id:`mod-${Es.key}`})),yt=[...Ve,...Je],Dt=Zs(Pe?.limit?.context),ks=s===ce&&n===le,Cs=D(ce,le);return e.jsxs("div",{ref:Es=>{de.current[He]=Es},className:F("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",Qe?"bg-accent":"hover:bg-accent/50"),onClick:()=>et(ce,le),onMouseEnter:()=>ye(He),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:ot(L)}),Pe?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:Dt}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[yt.length>0&&e.jsx("div",{className:F("items-center gap-0.5",Qe?"flex":"hidden group-hover:flex"),children:yt.map(({id:Es,icon:Rp,label:xc})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":xc,role:"img",title:xc,children:e.jsx(Rp,{className:"h-2.5 w-2.5"})},Es))}),ks&&e.jsx(Gt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:Es=>{Es.preventDefault(),Es.stopPropagation(),P(ce,le)},className:F("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Cs?"text-yellow-500":"text-muted-foreground"),"aria-label":Cs?"Unfavorite":"Favorite",title:Cs?"Remove from favorites":"Add to favorites",children:Cs?e.jsx(Cr,{className:"h-3.5 w-3.5"}):e.jsx(In,{className:"h-3.5 w-3.5"})})]})]},`${Re}-${ce}-${le}`)},yn=(L,ce,le)=>le.trim()?Gs(L,le)||Gs(ce,le):!0,si=()=>{const L=G.filter(({model:Oe,providerID:Je})=>{const Dt=r.find(Cs=>Cs.id===Je)?.name||Je,ks=ot(Oe);return yn(ks,Dt,ne)}),ce=O.filter(({model:Oe,providerID:Je})=>{const Dt=r.find(Cs=>Cs.id===Je)?.name||Je,ks=ot(Oe);return yn(ks,Dt,ne)}),le=r.map(Oe=>{const yt=(Array.isArray(Oe.models)?Oe.models:[]).filter(Dt=>{const ks=ot(Dt);return yn(ks,Oe.name||Oe.id||"",ne)});return{...Oe,models:yt}}).filter(Oe=>Oe.models.length>0),Re=L.length>0||ce.length>0||le.length>0,He=[];L.forEach(({model:Oe,providerID:Je,modelID:yt})=>{He.push({model:Oe,providerID:Je,modelID:yt,section:"fav"})}),ce.forEach(({model:Oe,providerID:Je,modelID:yt})=>{He.push({model:Oe,providerID:Je,modelID:yt,section:"recent"})}),le.forEach(Oe=>{Oe.models.forEach(Je=>{He.push({model:Je,providerID:Oe.id,modelID:Je.id,section:"provider"})})});const Qe=He.length,Pe=Oe=>{if(Oe.key==="ArrowDown")Oe.preventDefault(),Oe.stopPropagation(),ye(Je=>(Je+1)%Math.max(1,Qe)),setTimeout(()=>{const Je=(Z+1)%Math.max(1,Qe);de.current[Je]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Oe.key==="ArrowUp")Oe.preventDefault(),Oe.stopPropagation(),ye(Je=>(Je-1+Math.max(1,Qe))%Math.max(1,Qe)),setTimeout(()=>{const Je=(Z-1+Math.max(1,Qe))%Math.max(1,Qe);de.current[Je]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Oe.key==="Enter"){Oe.preventDefault(),Oe.stopPropagation();const Je=He[Z];Je&&et(Je.providerID,Je.modelID)}else Oe.key==="Escape"&&(Oe.preventDefault(),Oe.stopPropagation(),he(!1))};let Ve=0;return e.jsxs(lt,{delayDuration:1e3,children:[Q?e.jsxs("button",{type:"button",onClick:()=>se("model"),onTouchStart:()=>$e("model"),onTouchEnd:kt,onTouchCancel:kt,className:F("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",zt),children:[s?e.jsx(ws,{providerId:s,className:F(ut,"flex-shrink-0")}):e.jsx(Nr,{className:F(ut,"text-muted-foreground")}),e.jsx("span",{className:F("model-controls__model-label typography-micro font-medium overflow-hidden min-w-0",Y?"max-w-[120px]":"max-w-[220px]"),children:e.jsx("span",{className:"marquee-text",children:$t()})})]}):e.jsxs(es,{open:we,onOpenChange:he,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs("div",{className:F("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",zt),children:[s?e.jsxs(e.Fragment,{children:[e.jsx(ws,{providerId:s,className:F(ut,"flex-shrink-0")}),e.jsx(Nr,{className:F(ut,"text-primary/60 hidden")})]}):e.jsx(Nr,{className:F(ut,"text-muted-foreground")}),e.jsx("span",{className:F("model-controls__model-label overflow-hidden",vt,"font-medium whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:e.jsx("span",{className:"marquee-text",children:$t()})},`${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(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{type:"text",placeholder:"Search models",value:ne,onChange:Oe=>ke(Oe.target.value),onKeyDown:Pe,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(gt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!Re&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),L.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs($r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Cr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),L.map(({model:Oe,providerID:Je,modelID:yt})=>{const Dt=Ve++;return Vs(Oe,Je,yt,"fav",Dt,Z===Dt)})]}),ce.length>0&&e.jsxs(e.Fragment,{children:[L.length>0&&e.jsx(Ds,{}),e.jsxs($r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(br,{className:"h-4 w-4"}),"Recent"]}),ce.map(({model:Oe,providerID:Je,modelID:yt})=>{const Dt=Ve++;return Vs(Oe,Je,yt,"recent",Dt,Z===Dt)})]}),(L.length>0||ce.length>0)&&le.length>0&&e.jsx(Ds,{}),le.map((Oe,Je)=>e.jsxs(i.Fragment,{children:[Je>0&&e.jsx(Ds,{}),e.jsxs($r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ws,{providerId:Oe.id,className:"h-4 w-4 flex-shrink-0"}),Oe.name]}),Oe.models.map(yt=>{const Dt=Ve++;return Vs(yt,Oe.id,yt.id,"provider",Dt,Z===Dt)})]},Oe.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"})]})]}),Yt()]})},ri=()=>{if(!ie)return e.jsx(it,{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 L=!!(ie.prompt&&ie.prompt.trim().length>0),ce=ie.model?.providerID&&ie.model?.modelID,le=ie.temperature!==void 0||ie.topP!==void 0,Re=Ve=>{const Oe=Fa(ie.permission)??[],Je=Oe.some(Dt=>Dt.permission===Ve&&Dt.pattern!=="*"),yt=Uo(Oe,Ve)??"ask";return Je?{mode:"ask",label:"Custom"}:yt==="allow"?{mode:"allow",label:"Allow"}:yt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},He=Re("edit"),Qe=Re("bash"),Pe=Re("webfetch");return e.jsx(it,{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:xe(ie.name)}),ie.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:ie.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:ie.mode==="primary"?"Primary":ie.mode==="subagent"?"Subagent":ie.mode==="all"?"All":"—"})]}),(ce||le)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Model"}),ce?e.jsxs("span",{className:"typography-meta text-foreground",children:[ie.model.providerID," / ",ie.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),le&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[ie.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:ie.temperature})]}),ie.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:ie.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:[Ct(He.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:He.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:[Ct(Qe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Qe.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:[Ct(Pe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Pe.label})]})]})]}),L&&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(ea,{className:"h-4 w-4 text-foreground"})]})]})})},Do=()=>{if(!Ee)return null;const L=o??"Default",ce=!o,le=ce?"text-muted-foreground":"text-[color:var(--status-info)]";return Q?e.jsxs("button",{type:"button",onClick:()=>se("variant"),className:F("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",zt,"cursor-pointer hover:opacity-70"),children:[e.jsx(wr,{className:F(ut,"flex-shrink-0",le)}),e.jsx("span",{className:F("model-controls__variant-label",vt,"font-medium truncate min-w-0",Y&&"max-w-[60px]",le),children:L})]}):e.jsxs(lt,{delayDuration:800,children:[e.jsxs(es,{children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs("div",{className:F("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",zt),children:[e.jsx(wr,{className:F(ut,"flex-shrink-0",le)}),e.jsx("span",{className:F("model-controls__variant-label",vt,"font-medium min-w-0 truncate",K?"max-w-[180px]":void 0,le),children:L})]})})}),e.jsxs(ss,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx($r,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(Nt,{className:"typography-meta",onSelect:()=>Me(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"}),ce&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),be.length>0&&e.jsx(Ds,{}),be.map(Re=>{const He=o===Re,Qe=Re.charAt(0).toUpperCase()+Re.slice(1);return e.jsx(Nt,{className:"typography-meta",onSelect:()=>Me(Re),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:Qe}),He&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},Re)})]})]}),e.jsx(it,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",L]})})]})},ni=()=>Q?e.jsxs("button",{type:"button",onClick:()=>se("agent"),onTouchStart:()=>$e("agent"),onTouchEnd:kt,onTouchCancel:kt,className:F("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",zt,"cursor-pointer hover:opacity-70"),children:[e.jsx(fn,{className:F(ut,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Or(a).var})`}:void 0}),e.jsx("span",{className:F("model-controls__agent-label",vt,"font-medium truncate min-w-0",Y&&"max-w-[60px]"),style:a?{color:`var(${Or(a).var})`}:void 0,children:wt()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(lt,{delayDuration:1e3,children:[e.jsxs(es,{children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs("div",{className:F("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",zt),children:[e.jsx(fn,{className:F(ut,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Or(a).var})`}:void 0}),e.jsx("span",{className:F("model-controls__agent-label",vt,"font-medium min-w-0 truncate",K?"max-w-[220px]":void 0),style:a?{color:`var(${Or(a).var})`}:void 0,children:wt()})]})})}),e.jsxs(ss,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[b.filter(L=>Ho(L.mode)).map(L=>e.jsx(Nt,{className:"typography-meta",onSelect:()=>qe(L.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:F("h-1 w-1 rounded-full agent-dot",Or(L.name).class)}),e.jsx("span",{className:"font-medium",children:xe(L.name)})]}),L.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:L.description})]})},L.name)),e.jsx(Ds,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:It,onClick:()=>{It||te(L=>!L)},className:F("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",It?"cursor-not-allowed opacity-60":void 0),"aria-expanded":_e,"aria-controls":J,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:nt?nt.text:"var(--foreground)"},children:Tt})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:F("flex items-center justify-center p-1",!nt&&"text-muted-foreground"),style:nt?{color:nt.text}:void 0,children:Ct(Ye)}),e.jsx(Ot,{className:F("h-3.5 w-3.5 transition-transform text-muted-foreground",_e?"rotate-180":"")})]})]}),_e&&!It&&e.jsx("div",{id:J,className:"flex flex-col gap-1 rounded-xl border border-border/40 px-2 py-2 bg-transparent",role:"group","aria-label":"Edit permission options",children:xt.map(L=>{const ce=L.mode===Ye,le=oo(L.mode);return e.jsxs("button",{type:"button",disabled:L.disabled,onClick:()=>os(L.mode),className:F("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",L.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",ce?"bg-primary/10":void 0),style:ce&&le?{backgroundColor:le.background??void 0}:void 0,children:[Ct(L.mode,We),e.jsx("span",{className:"typography-meta font-medium",style:{color:le?le.text:"var(--foreground)"},children:L.label})]},L.mode)})})]})]})]}),ri()]})}),oi=F("@container/model-controls flex items-center min-w-0",Y&&"w-full",t);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:oi,children:e.jsxs("div",{className:F("flex items-center min-w-0 flex-1 justify-end",dt,Y&&"overflow-hidden"),children:[Do(),si(),ni()]})}),pt(),Ss(),ms(),Mt(),Kt()]})},Fv=t=>t?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(t):!0,Rd=(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(!Fv(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}},Uf=t=>({id:t.id,content:t.content,status:t.status||"pending",priority:t.priority||"medium"}),gl=ns()(cs((t,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async s=>{if(s){t({isLoading:!0});try{const n=me.getState().getDirectoryForSession(s),a=(n?await Fe.withDirectory(n,()=>Fe.getSessionTodos(s)):await Fe.getSessionTodos(s)).map(Uf);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"})),Rv=(t,r)=>{const s=r.map(Uf);gl.getState().updateTodos(t,s)},Ld=[{variant:"shine",component:({children:t,className:r,...s})=>e.jsx(Nn.span,{...s,className:F("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)=>Te.createElement(Nn.span,{...s,key:n+String(o),className:F("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:F("invisible",r),children:t}),e.jsx("span",{...s,className:F("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:F("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(Nn.span,{...s,className:F("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(Nn.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:F("absolute inset-0"),children:a.map((l,c)=>e.jsx(Nn.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:F("text-primary-muted hover:animate-text-shake",r),children:t})},{variant:"hover-decoration",component:({children:t,className:r,...s})=>e.jsx("div",{className:F("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:F("text-primary-muted",r),children:t})})}];function Di({variant:t="shine",className:r,...s}){const a=Ld.find(l=>l.variant===t)?.component||Ld[0].component;return e.jsx(Zu,{children:e.jsx(a,{...s,className:r})})}const Od=1500,Lv=2e3;function Ov({statusText:t,isGenericStatus:r,isWaitingForPermission:s,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:l}){const[c,d]=Te.useState("idle"),[u,m]=Te.useState(null),[f,p]=Te.useState(!1),h=Te.useRef(0),x=Te.useRef(null),g=Te.useRef(null),b=Te.useRef(null),y=Te.useRef(null),v=Te.useRef(!1),S=Te.useRef(!1),N=Te.useRef(!1),w=Te.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),b.current&&(clearTimeout(b.current),b.current=null)},[]),k=Te.useCallback((P,D)=>{w(),x.current=null,m(P),p(D),d("showing"),h.current=Date.now(),v.current=!0},[w]),A=Te.useCallback(()=>{if(g.current)return;const P=Date.now()-h.current,D=Math.max(0,Od-P);g.current=setTimeout(()=>{g.current=null;const T=x.current;T&&k(T.text,T.permission)},D)},[k]),j=Te.useCallback(P=>{if(w(),x.current=null,!v.current){d("idle"),m(null),l?.(!1);return}if(P==="done"&&o&&y.current===o){d("idle"),m(null),v.current=!1,l?.(!1);return}P==="done"&&o&&(y.current=o),d(P),m(null),l?.(!0),b.current=setTimeout(()=>{b.current=null,d("idle"),v.current=!1,l?.(!1)},Lv)},[w,o,l]);if(Te.useEffect(()=>{if(n&&!N.current){N.current=!0,j("aborted");return}if(N.current=!!n,a&&!S.current){S.current=!0,j("done");return}if(!a&&S.current&&(S.current=!1),!(c==="done"||c==="aborted")&&t){const D=Date.now()-h.current;if(c==="idle"||!u)k(t,!!s);else if(t!==u||!!s!==f){if(r)return;D>=Od?k(t,!!s):(x.current={text:t,permission:!!s},A())}}},[t,s,n,a,c,u,f,k,j,A,r]),Te.useEffect(()=>()=>w(),[w]),Te.useEffect(()=>{const P=()=>{typeof document>"u"||document.visibilityState==="visible"&&(c==="done"||c==="aborted")&&(w(),d("idle"),m(null),v.current=!1)};return document.addEventListener("visibilitychange",P),()=>document.removeEventListener("visibilitychange",P)},[c,w]),c==="idle"&&!u)return null;let M,C=!0;c==="done"?(M="Done",C=!1):c==="aborted"?(M="Aborted",C=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const I=C?`${M}...`:M,E=c!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${E?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":M,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:c==="done"?e.jsx(Di,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):c==="aborted"?e.jsx(Di,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(Di,{variant:"shine",className:"typography-ui-header",children:I})})})}const _d={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},_v=({todo:t})=>{const r=_d[t.status]||_d.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:F("flex-1 typography-ui-label",r.textClassName),children:t.content})})},$d=[],$v=({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=me(D=>D.currentSessionId),x=gl(D=>h?D.sessionTodos.get(h)??$d:$d),g=gl(D=>D.loadTodos),{isMobile:b}=Ce(),y=b||Wt();i.useEffect(()=>{h&&g(h)},[h,g]);const v=i.useMemo(()=>{const D={in_progress:0,pending:1,completed:2,cancelled:3};return[...x].filter(T=>T.status!=="cancelled").sort((T,R)=>D[T.status]-D[R.status])},[x]),S=i.useMemo(()=>v.find(D=>D.status==="in_progress")||v.find(D=>D.status==="pending")||null,[v]),N=i.useMemo(()=>{const D=x.filter(R=>R.status!=="cancelled").length;return{completed:x.filter(R=>R.status==="completed").length,total:D}},[x]),w=v.some(D=>D.status==="in_progress"||D.status==="pending"),k=!m&&(o||!a),[A,j]=i.useState(!1),M=t||c||o||A||w||m,C=i.useRef(null);if(i.useEffect(()=>{if(!f)return;const D=T=>{C.current&&!C.current.contains(T.target)&&p(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[f]),!M)return null;const I=()=>p(D=>!D),E=d&&u?e.jsx("button",{type:"button",onClick:u,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:e.jsx(Ln,{size:18,"aria-hidden":"true"})}):null,P=w?e.jsxs("button",{type:"button",onClick:I,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:[N.completed,"/",N.total]}),f?e.jsx(_a,{className:"h-3.5 w-3.5"}):e.jsx(Ot,{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(Ln,{size:16,"aria-hidden":"true"}),"Aborted"]})}):k?e.jsx(Ov,{statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,completionId:l??null,isComplete:c,onResultVisibilityChange:j},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:C,children:[E,P,f&&w&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:F("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:[N.completed,"/",N.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:v.map(D=>e.jsx(_v,{todo:D},D.id))})]})]})]})})},ua=t=>!t||typeof t!="object"?!1:!!t.synthetic,Bd=t=>!Array.isArray(t)||t.length===0?!1:t.every(r=>ua(r)),Bv=t=>!Array.isArray(t)||t.length===0?[]:t.some(s=>!ua(s))&&t.some(n=>ua(n))?t.filter(n=>!ua(n)):t,zv={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Wv(t){const r=me(s=>!t||!s.sessionActivityPhase?"idle":s.sessionActivityPhase.get(t)??"idle");return i.useMemo(()=>{if(r==="idle")return zv;const s=r==="busy",n=r==="cooldown";return{phase:r,isWorking:s||n,isBusy:s,isCooldown:n}},[r])}function ic(){const t=me(r=>r.currentSessionId);return Wv(t)}const Hv={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},zd=t=>t.role==="assistant",Uv=t=>t.type==="reasoning",Vf=t=>t.type==="text",Wd=t=>{if(Vf(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},Hd=t=>(Vf(t)||Uv(t),t.time),Vv=t=>{if(t.tool)return t.tool;const r=t;return typeof r.name=="string"?r.name:"tool"};function Gf(){const{currentSessionId:t,messages:r,permissions:s,sessionAbortFlags:n}=me(Il(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:l}=ic(),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(M=>zd(M.info)&&!Bd(M.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const x=[...h].sort((M,C)=>{const I=typeof M.info.time?.created=="number"?M.info.time.created:null,E=typeof C.info.time?.created=="number"?C.info.time.created:null;return I!==null&&E!==null&&I!==E?I-E:M.info.id.localeCompare(C.info.id)}),g=x[x.length-1];let b,y;const v=new Set(["edit","write","apply_patch"]);for(let M=(g.parts??[]).length-1;M>=0;M-=1){const C=g.parts?.[M];if(C)switch(C.type){case"reasoning":{const I=C.time??Hd(C);(!I||typeof I.end>"u")&&!b&&(b="reasoning");break}case"tool":{const I=C.state?.status;if((I==="running"||I==="pending")&&!b){const E=Vv(C);v.has(E)?b="editing":(b="tool",y=E)}break}case"text":{const I=Wd(C)??"";if(typeof I=="string"&&I.trim().length>0){const E=Hd(C);(!E||typeof E.end>"u")&&!b&&(b="text")}break}}}const S={read:"reading file",write:"writing file",edit:"editing file",multiedit:"editing files",apply_patch:"applying patch",bash:"running command",grep:"searching content",glob:"finding files",list:"listing directory",task:"delegating task",webfetch:"fetching URL",websearch:"searching web",codesearch:"web code search",todowrite:"updating todos",todoread:"reading todos",skill:"learning skill",question:"asking question"},N=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],w=M=>S[M]??`using ${M}`,k=()=>N[Math.floor(Math.random()*N.length)],A=b===void 0,j=b==="editing"?"editing file":b==="tool"&&y?w(y):b==="reasoning"?"thinking":b==="text"?"composing":k();return{activePartType:b,activeToolName:y,statusText:j,isGenericStatus:A}},[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{...Hv,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=>zd(y.info)&&!Bd(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 v=Wd(y)??"";typeof v=="string"&&v.trim().length>0&&(b+=v.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 Gv=8,Ud=[],qv=t=>t==="primary"||t==="all"||t===void 0||t===null,qf=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},Vd=(t,r)=>{const s=qf(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}}},Kv=(t,r)=>{const s=qf(t);if(!s||s.length===0)return;const n={};for(const o of s)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},Go=({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(""),[v,S]=i.useState(!1),[N,w]=i.useState(""),[k,A]=i.useState(null),j=i.useRef(null),M=i.useRef(null),C=i.useRef(null),I=i.useRef(null),E=i.useRef(null),P=i.useRef(null),D=me(L=>L.sendMessage),T=me(L=>L.currentSessionId),R=me(L=>L.newSessionDraft?.open),V=me(L=>L.abortCurrentOperation),G=me(L=>L.acknowledgeSessionAbort),O=me(L=>L.abortPromptSessionId),Y=me(L=>L.abortPromptExpiresAt),K=me(L=>L.clearAbortPrompt),U=me(L=>L.sessionAbortFlags),Q=me(L=>L.attachedFiles),W=me(L=>L.addAttachedFile),se=me(L=>L.addServerFile),ee=me(L=>L.clearAttachedFiles),pe=me(L=>L.saveSessionAgentSelection),$=me(L=>L.consumePendingInputText),oe=me(L=>L.pendingInputText),{currentProviderId:_,currentModelId:z,currentVariant:X,currentAgentName:re,setAgent:ge,getVisibleAgents:H}=at(),fe=H(),{isMobile:we,inputBarOffset:he,isKeyboardOpen:_e,setTimelineDialogOpen:te,cornerRadius:J}=Ce(),{working:ne}=Gf(),[ke,Z]=i.useState(!1),ye=i.useRef(null),de=i.useRef(!1),je=i.useRef(!1),ie=pr(L=>L.queueModeEnabled),Xe=pr(i.useCallback(L=>T?L.queuedMessages[T]??Ud:Ud,[T])),mt=pr(L=>L.addToQueue),Ae=pr(L=>L.clearQueue),{phase:ae}=ic(),Ue=i.useRef(ae),Se=i.useRef(!1),Ne=i.useCallback(L=>{if(!we||L.pointerType!=="touch")return;const ce=j.current;if(!ce||document.activeElement===ce)return;L.preventDefault(),L.stopPropagation();const le=document.scrollingElement;le&&le.scrollTop!==0&&(le.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{ce.focus({preventScroll:!0})}catch{ce.focus()}const Re=ce.value.length;try{ce.setSelectionRange(Re,Re)}catch{}},[we]);i.useEffect(()=>{if(oe!==null){const L=$();L&&(n(L),setTimeout(()=>{j.current?.focus()},0))}},[oe,$]);const Ge=i.useMemo(()=>{if(re)return fe.find(L=>L.name===re)},[fe,re]),rt=i.useMemo(()=>Ge?Vd(Ge.permission,"edit")??"ask":"deny",[Ge]),Ke=me(i.useCallback(L=>!T||!re?void 0:L.sessionAgentEditModes.get(T)?.get(re),[T,re])),Le=i.useMemo(()=>{if(Ge)return Vd(Ge.permission,"webfetch")},[Ge]),Ye=i.useMemo(()=>{if(!Ge)return;const L=Kv(Ge.permission,"bash");return L||void 0},[Ge]),xt=i.useMemo(()=>Hf({agentDefaultEditMode:rt,webfetchPermission:Le,bashPermission:Ye}),[rt,Le,Ye]),nt=!!(T&&re),It=i.useMemo(()=>nt&&Ke&&xt.modeAvailability[Ke]?Ke:xt.cascadeDefaultMode,[xt,nt,Ke]),Pt=i.useMemo(()=>oo(It),[It]),zt=i.useCallback(L=>Wt()?`color-mix(in srgb, ${L} 55%, transparent)`:L,[]),We=i.useMemo(()=>{const L=Wt()?1:2,ce={borderRadius:J};if(!Pt)return{...ce,borderWidth:L};const le=Pt.border??Pt.text;return{...ce,borderColor:zt(le),borderWidth:L}},[Pt,zt,J]),ut=s.trim()||Q.length>0,vt=Xe.length>0,dt=ut||vt,Tt=ne.isWorking,Ct=i.useMemo(()=>T?O===T&&!!Y:!1,[O,Y,T]),os=i.useCallback(()=>{if(!ut||!T)return;const L=s.replace(/^\n+|\n+$/g,""),ce=Q.map(le=>({...le}));mt(T,{content:L,attachments:ce.length>0?ce:void 0}),n(""),ce.length>0&&ee(),we||j.current?.focus()},[ut,T,s,Q,mt,ee,we]),St=async L=>{if(L?.preventDefault(),!dt||!T&&!R)return;if(r?.({instant:!0,force:!0}),!_||!z){console.warn("Cannot send message: provider or model not selected");return}let ce="",le=[],Re;const He=[];for(let Ve=0;Ve<Xe.length;Ve++){const Oe=Xe[Ve],{sanitizedText:Je,mention:yt}=Rd(Oe.content,fe);!Re&&yt?.name&&(Re=yt.name),Ve===0?(ce=Je,le=Oe.attachments??[]):He.push({text:Je,attachments:Oe.attachments})}if(ut){const Ve=s.replace(/^\n+|\n+$/g,""),{sanitizedText:Oe,mention:Je}=Rd(Ve,fe),yt=Q.map(Dt=>({...Dt}));!Re&&Je?.name&&(Re=Je.name),Xe.length===0?(ce=Oe,le=yt):He.push({text:Oe,attachments:yt.length>0?yt:void 0})}if(!ce&&He.length===0)return;T&&vt&&Ae(T),n(""),Q.length>0&&ee(),we&&j.current?.blur();const Qe=ce.trimStart();if(Qe.startsWith("/")){const Ve=Qe.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(Ve==="undo"&&T){await me.getState().handleSlashUndo(T),r?.({instant:!0,force:!0});return}else if(Ve==="redo"&&T){await me.getState().handleSlashRedo(T),r?.({instant:!0,force:!0});return}else if(Ve==="timeline"&&T){te(!0),n("");return}else if(Ve==="compact"&&T){try{const{opencodeClient:Oe}=await bs(async()=>{const{opencodeClient:Dt}=await Promise.resolve().then(()=>Hx);return{opencodeClient:Dt}},void 0),Je=Oe.getDirectory();if((await Oe.getApiClient().session.summarize({sessionID:T,directory:Je||void 0,providerID:_,modelID:z})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(Oe){console.error("Failed to compact session:",Oe),q.error("Failed to compact session")}n("");return}}const Pe=[...le,...He.flatMap(Ve=>Ve.attachments??[])];await D(ce,_,z,re,le,Re,He.length>0?He:void 0,X).catch(Ve=>{const Oe=Ve instanceof Error?Ve.message:typeof Ve=="string"?Ve:String(Ve??""),Je=Oe.toLowerCase();console.error("Message send failed:",Oe||Ve);const yt=Je.includes("timeout")||Je.includes("timed out")||Je.includes("may still be processing")||Je.includes("being processed")||Je.includes("failed to fetch")||Je.includes("networkerror")||Je.includes("network error")||Je.includes("gateway timeout")||Je==="failed to send message";if(Je.includes("payload too large")||Je.includes("413")||Je.includes("entity too large")){q.error("Attachments are too large to send. Please try reducing the number or size of images."),Pe.length>0&&ar.setState({attachedFiles:Pe});return}yt||(Pe.length>0&&ar.setState({attachedFiles:Pe}),q.error(Oe||"Message failed to send. Attachments restored."))}),we||j.current?.focus()},Lt=i.useRef(St);Lt.current=St,i.useEffect(()=>{const L=Ue.current==="busy"||Ue.current==="cooldown",ce=ae==="idle",le=T&&U.has(T)&&(()=>{const Re=U.get(T);return Re?Date.now()-Re.timestamp<2e3:!1})();L&&ce&&Xe.length>0&&!Se.current&&!le&&(Se.current=!0,setTimeout(()=>{T&&_&&z&&Lt.current(),Se.current=!1},100)),Ue.current=ae},[ae,Xe.length,T,_,z,U]);const Ft=L=>{if(!nc(L)){if(m&&I.current&&(L.key==="Enter"||L.key==="ArrowUp"||L.key==="ArrowDown"||L.key==="Escape"||L.key==="Tab")){L.preventDefault(),I.current.handleKeyDown(L.key);return}if(x&&E.current&&(L.key==="Enter"||L.key==="ArrowUp"||L.key==="ArrowDown"||L.key==="Escape"||L.key==="Tab")){L.preventDefault(),E.current.handleKeyDown(L.key);return}if(v&&P.current&&(L.key==="Enter"||L.key==="ArrowUp"||L.key==="ArrowDown"||L.key==="Escape"||L.key==="Tab")){L.preventDefault(),P.current.handleKeyDown(L.key);return}if(l&&C.current&&(L.key==="Enter"||L.key==="ArrowUp"||L.key==="ArrowDown"||L.key==="Escape"||L.key==="Tab")){L.preventDefault(),C.current.handleKeyDown(L.key);return}if(L.key==="Tab"&&!m&&!x&&!l){L.preventDefault(),qt();return}if(L.key==="Enter"&&!L.shiftKey&&!we){L.preventDefault();const ce=L.ctrlKey||L.metaKey,le=ut&&T&&ae!=="idle";ie?ce||!le?St():os():ce&&le?os():St()}}},Ut=i.useCallback(()=>{ye.current&&(clearTimeout(ye.current),ye.current=null),Z(!0),ye.current=setTimeout(()=>{Z(!1),ye.current=null},1800)},[]),Rt=i.useCallback(()=>{K(),Ut(),V()},[V,K,Ut]),qt=()=>{const L=fe.filter(He=>qv(He.mode));if(L.length<=1)return;const le=(L.findIndex(He=>He.name===re)+1)%L.length,Re=L[le];ge(Re.name),T&&pe(T,Re.name)},be=i.useCallback(()=>{const L=j.current;if(!L)return;L.style.height="auto";const ce=L.ownerDocument?.defaultView,le=ce?ce.getComputedStyle(L):null,Re=le?parseFloat(le.lineHeight):NaN,He=le?parseFloat(le.paddingTop):NaN,Qe=le?parseFloat(le.paddingBottom):NaN,Pe=22,Oe=Number.isNaN(He)||Number.isNaN(Qe)?16:He+Qe,yt=(Number.isNaN(Re)?Pe:Re)*Gv+Oe,Dt=L.scrollHeight||L.offsetHeight,ks=Math.min(Dt,yt);L.style.height=`${ks}px`,L.style.maxHeight=`${yt}px`,A(Cs=>Cs&&Cs.height===ks&&Cs.maxHeight===yt?Cs:{height:ks,maxHeight:yt})},[]);i.useLayoutEffect(()=>{be()},[be,s,we]);const Ee=i.useCallback((L,ce)=>{if(L.startsWith("/")){const Pe=L.indexOf(" "),Ve=L.indexOf(`
88
- `),Oe=Math.min(Pe===-1?L.length:Pe,Ve===-1?L.length:Ve);if(ce<=Oe&&Pe===-1){const Je=L.substring(1,Oe);h(Je),f(!0),c(!1),g(!1),S(!1);return}}f(!1);const le=L.substring(0,ce),Re=le.lastIndexOf("#");if(Re!==-1){const Pe=Re>0?le[Re-1]:null,Ve=le.substring(Re+1),Oe=Ve.includes(" ")||Ve.includes(`
89
- `);if((!Pe||/\s/.test(Pe))&&!Oe){y(Ve),g(!0),c(!1);return}}g(!1),y("");const He=le.lastIndexOf("/");if(He!==-1){const Pe=He>0?le[He-1]:null,Ve=le.substring(He+1),Oe=Ve.includes(" ")||Ve.includes(`
90
- `);if((!Pe||/\s/.test(Pe))&&!Oe){w(Ve),S(!0),c(!1),g(!1);return}}S(!1),w("");const Qe=le.lastIndexOf("@");if(Qe!==-1){const Pe=le.substring(Qe+1);!Pe.includes(" ")&&!Pe.includes(`
91
- `)?(u(Pe),c(!0)):c(!1)}else c(!1)},[y,h,u,g,f,c,S,w]),B=i.useCallback(L=>{if(!L)return;const ce=j.current;if(!ce){const Pe=s+L;n(Pe),Ee(Pe,Pe.length),requestAnimationFrame(()=>be());return}const le=ce.selectionStart??s.length,Re=ce.selectionEnd??s.length,He=`${s.substring(0,le)}${L}${s.substring(Re)}`;n(He);const Qe=le+L.length;requestAnimationFrame(()=>{const Pe=j.current;Pe&&(Pe.selectionStart=Qe,Pe.selectionEnd=Qe),be()}),Ee(He,Qe)},[be,s,Ee]),ue=L=>{const ce=L.target.value,le=L.target.selectionStart??ce.length;n(ce),be(),Ee(ce,le)},ve=i.useCallback(async L=>{const ce=new Map;Array.from(L.clipboardData.files||[]).forEach(Qe=>{Qe.type.startsWith("image/")&&ce.set(`${Qe.name}-${Qe.size}`,Qe)}),Array.from(L.clipboardData.items||[]).forEach(Qe=>{if(Qe.kind==="file"&&Qe.type.startsWith("image/")){const Pe=Qe.getAsFile();Pe&&ce.set(`${Pe.name}-${Pe.size}`,Pe)}});const le=Array.from(ce.values());if(le.length===0||!T&&!R)return;L.preventDefault();const Re=L.clipboardData.getData("text");Re&&B(Re);let He=0;for(const Qe of le){const Pe=me.getState().attachedFiles.length;try{await W(Qe),me.getState().attachedFiles.length>Pe&&(He+=1)}catch(Ve){console.error("Clipboard image attach failed",Ve),q.error(Ve instanceof Error?Ve.message:"Failed to attach image from clipboard")}}He>0&&q.success(`Attached ${He} image${He>1?"s":""} from clipboard`)},[W,T,R,B]),Be=L=>{const ce=j.current?.selectionStart||0,Re=s.substring(0,ce).lastIndexOf("@");if(Re!==-1){const He=s.substring(0,Re)+L.name+s.substring(ce);n(He)}c(!1),u(""),j.current?.focus()},ze=L=>{const le=j.current?.selectionStart??s.length,He=s.substring(0,le).lastIndexOf("#");if(He!==-1){const Qe=s.substring(0,He)+`#${L} `+s.substring(le);n(Qe);const Pe=He+L.length+2;requestAnimationFrame(()=>{j.current&&(j.current.selectionStart=Pe,j.current.selectionEnd=Pe),be(),Ee(Qe,Pe)})}g(!1),y(""),j.current?.focus()},tt=L=>{const le=j.current?.selectionStart??s.length,He=s.substring(0,le).lastIndexOf("/");if(He!==-1){const Qe=s.substring(0,He)+`${L} `+s.substring(le);n(Qe);const Pe=He+L.length+1;requestAnimationFrame(()=>{j.current&&(j.current.selectionStart=Pe,j.current.selectionEnd=Pe),be(),Ee(Qe,Pe)})}S(!1),w(""),j.current?.focus()},Me=L=>{n(`/${L.name} `);const ce=j.current;ce&&(ce._commandMetadata=L),f(!1),h(""),setTimeout(()=>{j.current&&(j.current.focus(),j.current.setSelectionRange(j.current.value.length,j.current.value.length))},0)};i.useEffect(()=>{T&&j.current&&!we&&j.current.focus()},[T,we]),i.useEffect(()=>{O&&O!==T&&K()},[O,T,K]);const qe=L=>{L.preventDefault(),L.stopPropagation(),(T||R)&&!o&&a(!0)},et=L=>{L.preventDefault(),L.stopPropagation(),L.currentTarget===L.target&&a(!1)},ot=async L=>{if(L.preventDefault(),L.stopPropagation(),a(!1),!T&&!R)return;const ce=Array.from(L.dataTransfer.files);let le=0;for(const Re of ce){const He=me.getState().attachedFiles.length;try{await W(Re),me.getState().attachedFiles.length>He&&(le+=1)}catch(Qe){console.error("File attach failed",Qe),q.error(Qe instanceof Error?Qe.message:"Failed to attach file")}}le>0&&q.success(`Attached ${le} file${le>1?"s":""}`)},_t=i.useCallback(async L=>{let ce=0;for(const le of L){const Re=me.getState().attachedFiles.length;try{await se(le.path,le.name),me.getState().attachedFiles.length>Re&&(ce+=1)}catch(He){console.error("Server file attach failed",He),q.error(He instanceof Error?He.message:"Failed to attach file")}}ce>0&&q.success(`Attached ${ce} file${ce>1?"s":""}`)},[se]),$t=i.useRef(null),[wt,xe]=i.useState(!1),Ie=i.useCallback(async L=>{let ce=0;const le=Array.isArray(L)?L:Array.from(L);for(const Re of le){const He=me.getState().attachedFiles.length;try{await W(Re),me.getState().attachedFiles.length>He&&(ce+=1)}catch(Qe){console.error("File attach failed",Qe),q.error(Qe instanceof Error?Qe.message:"Failed to attach file")}}ce>0&&q.success(`Attached ${ce} file${ce>1?"s":""}`)},[W]),st=i.useCallback(async()=>{try{const ce=await(await fetch("/api/vscode/pick-files")).json(),le=Array.isArray(ce?.files)?ce.files:[],Re=Array.isArray(ce?.skipped)?ce.skipped:[];if(Re.length>0){const Qe=Re.map(Pe=>`${Pe?.name||"file"}: ${Pe?.reason||"skipped"}`).join(`
92
- `);q.error(`Some files were skipped:
93
- ${Qe}`)}const He=le.map(Qe=>{if(!Qe?.dataUrl)return null;try{const[Pe,Ve]=Qe.dataUrl.split(","),Oe=Qe.mimeType||Pe?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Ve)return null;const Je=atob(Ve),yt=new Uint8Array(Je.length);for(let ks=0;ks<Je.length;ks++)yt[ks]=Je.charCodeAt(ks);const Dt=new Blob([yt],{type:Oe});return new File([Dt],Qe.name||"file",{type:Oe})}catch(Pe){return console.error("Failed to decode VS Code picked file",Pe),null}}).filter(Boolean);He.length>0&&await Ie(He)}catch(L){console.error("VS Code file pick failed",L),q.error(L instanceof Error?L.message:"Failed to pick files in VS Code")}},[Ie]),$e=i.useCallback(()=>{if(Wt()){st();return}$t.current?.click()},[st]),kt=i.useCallback(async L=>{const ce=L.target.files;ce&&(await Ie(ce),L.target.value="")},[Ie]),Mt="gap-x-1.5 gap-y-0",Kt=Wt(),pt=we?"px-1.5 py-1.5":Kt?"px-1.5 py-1":"px-2.5 py-1.5",Ss=we?"h-9 w-9":Kt?"h-[22px] w-[22px]":"h-7 w-7",ms=we?"h-5 w-5":Kt?"h-4 w-4":"h-[18px] w-[18px]",Yt=F(Ss,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),yn=!we&&Ct&&Tt?e.jsx("button",{type:"button",onClick:Rt,className:F(Yt,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(Ln,{className:F(ms)})}):e.jsx("button",{type:we?"button":"submit",disabled:!dt||!T&&!R,onPointerDownCapture:L=>{!we||L.pointerType!=="touch"||!dt||!T&&!R||(je.current=!0,L.preventDefault(),L.stopPropagation(),St())},onClick:L=>{if(we){if(je.current){je.current=!1;return}L.preventDefault(),St()}},className:F(Yt,dt&&(T||R)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Oa,{className:F(ms)})}),si=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:$t,type:"file",multiple:!0,className:"hidden",onChange:kt,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(kv,{onFilesSelected:_t,multiSelect:!0,presentation:we?"modal":"dropdown",open:wt,onOpenChange:xe,children:we?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:Yt,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(lm,{className:F(ms,"text-current")})})}),e.jsxs(ss,{align:"start",children:[e.jsxs(Nt,{onSelect:()=>{requestAnimationFrame(()=>$e())},children:[e.jsx(xa,{}),"Attach files"]}),e.jsxs(Nt,{onSelect:()=>{requestAnimationFrame(()=>{xe(!0)})},children:[e.jsx(fg,{}),"Attach from project"]})]})]})]})]}),ri=t?e.jsx("button",{type:"button",onClick:t,className:Yt,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(fn,{className:F(ms,"text-current")})}):null,Do=e.jsxs(e.Fragment,{children:[si,ri]}),ni=ne.statusText;i.useEffect(()=>{const L=!!ne.wasAborted;!de.current&&L&&!ke&&(Ut(),T&&G(T)),de.current=L},[G,T,ke,Ut,ne.wasAborted]),i.useEffect(()=>()=>{ye.current&&(clearTimeout(ye.current),ye.current=null)},[]);const oi=we&&Tt;return e.jsxs("form",{onSubmit:St,className:F("relative pt-0 pb-2 md:pb-4",we&&_e?"ios-keyboard-safe-area":"bottom-safe-area"),"data-keyboard-avoid":"true",style:we&&he>0&&!_e?{marginBottom:`${he}px`}:void 0,children:[e.jsx("div",{className:"absolute bottom-full left-0 right-0",children:e.jsx($v,{isWorking:ne.isWorking,statusText:ni,isGenericStatus:ne.isGenericStatus,isWaitingForPermission:ne.isWaitingForPermission,wasAborted:ne.wasAborted,abortActive:ne.abortActive,completionId:ne.lastCompletionId,isComplete:ne.isComplete,showAbort:oi,onAbort:Rt,showAbortStatus:ke})}),e.jsxs("div",{ref:M,className:F("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:qe,onDragLeave:et,onDrop:ot,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:Yt,onClick:()=>$e(),title:"Attach files","aria-label":"Attach files",children:e.jsx(xa,{className:F(ms,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(xv,{}),e.jsx(Of,{onEditMessage:L=>{n(L),setTimeout(()=>{j.current?.focus()},0)}}),e.jsxs("div",{className:F("border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:We,children:[m&&e.jsx($f,{ref:I,searchQuery:p,onCommandSelect:Me,onClose:()=>f(!1)}),x&&e.jsx(Bf,{ref:E,searchQuery:b,onAgentSelect:ze,onClose:()=>g(!1)}),v&&e.jsx(zf,{ref:P,searchQuery:N,onSkillSelect:tt,onClose:()=>S(!1)}),l&&e.jsx(wv,{ref:C,searchQuery:d,onFileSelect:Be,onClose:()=>c(!1)}),e.jsx(Rs,{ref:j,"data-chat-input":"true",value:s,onChange:ue,onKeyDown:Ft,onPaste:ve,onPointerDownCapture:Ne,placeholder:T||R?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!T&&!R,className:F("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",we?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:k?`${k.height}px`:void 0,maxHeight:k?`${k.maxHeight}px`:void 0,borderTopLeftRadius:J,borderTopRightRadius:J},rows:1}),e.jsx("div",{className:F("bg-transparent",pt,we?"flex items-center gap-x-1.5":F("flex items-center justify-between",Mt)),style:{borderBottomLeftRadius:J,borderBottomRightRadius:J},"data-chat-input-footer":"true",children:we?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:Do}),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(Fd,{className:F("w-full flex items-center justify-end min-w-0")})}),yn]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("flex items-center flex-shrink-0",Mt),children:Do}),e.jsxs("div",{className:F("flex items-center flex-1 justify-end",Mt,"md:gap-x-3"),children:[e.jsx(Fd,{className:F("flex-1 min-w-0 justify-end")}),yn]})]})})]})]})]})};function Ai({className:t,...r}){return e.jsx("div",{"data-slot":"skeleton",className:F("bg-accent animate-pulse rounded-xl",t),...r})}const Gd=(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=(v,S,N)=>v+(S-v)*N,h=(v,S,N,w,k,A)=>{const j=p(v,S,k),M=p(w,N,k);return p(j,M,A)},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},lc=({className:t="",width:r=70,height:s=70,isAnimated:n=!1})=>{const o=Ya();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},v={x:50-m*f,y:h+m*p},S={x:50+m*f,y:h+m*p},N={x:50,y:h+m},k=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(x.y+g.y+y.y+b.y)/4})`,A=Gd(g,y,N,v),j=Gd(y,b,S,N),M=Te.useMemo(()=>{const C=[];for(let I=0;I<32;I++)C.push(.1+Math.random()*.5);return C},[]);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${v.x} ${v.y} L${N.x} ${N.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),A.map((C,I)=>e.jsx("path",{d:C.path,fill:u,opacity:M[I]},`left-${I}`)),e.jsx("path",{d:`M${y.x} ${y.y} L${b.x} ${b.y} L${S.x} ${S.y} L${N.x} ${N.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),j.map((C,I)=>e.jsx("path",{d:C.path,fill:u,opacity:M[I+16]},`right-${I}`)),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:`${k} 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 Qv({children:t,className:r,interval:s=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:l=!0,mode:c="popLayout"}){const[d,u]=Te.useState(0),m=Te.Children.toArray(t);Te.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:F("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(pg,{mode:c,initial:!1,children:e.jsx(Nn.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const Yv=["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"],Xv=()=>{const t=Ya();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(lc,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(Qv,{className:"text-body-md",interval:4,transition:{duration:.5},children:Yv.map(n=>e.jsxs("span",{style:{color:s},children:['"',n,'…"']},n))})]})},Ei=i.memo(Xv),Jv={'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"}},Zv={'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 Br{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Br.instance||(Br.instance=new Br),Br.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 cc(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 ir=({children:t,className:r,skipAnimation:s})=>{const[n,o]=i.useState(s??!1);return i.useEffect(()=>{if(s)return;let a=null;const l=()=>o(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?a=window.requestAnimationFrame(l):l(),()=>{a!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(a)}},[s]),s?e.jsx(e.Fragment,{children:t}):e.jsx("div",{className:F("w-full transition-all duration-300 ease-out",n?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:t})},ej=({isUser:t,providerID:r,agentName:s,modelName:n,variant:o,isDarkTheme:a})=>{const{src:l,onError:c,hasLogo:d}=Ef(r);return e.jsx(ir,{children:e.jsx("div",{className:F("mb-2"),children:e.jsx("div",{className:F("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(Ys,{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(wr,{className:"h-4 w-4",style:{color:`var(${Or(s).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:F("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:F("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)]",Or(s).class),children:[e.jsx(fn,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:s})]}),!t&&o&&e.jsxs("div",{className:F("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(wr,{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})]})]})]})})})})},tj=i.memo(ej),sj=t=>`https://opencode.ai/docs/agents/#${encodeURIComponent(t)}`,rj=({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:sj(s.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:b=>b.stopPropagation(),children:s.token}),g]})};return e.jsx("div",{className:F("break-words whitespace-pre-wrap font-sans typography-markdown",!l&&"line-clamp-3",(d||l)&&"cursor-pointer"),ref:m,onClick:f,children:p()},t.id||`${r}-user-text`)},nj=i.memo(rj),qd=(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},Kd=()=>{if(!Wt()||typeof window>"u")return id;const t=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(t?.light&&t?.dark){const r=qd({...t.light},`vscode-shiki-light:${String(t.light?.name??"theme")}`),s=qd({...t.dark},`vscode-shiki-dark:${String(t.dark?.name??"theme")}`);return[r,s]}return id},oj=()=>{const[t,r]=i.useState(Kd);return i.useEffect(()=>{if(!Wt()||typeof window>"u")return;const s=n=>{r(Kd())};return window.addEventListener("openchamber:vscode-shiki-themes",s),()=>window.removeEventListener("openchamber:vscode-shiki-themes",s)},[]),t},Kf=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}},Qf=({headers:t,rows:r})=>{const s=o=>o.includes(",")||o.includes('"')||o.includes(`
94
- `)?`"${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(`
95
- `)},aj=({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(`
96
- `)},ij=({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(`
97
- `)},lj=(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)},cj=({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=Kf(d),m=c==="csv"?Qf(u):aj(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(Gt,{className:"size-3.5"}):e.jsx(Xs,{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"})]})]})},dj=({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=Kf(l),d=a==="csv"?Qf(c):ij(c);lj(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(Hr,{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"})]})]})},uj=({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(cj,{tableRef:s}),e.jsx(dj,{tableRef:s})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:F("w-full border-collapse border border-border",r),"data-streamdown":"table",children:t})})]})},mj=({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(v=>v.trim()).filter(Boolean),y={};for(const v of b){const S=v.indexOf(":");if(S===-1)continue;const N=v.slice(0,S).trim(),w=v.slice(S+1).trim();!N.startsWith("--")||w.length===0||(y[N]=w)}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:F(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(Gt,{className:"size-3.5"}):e.jsx(Xs,{className:"size-3.5"})})})]})},fj={pre:mj,table:uj},dn=({content:t,className:r,variant:s="assistant"})=>{const n=oj(),o=s==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:F("break-words",r),children:e.jsx(hg,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:fj,children:t})})},pj=t=>{let r=t.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},hj=t=>t?t.includes("<file_diagnostics>")||t.includes("This file has errors")||t.includes("please fix"):!1,gj=t=>t?t.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Qd=(t,r)=>!t||typeof t!="object"?String(t):Xb(t,r||""),Ii=(t,r,s)=>{let n=pj(t);if((r==="edit"||r==="multiedit")&&hj(n)&&(n=gj(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&s?.diff){const o=s.diff;return typeof o=="string"?o:String(o)}return n},xj=(t,r)=>{try{const s=t.trim().split(`
98
- `).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:F("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:Mr.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}},yj=(t,r,s)=>{try{const n=t.trim().split(`
99
- `).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:F("space-y-2 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Mr.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:F("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:F("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}},bj=(t,r,s)=>{try{const n=t.trim().split(`
100
- `).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:F("space-y-2 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Mr.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:F("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[l,"/"]}),e.jsx("div",{className:F("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[l].sort().map(c=>e.jsxs("div",{className:F("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}},wj=(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:F("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Mr.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(Gt,{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(Gt,{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}},vj=(t,r,s)=>{try{return e.jsx("div",{className:F("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:Mr.tool.popup,children:e.jsx(dn,{content:t,variant:"tool"})})}catch{return null}},Yf=t=>{const r=t.split(`
101
- `);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},xl=(t,r,s)=>Qb(r,t,s),Xf=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(gg,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(cm,{className:r}):s==="read"||s==="view"||s==="file_read"||s==="cat"?e.jsx(ho,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"?e.jsx(Vr,{className:r}):s==="list"||s==="ls"||s==="dir"||s==="list_files"?e.jsx(sr,{className:r}):s==="search"||s==="grep"||s==="find"||s==="ripgrep"?e.jsx(xg,{className:r}):s==="glob"?e.jsx(yg,{className:r}):s==="fetch"||s==="curl"||s==="wget"||s==="webfetch"?e.jsx(Yi,{className:r}):s==="web-search"||s==="websearch"||s==="search_web"||s==="codesearch"||s==="google"||s==="bing"||s==="duckduckgo"||s==="perplexity"?e.jsx(Yi,{className:r}):s==="todowrite"||s==="todoread"?e.jsx(dm,{className:r}):s==="skill"?e.jsx(um,{className:r}):s==="question"?e.jsx(bg,{className:r}):s.startsWith("git")?e.jsx(Ht,{className:r}):e.jsx(Ba,{className:r})},jj=(t,r,s=Date.now())=>{const o=(r?r-t:s-t)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},Sj=({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:jj(t,r,n)})},kj=t=>{if(!t?.diff||typeof t.diff!="string")return null;const r=t.diff.split(`
102
- `);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}},ma=(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},Nj=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},Cj=(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"?ma(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 ma(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 ma(d,n,s)}if(t.tool==="bash"&&l?.command&&typeof l.command=="string"){const d=l.command.split(`
103
- `)[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;const c=l?.description||a?.description||"title"in r&&r.title||"";return typeof c=="string"?c:""},yl=({children:t,maxHeightClass:r="max-h-[60vh]",className:s,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(gt,{outerClassName:F("w-full min-w-0 flex-none overflow-hidden",r,n),className:F("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})}),Mj=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"},Dj=t=>t.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Aj=({entries:t,isExpanded:r,hasPrevTool:s,hasNextTool:n,output:o,sessionId:a})=>{const l=me(g=>g.setCurrentSession),c=i.useMemo(()=>t.filter(g=>g.state?.status==="completed"),[t]),d=typeof o=="string"?Dj(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:F("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(yl,{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",v=Mj(g),S=Gl(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:Xf(y)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:S}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:v})]},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(ga,{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:F("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(Ot,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Bs,{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(yl,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(dn,{content:d,variant:"tool"})})}):null]}):null]})},Ej=({diff:t,syntaxTheme:r,input:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Yf(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:F("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(Dr,{style:r,language:Tr(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))}),Ij=({content:t,syntaxTheme:r,filePath:s,displayPath:n})=>{const o=t.split(`
104
- `),a=Tr(s??"")||xl(t,"write",s?{filePath:s}:void 0),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(Dr,{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))})]})},Pj=({content:t,filePath:r,displayPath:s})=>{const n=ll(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"}})})]})},Tj=({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?vo(x):!1,v=b?x?ma(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"?Qd(u,t.tool):typeof u.content=="string"?u.content??"":Qd(u,t.tool),[u,t.tool]),N=t.tool!=="apply_patch"&&S.trim().length>0,w=(A,j)=>e.jsx(yl,{maxHeightClass:j?.maxHeightClass,className:j?.className,disableHorizontal:j?.disableHorizontal,outerClassName:j?.outerClassName,children:A}),k=()=>{if(t.tool==="question"){if(r.status==="completed"&&f){const A=Nj(p);if(A&&A.length>0)return w(e.jsx("div",{className:"space-y-2",children:A.map((j,M)=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:j.question}),e.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:j.answer})]},M))}),{maxHeightClass:"max-h-[40vh]"})}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(t.tool==="todowrite"||t.tool==="todoread"){if(r.status==="completed"&&f){const A=wj(p,{unstyled:!0});return w(A??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 A=xj(p,{unstyled:!0});return w(A??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 A=yj(p,n,{unstyled:!0});return w(A??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 A=bj(p,n,{unstyled:!0});return w(A??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 w(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(dn,{content:p,variant:"tool"})}));if((t.tool==="web-search"||t.tool==="websearch"||t.tool==="search_web")&&f){const A=vj(p,s,{unstyled:!0});return w(A??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 w(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(dn,{content:p,variant:"tool"})}));if(t.tool==="skill"&&f)return w(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(dn,{content:p,variant:"tool"})}));if((t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch")&&h)return w(e.jsx(Ej,{diff:h,syntaxTheme:s,input:u}),{className:"p-1"});if(f&&p.trim()){if(t.tool==="read"){const A=Ii(p,t.tool,d),j=A.split(`
105
- `),M=typeof u?.offset=="number"?u.offset:0,C=typeof u?.limit=="number"?u.limit:void 0,I=E=>E.trim().startsWith("(");return w(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:j.map((E,P)=>{const D=I(E),T=M+P+1,R=!D&&(C===void 0||P<C);return e.jsxs("div",{className:F("typography-code font-mono flex w-full min-w-0",D&&"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:R?T:""}),e.jsx("div",{className:"flex-1 min-w-0",children:D?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(Dr,{style:s,language:xl(A,t.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:E})})]},P)})}),{className:"p-1"})}return w(e.jsx(Dr,{style:s,language:xl(Ii(p,t.tool,d),t.tool,u),PreTag:"div",customStyle:{...ta.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Ii(p,t.tool,d)}),{className:"p-1"})}return w(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:F("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"?k():e.jsxs(e.Fragment,{children:[b&&y?e.jsx("div",{className:"my-1",children:w(e.jsx(Pj,{content:g,filePath:x,displayPath:v??"New file"}))}):b?e.jsx("div",{className:"my-1",children:w(e.jsx(Ij,{content:g,syntaxTheme:s,filePath:x,displayPath:v??"New file"}))}):N?e.jsx("div",{className:"my-1",children:w(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:"}),k()]}),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})]})]})})},bl=({part:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:l=!1,hasNextTool:c=!1})=>{const d=t.state,u=bt(T=>T.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,v=g.time,S=i.useRef({}),N=i.useRef(t.id);if(N.current!==t.id&&(N.current=t.id,S.current={}),m){if(typeof v?.start=="number"){const T=S.current.start;(typeof T!="number"||v.start<T)&&(S.current.start=v.start)}typeof v?.end=="number"&&(S.current.end=v.end)}const w=m?S.current.start??v?.start:v?.start,k=m?S.current.end??v?.end:v?.end,A=i.useMemo(()=>{if(!m)return;const T=b;return typeof T?.sessionId=="string"?T.sessionId:void 0},[m,b]),j=i.useMemo(()=>{if(!m)return[];const T=b?.summary;return Array.isArray(T)?T.filter(R=>typeof R=="object"&&R!==null):[]},[m,b]),M=i.useRef(j.length);i.useEffect(()=>{m&&M.current!==j.length&&(M.current=j.length,a?.("structural"))},[m,a,j.length]);const C=t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch"?kj(b):null,I=Cj(t,d,o,u),E=Gl(t.tool).displayName,P=i.useContext(ql),D=T=>{if(m||!P?.editor){s(t.id);return}let R;if((t.tool==="edit"||t.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(t.tool))&&(R=y?.filePath||y?.file_path||y?.path||b?.filePath||b?.file_path||b?.path),typeof R=="string"){T.stopPropagation();let V=R;R.startsWith("/")||(V=u.endsWith("/")?u+R:u+"/"+R),P.editor.openFile(V)}else s(t.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:F("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:D,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:T=>{T.stopPropagation(),s(t.id)},children:[e.jsx("div",{className:F("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&h?{color:"var(--status-error)"}:{},children:Xf(t.tool)}),e.jsx("div",{className:F("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(Ot,{className:"h-3.5 w-3.5"}):e.jsx(Bs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:E})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[I&&e.jsx("span",{className:F("truncate",o&&"max-w-[120px]"),children:I}),C&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",C.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",C.removed]})]}),typeof w=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(Sj,{start:w,end:typeof k=="number"?k:void 0,active:!!(m&&p&&typeof k!="number")})})]})]}),m&&(j.length>0||p||f||A)?e.jsx(Aj,{entries:j,isExpanded:r,hasPrevTool:l,hasNextTool:c,output:typeof g.output=="string"?g.output:void 0,sessionId:A}):null,!m&&r?e.jsx(Tj,{part:t,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:l,hasNextTool:c}):null]})},Fj={thinking:{label:"Thinking",Icon:wr},justification:{label:"Justification",Icon:Dl}},Rj=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
106
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
107
- `).trim(),Lj=t=>{if(!t)return"";const r=t.trim(),s=r.indexOf(`
108
- `),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},Jf=({text:t,variant:r,onContentChange:s,blockId:n})=>{const[o,a]=i.useState(!1),l=i.useMemo(()=>Lj(t),[t]),{label:c,Icon:d}=Fj[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:F("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:F("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:F("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(Ot,{className:"h-3.5 w-3.5"}):e.jsx(Bs,{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:F("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(gt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:t})})]})},Oj=({part:t,onContentChange:r,messageId:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>Rj(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(Jf,{text:a,variant:"thinking",onContentChange:r,blockId:t.id||`${s}-reasoning`}):null},_j=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
109
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
110
- `).trim(),$j=({part:t,messageId:r,onContentChange:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>_j(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(Jf,{text:a,variant:"justification",onContentChange:s,blockId:t.id||`${r}-justification`}):null},Bj=i.memo($j),Yd=6,zj=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}),Xd=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},Wj=({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);i.useEffect(()=>{if(u.current===r)return;const A=u.current===!1;if(u.current=r,c?.("structural"),r&&A){h(M=>M+1),f(!0);const j=setTimeout(()=>f(!1),50);return()=>clearTimeout(j)}else f(!1)},[r,c]);const x=i.useMemo(()=>zj(t),[t]),g=Xd(x),b=i.useMemo(()=>x.slice(-Yd),[x]),y=i.useMemo(()=>{const A=new Set;return b.forEach(j=>{j.part.id&&A.add(j.part.id)}),A},[b]),v=i.useMemo(()=>Xd(b),[b]),S=Math.max(0,x.length-Yd);if(x.length===0)return null;const N=r?x:b,w=r?g:v,k=S>0;return e.jsx(ir,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:F("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl",k&&"cursor-pointer"),onClick:k?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:k?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(_n,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:F("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(Ot,{className:"h-3.5 w-3.5"}):e.jsx(Bs,{className:"h-3.5 w-3.5"})})]}):e.jsx(_n,{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:F("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&&S>0&&e.jsxs("div",{className:"typography-micro text-muted-foreground/70 mb-1 cursor-pointer hover:text-muted-foreground",onClick:s,children:["+",S," more..."]}),N.map((A,j)=>{const M=A.part.id||`group-part-${j}`,C=w[M],I=`${M}-exp${p}`,E=A.part.id?y.has(A.part.id):!1,P=m&&E;switch(A.kind){case"tool":return e.jsx(ir,{skipAnimation:P,children:e.jsx(bl,{part:A.part,isExpanded:a.has(M),onToggle:l,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:C?.hasPrev??!1,hasNextTool:C?.hasNext??!1})},I);case"reasoning":return e.jsx(ir,{skipAnimation:P,children:e.jsx(Oj,{part:A.part,messageId:A.messageId,onContentChange:c})},I);case"justification":return e.jsx(ir,{skipAnimation:P,children:e.jsx(Bj,{part:A.part,messageId:A.messageId,onContentChange:c})},I);default:return null}})]})]})})},Hj=i.memo(Wj),Zf=t=>{const r=t,s=r.text;return typeof s=="string"?s:r.content||r.value||""},ep=t=>{if(t.type!=="text")return!1;const r=Zf(t);return!r||r.trim().length===0},Uj=(t,r={})=>{const{includeReasoning:s=!0}=r,n=t.some(o=>!o.synthetic);return t.filter(o=>!!o.synthetic&&n||!s&&o.type==="reasoning"?!1:!(o.type==="patch"))},Vj=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`},Gj=new Set(["task"]),qo=t=>typeof t=="string"&&Gj.has(t.toLowerCase()),qj=({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(j=>j.type!=="text"?!1:!ep(j)),[r]),g=d?.token;let b=!1;const y=!!a,v=!!l,S=!!(n??s),N=!!o,w=i.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),k=i.useCallback(()=>{!S||!y||!N||typeof window>"u"||(w(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[y,w,N,S]);i.useEffect(()=>{N||(p(!1),w())},[w,N]);const A=i.useCallback(j=>{!a||!N||(j.stopPropagation(),j.preventDefault(),a(),S&&k())},[N,S,a,k]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&y&&N?k:void 0,children:[e.jsx("div",{className:"leading-relaxed overflow-hidden text-foreground/90 text-base",children:x.map((j,M)=>{let C;return d&&g&&!b&&Zf(j).includes(g)&&(C=d,b=!0),e.jsx(ir,{children:e.jsx(nj,{part:j,messageId:t,isMobile:s,agentMention:C})},`user-text-${M}`)})}),e.jsx(Rf,{files:r,onShowPopup:c}),y&&N||u||m?e.jsxs("div",{className:F("mt-1 flex items-center justify-end gap-2"),children:[u&&e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{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:j=>j.stopPropagation(),onClick:j=>{j.stopPropagation(),u()},children:e.jsx(On,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{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:j=>j.stopPropagation(),onClick:j=>{j.stopPropagation(),m()},children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Fork from here"})]}),y&&N&&e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon","data-visible":f||v?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:j=>j.stopPropagation(),onClick:A,onFocus:()=>p(!0),onBlur:()=>{v||p(!1)},children:v?e.jsx(Gt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Xs,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Copy message"})]})]}):null]})},Kj=({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:v=!1,turnGroupingContext:S,errorMessage:N})=>{const[w,k]=i.useState(!1),A=i.useRef(null),j=!!g,M=!!b,C=!!(c??l),I=!s,E=i.useMemo(()=>r.filter(We=>!ep(We)).filter(We=>We.type!=="compaction"),[r]),P=i.useMemo(()=>E.filter(We=>We.type==="tool"),[E]),D=i.useMemo(()=>E.filter(We=>We.type==="text"),[E]),T=me(We=>We.createSessionFromAssistantMessage),R=Ce(We=>We.openMultiRunLauncherWithPrompt),V=S?.isLastAssistantInTurn??!1,G=n==="stop",O=P.length>0,Y=i.useMemo(()=>P.some(We=>{const vt=(We.state??{})?.status;return vt==="pending"||vt==="running"||vt==="started"}),[P]),K=i.useCallback(We=>{const ut=We.state??{},vt=ut?.status;if(vt==="pending"||vt==="running"||vt==="started")return!1;const dt=ut?.time??{},Tt=typeof dt?.end=="number"?dt.end:void 0,Ct=typeof dt?.start=="number"?dt.start:void 0;return!(typeof Tt!="number"||typeof Ct=="number"&&Tt<Ct)},[]),U=i.useMemo(()=>P.length===0?!0:Y?!1:P.every(We=>K(We)),[P,Y,K]),Q=i.useMemo(()=>E.filter(We=>We.type==="reasoning"),[E]),W=i.useMemo(()=>Q.length===0?!0:Q.every(We=>typeof We.time?.end=="number"),[Q]),se=typeof n!="string",ee=Q.length>0&&O&&(Y||se||!U),pe=I||O&&(Y||se||!U),$=I||ee,oe=O||Q.length>0,_=D.length===0,z=oe&&_&&!pe&&!$&&U&&W,X=i.useRef(!1),re=i.useRef(!1);i.useEffect(()=>{re.current=!1},[t]),i.useEffect(()=>{if(!z){X.current=!1;return}X.current||(X.current=!0,y?.())},[z,y]),i.useEffect(()=>{if(I){re.current=!1;return}if(O){re.current=!1;return}Q.length!==0&&($||!W||re.current||(re.current=!0,h?.("structural")))},[I,O,h,W,Q.length,$]);const ge=!!x&&!I,H=i.useCallback(()=>{A.current!==null&&typeof window<"u"&&(window.clearTimeout(A.current),A.current=null)},[]),fe=i.useCallback(()=>{!C||!j||!ge||typeof window>"u"||(H(),k(!0),A.current=window.setTimeout(()=>{k(!1),A.current=null},1800))},[j,H,ge,C]);i.useEffect(()=>{ge||(k(!1),H())},[H,ge]);const we=i.useCallback(We=>{!g||!ge||(We.stopPropagation(),We.preventDefault(),g(),C&&fe())},[ge,C,g,fe]),he=i.useCallback(We=>{We.stopPropagation(),We.preventDefault(),T&&T(t)},[T,t]),_e=i.useCallback(We=>{We.stopPropagation(),We.preventDefault();const ut=Hl(D);if(!ut.trim())return;const vt=`${ub}
111
-
112
- ${ut}`;R(vt)},[D,R]);i.useEffect(()=>()=>{H()},[H]);const te=i.useMemo(()=>{const We={},ut=P.filter(vt=>qo(vt.tool)||pe?!1:K(vt));return ut.forEach((vt,dt)=>{We[vt.id]={hasPrev:dt>0,hasNext:dt<ut.length-1}}),We},[P,pe,K]),J=i.useMemo(()=>S?.activityParts??[],[S]),ne=i.useMemo(()=>S?J.filter(We=>We.messageId===t):[],[J,t,S]),ke=i.useMemo(()=>S?S.activityGroupSegments.filter(We=>We.anchorMessageId===t):[],[t,S]),Z=i.useMemo(()=>{const We=new Map;return ne.forEach(ut=>{We.set(ut.part,ut)}),We},[ne]),ye=i.useMemo(()=>S?(v?J:J.filter(ut=>ut.kind==="tool")).filter(ut=>{if(ut.kind!=="tool")return!0;const vt=ut.part.tool;return!qo(vt)}):[],[J,v,S]),[de,je]=i.useState(!1);i.useEffect(()=>{if(!S)return;const We=S.activityGroupSegments.some(ut=>ut.afterToolPartId!==null);(ye.length>1||We&&ye.length>0)&&je(!0)},[S,ye.length]);const ie=!!(S&&de),Xe=!!(S&&ie&&ye.length>0&&ke.length>0),mt=i.useMemo(()=>P.filter(We=>qo(We.tool)),[P]),Ae=i.useMemo(()=>{const We=[],ut=dt=>{!S||!Xe||ke.filter(Tt=>(Tt.afterToolPartId??null)===dt).forEach(Tt=>{const Ct=v?Tt.parts:Tt.parts.filter(os=>os.kind==="tool");Ct.length!==0&&We.push(e.jsx(Hj,{parts:Ct,isExpanded:S.isGroupExpanded,onToggle:S.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,diffStats:S.diffStats},`progressive-group-${Tt.id}`))})};ut(null),mt.forEach(dt=>{We.push(e.jsx(ir,{children:e.jsx(bl,{part:dt,isExpanded:d.has(dt.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${dt.id}`)),ut(dt.id)});const vt=[];return E.forEach((dt,Tt)=>{const Ct=Z.get(dt);if(!Ct||!S)return;let os=null,St=null;if(!ie){if(Ct.kind==="tool"){const Lt=dt;if(qo(Lt.tool))return;const Ut=Lt.state?.time,Rt=K(Lt);if(!(!pe&&Rt))return;const be=te[Lt.id];St=e.jsx(ir,{children:e.jsx(bl,{part:Lt,isExpanded:d.has(Lt.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:be?.hasPrev??!1,hasNextTool:be?.hasNext??!1})},`tool-${Lt.id}`),os=Rt&&typeof Ut?.end=="number"?Ut.end:null}St&&vt.push({part:dt,index:Tt,endTime:os,element:St})}}),vt.sort((dt,Tt)=>dt.endTime===null&&Tt.endTime===null?dt.index-Tt.index:dt.endTime===null?1:Tt.endTime===null?-1:dt.endTime-Tt.endTime),vt.forEach(({element:dt})=>{We.push(dt)}),We},[Z,ke,d,l,K,h,m,u,pe,ie,v,a,te,S,E,mt,Xe]),ae=S?.turnId,Ue=me(We=>We.currentSessionId),Se=Et(We=>{if(!ae||!Ue)return;const ut=We.messages.get(Ue);if(!ut)return;const vt=ut.find(Ct=>Ct.info?.id===ae);if(!vt)return;const Tt=vt.info.summary?.body;return typeof Tt=="string"&&Tt.trim().length>0?Tt:void 0}),Ne=typeof S?.summaryBody=="string"&&S.summaryBody.trim().length>0?S.summaryBody:Se,Ge=i.useRef(void 0);Ne&&Ne.trim().length>0&&(Ge.current=Ne);const rt=i.useRef(ae);rt.current!==ae&&(rt.current=ae,Ge.current=void 0);const Ke=Ge.current,Le=S?.isLastAssistantInTurn&&Ke&&Ke.trim().length>0,Ye=!!N,xt=V&&x&&(G||!!N),[nt,It]=i.useState(!1),Pt=i.useMemo(()=>{if(!V||!G)return;const We=S?.userMessageCreatedAt;if(!(typeof We!="number"||typeof o!="number")&&!(o<=We))return Vj(o-We)},[V,G,S?.userMessageCreatedAt,o]),zt=e.jsxs(e.Fragment,{children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{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:We=>We.stopPropagation(),onClick:he,children:e.jsx(wg,{className:"h-4 w-4"})})}),e.jsx(it,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{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:We=>We.stopPropagation(),onClick:_e,children:e.jsx(Cf,{className:"h-4 w-4"})})}),e.jsx(it,{sideOffset:6,children:"Start new multi-run from this answer"})]}),g&&e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon","data-visible":w||M?"true":void 0,className:F("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",!ge&&"opacity-50"),disabled:!ge,"aria-label":"Copy message text","aria-hidden":!ge,onPointerDown:We=>We.stopPropagation(),onClick:we,onFocus:()=>{ge&&k(!0)},onBlur:()=>{M||k(!1)},children:M?e.jsx(Gt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Xs,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:F("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:C&&j&&ge?fe: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:[Ae,Ye&&e.jsx(ir,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(dn,{content:N??""})})},"assistant-error"),Le&&e.jsx(ir,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>It(!0),onMouseLeave:()=>It(!1),children:[e.jsx(dn,{content:Ke}),xt&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[Pt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(vc,{className:"h-3.5 w-3.5"}),Pt]}):e.jsx("span",{}),e.jsx("div",{className:F("flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",nt&&"opacity-100 pointer-events-auto"),children:zt})]})]})},"summary-body")]}),e.jsx(Rf,{files:r,onShowPopup:m}),!Le&&xt&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[Pt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(vc,{className:"h-3.5 w-3.5"}),Pt]}):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:zt})]})]})})},Qj=({isUser:t,...r})=>t?e.jsx(qj,{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(Kj,{...r}),Jd=i.memo(Qj),Pi=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}},Yj=i.lazy(()=>bs(()=>import("./ToolOutputDialog-CLg_YFoi.js"),__vite__mapDeps([2,0,1,3,4]))),Xj=new Set(["task","edit","multiedit","write","bash"]),Zd=t=>typeof t=="string"&&Xj.has(t.toLowerCase());function Ti(t){const r=i.useRef({hasValue:!1,value:void 0});return!r.current.hasValue&&t!==void 0&&t!==null&&(r.current={hasValue:!0,value:t}),r.current.hasValue?r.current.value:t}const fr=(t,r)=>{if(typeof t=="object"&&t!==null)return t[r]},Jj=({message:t,previousMessage:r,nextMessage:s,onContentChange:n,animationHandlers:o,turnGroupingContext:a})=>{const{isMobile:l,hasTouchInput:c}=Qt(),{currentTheme:d}=Xr(),u=i.useRef(null),m=me(Il(Me=>({lifecyclePhase:Me.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const qe=t.info.sessionID??Me.currentSessionId??null;return qe?(Me.streamingMessageIds.get(qe)??null)===t.info.id:!1})(),currentSessionId:Me.currentSessionId,getCurrentAgent:Me.getCurrentAgent,getSessionAgentSelection:Me.getSessionAgentSelection,getAgentModelForSession:Me.getAgentModelForSession,getSessionModelSelection:Me.getSessionModelSelection}))),{lifecyclePhase:f,isStreamingMessage:p,currentSessionId:h,getCurrentAgent:x,getSessionAgentSelection:g,getAgentModelForSession:b,getSessionModelSelection:y}=m,v=at(Me=>Me.providers),S=Ce(Me=>Me.showReasoningTraces),N=Ce(Me=>Me.toolCallExpansion);i.useEffect(()=>{h&&Br.getInstance().recordSessionStart(h)},[h]);const[w,k]=i.useState(null),[A,j]=i.useState(!1),[M,C]=i.useState(new Set),[I,E]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{C(new Set)},[t.info.id,N]);const D=i.useMemo(()=>Pi(t.info),[t.info]).isUser,T=i.useMemo(()=>D?t.parts.map(Me=>Me.type==="compaction"?{type:"text",text:"/compact"}:Me):t.parts,[D,t.parts]),R=i.useMemo(()=>{if(D||!r)return null;const Me=fr(r.info,"clientRole"),qe=fr(r.info,"role");if((typeof Me=="string"?Me:typeof qe=="string"?qe:void 0)!=="user")return null;const ot=fr(r.info,"mode"),_t=fr(r.info,"providerID"),$t=fr(r.info,"modelID"),wt=fr(r.info,"variant"),xe=typeof ot=="string"&&ot.trim().length>0?ot:void 0,Ie=typeof _t=="string"&&_t.trim().length>0?_t:void 0,st=typeof $t=="string"&&$t.trim().length>0?$t:void 0,$e=typeof wt=="string"&&wt.trim().length>0?wt:void 0;return!xe&&!Ie&&!st&&!$e?null:{agentName:xe,providerId:Ie,modelId:st,variant:$e}},[D,r]),V=i.useMemo(()=>{if(D)return;const Me=fr(t.info,"mode");if(typeof Me=="string"&&Me.trim().length>0)return Me;if(R?.agentName)return R.agentName;const qe=t.info.sessionID;if(!qe)return;const et=x(qe);return et||(g(qe)??void 0)},[D,t.info,R,x,g]),G=t.info.sessionID,O=D?null:fr(t.info,"providerID"),Y=D?null:fr(t.info,"modelID"),K=i.useMemo(()=>{if(D||!G)return null;if(R?.providerId&&R?.modelId)return{providerId:R.providerId,modelId:R.modelId};if(V){const qe=b(G,V);if(qe?.providerId&&qe?.modelId)return qe}const Me=y(G);return Me?.providerId&&Me?.modelId?Me:null},[D,G,V,R,b,y]),U=i.useMemo(()=>D?null:typeof O=="string"&&O.trim().length>0?O:K?.providerId??null,[D,O,K]),Q=i.useMemo(()=>D?null:typeof Y=="string"&&Y.trim().length>0?Y:K?.modelId??null,[D,Y,K]),W=i.useMemo(()=>{if(!D&&U&&Q&&v.length>0){const Me=v.find(qe=>qe.id===U);if(Me?.models&&Array.isArray(Me.models)){const ot=Me.models.find(_t=>_t.id===Q)?.name;return typeof ot=="string"?ot:void 0}}},[D,U,Q,v]),se=i.useMemo(()=>{if(D||!U||!Q)return!1;const Me=v.find(ot=>ot.id===U);if(!Me?.models||!Array.isArray(Me.models))return!1;const et=Me.models.find(ot=>ot.id===Q)?.variants;return!!(et&&Object.keys(et).length>0)},[D,Q,U,v]),ee=Ti(V),pe=Ti(U??void 0),$=Ti(W),oe=ee??void 0,_=pe??null,z=$??void 0,X=i.useMemo(()=>{const Me=t.info.time;return typeof Me?.completed=="number"?Me.completed:null},[t.info.time]),re=i.useMemo(()=>D?!0:!!(X&&X>0),[D,X]),ge=i.useMemo(()=>{const Me=t.info.finish;return typeof Me=="string"?Me:void 0},[t.info]),H=i.useMemo(()=>Uj(T,{includeReasoning:S}),[T,S]),fe=i.useMemo(()=>D||re?H:[],[D,re,H]),we=i.useMemo(()=>D?[]:H.filter(Me=>Me.type==="text"),[D,H]),he=i.useMemo(()=>D?[]:H.filter(qe=>qe.type==="tool"),[D,H]),_e=i.useMemo(()=>{if(N==="collapsed"||N==="activity")return M;const Me=new Set;for(const et of he){const ot=et.tool;et.id&&Zd(ot)&&Me.add(et.id)}if(a?.isFirstAssistantInTurn)for(const et of a.activityParts){if(et.kind!=="tool")continue;const ot=et.part;ot.id&&Zd(ot.tool)&&Me.add(ot.id)}const qe=new Set(Me);for(const et of M)qe.has(et)?qe.delete(et):qe.add(et);return qe},[M,N,he,a]),te=i.useMemo(()=>{if(!D)return;const Me=t.parts.find(_t=>_t.type==="agent");if(!Me)return;const qe=Me,et=typeof qe.name=="string"?qe.name:void 0;if(!et)return;const ot=qe.source&&typeof qe.source.value=="string"&&qe.source.value.trim().length>0?qe.source.value:`#${et}`;return{name:et,token:ot}},[D,t.parts]),J=typeof ge!="string",ne=i.useMemo(()=>D?!1:we.length===0||he.length===0?J:!0,[we.length,he.length,J,D]),ke=d?.metadata.variant,Z=i.useMemo(()=>ke?ke==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[ke]),ye=i.useMemo(()=>d?cc(d):Z?Jv:Zv,[d,Z]),de=i.useMemo(()=>D?!1:Br.getInstance().shouldAnimateMessage(t.info,h||t.info.sessionID),[t.info,h,D]),je=i.useRef(!1),ie=i.useMemo(()=>r?Pi(r.info):null,[r]),Xe=i.useMemo(()=>s?Pi(s.info):null,[s]),mt=i.useMemo(()=>D||!Xe?!1:!Xe.isUser&&Xe.role==="assistant",[D,Xe]),Ae=i.useMemo(()=>re?"completed":f||(p?"streaming":"completed"),[re,f,p]),ae=i.useMemo(()=>{if(D)return!0;const Me=a?.headerMessageId;if(Me){if(t.info.id===Me){if(Ae==="completed")return!0;const et=Ae==="streaming"||Ae==="cooldown",ot=je.current;return et&&!ot&&(je.current=!0),ot||et}return!1}return ie?ie.isUser:!0},[D,ie,a,Ae,t.info]),Ue=i.useCallback(Me=>{navigator.clipboard.writeText(Me),k(Me),setTimeout(()=>k(null),2e3)},[]),Se=a?.turnId,Ne=Et(Me=>{if(!Se)return;const qe=t.info.sessionID;if(!qe)return;const et=Me.messages.get(qe);if(!et)return;const ot=et.find(wt=>wt.info?.id===Se);if(!ot)return;const $t=ot.info.summary?.body;return typeof $t=="string"&&$t.trim().length>0?$t:void 0}),Ge=Et(Me=>{if(!Se)return;const qe=t.info.sessionID;if(!qe)return;const et=Me.messages.get(qe);if(!et)return;const ot=et.find($t=>$t.info?.id===Se);if(!ot)return;const _t=ot.info.variant;return typeof _t=="string"&&_t.trim().length>0?_t:void 0}),rt=D?void 0:Ge??R?.variant,Ke=!D&&se?rt??"Default":void 0,Le=typeof a?.summaryBody=="string"&&a.summaryBody.trim().length>0?a.summaryBody:Ne,Ye=i.useRef(void 0);Le&&Le.trim().length>0&&(Ye.current=Le);const xt=i.useRef(Se);xt.current!==Se&&(xt.current=Se,Ye.current=void 0);const nt=Ye.current,It=i.useMemo(()=>{if(D)return;const Me=t.info?.error;if(!Me)return;const qe=typeof Me.data?.message=="string"?Me.data.message:void 0,et=typeof Me.message=="string"?Me.message:void 0,ot=typeof Me.name=="string"?Me.name:void 0,_t=qe||et||ot;if(_t)return`Opencode failed to send message with error:
113
- \`${_t}\``},[D,t.info]),Pt=i.useMemo(()=>D?fe.filter(et=>et.type==="text").map(et=>(et.text||et.content||"").trim()).filter(et=>et.length>0).join(`
114
- `).replace(/\n\s*\n+/g,`
115
- `):It&&It.trim().length>0?It:nt&&nt.trim().length>0?nt:Hl(fe),[It,nt,fe,D]),zt=Pt.length>0,We=i.useCallback(async Me=>{if(!Me)return!1;if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(Me),!0}catch{}if(typeof document>"u")return!1;const qe=document.createElement("textarea");qe.value=Me,qe.setAttribute("readonly",""),qe.style.position="fixed",qe.style.top="-1000px",qe.style.left="-1000px",document.body.appendChild(qe),qe.select(),qe.setSelectionRange(0,qe.value.length);const et=document.execCommand("copy");return document.body.removeChild(qe),et},[]),ut=i.useCallback(async()=>{await We(Pt)&&(j(!0),setTimeout(()=>j(!1),2e3))},[We,Pt]),vt=me(Me=>Me.revertToMessage),dt=me(Me=>Me.forkFromMessage),Tt=i.useCallback(()=>{!G||!t.info.id||vt(G,t.info.id)},[G,t.info.id,vt]),Ct=i.useCallback(()=>{!G||!t.info.id||dt(G,t.info.id)},[G,t.info.id,dt]),os=i.useCallback(Me=>{C(qe=>{const et=new Set(qe);return et.has(Me)?et.delete(Me):et.add(Me),et})},[]),St=o??null,Lt=i.useRef(!1),Ft=i.useRef(!1),Ut=i.useRef(!1),Rt=i.useRef(!1),qt=i.useRef(!1);i.useEffect(()=>{Ft.current=!1,Ut.current=!1,Rt.current=!1,qt.current=!1,Lt.current=!1},[t.info.id]);const be=i.useCallback(()=>{D||Lt.current||(Lt.current=!0,n?.("structural"))},[D,n]),Ee=i.useCallback(Me=>{Me.image&&E(Me)},[]),B=i.useCallback(Me=>{E(qe=>({...qe,open:Me}))},[]),ue=!!fr(t.info,"animationSettled"),ve=Ae==="streaming",Be=i.useMemo(()=>D?!1:H.some(Me=>Me.type==="reasoning"),[D,H]),ze=de&&!ue&&!ve,tt=!D&&de&&we.length>0&&!ne;return i.useEffect(()=>{if(St?.onStreamingCandidate){if(!tt){Ut.current&&(Be&&St?.onReasoningBlock?St.onReasoningBlock():St?.onReservationCancelled&&St.onReservationCancelled(),Ut.current=!1);return}qt.current||(qt.current=!0,St.onStreamingCandidate(),Ut.current=!0)}},[St,tt,Be]),i.useEffect(()=>{St?.onAnimationStart&&ze&&(Rt.current||(St.onAnimationStart(),Rt.current=!0))},[St,ze]),i.useEffect(()=>{if(D)return;const Me=St?.onAnimatedHeightChange;if(!Me||!(ze||tt))return;const et=u.current;if(!et)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Me(et.getBoundingClientRect().height);return}let ot=null;const _t=wt=>{if(typeof window>"u"){Me(wt);return}ot!==null&&window.cancelAnimationFrame(ot),ot=window.requestAnimationFrame(()=>{Me(wt)})},$t=new ResizeObserver(wt=>{const xe=wt[0];xe&&_t(xe.contentRect.height)});return $t.observe(et),_t(et.getBoundingClientRect().height),()=>{ot!==null&&(window.cancelAnimationFrame(ot),ot=null),$t.disconnect()}},[ze,D,St,tt]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("group w-full",ae?"pt-6":"pt-0",D?"pb-4":mt?"pb-0":"pb-8"),"data-message-id":t.info.id,ref:u,children:e.jsx("div",{className:"chat-message-column relative",children:D?e.jsx(ir,{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(Jd,{messageId:t.info.id,parts:H,isUser:D,isMessageCompleted:re,messageFinish:ge,syntaxTheme:ye,isMobile:l,hasTouchInput:c,copiedCode:w,onCopyCode:Ue,expandedTools:M,onToggleTool:os,onShowPopup:Ee,streamPhase:Ae,allowAnimation:ze,onContentChange:n,shouldShowHeader:!1,hasTextContent:zt,onCopyMessage:ut,copiedMessage:A,showReasoningTraces:S,onAuxiliaryContentComplete:be,agentMention:te,onRevert:Tt,onFork:D?Ct:void 0,errorMessage:It})})})}):e.jsxs("div",{className:"relative pl-4 ml-1",children:[ae&&e.jsx(tj,{isUser:D,providerID:_,agentName:oe,modelName:z,variant:Ke,isDarkTheme:Z}),e.jsx(Jd,{messageId:t.info.id,parts:H,isUser:D,isMessageCompleted:re,messageFinish:ge,messageCompletedAt:X??void 0,syntaxTheme:ye,isMobile:l,hasTouchInput:c,copiedCode:w,onCopyCode:Ue,expandedTools:_e,onToggleTool:os,onShowPopup:Ee,streamPhase:Ae,allowAnimation:ze,onContentChange:n,shouldShowHeader:ae,hasTextContent:zt,onCopyMessage:ut,copiedMessage:A,onAuxiliaryContentComplete:be,showReasoningTraces:S,agentMention:te,turnGroupingContext:a,errorMessage:It})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(Yj,{popup:I,onOpenChange:B,syntaxTheme:ye,isMobile:l})})]})},Zj=i.memo(Jj),e0=({diff:t,syntaxTheme:r,filePath:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Yf(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:F("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(Dr,{style:r,language:Tr(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))}),t0=({content:t,syntaxTheme:r,filePath:s})=>{const n=t.split(`
116
- `),o=Tr(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(Dr,{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))})]})},s0=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(Nr,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(cm,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?e.jsx(Vr,{className:r}):s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?e.jsx(Yi,{className:r}):e.jsx(Ba,{className:r})},r0=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},n0=({permission:t,onResponse:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(!1),{respondToPermission:l}=me(),{currentTheme:c}=Xr(),d=i.useMemo(()=>cc(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,v="")=>{const S=t.metadata[y];return typeof S=="string"?S:typeof S=="number"?String(S):v},h=y=>{const v=t.metadata[y];return typeof v=="number"?v:void 0},x=y=>!!t.metadata[y],g=r0(m),b=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const S=p("command")||p("cmd")||p("script"),N=p("description"),w=p("cwd")||p("working_directory")||p("directory")||p("path"),k=h("timeout");return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:N}),w&&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:w})]}),k&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",k,"ms"]}),S&&e.jsx("div",{children:e.jsx(Dr,{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"),N=p("changes")||p("diff"),w=x("replace_all")||x("replaceAll");return e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),N&&e.jsx(gt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(e0,{diff:N,syntaxTheme:d,filePath:S})})]})}if(f==="write"||f==="create"||f==="file_write"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("content")||p("text")||p("data");return N?e.jsx(gt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(t0,{content:N,syntaxTheme:d,filePath:S})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const S=p("url")||p("uri")||p("endpoint"),N=p("method")||"GET",w=t.metadata.headers&&typeof t.metadata.headers=="object"?t.metadata.headers:void 0,k=p("body")||p("data")||p("payload"),A=h("timeout"),j=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:N}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:S})]})]}),w&&Object.keys(w).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(gt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(Dr,{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(w,null,2)})})]}),k&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(gt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(Dr,{language:typeof k=="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 k=="object"?JSON.stringify(k,null,2):String(k)})})]}),(A||j)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[A&&e.jsxs("span",{children:["Timeout: ",A,"ms"]}),A&&j&&e.jsx("span",{children:" • "}),j&&e.jsxs("span",{children:["Response format: ",j]})]})]})}const y=p("command")||p("content")||p("action")||p("operation"),v=p("description");return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),y&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(gt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(y)})})]}),Object.keys(t.metadata).length>0&&!y&&!v&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(gt,{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(mn,{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:[s0(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-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{onClick:()=>u("once"),disabled:s,className:F("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","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(Gt,{className:"h-3 w-3"}),"Allow Once"]}),t.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:s,className:F("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","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(br,{className:"h-3 w-3"}),(()=>{const y=t.always||t.metadata.always||[];if(y.length===0)return"Always Allow";const S=y.slice(0,2).join(", ");return y.length>2?`Always: ${S}...`:`Always: ${S}`})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:s,className:F("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","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(br,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:s,className:F("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","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(Zt,{className:"h-3 w-3"}),"Deny"]}),s&&e.jsx("div",{className:"ml-auto typography-meta text-muted-foreground",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})})]})]})})})},Fi="summary",o0=({question:t})=>{const{respondToQuestion:r,rejectQuestion:s}=me(),[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===Fi,y=b?-1:Math.max(0,Math.min(g.length-1,Number(n)||0)),v=b?null:g[y];i.useEffect(()=>{o("0"),m({}),p({}),x({}),d(!1)},[t.id]);const S=i.useMemo(()=>{const D=g.map((T,R)=>({value:String(R),label:T.header?.trim()||`Q${R+1}`}));return g.length>1&&D.push({value:Fi,label:"Summary"}),D},[g]),N=i.useCallback(D=>{if(!!f[D])return(h[D]??"").trim()||"(no answer)";const R=u[D]??[];return R.length>0?R.join(", "):"(no answer)"},[f,h,u]),w=!!v?.multiple,k=u[y]??[],A=!!f[y],j=i.useMemo(()=>{if(g.length===0)return!1;for(let D=0;D<g.length;D+=1){if(!!f[D]){if(!(h[D]??"").trim())return!1;continue}if((u[D]??[]).length===0)return!1}return!0},[f,h,g.length,u]),M=i.useCallback(()=>{const D=[];for(let T=0;T<g.length;T+=1){if(!!f[T]){const V=(h[T]??"").trim();D.push(V?[V]:[]);continue}D.push(u[T]??[])}return D},[f,h,g.length,u]),C=i.useCallback(D=>{v&&(p(T=>({...T,[y]:!1})),m(T=>{const R=T[y]??[];if(w){const G=R.includes(D)?R.filter(O=>O!==D):[...R,D];return{...T,[y]:G}}return{...T,[y]:[D]}}))},[y,v,w]),I=i.useCallback(()=>{p(D=>({...D,[y]:!0})),m(D=>({...D,[y]:[]}))},[y]),E=i.useCallback(async()=>{if(j){l(!0);try{const D=M();await r(t.sessionID,t.id,D),d(!0)}catch{}finally{l(!1)}}},[M,t.id,t.sessionID,j,r]),P=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(mn,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Input needed"})]})}),e.jsxs("div",{className:"px-2 py-2",children:[S.length>1?e.jsx("div",{className:"flex items-center gap-1 mb-2 flex-wrap",children:S.map(D=>{const T=n===D.value,R=D.value===Fi;return e.jsxs("button",{type:"button",onClick:()=>o(D.value),className:F("px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1",T?"bg-muted/40 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-muted/20"),children:[R?e.jsx(dm,{className:"h-3 w-3"}):null,D.label]},D.value)})}):null,b?e.jsx("div",{className:"space-y-2",children:g.map((D,T)=>{const R=N(T),V=R!=="(no answer)";return e.jsxs("button",{type:"button",onClick:()=>o(String(T)),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:D.header||`Question ${T+1}`}),e.jsx("div",{className:F("typography-meta",V?"text-foreground":"text-muted-foreground/50 italic"),children:R})]},T)})}):v?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:v.question}),w?e.jsx("div",{className:"typography-micro text-muted-foreground mb-1.5",children:"Select multiple"}):null,e.jsxs("div",{className:"space-y-0.5",children:[v.options.map((D,T)=>{const R=k.includes(D.label),V=/\(recommended\)/i.test(D.label);return e.jsx("button",{type:"button",onClick:()=>C(D.label),disabled:a,className:F("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",R?"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:R?e.jsx(vg,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(Xi,{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:F("typography-meta break-all",R?"text-foreground font-medium":"text-foreground/80"),children:D.label}),V?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),D.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:D.description}):null]})]})},`${T}:${D.label}`)}),e.jsx("button",{type:"button",onClick:I,disabled:a,className:F("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",A?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gn,{className:F("h-3.5 w-3.5",A?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:F("typography-meta",A?"text-foreground font-medium":"text-muted-foreground"),children:"Other…"})]})}),A?e.jsx("div",{className:"pl-6 pr-1 pt-0.5",children:e.jsx("textarea",{ref:D=>{if(D){D.style.height="auto";const T=20,R=T*2,V=T*4;D.style.height=`${Math.min(Math.max(D.scrollHeight,R),V)}px`}},value:h[y]??"",onChange:D=>{const T=D.target;T.style.height="auto";const R=20,V=R*2,G=R*4;T.style.height=`${Math.min(Math.max(T.scrollHeight,V),G)}px`,x(O=>({...O,[y]:T.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||!j,className:F("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(Gt,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:P,disabled:a,className:F("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(Zt,{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]})]})})})},a0=new Set(["task"]),eu=t=>typeof t=="string"&&a0.has(t.toLowerCase()),i0=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},l0=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}}},c0=t=>{const r=l0(t);let s;const o=t.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let y=0,v=0,S=0;o.forEach(N=>{if(!N)return;const w=typeof N.additions=="number"?N.additions:0,k=typeof N.deletions=="number"?N.deletions:0;(w!==0||k!==0)&&(S+=1),y+=w,v+=k}),S>0&&(s={additions:y,deletions:v,files:S})}let a=!1,l=!1;t.assistantMessages.forEach(y=>{y.parts.forEach(v=>{v.type==="tool"?a=!0:v.type==="reasoning"&&(l=!0)})});const c=[];let d=0;t.assistantMessages.forEach(y=>{const v=y.info.id;y.info.finish,y.parts.forEach(S=>{const N=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-activity-${d++}`;if(S.type==="tool"){const k=S.state?.time,A=typeof k?.end=="number"?k.end:void 0;c.push({id:N,turnId:t.turnId,messageId:v,kind:"tool",part:S,endedAt:A});return}if(S.type==="reasoning"){const w=S.text??S.content;if(typeof w!="string"||w.trim().length===0)return;const k=S.time,A=typeof k?.end=="number"?k.end:void 0;c.push({id:N,turnId:t.turnId,messageId:v,kind:"reasoning",part:S,endedAt:A});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 v=y.info.id;y.parts.forEach(S=>{if(S.type==="tool"){const k=S.tool;if(eu(k)){const A=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-task-${p.length+1}`;f.has(A)||(f.set(A,v),p.push(A)),x=A;return}}const N=m.get(S);if(!N)return;if(N.kind==="tool"){const k=N.part.tool;if(eu(k))return}const w=h.get(x)??[];w.push(N),h.set(x,w)})});const g=y=>{if(y.length===0)return;const v=new Map;y.forEach(w=>{v.set(w.messageId,(v.get(w.messageId)??0)+1)});let S,N=0;for(const w of t.assistantMessages){const k=v.get(w.info.id)??0;if(k>0&&!S&&(S=w.info.id),N+=k,N>=2)return w.info.id}return S};return[null,...p].forEach(y=>{const v=h.get(y)??[];if(v.length===0)return;const S=y===null?g(v):f.get(y);S&&u.push({id:`${t.turnId}:${S}:${y??"start"}`,anchorMessageId:S,afterToolPartId:y,parts:v})}),{activityParts:c,activityGroupSegments:u,hasTools:a,hasReasoning:l,summaryBody:r,diffStats:s}},d0=t=>{const{isWorking:r}=ic(),s=i.useMemo(()=>i0(t),[t]),n=i.useMemo(()=>s.length===0?null:s[s.length-1].turnId,[s]),o=i.useMemo(()=>{const x=new Map;return s.forEach(g=>{x.set(g.userMessage.info.id,g),g.assistantMessages.forEach(b=>{x.set(b.info.id,g)})}),x},[s]),a=i.useMemo(()=>{const x=new Map;return s.forEach(g=>{x.set(g.turnId,c0(g))}),x},[s]),[l,c]=i.useState(()=>new Map),d=Ce(x=>x.toolCallExpansion),u=d==="activity"||d==="detailed";i.useEffect(()=>{c(new Map)},[d]);const m=i.useCallback(x=>{const g=l.get(x);return g||{isExpanded:u}},[l,u]),f=i.useCallback(x=>{c(g=>{const b=new Map(g),y=b.get(x)??{isExpanded:u};return b.set(x,{isExpanded:!y.isExpanded}),b})},[u]),p=i.useCallback(x=>o.get(x),[o]),h=i.useCallback(x=>{const g=o.get(x);if(!g||!g.assistantMessages.some(V=>V.info.id===x))return;const y=a.get(g.turnId),v=y?.activityParts??[],S=y?.activityGroupSegments??[],N=!!y?.hasTools,w=!!y?.hasReasoning,k=y?.summaryBody,A=y?.diffStats,j=g.assistantMessages[0]?.info.id,M=x===j,C=g.assistantMessages[g.assistantMessages.length-1]?.info.id,I=x===C,E=j,P=m(g.turnId),D=r&&n===g.turnId,T=g.userMessage.info.time,R=typeof T?.created=="number"?T.created:void 0;return{turnId:g.turnId,isFirstAssistantInTurn:M,isLastAssistantInTurn:I,summaryBody:k,activityParts:v,activityGroupSegments:S,headerMessageId:E,hasTools:N,hasReasoning:w,diffStats:A,userMessageCreatedAt:R,isWorking:D,isGroupExpanded:P.isExpanded,toggleGroup:()=>f(g.turnId)}},[m,n,o,r,f,a]);return{turns:s,getTurnForMessage:p,getContextForMessage:h}},u0=({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 f=new Set;return t.filter(p=>{const h=p.info?.id;if(typeof h=="string"){if(f.has(h))return!1;f.add(h)}return!0}).map(p=>{const h=Bv(p.parts);return h===p.parts?p:{...p,parts:h}})},[t]),{getContextForMessage:m}=d0(u);return 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("div",{className:"flex flex-col",children:u.map((f,p)=>e.jsx(Zj,{message:f,previousMessage:p>0?u[p-1]:void 0,nextMessage:p<u.length-1?u[p+1]:void 0,onContentChange:n,animationHandlers:o(f.info.id),scrollToBottom:d,turnGroupingContext:m(f.info.id)},f.info.id))}),(s.length>0||r.length>0)&&e.jsxs("div",{children:[s.map(f=>e.jsx(o0,{question:f},f.id)),r.map(f=>e.jsx(n0,{permission:f},f.id))]}),e.jsx("div",{className:"flex-shrink-0",style:{height:"10vh"},"aria-hidden":"true"})]})},m0=i.memo(u0);function f0(...t){return r=>{t.forEach(s=>{typeof s=="function"?s(r):s&&typeof s=="object"&&(s.current=r)})}}const tp=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 v={...l};return v["--scroll-shadow-size"]=`${s}px`,v},[s,l]),g=i.useCallback((v,S,N,w,k)=>{const A=`${w}${k.charAt(0).toUpperCase()}${k.slice(1)}Scroll`;S&&N?(v.dataset[A]="true",v.removeAttribute(`data-${w}-scroll`),v.removeAttribute(`data-${k}-scroll`)):(v.dataset[`${w}Scroll`]=String(S),v.dataset[`${k}Scroll`]=String(N),v.removeAttribute(`data-${w}-${k}-scroll`))},[]),b=i.useCallback(v=>{["top","bottom","top-bottom","left","right","left-right"].forEach(S=>{v.removeAttribute(`data-${S}-scroll`)})},[]),y=i.useCallback(()=>{const v=f.current;if(!v)return;if(!n){b(v);return}const S=t==="vertical"?v.scrollTop>r:v.scrollLeft>r;let N=t==="vertical"?v.scrollTop+v.clientHeight+r<v.scrollHeight:v.scrollLeft+v.clientWidth+r<v.scrollWidth;o&&t==="vertical"&&(N=!1),g(v,S,N,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const w=S&&N?"both":S?t==="vertical"?"top":"left":N?t==="vertical"?"bottom":"right":"none";w!==p.current&&(p.current=w,a?.(w))},[b,o,n,r,a,t,g]);return i.useEffect(()=>{const v=f.current;if(!v)return;const S=()=>y(),N=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null,w=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return y(),v.addEventListener("scroll",S,{passive:!0}),N?.observe(v),w?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{v.removeEventListener("scroll",S),N?.disconnect(),w?.disconnect()}},[y]),e.jsx("div",{...u,ref:f0(f,m),className:c,"data-orientation":t,"data-scroll-shadow":h??!0,style:x,children:d})});tp.displayName="ScrollShadow";const p0=160,h0=({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(N=>{const w=t.current;if(!w){m();return}l.current===null&&(l.current=N),u.current&&(d.current=w.scrollHeight-w.clientHeight);const k=Math.min(1,(N-l.current)/p0),A=1-Math.pow(1-k,3),j=c.current,M=d.current,C=j+(M-j)*A;if(w.scrollTop=C,k<1){a.current=window.requestAnimationFrame(f);return}w.scrollTop=M,m(),n.current&&(n.current=!1,s(!1))},[m,t,s]),p=i.useCallback((N,w)=>{const k=t.current;if(!k)return;const A=Math.max(0,N),j=w?.instant??!1,M=w?.followBottom??!1;if(o.current=!1,typeof window>"u"||j){m(),k.scrollTop=A;const I=A<=1;n.current!==I&&(n.current=I,s(I));return}if(M&&u.current&&a.current!==null)return;if(m(),Math.abs(A-k.scrollTop)<=.5){k.scrollTop=A;const I=A<=1;n.current!==I&&(n.current=I,s(I));return}c.current=k.scrollTop,d.current=A,l.current=null,u.current=M,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]),v=i.useCallback(()=>t.current?.clientHeight??0,[t]),S=i.useCallback(()=>{const N=t.current;if(!N)return;o.current&&a.current!==null&&m();const w=N.scrollTop<=1;n.current!==w&&(n.current=w,s(w))},[m,t]);return i.useEffect(()=>{const N=t.current;if(N)return N.addEventListener("wheel",x,{passive:!0}),N.addEventListener("touchstart",x,{passive:!0}),()=>{N.removeEventListener("wheel",x),N.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:v}),[S,p,h,r,g,b,y,v])},g0=typeof window<"u"?i.useLayoutEffect:i.useEffect,x0=200,y0=250,b0=.1,w0=({currentSessionId:t,sessionMessages:r,updateViewportAnchor:s,isSyncing:n,isMobile:o})=>{const a=i.useRef(null),l=h0({containerRef:a}),c=i.useCallback(()=>{const P=a.current;if(!P||P.clientHeight<=0)return 0;const D=P.clientHeight*b0;return Math.max(24,Math.min(200,D))},[]),[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 v=i.useCallback(()=>{x.current=Date.now()+x0},[]),S=i.useCallback(()=>{const P=a.current;return P?P.scrollHeight-P.scrollTop-P.clientHeight:0},[]),N=i.useCallback(P=>{b.current!==P&&(b.current=P,f(P))},[]),w=i.useCallback(P=>{const D=a.current;if(!D)return;const T=D.scrollHeight-D.clientHeight;v(),l.scrollToPosition(Math.max(0,T),P)},[v,l]),k=i.useCallback(()=>{const P=a.current;if(!P){u(!1);return}if(!(P.scrollHeight>P.clientHeight)){u(!1);return}const T=S();u(T>c())},[S,c]),A=i.useCallback((P,D)=>{a.current&&(v(),l.scrollToPosition(Math.max(0,P),D))},[v,l]),j=i.useCallback(P=>{a.current&&(N(!0),w(P),u(!1))},[w,N]),M=i.useCallback(P=>{const D=a.current;if(!D||!t)return;const T=Date.now(),R=T<x.current,V=T-g.current<=y0;l.handleScroll(),k();const G=D.scrollTop;P?.isTrusted&&!R&&V&&G<y.current&&b.current&&N(!1),b.current||S()<=c()&&N(!0),y.current=G;const{scrollTop:O,scrollHeight:Y,clientHeight:K}=D,U=(O+K/2)/Math.max(Y,1),Q=Math.floor(U*r.length);s(t,Q)},[t,S,c,l,r.length,N,k,s]);i.useEffect(()=>{const P=a.current;if(!P)return;const D=()=>{g.current=Date.now()};return P.addEventListener("scroll",M,{passive:!0}),P.addEventListener("wheel",D,{passive:!0}),P.addEventListener("touchmove",D,{passive:!0}),()=>{P.removeEventListener("scroll",M),P.removeEventListener("wheel",D),P.removeEventListener("touchmove",D)}},[M]),g0(()=>{if(!t||t===p.current)return;p.current=t,Br.getInstance().recordSessionStart(t),N(!0),u(!1),a.current&&(v(),w({instant:!0}))},[t,v,w,N]),i.useEffect(()=>{if(!b.current||n||!a.current)return;S()>c()&&(v(),w({instant:!0}))},[S,c,n,v,w,r]),i.useEffect(()=>{const P=a.current;if(!P||typeof ResizeObserver>"u")return;const D=new ResizeObserver(()=>{k(),b.current&&S()>c()&&w({instant:!0})});D.observe(P);const T=new MutationObserver(()=>{b.current&&S()>c()&&w({instant:!0})});return T.observe(P,{childList:!0,subtree:!0}),()=>{D.disconnect(),T.disconnect()}},[S,c,w,k]),i.useEffect(()=>{if(typeof window>"u"){k();return}const P=window.requestAnimationFrame(()=>{k()});return()=>{window.cancelAnimationFrame(P)}},[t,r.length,k]);const C=i.useRef(new Map),I=i.useCallback(()=>{k(),b.current&&S()>c()&&w({instant:!0})},[S,c,w,k]),E=i.useCallback(P=>{const D=C.current.get(P);if(D)return D;const T={onChunk:()=>{k(),b.current&&S()>c()&&w({instant:!0})},onComplete:()=>{k()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{k(),b.current&&S()>c()&&w({instant:!0})},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return C.current.set(P,T),T},[S,c,w,k]);return{scrollRef:a,handleMessageContentChange:I,getAnimationHandlers:E,showScrollButton:d,scrollToBottom:j,scrollToPosition:A,isPinned:m}};function v0(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 j0=({open:t,onOpenChange:r,onScrollToMessage:s})=>{const n=me(g=>g.currentSessionId),o=Et(g=>n?g.messages.get(n)||[]:[]),a=me(g=>g.revertToMessage),l=me(g=>g.forkFromMessage),c=me(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=>tu(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(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(vs,{children:[e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(br,{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(lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{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=tu(g.parts),y=g.info.time.created,v=v0(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:v}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{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 N=>{N.stopPropagation(),await a(n,g.info.id),r(!1)},children:e.jsx(On,{className:"h-4 w-4"})})}),e.jsx(it,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{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:N=>{N.stopPropagation(),x(g.info.id)},disabled:d===g.info.id,children:d===g.info.id?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ht,{className:"h-4 w-4"})})}),e.jsx(it,{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(On,{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(Ht,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function tu(t){const r=t.find(s=>s.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const sp=()=>{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}=me(),{isTimelineDialogOpen:b,setTimelineDialogOpen:y}=Ce(),v=i.useMemo(()=>t?o.get(t)??null:null,[t,o]),{isMobile:S}=Qt(),N=!!g?.open;i.useEffect(()=>{!t&&!N&&m()},[t,N,m]);const w=i.useMemo(()=>t?r.get(t)||[]:[],[t,r]),k=i.useMemo(()=>t?s.get(t)||[]:[],[t,s]),A=i.useMemo(()=>t?n.get(t)||[]:[],[t,n]);i.useMemo(()=>[...k,...A],[k,A]);const{scrollRef:j,handleMessageContentChange:M,getAnimationHandlers:C,showScrollButton:I,scrollToBottom:E,scrollToPosition:P,isPinned:D}=w0({currentSessionId:t,sessionMessages:w,updateViewportAnchor:d,isSyncing:f,isMobile:S}),R=!!i.useMemo(()=>t?u.get(t)??null:null,[t,u])?.hasMoreAbove,[V,G]=i.useState(!1);i.useEffect(()=>{G(!1)},[t]);const O=i.useCallback(async()=>{if(!t||V)return;const K=j.current,U=K?.scrollHeight??null,Q=K?.scrollTop??null;G(!0);try{if(await c(t,"up"),K&&U!==null&&Q!==null){const W=K.scrollHeight-U;P(Q+W,{instant:!0})}}finally{G(!1)}},[t,V,c,j,P]),Y=i.useCallback(K=>{const U=j.current;if(!U)return;const Q=U.querySelector(`[data-message-id="${K}"]`);if(Q){const W=U.getBoundingClientRect(),pe=Q.getBoundingClientRect().top-W.top+U.scrollTop-50;U.scrollTo({top:pe,behavior:"smooth"})}},[j]);return i.useEffect(()=>{if(!t||(r.has(t)?r.get(t)??[]:[]).length>0)return;(async()=>{try{await l(t)}finally{const W=x?.get(t)??"idle";(W==="busy"||W==="cooldown")&&D||(typeof window>"u"?E():window.requestAnimationFrame(()=>{E()}))}})()},[t,D,l,r,E,x]),!t&&!N?e.jsx("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(Ei,{})}):!t&&N?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(Ei,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Go,{scrollToBottom:E})})]}):t?a&&w.length===0&&!v&&!r.has(t)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-message-column space-y-4",children:[1,2,3].map(U=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(Ai,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ai,{className:"h-4 w-24"}),e.jsx(Ai,{className:"h-20 w-full"})]})]},U))})}),e.jsx(Go,{scrollToBottom:E})]}):w.length===0&&!v?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Ei,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Go,{scrollToBottom:E})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(tp,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:j,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",children:e.jsx("div",{className:"relative z-0 min-h-full",children:e.jsx(m0,{messages:w,permissions:k,questions:A,onMessageContentChange:M,getAnimationHandlers:C,hasMoreAbove:R,isLoadingOlder:V,onLoadOlder:O,scrollToBottom:E})})}),e.jsx(Ul,{containerRef:j})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[I&&w.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(De,{variant:"outline",size:"sm",onClick:()=>E({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-accent","aria-label":"Scroll to bottom",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsx(Go,{scrollToBottom:E})]}),e.jsx(j0,{open:b,onOpenChange:y,onScrollToMessage:Y})]}):null};class rp 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(Zl,{className:"w-full max-w-md",children:[e.jsx(wf,{className:"text-center",children:e.jsxs(vf,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(jg,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(jf,{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(De,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Reset Chat"]})}),e.jsx("div",{className:"text-xs text-muted-foreground text-center",children:"If the problem persists, try refreshing the page."})]})]})}):this.props.children}}const po=()=>{const t=me(r=>r.currentSessionId);return e.jsx(rp,{sessionId:t||void 0,children:e.jsx(sp,{})})},su=12,S0=[{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"}],k0=({isActive:t,burstKey:r=0,className:s,durationMs:n=900,bursts:o=S0,onComplete:a})=>{const l=Te.useRef(!1);Te.useEffect(()=>{!t&&l.current&&a?.(),t&&(l.current=!0)},[t,a]);const c=Te.useMemo(()=>Array.from({length:su},(d,u)=>{const m=Math.PI*2*u/su;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return t?e.jsx("div",{className:F("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},N0=({durationMs:t=3400}={})=>{const[r,s]=Te.useState({isActive:!1,cycle:0}),n=Te.useRef(null),o=Te.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Te.useCallback(()=>{o(),s(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Te.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 Te.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:l,dismissFireworks:a}},np=i.createContext(void 0),ru=({children:t})=>{const{isActive:r,burstKey:s,triggerFireworks:n,dismissFireworks:o}=N0(),a=i.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(np.Provider,{value:a,children:[t,e.jsx(k0,{isActive:r,burstKey:s})]})},C0=()=>{const t=i.useContext(np);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},Hn=ns()(cs(Ws((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 Gy();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 Xy();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 Yy();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(ls()){const o=await Pr();n=s(o?.defaultGitIdentityId)}else{const o=As()?.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 us({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 qy(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 Ky(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 Qy(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:Hs(()=>hs()),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Hn);const M0=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),D0=({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),v=i.useMemo(()=>M0(h),[h]),S=i.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(C=>C.toLowerCase().includes(M)):r},[u,r]),N=i.useMemo(()=>{const M=u.toLowerCase();return M?s.filter(C=>C.toLowerCase().includes(M)):s},[u,s]),w=M=>{if(M===t){d(!1);return}o(M),d(!1),m("")},k=()=>{p(!0),setTimeout(()=>y.current?.focus(),50)},A=async()=>{if(!(!v||g)){b(!0);try{await a(v),x(""),p(!1),d(!1)}finally{b(!1)}}},j=()=>{x(""),p(!1)};return i.useEffect(()=>{c||(m(""),p(!1),x(""))},[c]),e.jsxs(es,{open:c,onOpenChange:d,children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:l,children:[e.jsx(Ht,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:t||"Detached HEAD"}),e.jsx(Ot,{className:"size-4 opacity-60"})]})})}),e.jsxs(it,{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(ec,{className:"h-full min-h-0",children:[e.jsx(tc,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(sc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(rc,{children:"No branches found."}),e.jsx(ln,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:y,placeholder:"New branch name",value:h,onChange:M=>x(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),A()):M.key==="Escape"&&(M.preventDefault(),j())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:A,disabled:!v||g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:g?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(is,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:j,disabled:g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Zt,{className:"size-4"})})]}):e.jsxs(gs,{onSelect:k,children:[e.jsx(is,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(Ea,{}),e.jsxs(ln,{heading:"Local branches",children:[S.map(M=>e.jsxs(gs,{onSelect:()=>w(M),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:M}),(n?.[M]?.ahead||n?.[M]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[M].ahead||0," ahead ·"," ",n[M].behind||0," behind"]})]}),t===M&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${M}`)),S.length===0&&e.jsx(gs,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Ea,{}),e.jsxs(ln,{heading:"Remote branches",children:[N.map(M=>e.jsx(gs,{onSelect:()=>w(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),N.length===0&&e.jsx(gs,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},A0=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),E0=({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=A0(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(Ht,{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(Jt,{className:"size-4 animate-spin"}):e.jsx(Gt,{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(Zt,{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(Ht,{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(De,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(Gn,{className:"size-4"})})]})},I0=({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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[t==="fetch"?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(Wr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(it,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:s,disabled:a,children:[t==="pull"?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(qn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(it,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[t==="push"?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(So,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(it,{sideOffset:8,children:"Push changes"})]})]})},P0={branch:Ht,briefcase:Fl,house:Tl,graduation:Pl,code:Qs,heart:mm,user:Ys},T0={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 op(t){return t&&T0[t]||"var(--primary)"}const nu=({icon:t,className:r,colorToken:s})=>{const n=P0[t??"branch"]??Ys;return e.jsx(n,{className:r,style:{color:op(s)}})},F0=({activeProfile:t,identities:r,onSelect:s,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(es,{children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:op(t?.color)},disabled:o,children:[n?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(nu,{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(Ot,{className:"size-4 opacity-60"})]})})}),e.jsxs(it,{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(Nt,{onSelect:()=>s(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(nu,{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))})]})},R0=({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(E0,{currentBranch:t.current,onRename:m}):e.jsx(D0,{currentBranch:t.current,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:d,onCreate:u}),(!!t.tracking||t.ahead>0||t.behind>0)&&e.jsxs(lt,{delayDuration:800,children:[e.jsx(ct,{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(So,{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(qn,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:t.behind})]})]})}),e.jsx(it,{sideOffset:8,children:t.tracking?`Upstream: ${t.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(I0,{syncAction:o,onFetch:a,onPull:l,onPush:c,disabled:!t}),e.jsx("div",{className:"flex-1"}),e.jsx(F0,{activeProfile:f,identities:p,onSelect:h,isApplying:x})]}):null,L0=({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(Nl,{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(De,{variant:"outline",onClick:r,disabled:s,children:[s?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(qn,{className:"size-4"}),"Pull ",t," commit",t===1?"":"s"]})]}),ap={"?":{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"}},O0=ap.M;function _0(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 $0(t){const r=_0(t);return ap[r]??O0}const B0=i.memo(function({file:r,checked:s,onToggle:n,onViewDiff:o,onRevert:a,isReverting:l,stats:c}){const d=Te.useMemo(()=>$0(r),[r]),u=d.description,m=c?.insertions??0,f=c?.deletions??0,p=Te.useCallback(g=>{g.key===" "?(g.preventDefault(),n()):g.key==="Enter"&&(g.preventDefault(),o())},[n,o]),h=Te.useCallback(g=>{g.preventDefault(),g.stopPropagation(),n()},[n]),x=Te.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(Al,{className:"size-4 text-primary"}):e.jsx(El,{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(lt,{delayDuration:200,children:[e.jsx(ct,{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(Jt,{className:"size-3.5 animate-spin"}):e.jsx(On,{className:"size-3.5"})})}),e.jsx(it,{sideOffset:8,children:"Revert changes"})]})]})})}),z0=({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(De,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(De,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:l,disabled:u===0,children:"None"})]})]})]}),e.jsx(gt,{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(B0,{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 hn({className:t,variant:r,...s}){return e.jsx(De,{variant:r,size:"sm",className:F("h-7 px-2 py-0",t),...s})}const Ri=38,ou=200,W0=({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=`${Ri}px`;const l=Math.min(Math.max(a.scrollHeight,Ri),ou);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:F("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:Ri,maxHeight:ou}})},H0=({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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(qn,{className:"size-4"})})}),e.jsx(it,{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))})]})},U0=({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;return e.jsxs(No,{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(Co,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(H0,{highlights:n,onInsert:o,onClear:a}),e.jsx(W0,{value:r,onChange:s,placeholder:"Commit message",disabled:m!==null}),p&&e.jsxs(De,{variant:"outline",size:"sm",onClick:h,className:"w-fit",type:"button",children:[e.jsx(Sg,{className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:l,disabled:c||m!==null||t===0||f,"aria-label":"Generate commit message",children:c?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(om,{className:"size-4 text-primary"})})}),e.jsx(it,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(hn,{variant:"outline",onClick:d,disabled:!g||c,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nl,{className:"size-4"}),"Commit"]})}),e.jsx(hn,{variant:"default",onClick:u,disabled:!g||c,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(So,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function au(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 V0(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 G0=({entry:t,isExpanded:r,onToggle:s,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:s,className:F("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:au(t.date),children:au(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(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:l=>{l.stopPropagation(),a(t.hash)},children:e.jsx(Xs,{className:"size-3"})})}),e.jsx(it,{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(Jt,{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:F("font-semibold w-3 text-center",V0(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))})})]}),q0=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],K0=({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(No,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Qa,{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(Ls,{value:String(s),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Os,{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(pn,{placeholder:"Commits"})}),e.jsx(_s,{children:q0.map(f=>e.jsx(rs,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(_a,{className:"size-4 text-muted-foreground"}):e.jsx(Ot,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(Co,{children:e.jsx(gt,{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(G0,{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},ip="gitmojiCache",Q0=1e3*60*60*24*7,lp="1",Y0="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",iu={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:"},cp=t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.emoji=="string"&&typeof r.code=="string"&&typeof r.description=="string"},X0=()=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(ip);if(!t)return null;const r=JSON.parse(t);return!r||r.version!==lp||typeof r.fetchedAt!="number"||!Array.isArray(r.gitmojis)?null:{gitmojis:r.gitmojis.filter(cp),fetchedAt:r.fetchedAt,version:r.version}}catch{return null}},J0=t=>{if(!(typeof window>"u"))try{const r={gitmojis:t,fetchedAt:Date.now(),version:lp};localStorage.setItem(ip,JSON.stringify(r))}catch{return}},Z0=t=>Date.now()-t.fetchedAt<Q0,eS=(t,r)=>{const s=t.toLowerCase(),n=/^([a-z]+)(?:\(.*\))?!?:/,o=s.match(n);if(o){const c=o[1],d=iu[c];if(d)return r.find(u=>u.code===d)||null}const a=s.split(" ")[0],l=iu[a];return l&&r.find(c=>c.code===l)||null};let so=null;const tS=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=me(),{currentDirectory:n}=bt(),o=t?s.get(t)??void 0:void 0,l=r.find(c=>c.id===t)?.directory;return o?.path??l??n??void 0},sS=()=>{const{git:t}=Fr(),r=tS(),{currentSessionId:s,worktreeMetadata:n}=me(),o=s?n.get(s)??void 0:void 0,{profiles:a,globalIdentity:l,defaultGitIdentityId:c,loadProfiles:d,loadGlobalIdentity:u,loadDefaultGitIdentityId:m}=Hn(),f=Vl(r??null),p=cf(r??null),h=df(r??null),x=Ub(r??null),g=Vb(r??null),b=as(be=>be.isLoadingStatus),y=as(be=>be.isLoadingLog),{setActiveDirectory:v,fetchAll:S,fetchStatus:N,fetchBranches:w,fetchLog:k,fetchIdentity:A,setLogMaxCount:j}=as(),M=i.useMemo(()=>!so||so.directory!==r?null:so,[r]),C=at(be=>be.settingsGitmojiEnabled),[I,E]=i.useState(M?.commitMessage??""),[P,D]=i.useState(!1),[T,R]=i.useState(null),[V,G]=i.useState(null),[O,Y]=i.useState(25),[K,U]=i.useState(!1),{triggerFireworks:Q}=C0(),W=i.useRef(new Map),se=i.useRef(0),ee=i.useCallback(()=>{se.current+=1,U(!0)},[]),pe=i.useCallback(()=>{se.current=Math.max(0,se.current-1),se.current===0&&U(!1)},[]),[$,oe]=i.useState(()=>new Set(M?.selectedPaths??[])),[_,z]=i.useState(!1),[X,re]=i.useState(new Set),[ge,H]=i.useState(!1),[fe,we]=i.useState([]),he=i.useCallback(()=>{we([])},[]),[_e,te]=i.useState(new Set),[J,ne]=i.useState(new Map),[ke,Z]=i.useState(new Set),[ye,de]=i.useState(null),[je,ie]=i.useState([]),[Xe,mt]=i.useState(""),Ae=i.useCallback(be=>{navigator.clipboard.writeText(be).then(()=>{q.success("Commit hash copied")}).catch(()=>{q.error("Failed to copy")})},[]),ae=i.useCallback(be=>{te(Ee=>{const B=new Set(Ee);return B.has(be)?B.delete(be):B.add(be),B})},[]);i.useEffect(()=>{if(!r||!t)return;const be=Array.from(_e).filter(Ee=>!J.has(Ee)&&!ke.has(Ee));if(be.length!==0){Z(Ee=>{const B=new Set(Ee);for(const ue of be)B.add(ue);return B});for(const Ee of be)t.getCommitFiles(r,Ee).then(B=>{ne(ue=>new Map(ue).set(Ee,B.files))}).catch(B=>{console.error("Failed to fetch commit files:",B),ne(ue=>new Map(ue).set(Ee,[]))}).finally(()=>{Z(B=>{const ue=new Set(B);return ue.delete(Ee),ue})})}},[_e,r,t,J,ke]),i.useEffect(()=>()=>{if(!r){so=null;return}so={directory:r,selectedPaths:Array.from($),commitMessage:I}},[I,r,$]),i.useEffect(()=>{d(),u(),m()},[d,u,m]),i.useEffect(()=>{if(!r||!t?.getRemoteUrl){de(null);return}t.getRemoteUrl(r).then(de).catch(()=>de(null))},[r,t]),i.useEffect(()=>{if(!C){ie([]);return}let be=!1;const Ee=X0();return Ee&&(ie(Ee.gitmojis),Z0(Ee))?()=>{be=!0}:((async()=>{try{const ue=await fetch(Y0);if(!ue.ok)throw new Error(`Failed to load gitmojis: ${ue.statusText}`);const ve=await ue.json(),Be=Array.isArray(ve.gitmojis)?ve.gitmojis.filter(cp):[];be||(ie(Be),J0(Be))}catch(ue){be||console.warn("Failed to load gitmoji list:",ue)}})(),()=>{be=!0})},[C]),i.useEffect(()=>{r&&(v(r),as.getState().directories.get(r)?.status||S(r,t,{force:!0}))},[r,v,S,t]);const Ue=i.useCallback(async(be=!0)=>{if(r)try{await Promise.all([N(r,t),w(r,t)])}catch(Ee){if(be){const B=Ee instanceof Error?Ee.message:"Failed to refresh repository state";q.error(B)}}},[r,t,N,w]),Se=i.useCallback(async()=>{r&&await k(r,t,O)},[r,t,k,O]),Ne=i.useCallback(async()=>{r&&await A(r,t)},[r,t,A]);i.useEffect(()=>{if(!r||!t?.hasLocalIdentity||f!==!0)return;const be=typeof c=="string"?c.trim():"";if(!be||be==="global"||W.current.get(r)===be)return;let B=!1;return(async()=>{try{const ve=await t.hasLocalIdentity?.(r);if(B||ve===!0)return;ee(),await t.setGitIdentity(r,be),W.current.set(r,be),await Ne()}catch(ve){console.warn("Failed to auto-apply default git identity:",ve)}finally{B||pe()}})(),()=>{B=!0}},[ee,r,c,pe,t,f,Ne]);const Ge=i.useMemo(()=>{if(!p)return[];const be=p.files??[],Ee=new Map;for(const B of be)Ee.set(B.path,B);return Array.from(Ee.values()).sort((B,ue)=>B.path.localeCompare(ue.path))},[p]);i.useEffect(()=>{if(!p||Ge.length===0){oe(new Set),z(!1);return}oe(be=>{const Ee=new Set,B=be??new Set;for(const ue of Ge)B.has(ue.path)?Ee.add(ue.path):_||Ee.add(ue.path);return Ee})},[p,Ge,_]);const rt=async be=>{if(r){R(be);try{if(be==="fetch")await t.gitFetch(r),q.success("Fetched latest updates");else if(be==="pull"){const Ee=await t.gitPull(r);q.success(`Pulled ${Ee.files.length} file${Ee.files.length===1?"":"s"}`)}else be==="push"&&(await t.gitPush(r),q.success("Pushed to remote"));await Ue(!1),await Se()}catch(Ee){const B=Ee instanceof Error?Ee.message:`Failed to ${be==="pull"?"pull":be}`;q.error(B)}finally{R(null)}}},Ke=async(be={})=>{if(!r)return;if(!I.trim()){q.error("Please enter a commit message");return}const Ee=Array.from($).sort();if(Ee.length===0){q.error("Select at least one file to commit");return}const B=be.pushAfter?"commitAndPush":"commit";G(B);try{await t.createGitCommit(r,I.trim(),{files:Ee}),q.success("Commit created successfully"),E(""),oe(new Set),z(!1),he(),await Ue(),be.pushAfter?(await t.gitPush(r),q.success("Pushed to remote"),Q(),await Ue(!1)):await Ue(!1),await Se()}catch(ue){const ve=ue instanceof Error?ue.message:"Failed to create commit";q.error(ve)}finally{G(null)}},Le=i.useCallback(async()=>{if(r){if($.size===0){q.error("Select at least one file to describe");return}H(!0);try{const{message:be}=await t.generateCommitMessage(r,Array.from($)),Ee=be.subject?.trim()??"",B=Array.isArray(be.highlights)?be.highlights:[];if(Ee){let ue=Ee;if(C&&je.length>0){const ve=eS(Ee,je);if(ve){const{code:Be,emoji:ze}=ve;!Ee.startsWith(Be)&&!Ee.startsWith(ze)&&(ue=`${Be} ${Ee}`)}}E(ue)}we(B),q.success("Commit message generated")}catch(be){const Ee=be instanceof Error?be.message:"Failed to generate commit message";q.error(Ee)}finally{H(!1)}}},[r,$,t,C,je]),Ye=async be=>{if(!r||!p)return;const Ee=p.current??null;try{await t.createBranch(r,be,Ee??"HEAD"),q.success(`Created branch ${be}`);let B=!1;try{await t.checkoutBranch(r,be),await t.gitPush(r,{remote:"origin",branch:be,options:["--set-upstream"]}),B=!0}catch(ue){const ve=ue instanceof Error?ue.message:"Unable to push new branch to origin.";q.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",ve]})})}finally{if(Ee)try{await t.checkoutBranch(r,Ee)}catch(ue){console.warn("Failed to restore original branch after creation:",ue)}}await Ue(),await Se(),B&&q.success(`Upstream set for ${be}`)}catch(B){const ue=B instanceof Error?B.message:"Failed to create branch";throw q.error(ue),B}},xt=async(be,Ee)=>{if(r)try{await t.renameBranch(r,be,Ee),q.success(`Renamed branch ${be} to ${Ee}`),await Ue(),await Se()}catch(B){const ue=B instanceof Error?B.message:`Failed to rename branch ${be} to ${Ee}`;q.error(ue)}},nt=async be=>{if(!r)return;const Ee=be.replace(/^remotes\//,"");if(p?.current!==Ee)try{await t.checkoutBranch(r,Ee),q.success(`Checked out ${Ee}`),await Ue(),await Se()}catch(B){const ue=B instanceof Error?B.message:`Failed to checkout ${Ee}`;q.error(ue)}},It=async be=>{if(r){ee();try{await t.setGitIdentity(r,be.id),q.success(`Applied "${be.name}" to repository`),await Ne()}catch(Ee){const B=Ee instanceof Error?Ee.message:"Failed to apply git identity";q.error(B)}finally{pe()}}},Pt=i.useMemo(()=>h?.all?h.all.filter(be=>!be.startsWith("remotes/")).sort():[],[h]),zt=i.useMemo(()=>h?.all?h.all.filter(be=>be.startsWith("remotes/")).map(be=>be.replace(/^remotes\//,"")).sort():[],[h]),We=i.useMemo(()=>{const be=new Map;l&&be.set(l.id,l);let Ee=null;if(ye)try{let B=ye.trim();B.startsWith("git@")&&(B=`https://${B.slice(4).replace(":","/")}`),B.endsWith(".git")&&(B=B.slice(0,-4));const ue=new URL(B);Ee=ue.hostname+ue.pathname}catch{}for(const B of a){if(B.authType!=="token"){be.set(B.id,B);continue}const ue=B.host;if(!ue){be.set(B.id,B);continue}if(!ue.includes("/")){be.set(B.id,B);continue}Ee&&Ee===ue&&be.set(B.id,B)}return Array.from(be.values())},[a,l,ye]),ut=i.useMemo(()=>{if(g?.userName&&g?.userEmail){const be=a.find(Ee=>Ee.userName===g.userName&&Ee.userEmail===g.userEmail);return be||(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]),vt=Ge.length,dt=$.size,Tt=b||T!==null||V!==null,Ct=vt>0,os=be=>{oe(Ee=>{const B=new Set(Ee);return B.has(be)?B.delete(be):B.add(be),B}),z(!0)},St=()=>{const be=new Set(Ge.map(Ee=>Ee.path));oe(be),z(!0)},Lt=()=>{oe(new Set),z(!0)},Ft=i.useCallback(async be=>{if(r){re(Ee=>{const B=new Set(Ee);return B.add(be),B});try{await t.revertGitFile(r,be),q.success(`Reverted ${be}`),await Ue(!1)}catch(Ee){const B=Ee instanceof Error?Ee.message:"Failed to revert changes";q.error(B)}finally{re(Ee=>{const B=new Set(Ee);return B.delete(be),B})}}},[r,Ue,t]),Ut=i.useCallback(()=>{if(fe.length===0)return;const be=fe.map(Ee=>Ee.trim()).filter(Boolean);if(be.length===0){he();return}E(Ee=>{const B=Ee.trim(),ue=B.length>0?`
117
-
118
- `:"";return`${B}${ue}${be.join(`
119
- `)}`.trim()})},[fe,he]),Rt=i.useCallback((be,Ee)=>{const B=Ee||be;E(ue=>{const ve=ue.trimStart();return ve.startsWith(be)||Ee&&ve.startsWith(Ee)?ue:`${B.endsWith(" ")?B:`${B} `}${ue}`.trimStart()}),mt(""),D(!1)},[]),qt=i.useCallback(be=>{Y(be),r&&(j(r,be),k(r,t,be))},[r,j,k,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(Jt,{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(Ht,{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(R0,{status:p,localBranches:Pt,remoteBranches:zt,branchInfo:h?.branches,syncAction:T,onFetch:()=>rt("fetch"),onPull:()=>rt("pull"),onPush:()=>rt("push"),onCheckoutBranch:nt,onCreateBranch:Ye,onRenameBranch:xt,activeIdentityProfile:ut,availableIdentities:We,onSelectIdentity:It,isApplyingIdentity:K,isWorktreeMode:!!o}),e.jsx(gt,{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:[Ct?e.jsx(z0,{changeEntries:Ge,selectedPaths:$,diffStats:p?.diffStats,revertingPaths:X,onToggleFile:os,onSelectAll:St,onClearSelection:Lt,onViewDiff:be=>Ce.getState().navigateToDiff(be),onRevertFile:Ft}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(L0,{behind:p?.behind??0,onPull:()=>rt("pull"),isPulling:T==="pull"})}),Ge.length>0&&e.jsx(U0,{selectedCount:dt,commitMessage:I,onCommitMessageChange:E,generatedHighlights:fe,onInsertHighlights:Ut,onClearHighlights:he,onGenerateMessage:Le,isGeneratingMessage:ge,onCommit:()=>Ke({pushAfter:!1}),onCommitAndPush:()=>Ke({pushAfter:!0}),commitAction:V,isBusy:Tt,gitmojiEnabled:C,onOpenGitmojiPicker:()=>D(!0)})]}),e.jsx(K0,{log:x,isLogLoading:y,logMaxCount:O,onLogMaxCountChange:qt,expandedCommitHashes:_e,onToggleCommit:ae,commitFilesMap:J,loadingCommitHashes:ke,onCopyHash:Ae})]})}),e.jsx(xs,{open:P,onOpenChange:D,children:e.jsxs(ys,{className:"max-w-md p-0 overflow-hidden",children:[e.jsx(vs,{className:"px-4 pt-4",children:e.jsx(js,{children:"Pick a gitmoji"})}),e.jsxs(ec,{className:"h-[420px]",children:[e.jsx(tc,{placeholder:"Search gitmojis...",value:Xe,onValueChange:mt}),e.jsxs(sc,{children:[e.jsx(rc,{children:"No gitmojis found."}),e.jsx(ln,{children:(je.length===0?[]:je.filter(be=>{const Ee=Xe.trim().toLowerCase();return Ee?be.emoji.includes(Ee)||be.code.toLowerCase().includes(Ee)||be.description.toLowerCase().includes(Ee):!0})).map(be=>e.jsxs(gs,{onSelect:()=>Rt(be.emoji,be.code),children:[e.jsx("span",{className:"text-lg",children:be.emoji}),e.jsx("span",{className:"typography-ui-label text-foreground",children:be.code}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:be.description})]},be.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."})})},rS=1e6;function en(t){let r=t.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const Ko=t=>({directory:t,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),lu=ns((t,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:s=>{const n=en(s);return r().sessions.get(n)},setTerminalSession:(s,n)=>{const o=en(s);t(a=>{const l=new Map(a.sessions),c=l.get(o),u=!c||c.terminalSessionId!==n.sessionId?Ko(o):c??Ko(o);return l.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:l}})},setConnecting:(s,n)=>{const o=en(s);t(a=>{const l=new Map(a.sessions),c=l.get(o)??Ko(o);return l.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(s,n)=>{if(!n)return;const o=en(s);t(a=>{const l=new Map(a.sessions),c=l.get(o)??Ko(o),d=a.nextChunkId,u={id:d,data:n},m=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>rS&&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=en(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=en(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=en(s);t(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{t({sessions:new Map,nextChunkId:1})}})),dp=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),nS=[{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'}],oS=[{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'}],up=t=>Object.fromEntries(t.map(r=>[r.id,r])),cu=up(nS),tn=up(oS),aS="ibm-plex-sans",fa="ibm-plex-mono";function iS(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 lS(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 Li=null;function cS(){return Li||(Li=Cg.load()),Li}function dS(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 wl=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(""),v=i.useRef(null),S=i.useRef(!1),N=i.useRef(null),w=i.useRef(null),k=i.useRef(null),A=i.useRef(0),j=i.useRef(null),[,M]=i.useReducer(O=>O+1,0),[C,I]=i.useReducer(O=>O+1,0);x.current=s,g.current=n;const E=i.useCallback((O,Y)=>{const K=j.current,U=m.current;if(!K||!U)return;const Q=U.getBoundingClientRect(),W=Q.left+Q.width/2,se=Q.top+Q.height-12,ee=typeof O=="number"?O:W,pe=typeof Y=="number"?Y:se,$=8,oe=Math.max($,Math.min(Q.width-$,ee-Q.left)),_=Math.max($,Math.min(Q.height-$,pe-Q.top));K.style.left=`${oe}px`,K.style.top=`${_}px`,K.style.bottom="";try{K.focus({preventScroll:!0})}catch{try{K.focus()}catch{}}},[]),P=i.useCallback(()=>{y.current="",v.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(v.current),v.current=null,S.current=!1,N.current=null},[]),D=i.useCallback(()=>{const O=h.current,Y=p.current,K=m.current;if(!O||!Y||!K)return;const U=K.getBoundingClientRect();if(!(U.width<24||U.height<24))try{O.fit();const Q={cols:Y.cols,rows:Y.rows},W=b.current;(!W||W.cols!==Q.cols||W.rows!==Q.rows)&&(b.current=Q,g.current(Q.cols,Q.rows))}catch{}},[]),T=i.useCallback(()=>{if(S.current)return;const O=p.current;if(!O){P();return}if(!y.current)return;const Y=y.current;y.current="",S.current=!0,O.write(Y,()=>{S.current=!1,y.current&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,T()}):T())})},[P]),R=i.useCallback(()=>{v.current===null&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,T()}):T())},[T]),V=i.useCallback(O=>{O&&(y.current+=O,R())},[R]),G=i.useCallback(()=>{if(w.current?.(),w.current=null,k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),!d){A.current=0;return}const O=m.current;if(!O)return;const Y=p.current;if(!Y)return;A.current=0;const K=2.2,U=2.8,Q=25,W=.25,se=8,ee=.05,pe=.015,$={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},oe=()=>typeof performance<"u"?performance.now():Date.now(),_=Math.max(12,Math.round(l*1.35));let z=0;const X=J=>{if(!J)return!1;const ne=Y.getViewportY(),ke=z+J,Z=Math.trunc(ke/_);return z=ke-Z*_,Z!==0&&Y.scrollLines(Z),Y.getViewportY()!==ne},re=()=>{$.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame($.rafId),$.rafId=null},ge={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const J=Object.assign($,{pointerId:null,startX:null,startY:null,moved:!1}),ne=6,ke=je=>{if(je.pointerType==="touch"){re(),J.pointerId=je.pointerId,J.startX=je.clientX,J.startY=je.clientY,J.moved=!1,J.lastY=je.clientY,J.lastTime=oe(),J.velocity=0;try{O.setPointerCapture(je.pointerId)}catch{}}},Z=je=>{if(je.pointerType!=="touch"||J.pointerId!==je.pointerId)return;if(J.startX!==null&&J.startY!==null&&!J.moved){const Ge=je.clientX-J.startX,rt=je.clientY-J.startY;Math.hypot(Ge,rt)>=ne&&(J.moved=!0)}if(J.lastY===null){J.lastY=je.clientY,J.lastTime=oe();return}const ie=J.lastY,Xe=J.lastTime??oe(),mt=oe();J.lastY=je.clientY,J.lastTime=mt;const Ae=ie-je.clientY;if(Math.abs(Ae)<1)return;const ae=Math.max(mt-Xe,8),Ue=K+Math.min(U,Math.abs(Ae)/Q),Se=Ae*Ue,Ne=Se/ae;J.velocity=J.velocity*(1-W)+Ne*W,J.velocity>se?J.velocity=se:J.velocity<-se&&(J.velocity=-se),J.moved&&(je.cancelable&&je.preventDefault(),je.stopPropagation()),X(Se)},ye=je=>{if(je.pointerType!=="touch"||J.pointerId!==je.pointerId)return;const ie=!J.moved;J.pointerId=null,J.startX=null,J.startY=null,J.moved=!1,J.lastY=null,J.lastTime=null;try{O.releasePointerCapture(je.pointerId)}catch{}if(ie){E(je.clientX,je.clientY);return}if(typeof window>"u")return;if(Math.abs(J.velocity)<ee){J.velocity=0;return}let Xe=oe();const mt=()=>{const Ae=oe(),ae=Math.max(Ae-Xe,8);Xe=Ae;const Ue=X(J.velocity*ae)??!1,Se=Math.sign(J.velocity),Ne=Math.max(0,Math.abs(J.velocity)-pe*ae);if(J.velocity=Ne*Se,!Ue||Ne<=ee){re(),J.velocity=0;return}J.rafId=window.requestAnimationFrame(mt)};J.rafId=window.requestAnimationFrame(mt)};O.addEventListener("pointerdown",ke,ge),O.addEventListener("pointermove",Z,ge),O.addEventListener("pointerup",ye,ge),O.addEventListener("pointercancel",ye,ge);const de=O.style.touchAction;O.style.touchAction="manipulation",w.current=()=>{re(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),A.current=0,O.removeEventListener("pointerdown",ke,ge),O.removeEventListener("pointermove",Z,ge),O.removeEventListener("pointerup",ye,ge),O.removeEventListener("pointercancel",ye,ge),O.style.touchAction=de};return}const fe=6,we=J=>{J.touches.length===1&&(re(),$.lastY=J.touches[0].clientY,$.lastTime=oe(),$.velocity=0,$.startX=J.touches[0].clientX,$.startY=J.touches[0].clientY,$.didMove=!1)},he=J=>{if(J.touches.length!==1){$.lastY=null,$.lastTime=null,$.velocity=0,$.startX=null,$.startY=null,$.didMove=!1,re();return}const ne=J.touches[0].clientX,ke=J.touches[0].clientY;if($.startX!==null&&$.startY!==null&&!$.didMove){const ae=ne-$.startX,Ue=ke-$.startY;Math.hypot(ae,Ue)>=fe&&($.didMove=!0)}if($.lastY===null){$.lastY=ke,$.lastTime=oe();return}const Z=$.lastY,ye=$.lastTime??oe(),de=oe();$.lastY=ke,$.lastTime=de;const je=Z-ke;if(Math.abs(je)<1)return;const ie=Math.max(de-ye,8),Xe=K+Math.min(U,Math.abs(je)/Q),mt=je*Xe,Ae=mt/ie;$.velocity=$.velocity*(1-W)+Ae*W,$.velocity>se?$.velocity=se:$.velocity<-se&&($.velocity=-se),$.didMove&&(J.preventDefault(),J.stopPropagation()),X(mt)},_e=J=>{const ne=!$.didMove;$.lastY=null,$.lastTime=null;const ke=$.velocity;if($.startX=null,$.startY=null,$.didMove=!1,ne){const de=J.changedTouches?.[0];E(de?.clientX,de?.clientY);return}if(typeof window>"u")return;if(Math.abs(ke)<ee){$.velocity=0;return}let Z=oe();const ye=()=>{const de=oe(),je=Math.max(de-Z,8);Z=de;const ie=X($.velocity*je)??!1,Xe=Math.sign($.velocity),mt=Math.max(0,Math.abs($.velocity)-pe*je);if($.velocity=mt*Xe,!ie||mt<=ee){re(),$.velocity=0;return}$.rafId=window.requestAnimationFrame(ye)};$.rafId=window.requestAnimationFrame(ye)};O.addEventListener("touchstart",we,ge),O.addEventListener("touchmove",he,ge),O.addEventListener("touchend",_e,ge),O.addEventListener("touchcancel",_e,ge);const te=O.style.touchAction;O.style.touchAction="manipulation",w.current=()=>{re(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),A.current=0,O.removeEventListener("touchstart",we,ge),O.removeEventListener("touchmove",he,ge),O.removeEventListener("touchend",_e,ge),O.removeEventListener("touchcancel",_e,ge),O.style.touchAction=te}},[d,E,l]);return i.useEffect(()=>{let O=!1,Y=null,K=null,U=[];const Q=m.current;return Q?(Q.tabIndex=0,(async()=>{try{const se=await cS();if(O)return;const ee=lS(a,l,o,se),pe=new kg(ee),$=new Ng;Y=pe,p.current=pe,h.current=$,pe.loadAddon($),pe.open(Q),I();const oe=dS(Q);oe?(oe.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=oe,M()):f.current=null,D(),G(),pe.focus(),U=[pe.onData(_=>{x.current(_)})],K=new ResizeObserver(()=>{D()}),K.observe(Q),typeof window<"u"&&window.setTimeout(()=>{D()},0)}catch{}})(),()=>{O=!0,w.current?.(),w.current=null,U.forEach(se=>se.dispose()),K?.disconnect(),Y?.dispose(),p.current=null,h.current=null,f.current=null,b.current=null,P()}):void 0},[D,a,l,G,o,P]),i.useEffect(()=>{const O=p.current;O&&(O.reset(),P(),b.current=null,D(),O.focus())},[t,C,D,P]),i.useEffect(()=>(G(),()=>{w.current?.(),w.current=null}),[G,t]),i.useEffect(()=>{const O=p.current;if(!O)return;if(r.length===0){N.current!==null&&(O.reset(),P(),D());return}const Y=N.current;let K;if(Y===null)K=r;else{const U=r.findIndex(Q=>Q.id===Y);K=U>=0?r.slice(U+1):r}K.length>0&&V(K.map(U=>U.data).join("")),N.current=r[r.length-1].id},[r,C,V,D,P]),i.useImperativeHandle(u,()=>({focus:()=>{if(d){E();return}p.current?.focus()},clear:()=>{const O=p.current;O&&(O.reset(),P(),D())},fit:()=>{D()}}),[d,E,D,P]),e.jsxs("div",{ref:m,className:F("relative h-full w-full terminal-viewport-container",c),style:{backgroundColor:o.background},onClick:O=>{d?E(O.clientX,O.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:j,inputMode:"text",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,"aria-hidden":"true",style:{position:"absolute",left:0,top:0,width:1,height:1,opacity:0,zIndex:1,background:"transparent",color:"transparent",caretColor:"transparent",resize:"none",overflow:"hidden",whiteSpace:"nowrap",border:"none",padding:0,margin:0,outline:"none"},onInput:O=>{const Y=String(O.currentTarget.value||"");if(!Y)return;const K=Y.replace(/\r\n|\r|\n/g,"\r");x.current(K),O.currentTarget.value=""},onKeyDown:O=>{O.key==="Backspace"&&(O.currentTarget.value||x.current(""))}}):null,f.current&&!d?e.jsx(Ul,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});wl.displayName="TerminalViewport";const du=13,uS={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Qo={ctrl:"5",cmd:"3"},mS={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},fS=(t,r)=>{if(r)switch(t){case"arrow-up":return`\x1B[1;${Qo[r]}A`;case"arrow-down":return`\x1B[1;${Qo[r]}B`;case"arrow-right":return`\x1B[1;${Qo[r]}C`;case"arrow-left":return`\x1B[1;${Qo[r]}D`}return uS[t]??null},pS=()=>{const{terminal:t}=Fr(),{currentTheme:r}=Xr(),{monoFont:s}=dp(),{isMobile:n,hasTouchInput:o}=Qt(),{currentSessionId:a,sessions:l,worktreeMetadata:c}=me(),d=a?c.get(a)??void 0:void 0,u=i.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const ne=l.find(Z=>Z.id===a),ke=typeof ne?.directory=="string"?ne.directory:null;return ke&&ke.length>0?ke:null},[a,l,d]),{currentDirectory:m,homeDirectory:f}=bt(),p=u||m||null,h=i.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),x=lu(),g=x.sessions,b=x.setTerminalSession,y=x.setConnecting,v=x.appendToBuffer,S=x.clearTerminalSession,N=x.removeTerminalSession,w=x.clearBuffer,k=i.useMemo(()=>{if(p)return g.get(p)},[g,p]),A=k?.terminalSessionId??null,j=k?.bufferChunks??[],M=k?.bufferLength??0,C=k?.isConnecting??!1,I=A,[E,P]=i.useState(null),[D,T]=i.useState(!1),[R,V]=i.useState(null),[G,O]=i.useState(!1),Y=i.useRef(null),K=i.useRef(null),U=i.useRef(I),Q=i.useRef(p),W=i.useRef(null),ee=Ce(ne=>ne.activeMainTab)==="terminal";i.useEffect(()=>{U.current=I},[I]),i.useEffect(()=>{Q.current=p},[p]),i.useEffect(()=>{!n&&R!==null&&V(null)},[n,R,V]),i.useEffect(()=>{!I&&R!==null&&V(null)},[I,R,V]);const pe=i.useCallback(()=>{Y.current?.(),Y.current=null,K.current=null},[]);i.useEffect(()=>()=>{pe(),U.current=null},[pe]);const $=i.useCallback(ne=>{if(K.current===ne)return;pe();const ke=t.connect(ne,{onEvent:Z=>{const ye=Q.current;if(ye)switch(Z.type){case"connected":{(Z.runtime||Z.ptyBackend)&&console.log(`[Terminal] connected runtime=${Z.runtime??"unknown"} pty=${Z.ptyBackend??"unknown"}`),y(ye,!1),P(null),T(!1),W.current?.focus();break}case"reconnecting":{const de=Z.attempt??0,je=Z.maxAttempts??3;P(`Reconnecting (${de}/${je})...`),T(!1);break}case"data":{Z.data&&v(ye,Z.data);break}case"exit":{const de=typeof Z.exitCode=="number"?Z.exitCode:null,je=typeof Z.signal=="number"?Z.signal:null;v(ye,`\r
120
- [Process exited${de!==null?` with code ${de}`:""}${je!==null?` (signal ${je})`:""}]\r
121
- `),S(ye),y(ye,!1),P("Terminal session ended"),T(!1),pe();break}}},onError:(Z,ye)=>{const de=Q.current;if(!de)return;const je=ye?`Connection failed: ${Z.message}`:Z.message||"Terminal stream connection error";P(je),T(!!ye),ye&&(y(de,!1),pe(),N(de))}},mS);Y.current=()=>{ke.close(),K.current=null},K.current=ne},[v,S,pe,N,y,t,P]);i.useEffect(()=>{let ne=!1;if(!p){P(a?"No working directory available for terminal.":"Select a session to open the terminal."),pe();return}return(async()=>{const Z=p;if(!Q.current||Q.current!==Z)return;let de=lu.getState().getTerminalSession(Z)?.terminalSessionId??null;if(!de){P(null),T(!1),y(Z,!0);try{const je=await t.createSession({cwd:Z});if(ne){try{await t.close(je.sessionId)}catch{}return}b(Z,je),de=je.sessionId}catch(je){ne||(P(je instanceof Error?je.message:"Failed to start terminal session"),T(!0),y(Z,!1));return}}!de||ne||(U.current=de,$(de))})(),()=>{ne=!0,U.current=null,pe()}},[a,p,I,N,y,b,$,pe,t]);const oe=i.useCallback(async()=>{if(!p||G)return;O(!0),P(null),T(!1),pe();const ne=U.current;try{if(t.restartSession&&ne){const ke=await t.restartSession(ne,{cwd:p});b(p,ke),U.current=ke.sessionId,$(ke.sessionId)}else{if(ne)try{await t.close(ne)}catch{}N(p)}}catch(ke){P(ke instanceof Error?ke.message:"Failed to restart terminal"),T(!0)}finally{O(!1)}},[p,G,pe,t,b,$,N]),_=i.useCallback(async()=>{if(p&&!G){O(!0),P(null),T(!1),pe();try{t.forceKill&&await t.forceKill({cwd:p})}catch{}N(p),w(p),W.current?.clear(),await new Promise(ne=>setTimeout(ne,100));try{y(p,!0);const ne=await t.createSession({cwd:p});b(p,ne),U.current=ne.sessionId,$(ne.sessionId)}catch(ne){P(ne instanceof Error?ne.message:"Failed to create terminal"),T(!0),y(p,!1)}finally{O(!1)}}},[p,G,pe,t,N,w,y,b,$]),z=i.useCallback(()=>{if(!p)return;w(p),W.current?.clear(),W.current?.focus();const ne=U.current;ne&&t.sendInput(ne,"\f").catch(ke=>{P(ke instanceof Error?ke.message:"Failed to refresh prompt")})},[w,p,P,t]),X=i.useCallback(ne=>{if(!ne)return;let ke=ne,Z=!1;if(R&&ne.length>0){const de=ne[0];if(de.length===1&&/[a-zA-Z]/.test(de)){const je=de.toUpperCase();(R==="ctrl"||R==="cmd")&&(ke=String.fromCharCode(je.charCodeAt(0)&31),Z=!0)}Z||(Z=!0)}const ye=U.current;ye&&(t.sendInput(ye,ke).catch(de=>{P(de instanceof Error?de.message:"Failed to send input")}),Z&&(V(null),W.current?.focus()))},[R,V,t]),re=i.useCallback((ne,ke)=>{const Z=U.current;Z&&t.resize({sessionId:Z,cols:ne,rows:ke}).catch(()=>{})},[t]),ge=i.useCallback(ne=>{V(ke=>ke===ne?null:ne),W.current?.focus()},[V]),H=i.useCallback(ne=>{const ke=fS(ne,R);ke&&(X(ke),V(null),W.current?.focus())},[R,X,V]);i.useEffect(()=>{if(!n||!R||!I)return;const ne=ke=>{if(ke.repeat)return;const Z=ke.key;if(!Z||Z==="Control"||Z==="Meta"||Z==="Alt"||Z==="Shift")return;const ye=Z.length===1?Z.toLowerCase():Z,de=ke.code??"",je=de.startsWith("Key")&&de.length===4?de.slice(3).toUpperCase():null,ie=Z.length===1&&/[a-zA-Z]/.test(Z)?Z.toUpperCase():je,Xe={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(ye in Xe){ke.preventDefault(),ke.stopPropagation(),H(Xe[ye]);return}if(R==="ctrl"&&ie&&ie.length===1&&ie>="A"&&ie<="Z"){const mt=String.fromCharCode(ie.charCodeAt(0)&31);ke.preventDefault(),ke.stopPropagation(),X(mt),V(null),W.current?.focus()}};return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[R,H,X,n,V,I]);const fe=i.useMemo(()=>{const ne=tn[fa].stack;if(typeof window>"u")return(tn[s]??tn[fa]).stack;const Z=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return Z&&Z.trim().length>0?Z.trim():(tn[s]??tn[fa]).stack??ne},[s]),we=i.useMemo(()=>iS(r),[r]),he=i.useMemo(()=>`${p??"no-dir"}::${I??"pending"}`,[p,I]);i.useEffect(()=>{if(!ee)return;const ne=W.current;if(!ne)return;const ke=()=>{ne.fit()};if(typeof window<"u"){const Z=window.requestAnimationFrame(()=>{ke(),ne.focus()}),ye=[220,400].map(de=>window.setTimeout(ke,de));return()=>{window.cancelAnimationFrame(Z),ye.forEach(de=>window.clearTimeout(de))}}ke()},[ee,he,I]);const _e=E?.includes("Reconnecting"),te=E?_e?e.jsx(Mg,{size:20,className:"text-amber-400"}):e.jsx(Zt,{size:20,className:"text-destructive"}):I&&!C&&!G?e.jsx(ea,{size:20,className:"text-emerald-400"}):C||G?e.jsx(Xi,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Xi,{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:oe,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const J=!I||C||G;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:[te,e.jsxs(De,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:z,disabled:!M,title:"Clear output",type:"button",children:[e.jsx(Us,{size:16}),"Clear"]}),e.jsxs(De,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:oe,disabled:G,title:"Restart terminal session",type:"button",children:[e.jsx(Is,{size:16,className:F((C||G)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(De,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>H("esc"),disabled:J,children:"Esc"}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("tab"),disabled:J,children:[e.jsx(jc,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(De,{type:"button",size:"sm",variant:R==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ge("ctrl"),disabled:J,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(De,{type:"button",size:"sm",variant:R==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ge("cmd"),disabled:J,children:[e.jsx(gn,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("arrow-up"),disabled:J,children:[e.jsx(So,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("arrow-left"),disabled:J,children:[e.jsx(fm,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("arrow-down"),disabled:J,children:[e.jsx(qn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("arrow-right"),disabled:J,children:[e.jsx(jc,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("enter"),disabled:J,children:[e.jsx(On,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:we.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:ee?n?e.jsx(wl,{ref:ne=>{W.current=ne},sessionKey:he,chunks:j,onInput:X,onResize:re,theme:we,fontFamily:fe,fontSize:du,enableTouchScroll:o},he):e.jsx(gt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(wl,{ref:ne=>{W.current=ne},sessionKey:he,chunks:j,onInput:X,onResize:re,theme:we,fontFamily:fe,fontSize:du,enableTouchScroll:o},he)}):null}),E&&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:E}),D&&e.jsx(De,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:_,disabled:G,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},uu=new za,mu=new za,fu=new za,pu=new za,hu=t=>{if(!t)return[];const r=Math.max(1,t.start),s=Math.max(r,t.end);return Lg.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 Og;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,_g.line({class:"oc-cm-selected-line"}))}return o.finish()}},{decorations:n=>n.decorations})};function hS({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=Dg.create({doc:u.current,extensions:[Ag({fixed:!0}),uu.of(Sc(a)),Eg(),Ig.of(" "),Pg.of([Tg,...Fg,...Rg]),Cn.updateListener.of(p=>{if(!p.docChanged)return;const h=p.state.doc.toString();u.current=h,m.current(h)}),mu.of(Cn.editable.of(!o)),fu.of(s??[]),pu.of(hu(l))]});return d.current=new Cn({state:f,parent:c.current}),()=>{d.current?.destroy(),d.current=null}},[]),i.useEffect(()=>{const f=d.current;f&&f.dispatch({effects:[uu.reconfigure(Sc(a)),mu.reconfigure(Cn.editable.of(!o)),fu.reconfigure(s??[]),pu.reconfigure(hu(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:F("h-full w-full","[&_.cm-editor]:h-full [&_.cm-editor]:w-full","[&_.cm-scroller]:font-mono [&_.cm-scroller]:text-[var(--text-code)] [&_.cm-scroller]:leading-6",n)})}const vl=Kn.define($g),mp=Kn.define(Bg),gS=Kn.define(zg),xS=Kn.define(Wg),yS=Kn.define(Hg),bS=Kn.define(Ug);function wS(t){const r=t.trim().toLowerCase();switch(r){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return vl;case"toml":return mp;case"diff":case"patch":return gS;case"json":case"jsonc":case"json5":return vm().language;case"js":case"javascript":return Mn().language;case"jsx":return Mn({jsx:!0}).language;case"ts":case"typescript":return Mn({typescript:!0}).language;case"tsx":return Mn({typescript:!0,jsx:!0}).language;case"yaml":case"yml":return ym().language;case"html":return bm().language;case"css":return wm().language;case"xml":case"svg":return hm().language;case"py":case"python":return xm().language;case"sql":return gm().language;case"rs":case"rust":return pm().language;default:return Gg.matchLanguageName(qg,r,!0)}}const vS=t=>t.split("/").pop()?.toLowerCase()??"";function jS(t){const r=t.toLowerCase();switch(vS(r)){case"dockerfile":return xS;case"makefile":case"gnumakefile":return vl}const n=r.lastIndexOf("."),o=n>=0?r.slice(n+1):"";switch(o){case"ts":case"tsx":case"mts":case"cts":return Mn({typescript:!0,jsx:o==="tsx"});case"js":case"jsx":case"mjs":case"cjs":return Mn({typescript:!1,jsx:o==="jsx"});case"json":case"jsonc":case"json5":case"jsonl":case"ndjson":case"geojson":return vm();case"css":case"scss":case"sass":case"less":return wm();case"html":case"htm":return bm();case"md":case"mdx":case"markdown":case"mdown":case"mkd":return Vg({codeLanguages:wS});case"yml":case"yaml":return ym();case"toml":return mp;case"ini":case"cfg":case"conf":case"config":case"properties":return bS;case"sh":case"bash":case"zsh":case"fish":case"env":return vl;case"py":case"pyw":case"pyi":return xm();case"sql":case"psql":case"plsql":return gm();case"xml":case"xsl":case"xslt":case"xsd":case"dtd":case"plist":case"svg":return hm();case"rs":return pm();case"rb":case"erb":case"rake":case"gemspec":return yS;default:return null}}function gu(t){const r=t.metadata.variant==="dark",s=t.config?.fonts?.mono||"monospace",n=t.colors.syntax.highlights||{},o=t.colors.syntax.tokens||{},a=Cn.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=Kg.define([{tag:Ze.comment,color:t.colors.syntax.base.comment},{tag:Ze.docComment,color:o.commentDoc||t.colors.syntax.base.comment},{tag:Ze.keyword,color:t.colors.syntax.base.keyword},{tag:Ze.controlKeyword,color:t.colors.syntax.base.keyword},{tag:Ze.operatorKeyword,color:t.colors.syntax.base.operator},{tag:Ze.moduleKeyword,color:o.keywordImport||t.colors.syntax.base.keyword},{tag:[Ze.definitionKeyword,Ze.modifier],color:o.storageModifier||t.colors.syntax.base.keyword},{tag:Ze.atom,color:o.boolean||t.colors.syntax.base.number},{tag:[Ze.null,Ze.self],color:t.colors.syntax.base.number},{tag:[Ze.meta,Ze.documentMeta],color:t.colors.syntax.base.comment},{tag:Ze.string,color:t.colors.syntax.base.string},{tag:Ze.escape,color:o.stringEscape||t.colors.syntax.base.foreground},{tag:Ze.regexp,color:o.regex||t.colors.syntax.base.string},{tag:Ze.number,color:t.colors.syntax.base.number},{tag:Ze.bool,color:o.boolean||t.colors.syntax.base.number},{tag:Ze.operator,color:t.colors.syntax.base.operator},{tag:[Ze.derefOperator,Ze.updateOperator,Ze.definitionOperator,Ze.typeOperator,Ze.controlOperator],color:t.colors.syntax.base.operator},{tag:[Ze.logicOperator,Ze.bitwiseOperator,Ze.arithmeticOperator],color:t.colors.syntax.base.operator},{tag:[Ze.compareOperator],color:o.diffModified||t.colors.syntax.base.operator},{tag:[Ze.punctuation,Ze.separator,Ze.bracket,Ze.paren,Ze.brace,Ze.squareBracket,Ze.angleBracket],color:o.punctuation||t.colors.syntax.base.comment},{tag:Ze.function(Ze.variableName),color:o.functionCall||t.colors.syntax.base.function},{tag:Ze.function(Ze.definition(Ze.variableName)),color:t.colors.syntax.base.function},{tag:Ze.function(Ze.propertyName),color:o.method||o.functionCall||t.colors.syntax.base.function},{tag:Ze.namespace,color:o.namespace||t.colors.syntax.base.type},{tag:Ze.moduleKeyword,color:o.module||t.colors.syntax.base.keyword},{tag:Ze.macroName,color:o.macro||t.colors.syntax.base.keyword},{tag:Ze.labelName,color:o.label||t.colors.syntax.base.keyword},{tag:Ze.annotation,color:o.decorator||t.colors.syntax.base.keyword},{tag:Ze.propertyName,color:o.variableProperty||t.colors.syntax.base.keyword},{tag:Ze.attributeName,color:o.tagAttribute||t.colors.syntax.base.keyword},{tag:Ze.standard(Ze.variableName),color:o.method||t.colors.syntax.base.function},{tag:Ze.definition(Ze.variableName),color:t.colors.syntax.base.variable},{tag:Ze.local(Ze.variableName),color:t.colors.syntax.base.variable},{tag:Ze.special(Ze.variableName),color:o.variableOther||t.colors.syntax.base.function},{tag:Ze.variableName,color:t.colors.syntax.base.variable},{tag:Ze.special(Ze.string),color:t.colors.syntax.base.string},{tag:Ze.className,color:o.className||t.colors.syntax.base.type},{tag:Ze.typeName,color:t.colors.syntax.base.type},{tag:Ze.constant(Ze.variableName),color:o.constant||t.colors.syntax.base.variable},{tag:Ze.literal,color:o.constant||t.colors.syntax.base.variable},{tag:Ze.tagName,color:o.tag||t.colors.syntax.base.keyword},{tag:Ze.attributeValue,color:o.tagAttributeValue||t.colors.syntax.base.string},{tag:[Ze.heading,Ze.heading1,Ze.heading2,Ze.heading3,Ze.heading4,Ze.heading5,Ze.heading6],color:t.colors.syntax.base.keyword,fontWeight:"600"},{tag:Ze.monospace,color:t.colors.syntax.base.string},{tag:Ze.link,color:o.url||t.colors.syntax.base.keyword,textDecoration:"underline"}]);return[a,Qg(l)]}const SS=t=>t.slice().sort((r,s)=>r.type!==s.type?r.type==="directory"?-1:1:r.name.localeCompare(s.name)),er=t=>t.replace(/\\/g,"/"),kS=new Set(["node_modules"]),NS=t=>kS.has(t),CS=t=>{const r=er(t);return r==="node_modules"||r.endsWith("/node_modules")||r.includes("/node_modules/")},MS=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=me(),{currentDirectory:n}=bt(),o=t?s.get(t)??void 0:void 0,l=r.find(c=>c.id===t)?.directory;return o?.path??l??n??""},ro=2e5,DS=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"]),AS=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"]),ES=new Set(["png","jpg","jpeg","gif","svg","webp","ico","icns","bmp","tiff","tif","psd","ai","eps","raw","cr2","nef","heic","heif","avif","jxl"]),IS=new Set(["md","mdx","markdown","mdown","mkd","txt","text","rtf","doc","docx","odt","pdf","rst","adoc","asciidoc","org","tex","latex","bib"]),xu=t=>{const r=t?.toLowerCase();return r&&DS.has(r)?e.jsx(Qs,{className:"h-4 w-4 flex-shrink-0 text-blue-500"}):r&&AS.has(r)?e.jsx(Qs,{className:"h-4 w-4 flex-shrink-0 text-yellow-500"}):r&&ES.has(r)?e.jsx(vr,{className:"h-4 w-4 flex-shrink-0 text-green-500"}):r&&IS.has(r)?e.jsx(ho,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(ho,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})},PS=()=>{const{files:t,runtime:r}=Fr(),{currentTheme:s}=Xr();i.useMemo(()=>cc(s),[s]);const{isMobile:n,screenWidth:o}=Qt(),a=Mo(),l=ei(),c=MS(),d=er(c),u=Va(xe=>xe.searchFiles),[m,f]=i.useState(""),p=Za(m,200),h=i.useRef(null),[x,g]=i.useState(!1),[b,y]=i.useState(n),[v,S]=i.useState(new Set),[N,w]=i.useState({}),k=i.useRef(new Set),A=i.useRef(new Set),[j,M]=i.useState([]),[C,I]=i.useState(!1),[E,P]=i.useState(null),[D,T]=i.useState(""),[R,V]=i.useState(!1),[G,O]=i.useState(null),[Y,K]=i.useState(""),[U,Q]=i.useState(""),[W,se]=i.useState(!1),[ee,pe]=i.useState(!1),$=i.useRef(null),oe=i.useRef(null),_=i.useRef(!1),[z,X]=i.useState(null),[re,ge]=i.useState(null),[H,fe]=i.useState(""),[we,he]=i.useState(!1),[_e,te]=i.useState(null),J=!!t.writeFile,ne=!!t.createDirectory,ke=!!t.rename,Z=!!t.delete,ye=i.useCallback((xe,Ie)=>{X(xe),ge(Ie),fe(xe==="rename"&&Ie.name||""),he(!1)},[]),[de,je]=i.useState(null),[ie,Xe]=i.useState(""),mt=i.useRef(!1),Ae=i.useRef(null),ae=me(xe=>xe.sendMessage),Ue=me(xe=>xe.currentSessionId),{currentProviderId:Se,currentModelId:Ne,currentAgentName:Ge,currentVariant:rt}=at(),Ke=ht(xe=>xe.getSessionAgentSelection),Le=ht(xe=>xe.getAgentModelForSession),Ye=ht(xe=>xe.getAgentModelVariantForSession),xt=Ce(xe=>xe.setActiveMainTab),nt=Ce(xe=>xe.setMainTabGuard),{inputBarOffset:It,isKeyboardOpen:Pt}=Ce();i.useEffect(()=>{const xe=()=>{mt.current=!1,Ae.current=null};return document.addEventListener("mouseup",xe),()=>document.removeEventListener("mouseup",xe)},[]),i.useEffect(()=>{je(null),Xe(""),nt(null),Q(""),se(!1)},[E?.path,nt]),i.useEffect(()=>{if(!de)return;const xe=st=>{const $e=st.target;document.querySelector("[data-comment-ui]")?.contains($e)||$e.closest(".cm-gutterElement")||$e.closest("[data-sonner-toast]")||$e.closest("[data-sonner-toaster]")||(je(null),Xe(""))},Ie=setTimeout(()=>{document.addEventListener("click",xe)},100);return()=>{clearTimeout(Ie),document.removeEventListener("click",xe)}},[de]);const zt=i.useCallback((xe,Ie)=>{const st=xe.split(`
122
- `),$e=Math.max(1,Ie.start),kt=Math.min(st.length,Ie.end);return $e>kt?"":st.slice($e-1,kt).join(`
123
- `)},[]),We=i.useCallback(async()=>{if(!de||!ie.trim()||!E)return;if(!Ue){q.error("Select a session to send comment");return}const xe=Ke(Ue)||Ge,Ie=xe?Le(Ue,xe):null,st=Ie?.providerId||Se,$e=Ie?.modelId||Ne;if(!st||!$e){q.error("Select a model to send comment");return}const kt=xe&&st&&$e?Ye(Ue,xe,st,$e)??rt:rt,Mt=zt(D,de),Kt=Tr(E.path)||"text",pt=E.name,Ss=de.start,ms=de.end,Yt=`Comment on \`${pt}\` lines ${Ss}-${ms}:
124
- \`\`\`${Kt}
125
- ${Mt}
126
- \`\`\`
127
-
128
- ${ie}`;Xe(""),je(null),xt("chat");try{await ae(Yt,st,$e,xe,void 0,void 0,void 0,kt)}catch(Vs){console.error("Failed to send comment",Vs)}},[de,ie,E,D,Ue,Se,Ne,Ge,rt,zt,ae,xt,Ke,Le,Ye]),ut=i.useCallback((xe,Ie)=>{const st=Ie.filter($e=>$e&&typeof $e.name=="string"&&$e.name.length>0).filter($e=>a||!$e.name.startsWith(".")).filter($e=>l||!NS($e.name)).map($e=>{const kt=$e.name,Mt=er($e.path||`${xe}/${kt}`),Kt=$e.isDirectory?"directory":"file",pt=Kt==="file"&&kt.includes(".")?kt.split(".").pop()?.toLowerCase():void 0;return{name:kt,path:Mt,type:Kt,extension:pt}});return SS(st)},[l,a]),vt=i.useCallback(async xe=>{const Ie=er(xe.trim());if(Ie&&!(k.current.has(Ie)||A.current.has(Ie))){A.current=new Set(A.current),A.current.add(Ie);try{const st=!l;let $e;r.isDesktop?$e=(await t.listDirectory(Ie,{respectGitignore:st})).entries.map(Kt=>({name:Kt.name,path:Kt.path,isDirectory:Kt.isDirectory})):$e=(await Fe.listLocalDirectory(Ie,{respectGitignore:st})).map(Kt=>({name:Kt.name,path:Kt.path,isDirectory:Kt.isDirectory}));const kt=ut(Ie,$e);k.current=new Set(k.current),k.current.add(Ie),w(Mt=>({...Mt,[Ie]:kt}))}catch{w(st=>({...st,[Ie]:st[Ie]??[]}))}finally{A.current=new Set(A.current),A.current.delete(Ie)}}},[t,ut,r.isDesktop,l]),dt=i.useCallback(async()=>{const xe=er(c.trim());xe&&(k.current=new Set,A.current=new Set,S(new Set),w({}),await vt(xe))},[c,vt]);i.useEffect(()=>{c&&(dt(),P(null),T(""),O(null),K(""),g(!1))},[c,dt]),i.useEffect(()=>{c&&dt()},[c,dt,l]);const Tt=i.useCallback(async xe=>{if(xe?.preventDefault(),!(!re||!z)){he(!0);try{if(z==="createFile"){if(!H.trim())throw new Error("Filename is required");const Ie=re.path,st=Ie?`${Ie}/`:"",$e=er(`${st}${H.trim()}`);if(!t.writeFile)throw new Error("Write not supported");(await t.writeFile($e,"")).success&&(q.success("File created"),await dt())}else if(z==="createFolder"){if(!H.trim())throw new Error("Folder name is required");const Ie=re.path,st=Ie?`${Ie}/`:"",$e=er(`${st}${H.trim()}`);(await t.createDirectory($e)).success&&(q.success("Folder created"),await dt())}else if(z==="rename"){if(!H.trim())throw new Error("Name is required");const Ie=re.path,st=Ie.split("/").slice(0,-1).join("/"),$e=st?`${st}/`:"",kt=er(`${$e}${H.trim()}`);t.rename?(await t.rename(Ie,kt)).success&&(q.success("Renamed successfully"),await dt(),E?.path===Ie&&P(null)):q.error("Rename not supported")}else z==="delete"&&(t.delete?(await t.delete(re.path)).success&&(q.success("Deleted successfully"),await dt(),(E?.path===re.path||E?.path.startsWith(re.path+"/"))&&(P(null),T(""))):q.error("Delete not supported"));X(null)}catch(Ie){q.error(Ie instanceof Error?Ie.message:"Operation failed")}finally{he(!1)}}},[z,re,H,t,dt,E]),Ct=i.useCallback((xe,Ie)=>{const st=xe.trim().toLowerCase();if(!st)return 0;const $e=Ie.toLowerCase();let kt=0,Mt=-1,Kt=0;for(let pt=0;pt<st.length;pt+=1){const Ss=st[pt];if(!Ss||Ss===" ")continue;const ms=$e.indexOf(Ss,Mt+1);if(ms===-1)return null;const Yt=ms-Mt-1;if(Yt===0?Kt+=1:Kt=0,kt+=10,kt+=Math.max(0,18-ms),kt-=Math.max(0,Yt),ms===0)kt+=12;else{const Vs=$e[ms-1];(Vs==="/"||Vs==="_"||Vs==="-"||Vs==="."||Vs===" ")&&(kt+=10)}kt+=Kt>0?12:0,Mt=ms}return kt+=Math.max(0,24-Math.round($e.length/3)),kt},[]);i.useEffect(()=>{c&&dt()},[c,dt,l]),i.useEffect(()=>{if(!c){M([]),I(!1);return}const xe=p.trim();if(!xe){M([]),I(!1);return}const Ie=xe.toLowerCase();let st=!1;return I(!0),u(c,xe,150,{includeHidden:a,respectGitignore:!l}).then($e=>{if(st)return;const Mt=$e.filter(pt=>l||!CS(pt.path)).map(pt=>{const Ss=pt.relativePath||pt.name||pt.path,ms=Ct(Ie,Ss);return ms===null?null:{hit:pt,score:ms,labelLength:Ss.length}}).filter(Boolean);Mt.sort((pt,Ss)=>Ss.score-pt.score||pt.labelLength-Ss.labelLength||pt.hit.path.localeCompare(Ss.hit.path));const Kt=Mt.map(({hit:pt})=>({name:pt.name,path:er(pt.path),type:"file",extension:pt.extension,relativePath:pt.relativePath}));M(Kt)}).catch(()=>{st||M([])}).finally(()=>{st||I(!1)}),()=>{st=!0}},[c,p,Ct,u,a,l]);const os=i.useCallback(async xe=>{if(t.readFile)return(await t.readFile(xe)).content??"";const Ie=await fetch(`/api/fs/read?path=${encodeURIComponent(xe)}`);if(!Ie.ok){const st=await Ie.json().catch(()=>({error:Ie.statusText}));throw new Error(st.error||"Failed to read file")}return Ie.text()},[t]),St=i.useMemo(()=>D.length>ro?`${D.slice(0,ro)}
129
-
130
- … truncated …`:D,[D]),Lt=i.useMemo(()=>U!==St,[U,St]),Ft=i.useCallback(async()=>{if(!E||!t.writeFile){q.error("Saving not supported");return}if(Lt){se(!0);try{if(!(await t.writeFile(E.path,U))?.success)throw new Error("Failed to write file");T(U)}catch(xe){q.error(xe instanceof Error?xe.message:"Save failed")}finally{se(!1)}}},[U,t,Lt,E]);i.useEffect(()=>{if(!Lt){nt(null);return}const xe=Ie=>_.current?(_.current=!1,!0):(pe(!0),oe.current=Ie,!1);return nt(xe),()=>{Ce.getState().mainTabGuard===xe&&nt(null)}},[Lt,nt]),i.useEffect(()=>{const xe=Ie=>{Ts(Ie)&&Ie.key.toLowerCase()==="s"&&(Ie.preventDefault(),W||Ft())};return window.addEventListener("keydown",xe),()=>window.removeEventListener("keydown",xe)},[W,Ft]);const Ut=i.useCallback(async xe=>{if(_.current)_.current=!1;else if(Lt){pe(!0),$.current=xe;return}P(xe),O(null),K("");const Ie=vo(xe.path);n&&g(!0);const st=xe.path.toLowerCase().endsWith(".svg");if(r.isDesktop&&Ie&&!st){T(""),V(!0);return}if(!r.isDesktop&&Ie&&!st){T(""),V(!1);return}V(!0);try{const $e=await os(xe.path);T($e),Q($e.length>ro?`${$e.slice(0,ro)}
131
-
132
- … truncated …`:$e)}catch($e){T(""),Q(""),O($e instanceof Error?$e.message:"Failed to read file")}finally{V(!1)}},[Lt,n,os,r.isDesktop]),Rt=i.useCallback(()=>{const xe=$.current,Ie=oe.current;if($.current=null,oe.current=null,_.current=!0,pe(!1),Q(St),xe){Ut(xe);return}Ie&&(nt(null),Ce.getState().setActiveMainTab(Ie))},[St,Ut,nt]),qt=i.useCallback(async()=>{const xe=$.current,Ie=oe.current;if($.current=null,oe.current=null,_.current=!0,pe(!1),await Ft(),xe){await Ut(xe);return}Ie&&(nt(null),Ce.getState().setActiveMainTab(Ie))},[Ut,Ft,nt]),be=i.useCallback(async xe=>{const Ie=er(xe);S(st=>{const $e=new Set(st);return $e.has(Ie)?$e.delete(Ie):$e.add(Ie),$e}),k.current.has(Ie)||await vt(Ie)},[vt]),Ee=i.useCallback((xe,Ie)=>{const st=N[xe]??[];return st.map(($e,kt)=>{const Mt=$e.type==="directory",Kt=Mt&&v.has($e.path),pt=E?.path===$e.path,Ss=Mt&&A.current.has($e.path),ms=kt===st.length-1;return e.jsxs("li",{className:"relative",children:[Ie>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),ms&&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:Yt=>{!ke&&!J&&!ne&&!Z||(Yt.preventDefault(),te($e.path))},children:[e.jsxs("button",{type:"button",onClick:()=>{Mt?be($e.path):Ut($e)},className:F("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",pt?"bg-accent/70":"hover:bg-accent/40"),children:[Mt?Ss?e.jsx(Jt,{className:"h-4 w-4 flex-shrink-0 animate-spin"}):Kt?e.jsx(Yg,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):e.jsx(Xg,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):xu($e.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:$e.path,children:$e.name})]}),(ke||J||ne||Z)&&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:_e===$e.path,onOpenChange:Yt=>te(Yt?$e.path:null),children:[e.jsx(ts,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(Jg,{className:"h-4 w-4"})})}),e.jsxs(ss,{align:"end",onCloseAutoFocus:()=>te(null),children:[ke&&e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),ye("rename",$e)},children:[e.jsx(Gn,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),navigator.clipboard.writeText($e.path),q.success("Path copied")},children:[e.jsx(Xs,{className:"mr-2 h-4 w-4"})," Copy Path"]}),Mt&&(J||ne)&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),J&&e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),ye("createFile",$e)},children:[e.jsx(kc,{className:"mr-2 h-4 w-4"})," New File"]}),ne&&e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),ye("createFolder",$e)},children:[e.jsx(Qi,{className:"mr-2 h-4 w-4"})," New Folder"]})]}),Z&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),ye("delete",$e)},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]})})]}),Mt&&Kt&&e.jsx("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:Ee($e.path,Ie+1)})]},$e.path)})},[N,v,Ut,E?.path,be,ye,J,ne,ke,Z,_e,te]),B=!!(E?.path&&vo(E.path)),ue=!!(E?.path&&E.path.toLowerCase().endsWith(".svg")),ve=i.useMemo(()=>{if(!E?.path)return"";const xe=er(E.path);if(d&&xe.startsWith(d)){const Ie=xe.slice(d.length);return Ie.startsWith("/")?Ie.slice(1):Ie}return xe},[E?.path,d]),Be=!!(E&&(!B||ue)&&D.length>0),ze=!!(E&&ve.length>0),tt=!!(E&&!B&&t.writeFile&&D.length<=ro),Me=i.useMemo(()=>{if(!E?.path)return[gu(s)];const xe=[gu(s)],Ie=jS(E.path);return Ie&&xe.push(Ie),b&&xe.push(Cn.lineWrapping),xe},[s,E?.path,b]),qe=E?.path&&B?r.isDesktop?ue?`data:${ll(E.path)};utf8,${encodeURIComponent(D)}`:Y:ue?`data:${ll(E.path)};utf8,${encodeURIComponent(D)}`:`/api/fs/raw?path=${encodeURIComponent(E.path)}`:"";i.useEffect(()=>{let xe=!1;return(async()=>{if(!r.isDesktop||!E?.path||!B||ue){K("");return}O(null);try{if(t.readFileBinary){const Mt=await t.readFileBinary(E.path);xe||K(Mt.dataUrl);return}const $e=(await bs(()=>import("./vendor-.bun-BrcdMJ39.js").then(Mt=>Mt.dc),__vite__mapDeps([0,1]))).convertFileSrc;if(!$e)return;const kt=$e(E.path,"asset");xe||K(kt)}catch(st){xe||(K(""),O(st instanceof Error?st.message:"Failed to read file"))}finally{xe||V(!1)}})(),()=>{xe=!0}},[t,B,ue,r.isDesktop,E?.path]);const et=()=>e.jsx(xs,{open:!!z,onOpenChange:xe=>!xe&&X(null),children:e.jsxs(ys,{children:[e.jsxs(vs,{children:[e.jsxs(js,{children:[z==="createFile"&&"Create File",z==="createFolder"&&"Create Folder",z==="rename"&&"Rename",z==="delete"&&"Delete"]}),e.jsxs(Ns,{children:[z==="createFile"&&`Create a new file in ${re?.path??"root"}`,z==="createFolder"&&`Create a new folder in ${re?.path??"root"}`,z==="rename"&&`Rename ${re?.name}`,z==="delete"&&`Are you sure you want to delete ${re?.name}? This action cannot be undone.`]})]}),z!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(jt,{value:H,onChange:xe=>fe(xe.target.value),placeholder:z==="rename"?"New name":"Name",onKeyDown:xe=>{xe.key==="Enter"&&Tt()},autoFocus:!0})}),e.jsxs(zs,{children:[e.jsx(De,{variant:"outline",onClick:()=>X(null),disabled:we,children:"Cancel"}),e.jsx(De,{variant:z==="delete"?"destructive":"default",onClick:()=>{Tt()},disabled:we||z!=="delete"&&!H.trim(),children:we?e.jsx(Jt,{className:"animate-spin"}):z==="delete"?"Delete":"Confirm"})]})]})}),ot=()=>!de||!E?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:ie,onChange:xe=>{Xe(xe.target.value);const Ie=xe.target;Ie.style.height="auto";const $e=20*5+8;Ie.style.height=`${Math.min(Ie.scrollHeight,$e)}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:xe=>{xe.key==="Enter"&&(xe.metaKey||xe.ctrlKey)&&(xe.preventDefault(),We()),xe.key==="Escape"&&(xe.preventDefault(),je(null),Xe(""))}}),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:[E.name,":",de.start,"-",de.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!n&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Xt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:xe=>{ie.trim()&&(xe.preventDefault(),We())},onClick:()=>{n||We()},disabled:!ie.trim(),className:F("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",ie.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Oa,{className:"h-[18px] w-[18px]"})})]})]})]})}),_t=e.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[e.jsx(xs,{open:ee,onOpenChange:xe=>{xe||pe(!0)},children:e.jsxs(ys,{showCloseButton:!1,className:"max-w-md",children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Unsaved changes"}),e.jsx(Ns,{children:"Save your edits before continuing?"})]}),e.jsxs(zs,{children:[e.jsx(De,{variant:"outline",onClick:()=>{qt()},disabled:W,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(De,{variant:"destructive",onClick:Rt,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(Cl,{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:E?E.name:"Select a file"}),E&&!n&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:ve,children:ve})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[tt&&e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>{Ft()},disabled:!Lt||W,className:"h-5 w-5 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Xt()}+S)`,"aria-label":`Save (${Xt()}+S)`,children:W?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Zg,{className:"h-4 w-4"})}),tt&&E&&!B&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),E&&!B&&e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>y(!b),className:F("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(em,{className:"size-4"})}),(Be||ze)&&(tt||E&&!B)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),Be&&e.jsx(De,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(D),q.success("Copied")}catch{q.error("Copy failed")}},className:"h-5 w-5 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:e.jsx(rm,{className:"h-4 w-4"})}),ze&&e.jsx(De,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(ve),q.success("Copied")}catch{q.error("Copy failed")}},className:"h-5 w-5 p-0",title:`Copy file path (${ve})`,"aria-label":`Copy file path (${ve})`,children:e.jsx(ex,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(gt,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:E?R?e.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):G?e.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:G}):B?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("img",{src:qe,alt:E?.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(hS,{value:U,onChange:Q,extensions:Me,className:"h-full",highlightLines:de?{start:Math.min(de.start,de.end),end:Math.max(de.start,de.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(xe,Ie,st)=>{if(!(st instanceof MouseEvent)||st.button!==0)return!1;st.preventDefault();const $e=xe.state.doc.lineAt(Ie.from).number;if(n&&de&&!st.shiftKey){const kt=Math.min(de.start,de.end,$e),Mt=Math.max(de.start,de.end,$e);return je({start:kt,end:Mt}),mt.current=!1,Ae.current=null,!0}if(mt.current=!0,Ae.current=$e,de&&st.shiftKey){const kt=Math.min(de.start,$e),Mt=Math.max(de.end,$e);je({start:kt,end:Mt})}else je({start:$e,end:$e});return!0},mouseover:(xe,Ie,st)=>{if(!(st instanceof MouseEvent)||st.buttons!==1||!mt.current||Ae.current===null)return!1;const $e=xe.state.doc.lineAt(Ie.from).number,kt=Math.min(Ae.current,$e),Mt=Math.max(Ae.current,$e);return je({start:kt,end:Mt}),!1},mouseup:()=>(mt.current=!1,Ae.current=null,!1)}}})}):e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}),de&&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:F("pointer-events-auto pb-2 transition-none w-full flex justify-center",n&&Pt?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:n&&!Pt&&It>0?`${It}px`:"16px"},"data-keyboard-avoid":"true",children:ot()})})]}),$t=!!(d&&N[d]),wt=e.jsxs("section",{className:F("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:F("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(lr,{className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{ref:h,value:m,onChange:xe=>f(xe.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(Zt,{className:"h-4 w-4"})})]}),e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>ye("createFile",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File",children:e.jsx(kc,{className:"h-4 w-4"})}),e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>ye("createFolder",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder",children:e.jsx(Qi,{className:"h-4 w-4"})}),e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>{dt()},className:"h-8 w-8 p-0 flex-shrink-0",children:e.jsx(Wr,{className:"h-4 w-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:F("py-2",n?"px-3":"px-2"),children:e.jsx("ul",{className:"flex flex-col",children:C?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Searching…"]}):j.length>0?j.map(xe=>{const Ie=E?.path===xe.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{Ut(xe)},className:F("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",Ie?"bg-accent/70":"hover:bg-accent/40"),children:[xu(xe.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:xe.path,children:xe.relativePath??xe.path})]})},xe.path)}):$t?Ee(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:[et(),n?x?_t:wt: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:wt}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:_t})]})]})},fp=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Dl},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:wr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:gn},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:um},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:_n},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Ht},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:un}],TS={},FS={},RS={};fp.forEach(t=>{TS[t.id]=t.label,FS[t.id]=t.description,RS[t.id]=t});const LS=t=>t==="doom_loop"||t==="external_directory"?"ask":"allow",OS=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},yu=t=>{const r=OS(t);if(r.length===0)return;const s={};for(const l of r)l.permission&&((s[l.permission]||={})[l.pattern]=l.action);const n=s["*"]?.["*"],o=Object.keys(s);if(o.length===1&&o[0]==="*"&&Object.keys(s["*"]||{}).length===1&&s["*"]?.["*"])return s["*"]["*"];const a={};for(const l of o){const c=s[l],d=Object.keys(c);if(d.length===1&&d[0]==="*"&&l!=="*"){const u=c["*"],m=LS(l);if(n){if(u===n)continue}else if(u===m)continue;a[l]=u}else l==="*"&&d.length===1&&d[0]==="*"?a[l]=c["*"]:a[l]=c}return Object.keys(a).length>0?a:void 0},_S=({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}=Qr(),{setSidebarOpen:p}=Ce(),{isMobile:h}=Qt(),[x,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=x?"bg-transparent":b?"bg-background":"bg-sidebar",v=()=>{const E="new-agent";let P=E,D=1;for(;l.some(T=>T.name===P);)P=`${E}-${D}`,D++;d({name:P,scope:"user"}),c(P),t?.(),h&&p(!1)},S=async E=>{if(sn(E)){q.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${E.name}"?`)&&(await m(E.name)?q.success(`Agent "${E.name}" deleted successfully`):q.error("Failed to delete agent"))},N=async E=>{sn(E)&&window.confirm(`Are you sure you want to reset agent "${E.name}" to its default configuration?`)&&(await m(E.name)?q.success(`Agent "${E.name}" reset to default`):q.error("Failed to reset agent"))},w=E=>{const P=E.name;let D=1,T=`${P}-copy`;for(;l.some(O=>O.name===T);)D++,T=`${P}-copy-${D}`;const R=E,V=E.model?.providerID&&E.model?.modelID?`${E.model.providerID}/${E.model.modelID}`:null,G=E;d({name:T,scope:R.scope||"user",description:E.description,model:V,temperature:E.temperature,top_p:E.topP,prompt:E.prompt,mode:E.mode,permission:yu(E.permission),disable:G.disable}),c(T),h&&p(!1)},k=E=>{o(E.name),s(E)},A=async()=>{if(!r)return;const E=n.trim().replace(/\s+/g,"-");if(!E){q.error("Agent name is required");return}if(E===r.name){s(null);return}if(l.some(R=>R.name===E)){q.error("An agent with this name already exists");return}const P=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,D=r;await u({name:E,description:r.description,model:P,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:yu(r.permission),disable:D.disable,scope:D.scope})?await m(r.name)?(q.success(`Agent renamed to "${E}"`),c(E)):q.error("Failed to remove old agent after rename"):q.error("Failed to rename agent"),s(null)},j=E=>{switch(E){case"primary":return e.jsx(fn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Sm,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(jm,{className:"h-3 w-3 text-primary"});default:return null}},M=l.filter(E=>!zm(E)),C=M.filter(sn),I=M.filter(E=>!sn(E));return e.jsxs("div",{className:F("flex h-full flex-col",y),children:[e.jsx("div",{className:F("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",M.length]}),e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(is,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:M.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(go,{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:[C.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"}),C.map(E=>e.jsx(bu,{agent:E,isSelected:a===E.name,onSelect:()=>{c(E.name),t?.(),h&&p(!1)},onReset:()=>N(E),onDuplicate:()=>w(E),getAgentModeIcon:j},E.name))]}),I.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"}),I.map(E=>e.jsx(bu,{agent:E,isSelected:a===E.name,onSelect:()=>{c(E.name),t?.(),h&&p(!1)},onRename:()=>k(E),onDelete:()=>S(E),onDuplicate:()=>w(E),getAgentModeIcon:j},E.name))]})]})}),e.jsx(xs,{open:r!==null,onOpenChange:E=>!E&&s(null),children:e.jsxs(ys,{children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Rename Agent"}),e.jsxs(Ns,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:E=>o(E.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:E=>{E.key==="Enter"&&A()}}),e.jsxs(zs,{children:[e.jsx(De,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(hn,{onClick:A,children:"Rename"})]})]})})]})},bu=({agent:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:l,getAgentModeIcon:c})=>{const d=t;return e.jsx("div",{className:F("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||sn(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:sn(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(De,{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(Gr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(Gn,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),l()},children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Is,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Ms({className:t,variant:r,...s}){return e.jsx(De,{variant:r,size:"sm",className:F("h-6 px-2 text-xs",t),...s})}const $S=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),BS=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=$S.format(t);return r.endsWith(".0")?r.slice(0,-2):r},dc=({providerId:t,modelId:r,onChange:s,className:n,allowedProviderIds:o})=>{const{providers:a,modelsMetadata:l}=at(),c=Ce(W=>W.isMobile),{toggleFavoriteModel:d,isFavoriteModel:u,addRecentModel:m}=Ce(),{favoriteModelsList:f,recentModelsList:p}=oc(),{isMobile:h}=Qt(),x=c||h,[g,b]=i.useState(!1),[y,v]=i.useState(new Set),[S,N]=i.useState(!1),[w,k]=i.useState(""),[A,j]=i.useState(0),M=i.useRef([]),C=i.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),I=i.useMemo(()=>C?a.filter(W=>C.has(String(W.id))):a,[a,C]),E=()=>b(!1),P=W=>{v(se=>{const ee=new Set(se);return ee.has(W)?ee.delete(W):ee.add(W),ee})};i.useEffect(()=>{S||(k(""),j(0))},[S]),i.useEffect(()=>{j(0)},[w]);const D=W=>{const se=W?.name||W?.id||"",ee=String(se);return ee.length>40?ee.substring(0,37)+"...":ee},T=(W,se)=>{const ee=`${W}/${se}`;return l.get(ee)},R=(W,se)=>{s(W,se),W&&se&&m(W,se),N(!1)},V=(W,se)=>{if(!w.trim())return!0;const ee=w.toLowerCase();return W.toLowerCase().includes(ee)||se.toLowerCase().includes(ee)},G=(W,se,ee,pe,$,oe)=>{const _=T(se,ee),z=BS(_?.limit?.context),X=t===se&&r===ee,re=u(se,ee);return e.jsxs("div",{ref:ge=>{M.current[$]=ge},className:F("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",oe?"bg-accent":"hover:bg-accent/50"),onClick:()=>R(se,ee),onMouseEnter:()=>j($),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:D(W)}),z?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:z}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[X&&e.jsx(Gt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:ge=>{ge.preventDefault(),ge.stopPropagation(),d(se,ee)},className:F("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",re?"text-yellow-500":"text-muted-foreground"),"aria-label":re?"Unfavorite":"Favorite",title:re?"Remove from favorites":"Add to favorites",children:re?e.jsx(Cr,{className:"h-3.5 w-3.5"}):e.jsx(In,{className:"h-3.5 w-3.5"})})]})]},`${pe}-${se}-${ee}`)},O=f.filter(({model:W,providerID:se})=>{if(C&&!C.has(se))return!1;const pe=a.find(oe=>oe.id===se)?.name||se,$=D(W);return V($,pe)}),Y=p.filter(({model:W,providerID:se})=>{if(C&&!C.has(se))return!1;const pe=a.find(oe=>oe.id===se)?.name||se,$=D(W);return V($,pe)}),K=I.map(W=>{const ee=(Array.isArray(W.models)?W.models:[]).filter(pe=>{const $=D(pe);return V($,W.name||W.id||"")});return{...W,models:ee}}).filter(W=>W.models.length>0),U=O.length>0||Y.length>0||K.length>0,Q=()=>x?e.jsx($s,{open:g,onClose:E,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[f.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Favorites"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:W,providerID:se,modelID:ee})=>{const pe=se===t&&ee===r;return e.jsxs("div",{className:F("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",pe?"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:()=>{R(se,ee),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{providerId:se,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:D(W)})]})}),e.jsx("button",{onClick:$=>{$.preventDefault(),$.stopPropagation(),d(se,ee)},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(Cr,{className:"h-4 w-4"})})]},`fav-mobile-${se}-${ee}`)})})]}),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:W,providerID:se,modelID:ee})=>{const pe=se===t&&ee===r;return e.jsxs("div",{className:F("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",pe?"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:()=>{R(se,ee),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{providerId:se,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:D(W)})]})}),e.jsx("button",{onClick:$=>{$.preventDefault(),$.stopPropagation(),d(se,ee)},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(In,{className:"h-4 w-4"})})]},`recent-mobile-${se}-${ee}`)})})]}),I.map(W=>{const se=Array.isArray(W.models)?W.models:[];if(se.length===0)return null;const ee=W.id===t,pe=y.has(W.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:()=>P(W.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{providerId:W.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:W.name}),ee&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),pe?e.jsx(Ot,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Bs,{className:"h-3 w-3 text-muted-foreground"})]}),pe&&e.jsx("div",{className:"border-t border-border/20",children:se.map($=>{const oe=W.id===t&&$.id===r;return e.jsxs("div",{className:F("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",oe?"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:()=>{R(W.id,$.id),E()},children:e.jsx("span",{className:"font-medium truncate",children:D($)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:_=>{_.preventDefault(),_.stopPropagation(),d(W.id,$.id)},className:F("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",u(W.id,$.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":u(W.id,$.id)?"Unfavorite":"Favorite",children:u(W.id,$.id)?e.jsx(Cr,{className:"h-4 w-4"}):e.jsx(In,{className:"h-4 w-4"})}),oe&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},$.id)})})]},W.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:()=>{R("",""),E()},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:F("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(ws,{providerId:t,className:"h-3.5 w-3.5"}):e.jsx(Nr,{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(Ot,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(es,{open:S,onOpenChange:N,children:[e.jsx(ts,{asChild:!0,children:e.jsxs("div",{className:F("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(ws,{providerId:t,className:"h-3 w-3 flex-shrink-0"}),e.jsx(Nr,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Nr,{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(Ot,{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 W=[];O.forEach(({model:$,providerID:oe,modelID:_})=>{W.push({model:$,providerID:oe,modelID:_,section:"fav"})}),Y.forEach(({model:$,providerID:oe,modelID:_})=>{W.push({model:$,providerID:oe,modelID:_,section:"recent"})}),K.forEach($=>{$.models.forEach(oe=>{W.push({model:oe,providerID:$.id,modelID:oe.id,section:"provider"})})});const se=W.length,ee=$=>{if($.key==="ArrowDown"){$.preventDefault(),$.stopPropagation();const oe=(A+1)%Math.max(1,se);j(oe),setTimeout(()=>{M.current[oe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if($.key==="ArrowUp"){$.preventDefault(),$.stopPropagation();const oe=(A-1+Math.max(1,se))%Math.max(1,se);j(oe),setTimeout(()=>{M.current[oe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if($.key==="Enter"){$.preventDefault(),$.stopPropagation();const oe=W[A];oe&&R(oe.providerID,oe.modelID)}else $.key==="Escape"&&($.preventDefault(),$.stopPropagation(),N(!1))};let pe=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(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{type:"text",placeholder:"Search models",value:w,onChange:$=>k($.target.value),onKeyDown:ee,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(gt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:F("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>R("",""),children:[e.jsx(Zt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!t&&!r&&e.jsx(Gt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Ds,{}),!U&&w&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),O.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs($r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Cr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),O.map(({model:$,providerID:oe,modelID:_})=>{const z=pe++;return G($,oe,_,"fav",z,A===z)})]}),Y.length>0&&e.jsxs(e.Fragment,{children:[O.length>0&&e.jsx(Ds,{}),e.jsxs($r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(br,{className:"h-4 w-4"}),"Recent"]}),Y.map(({model:$,providerID:oe,modelID:_})=>{const z=pe++;return G($,oe,_,"recent",z,A===z)})]}),(O.length>0||Y.length>0)&&K.length>0&&e.jsx(Ds,{}),K.map(($,oe)=>e.jsxs(i.Fragment,{children:[oe>0&&e.jsx(Ds,{}),e.jsxs($r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ws,{providerId:$.id,className:"h-4 w-4 flex-shrink-0"}),$.name]}),$.models.map(_=>{const z=pe++;return G(_,$.id,_.id,"provider",z,A===z)})]},$.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"})]})})()})]}),Q()]})},zS=["read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop"],Er=t=>t==="allow"||t==="ask"||t==="deny",WS=t=>{if(Er(t))return t;if(t&&typeof t=="object"&&!Array.isArray(t)){const r=t["*"];if(Er(r))return r}},HS=t=>{if(Er(t))return{entries:{"*":t}};if(!t||typeof t!="object"||Array.isArray(t))return{entries:{}};const r={};for(const[s,n]of Object.entries(t)){const o=WS(n);o!==void 0&&(r[s]=o)}return{entries:r}},US=t=>{const r={...t},s=r["*"];return Er(s)?(delete r["*"],{defaultOverride:s,overrides:r}):{defaultOverride:"default",overrides:r}},ti=t=>t==="doom_loop"||t==="external_directory"?"ask":"allow",pa=(t,r)=>r==="default"?ti(t):r,wu=(t,r)=>{const s={...t};for(const[n,o]of Object.entries(t)){if(n==="*")continue;const a=pa(n,r),l=ti(n);if(!(Er(o)&&o!==l)){if(Er(o)&&o===a){delete s[n];continue}if(o&&typeof o=="object"&&!Array.isArray(o)){const c=o,d=Object.keys(c),u=c["*"];if(u!==void 0&&u!==l)continue;d.length===1&&d[0]==="*"&&u===a&&delete s[n]}}}return s},pp=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},VS=t=>{const r=pp(t);if(!r||r.length===0)return{entries:{}};const s={};for(const a of r)!a.permission||a.permission==="invalid"||a.pattern==="*"&&(s[a.permission]=a.action);const n=s["*"],o={};for(const[a,l]of Object.entries(s)){if(a==="*"){o[a]=l;continue}const c=ti(a);if(n){if(l===n)continue}else if(l===c)continue;o[a]=l}return{entries:o}},GS=()=>{const{selectedAgentName:t,getAgentByName:r,createAgent:s,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:l}=Qr();at();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,v]=i.useState(""),[S,N]=i.useState(void 0),[w,k]=i.useState(void 0),[A,j]=i.useState(""),[M,C]=i.useState("default"),[I,E]=i.useState({}),[P,D]=i.useState(""),[T,R]=i.useState(!1),V=bt(z=>z.currentDirectory??null),[G,O]=i.useState([]),Y=wo(z=>z.permissions);i.useEffect(()=>{let z=!1;return(async()=>{const re=await Fe.listToolIds({directory:V});if(z)return;const ge=new Set(["write","patch","multiedit"]),H=re.map(fe=>typeof fe=="string"?fe.trim():"").filter(Boolean).filter(fe=>fe!=="*").filter(fe=>fe!=="invalid").filter(fe=>!ge.has(fe));O(Array.from(new Set(H)).sort((fe,we)=>fe.localeCompare(we)))})(),()=>{z=!0}},[V]);const K=i.useMemo(()=>{const z=new Set;for(const X of o){const re=pp(X.permission);if(re)for(const ge of re)ge.permission&&ge.permission!=="*"&&ge.permission!=="invalid"&&z.add(ge.permission)}for(const X of Y.values())for(const re of X){const ge=re.permission?.trim();ge&&ge!=="invalid"&&z.add(ge)}for(const X of G)z.add(X);return Array.from(z).sort((X,re)=>X.localeCompare(re))},[o,Y,G]),U=i.useCallback(z=>{const X=I[z];if(Er(X))return X;if(X&&typeof X=="object"&&!Array.isArray(X)){const re=X["*"];if(Er(re))return re}},[I]),Q=i.useCallback(z=>{const X=I[z];return!X||typeof X!="object"||Array.isArray(X)?0:Object.keys(X).filter(ge=>ge!=="*").length},[I]),W=i.useCallback((z,X)=>{z!=="*"&&E(re=>{const ge={...re},H=ge[z],fe=pa(z,M),we=ti(z),he=X===fe&&X===we;if(H&&typeof H=="object"&&!Array.isArray(H)){const _e={...H};_e["*"]=X;const te=Object.keys(_e).filter(J=>J!=="*");return he&&te.length===0?(delete ge[z],ge):(ge[z]=_e,ge)}return he?(delete ge[z],ge):(ge[z]=X,ge)})},[M]),se=i.useCallback(z=>{E(X=>{if(!(z in X))return X;const re={...X};return delete re[z],re})},[]),ee=i.useMemo(()=>{const z=Object.entries(I).filter(([X])=>X!=="*");return z.sort(([X],[re])=>X.localeCompare(re)),z},[I]),pe=i.useMemo(()=>{const z=new Set;for(const X of zS)z.add(X);for(const X of K)z.add(X);for(const X of Object.keys(I))z.delete(X);return Array.from(z).sort((X,re)=>X.localeCompare(re))},[K,I]),$=i.useCallback(z=>{const X=P.trim();if(!X)return;const re=pa(X,M);if(z===re){const ge=M==="default"?"OpenCode defaults":`Default Permissions ("${M}")`;q.message(`"${X}" already matches ${ge} (${re}).`),D("");return}W(X,z),D("")},[P,W,M]),oe=i.useCallback(z=>z==="webfetch"?"WebFetch":z==="websearch"?"WebSearch":z==="codesearch"?"CodeSearch":z==="doom_loop"?"Doom Loop":z==="external_directory"?"External Directory":z==="todowrite"?"TodoWrite":z==="todoread"?"TodoRead":z.split(/[_-]+/g).filter(Boolean).map(X=>X.charAt(0).toUpperCase()+X.slice(1)).join(" "),[]);i.useEffect(()=>{D("");const z=X=>{const re=US(X);C(re.defaultOverride),E(wu(re.overrides,re.defaultOverride))};if(d&&a){m(a.name||""),p(a.scope||"user"),x(a.description||""),b(a.mode||"subagent"),v(a.model||""),N(a.temperature),k(a.top_p),j(a.prompt||"");const X=HS(a.permission);z(X.entries);return}if(c&&t===c.name){x(c.description||""),b(c.mode||"subagent"),c.model?.providerID&&c.model?.modelID?v(`${c.model.providerID}/${c.model.modelID}`):v(""),N(c.temperature),k(c.topP),j(c.prompt||"");const X=VS(c.permission);z(X.entries)}},[a,d,c,t]);const _=async()=>{const z=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!z){q.error("Agent name is required");return}if(d&&o.some(X=>X.name===z)){q.error("An agent with this name already exists");return}R(!0);try{const X=y.trim(),re={name:z,description:h.trim()||void 0,mode:g,model:X===""?null:X,temperature:S,top_p:w,prompt:A.trim()||void 0,permission:(()=>{const H=wu(I,M),fe=M==="default"?H:{"*":M,...H},we=["doom_loop","external_directory"];for(const _e of we)if(!(_e in fe)){const te=I[_e];Er(te)?fe[_e]=te:fe[_e]=pa(_e,M)}return Object.keys(fe).length===0?d?void 0:null:fe})(),scope:d?f:void 0};let ge;d?(ge=await s(re),ge&&l(null)):ge=await n(z,re),ge?q.success(d?"Agent created successfully":"Agent updated successfully"):q.error(d?"Failed to create agent":"Failed to update agent")}catch(X){console.error("Error saving agent:",X);const re=X instanceof Error&&X.message?X.message:"An error occurred while saving";q.error(re)}finally{R(!1)}};return t?e.jsx(gt,{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(jt,{value:u,onChange:z=>m(z.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Ls,{value:f,onValueChange:z=>p(z),children:[e.jsxs(Os,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Ys,{className:"h-4 w-4"}):e.jsx(cr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(_s,{align:"end",children:[e.jsx(rs,{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(Ys,{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(rs,{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(cr,{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:z=>x(z.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(Ms,{variant:g==="primary"?"default":"outline",onClick:()=>b("primary"),className:F("gap-2",g==="primary"?void 0:"text-foreground"),children:[e.jsx(fn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Ms,{variant:g==="subagent"?"default":"outline",onClick:()=>b("subagent"),className:F("gap-2",g==="subagent"?void 0:"text-foreground"),children:[e.jsx(jm,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Ms,{variant:g==="all"?"default":"outline",onClick:()=>b("all"),className:F("gap-2",g==="all"?void 0:"text-foreground"),children:[e.jsx(Sm,{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(dc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(z,X)=>{v(z&&X?`${z}/${X}`:"")}})]}),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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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 X=Math.max(0,(S!==void 0?S:.7)-.1);N(parseFloat(X.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(li,{className:"h-3.5 w-3.5"})}),e.jsx(jt,{type:"text",inputMode:"decimal",value:S!==void 0?S:"",onChange:z=>{const X=z.target.value;if(X===""){N(void 0);return}const re=parseFloat(X);!isNaN(re)&&re>=0&&re<=2&&N(re)},onBlur:z=>{const X=z.target.value;if(X!==""){const re=parseFloat(X);if(!isNaN(re)){const ge=Math.max(0,Math.min(2,re));N(parseFloat(ge.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 X=Math.min(2,(S!==void 0?S:.7)+.1);N(parseFloat(X.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(is,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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 X=Math.max(0,(w!==void 0?w:.9)-.1);k(parseFloat(X.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(li,{className:"h-3.5 w-3.5"})}),e.jsx(jt,{type:"text",inputMode:"decimal",value:w!==void 0?w:"",onChange:z=>{const X=z.target.value;if(X===""){k(void 0);return}const re=parseFloat(X);!isNaN(re)&&re>=0&&re<=1&&k(re)},onBlur:z=>{const X=z.target.value;if(X!==""){const re=parseFloat(X);if(!isNaN(re)){const ge=Math.max(0,Math.min(1,re));k(parseFloat(ge.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 X=Math.min(1,(w!==void 0?w:.9)+.1);k(parseFloat(X.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(is,{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:A,onChange:z=>j(z.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.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:'This editor only updates wildcard ("*") rules; existing pattern rules are preserved.'})]}),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:"Default Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Set the default behavior for all permissions for this agent."}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(De,{size:"sm",variant:M==="default"?"default":"outline",onClick:()=>C("default"),className:"h-6 px-2 text-xs",children:"Default"}),e.jsx(De,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>C("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>C("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:M==="deny"?"default":"outline",onClick:()=>C("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:M==="default"?"Uses OpenCode defaults unless overridden below.":"Applies to any permission without an explicit override below."}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Default:"})," Follow OpenCode default behavior"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block the operation"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Overrides"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Add overrides for permissions that should behave differently for this agent."}),e.jsx("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs(Ls,{value:P,onValueChange:D,children:[e.jsx(Os,{className:"h-8 w-full sm:w-72",children:P?e.jsx("span",{className:"truncate",children:oe(P)}):e.jsx("span",{className:"text-muted-foreground",children:"Add override…"})}),e.jsx(_s,{children:pe.map(z=>e.jsx(rs,{value:z,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:oe(z)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:z})]})},z))})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(De,{size:"sm",variant:"outline",disabled:!P,onClick:()=>$("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:"outline",disabled:!P,onClick:()=>$("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:"outline",disabled:!P,onClick:()=>$("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})}),ee.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:M==="default"?"No overrides configured. Everything follows OpenCode defaults.":`No overrides configured. All permissions default to "${M}" for this agent.`}):e.jsx("div",{className:"space-y-4",children:ee.map(([z])=>{const X=U(z),re=Q(z),ge=oe(z);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:[e.jsx("span",{children:ge}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:z}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block this operation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Remove:"})," Return to default behavior"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Note:"}),' Buttons set the "*" rule only']}),re>0?e.jsxs("p",{children:[e.jsx("strong",{children:"Patterns:"})," ",re," pattern rules preserved"]}):null]})})]})]}),e.jsxs(De,{size:"sm",variant:"outline",onClick:()=>se(z),className:"h-6 px-2 text-xs gap-1",children:[e.jsx(li,{className:"h-3 w-3"}),"Remove"]})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(De,{size:"sm",variant:X==="allow"?"default":"outline",onClick:()=>W(z,"allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:X==="ask"?"default":"outline",onClick:()=>W(z,"ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:X==="deny"?"default":"outline",onClick:()=>W(z,"deny"),className:"h-6 px-2 text-xs",children:"Deny"})]})]},z)})})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(De,{size:"sm",variant:"default",onClick:_,disabled:T,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Wa,{className:"h-3 w-3"}),T?"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(go,{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"})]})})},qS=({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}=Kr(),{setSidebarOpen:p}=Ce(),{isMobile:h}=Qt(),[x,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=x?"bg-transparent":b?"bg-background":"bg-sidebar",v=()=>{const C="new-command";let I=C,E=1;for(;l.some(P=>P.name===I);)I=`${C}-${E}`,E++;d({name:I,scope:"user"}),c(I),t?.(),h&&p(!1)},S=async C=>{if(Dn(C)){q.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${C.name}"?`)&&(await m(C.name)?q.success(`Command "${C.name}" deleted successfully`):q.error("Failed to delete command"))},N=async C=>{Dn(C)&&window.confirm(`Are you sure you want to reset command "${C.name}" to its default configuration?`)&&(await m(C.name)?q.success(`Command "${C.name}" reset to default`):q.error("Failed to reset command"))},w=C=>{const I=C.name;let E=1,P=`${I}-copy`;for(;l.some(D=>D.name===P);)E++,P=`${I}-copy-${E}`;d({name:P,scope:C.scope||"user",description:C.description,template:C.template,agent:C.agent,model:C.model,subtask:C.subtask}),c(P),h&&p(!1)},k=C=>{o(C.name),s(C)},A=async()=>{if(!r)return;const C=n.trim().replace(/\s+/g,"-");if(!C){q.error("Command name is required");return}if(C===r.name){s(null);return}if(l.some(E=>E.name===C)){q.error("A command with this name already exists");return}await u({name:C,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(q.success(`Command renamed to "${C}"`),c(C)):q.error("Failed to remove old command after rename"):q.error("Failed to rename command"),s(null)},j=l.filter(Dn),M=l.filter(C=>!Dn(C));return e.jsxs("div",{className:F("flex h-full flex-col",y),children:[e.jsx("div",{className:F("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(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(is,{className:"size-4"})})]})}),e.jsx(gt,{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(Vr,{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:[j.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"}),[...j].sort((C,I)=>C.name.localeCompare(I.name)).map(C=>e.jsx(vu,{command:C,isSelected:a===C.name,onSelect:()=>{c(C.name),t?.(),h&&p(!1)},onReset:()=>N(C),onDuplicate:()=>w(C)},C.name))]}),M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Commands"}),[...M].sort((C,I)=>C.name.localeCompare(I.name)).map(C=>e.jsx(vu,{command:C,isSelected:a===C.name,onSelect:()=>{c(C.name),t?.(),h&&p(!1)},onRename:()=>k(C),onDelete:()=>S(C),onDuplicate:()=>w(C)},C.name))]})]})}),e.jsx(xs,{open:r!==null,onOpenChange:C=>!C&&s(null),children:e.jsxs(ys,{children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Rename Command"}),e.jsxs(Ns,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:C=>o(C.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:C=>{C.key==="Enter"&&A()}}),e.jsxs(zs,{children:[e.jsx(De,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(hn,{onClick:A,children:"Rename"})]})]})})]})},vu=({command:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:l})=>e.jsx("div",{className:F("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||Dn(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:Dn(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(De,{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(Gr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(Gn,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),l()},children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(Is,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),hp=({agentName:t,onChange:r,className:s})=>{const{loadAgents:n,getVisibleAgents:o}=Qr(),a=o(),l=Ce(x=>x.isMobile),{isMobile:c}=Qt(),d=l||c,[u,m]=i.useState(!1);i.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=x=>{r(x)},h=()=>d?e.jsx($s,{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:F("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:F("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(go,{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(Ot,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsxs("div",{className:F("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(go,{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(Ot,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(ss,{className:"max-w-[300px]",children:[a.map(x=>e.jsx(Nt,{className:"typography-meta",onSelect:()=>p(x.name),children:e.jsx("span",{className:"font-medium",children:x.name})},x.name)),e.jsx(Nt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},KS=()=>{const{selectedCommandName:t,getCommandByName:r,createCommand:s,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:l}=Kr(),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,v]=i.useState(""),[S,N]=i.useState(""),[w,k]=i.useState(!1),[A,j]=i.useState(!1);i.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),x(a.description||""),b(a.agent||""),v(a.model||""),N(a.template||""),k(a.subtask||!1)):c&&(x(c.description||""),b(c.agent||""),v(c.model||""),N(c.template||""),k(c.subtask||!1))},[c,d,t,o,a]);const M=async()=>{const C=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!C){q.error("Command name is required");return}if(!S.trim()){q.error("Command template is required");return}if(d&&o.some(I=>I.name===C)){q.error("A command with this name already exists");return}j(!0);try{const I=g.trim(),E=y.trim(),P=S.trim(),D={name:C,description:h.trim()||void 0,agent:I===""?null:I,model:E===""?null:E,template:P,subtask:w,scope:d?f:void 0};let T;d?(T=await s(D),T&&l(null)):T=await n(C,D),T?q.success(d?"Command created successfully":"Command updated successfully"):q.error(d?"Failed to create command":"Failed to update command")}catch(I){console.error("Error saving command:",I),q.error("An error occurred while saving")}finally{j(!1)}};return t?e.jsx(gt,{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(jt,{value:u,onChange:C=>m(C.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Ls,{value:f,onValueChange:C=>p(C),children:[e.jsxs(Os,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Ys,{className:"h-4 w-4"}):e.jsx(cr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(_s,{align:"end",children:[e.jsx(rs,{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(Ys,{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(rs,{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(cr,{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:C=>x(C.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(hp,{agentName:g,onChange:C=>b(C)}),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(dc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(C,I)=>{v(C&&I?`${C}/${I}`:"")}}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default model for this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",checked:w,onChange:C=>k(C.target.checked),className:"sr-only"}),e.jsx("div",{className:F("w-5 h-5 rounded border-2 flex items-center justify-center",w?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:w&&e.jsx(Gt,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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:C=>N(C.target.value),placeholder:`Your command template here...
133
-
134
- Use $ARGUMENTS to reference user input.
135
- Use !\`shell command\` to inject shell output.
136
- 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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(De,{size:"sm",variant:"default",onClick:M,disabled:A,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Wa,{className:"h-3 w-3"}),A?"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(Vr,{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"})]})})},QS=({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}=or(),{setSidebarOpen:h}=Ce(),{isMobile:x}=Qt(),[g,b]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||b(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const v=g?"bg-transparent":y?"bg-background":"bg-sidebar",S=()=>{const C="new-skill";let I=C,E=1;for(;l.some(P=>P.name===I);)I=`${C}-${E}`,E++;d({name:I,scope:"user",description:""}),c(I),t?.(),x&&h(!1)},N=async C=>{window.confirm(`Are you sure you want to delete skill "${C.name}"?`)&&(await m(C.name)?q.success(`Skill "${C.name}" deleted successfully`):q.error("Failed to delete skill"))},w=async C=>{const I=C.name;let E=1,P=`${I}-copy`;for(;l.some(T=>T.name===P);)E++,P=`${I}-copy-${E}`;const D=await p(C.name);if(!D){q.error("Failed to load skill details for duplication");return}d({name:P,scope:C.scope||"user",description:(D.sources.md.fields.includes("description"),""),instructions:""}),c(P),x&&h(!1)},k=C=>{o(C.name),s(C)},A=async()=>{if(!r)return;const C=n.trim().replace(/\s+/g,"-").toLowerCase();if(!C){q.error("Skill name is required");return}if(C===r.name){s(null);return}if(l.some(P=>P.name===C)){q.error("A skill with this name already exists");return}if(!await p(r.name)){q.error("Failed to load skill details"),s(null);return}await u({name:C,description:"Renamed skill",scope:r.scope})?await m(r.name)?(q.success(`Skill renamed to "${C}"`),c(C)):q.error("Failed to remove old skill after rename"):q.error("Failed to rename skill"),s(null)},j=l.filter(C=>C.scope==="project"),M=l.filter(C=>C.scope==="user");return e.jsxs("div",{className:F("flex h-full flex-col",v),children:[e.jsx("div",{className:F("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(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:S,children:e.jsx(is,{className:"size-4"})})]})}),e.jsx(gt,{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(km,{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:[j.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"}),j.map(C=>e.jsx(ju,{skill:C,isSelected:a===C.name,onSelect:()=>{c(C.name),t?.(),x&&h(!1)},onRename:()=>k(C),onDelete:()=>N(C),onDuplicate:()=>w(C)},C.name))]}),M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"User Skills"}),M.map(C=>e.jsx(ju,{skill:C,isSelected:a===C.name,onSelect:()=>{c(C.name),t?.(),x&&h(!1)},onRename:()=>k(C),onDelete:()=>N(C),onDuplicate:()=>w(C)},C.name))]})]})}),e.jsx(xs,{open:r!==null,onOpenChange:C=>!C&&s(null),children:e.jsxs(ys,{children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Rename Skill"}),e.jsxs(Ns,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:C=>o(C.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:C=>{C.key==="Enter"&&A()}}),e.jsxs(zs,{children:[e.jsx(De,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(hn,{onClick:A,children:"Rename"})]})]})})]})},ju=({skill:t,isSelected:r,onSelect:s,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:F("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(De,{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(Gr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(Gn,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function gp({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:F("relative isolate w-full",n),children:[e.jsx("div",{ref:l,"aria-hidden":!0,className:F("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:F("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:F("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const YS=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,XS=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},JS=async()=>{try{if(ls())return await Pr();const t=As()?.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}},ZS=({open:t,onOpenChange:r})=>{const{scanRepo:s,loadCatalog:n,isScanning:o}=ko(),a=Hn(C=>C.defaultGitIdentityId),l=Hn(C=>C.loadDefaultGitIdentityId),[c,d]=i.useState(""),[u,m]=i.useState(""),[f,p]=i.useState(""),[h,x]=i.useState([]),[g,b]=i.useState(null),[y,v]=i.useState(!1),[S,N]=i.useState([]),[w,k]=i.useState(null);i.useEffect(()=>{t&&(d(""),m(""),p(""),b(null),v(!1),N([]),k(null),l(),(async()=>{const C=await JS(),I=Array.isArray(C?.skillCatalogs)?C?.skillCatalogs:[];x(I||[])})())},[t,l]);const A=i.useMemo(()=>{const C=u.trim(),I=f.trim();return h.some(E=>{const P=(E.source||"").trim(),D=(E.subpath||"").trim();return P===C&&D===I})},[h,u,f]),j=async()=>{const C=u.trim();if(!C){q.error("Repository source is required");return}c.trim()||d(XS(C)),v(!1),b(null);const I=await s({source:C,subpath:f.trim()||void 0,gitIdentityId:w||void 0});if(!I.ok){if(I.error?.kind==="authRequired"){if(Wt()){q.error("Private repositories are not supported in VS Code yet");return}const P=I.error.identities||[];if(N(P),!w&&P.length>0){const D=a&&a!=="global"&&P.some(T=>T.id===a)?a:P[0].id;k(D)}q.error("Authentication required. Select a Git identity and scan again.");return}q.error(I.error?.message||"Failed to scan repository");return}const E=I.items?.length||0;if(b(E),E===0){q.error("No skills found in this repository"),v(!1);return}N([]),v(!0),q.success(`Found ${E} skill(s)`)},M=async()=>{const C=c.trim(),I=u.trim(),E=f.trim();if(!C){q.error("Catalog name is required");return}if(!I){q.error("Repository source is required");return}if(!y){q.error("Scan the repository before adding this catalog");return}if(A){q.error("This catalog already exists");return}const P={id:YS(),label:C,source:I,...E?{subpath:E}:{},...w?{gitIdentityId:w}:{}},D=[...h,P];try{await us({skillCatalogs:D}),x(D),q.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(T){q.error(T instanceof Error?T.message:"Failed to save catalog")}};return e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(vs,{children:[e.jsx(js,{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(jt,{value:c,onChange:C=>d(C.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(jt,{value:u,onChange:C=>{m(C.target.value),v(!1),b(null)},placeholder:"owner/repo or git@github.com:owner/repo.git"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Public repos work everywhere. Private repos require SSH identity (Desktop/Web only)."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Optional subpath"}),e.jsx(jt,{value:f,onChange:C=>{p(C.target.value),v(!1),b(null)},placeholder:"e.g. skills"})]}),S.length>0&&!Wt()?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(Ls,{value:w||"",onValueChange:C=>k(C),children:[e.jsx(Os,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:S.find(C=>C.id===w)?.name||"Choose identity"})}),e.jsx(_s,{align:"start",children:S.map(C=>e.jsx(rs,{value:C.id,className:"pr-2 [&>span:first-child]:hidden",children:C.name},C.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,A?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(zs,{children:[e.jsx(De,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(De,{variant:"outline",onClick:()=>{j()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(im,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(De,{variant:"default",onClick:()=>{M()},disabled:!y||A||!c.trim()||!u.trim(),children:"Add catalog"})]})]})})},ek=({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(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(vs,{children:[e.jsx(js,{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(De,{variant:"outline",size:"sm",onClick:()=>l("skip"),children:"Skip all"}),e.jsx(De,{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(Ls,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Os,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(_s,{align:"end",children:[e.jsx(rs,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(rs,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(zs,{children:[e.jsx(De,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(hn,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},tk=({open:t,onOpenChange:r,item:s})=>{const{installSkills:n,isInstalling:o}=ko(),[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){q.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"){q.error(b.error.message||"Authentication required");return}q.error(b.error?.message||"Failed to install skill")};return s?e.jsxs(e.Fragment,{children:[e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(vs,{children:[e.jsx(js,{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(zs,{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(Ls,{value:a,onValueChange:x=>l(x),children:[e.jsx(Os,{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(Ys,{className:"h-4 w-4"}):e.jsx(cr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(_s,{align:"start",children:[e.jsx(rs,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(rs,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cr,{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(De,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(De,{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(ek,{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},sk=async()=>{try{if(ls())return await Pr();const t=As()?.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}},rk=({mode:t,onModeChange:r})=>{const{sources:s,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:l,isLoadingCatalog:c,lastCatalogError:d}=ko(),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,x]=i.useState(!1),[g,b]=i.useState(null),[y,v]=i.useState(!1);i.useEffect(()=>{l()},[l]);const S=i.useMemo(()=>o?n[o]||[]:[],[n,o]),N=i.useMemo(()=>{const j=u.trim().toLowerCase();return j?S.filter(M=>{const C=M.skillName.toLowerCase(),I=(M.description||"").toLowerCase(),E=(M.frontmatterName||"").toLowerCase();return C.includes(j)||I.includes(j)||E.includes(j)}):S},[S,u]),w=i.useMemo(()=>s.find(j=>j.id===o)||null,[s,o]),k=!!(o&&o.startsWith("custom:")),A=async()=>{if(!(!o||!k)&&window.confirm("Remove this catalog?")){v(!0);try{const j=await sk(),C=(Array.isArray(j?.skillCatalogs)?j?.skillCatalogs:[]).filter(I=>I.id!==o);await us({skillCatalogs:C}),await l({refresh:!0})}finally{v(!1)}}};return e.jsx(gt,{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(gp,{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(Ls,{value:o||"",onValueChange:j=>a(j),children:[e.jsx(Os,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:w?.label||"Select source"})}),e.jsx(_s,{align:"start",children:s.map(j=>e.jsx(rs,{value:j.id,className:"pr-2 [&>span:first-child]:hidden",children:j.label},j.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(De,{type:"button",variant:"outline",onClick:()=>{l({refresh:!0})},disabled:c,className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Refresh"]}),k?e.jsxs(De,{type:"button",variant:"outline",onClick:()=>{A()},disabled:y,className:"gap-2",children:[e.jsx(Us,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(De,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(is,{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(jt,{value:u,onChange:j=>m(j.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:c?"Loading…":`${N.length} skill(s)`})]}),d?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:d.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:N.length===0?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"})]}):N.map(j=>{const M=j.installed?.isInstalled,C=j.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:j.skillName}),M?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 (",C||"unknown",")"]}):null,j.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"})]}),j.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:j.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),j.clawdhub?e.jsxs("div",{className:"typography-micro text-muted-foreground mt-1 flex items-center gap-3",children:[j.clawdhub.owner?e.jsxs("span",{children:["by ",j.clawdhub.owner]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),j.clawdhub.downloads?.toLocaleString()??0]}),(j.clawdhub.stars??0)>0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(In,{className:"h-3 w-3"}),j.clawdhub.stars]}):null,e.jsxs("span",{children:["v",j.clawdhub.version]})]}):null,j.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:j.warnings.join(" · ")}):null]}),e.jsx(De,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!j.installable,onClick:()=>{b(j),x(!0)},children:"Install"})]})},`${j.sourceId}:${j.skillDir}`)})}),e.jsx(ZS,{open:f,onOpenChange:p}),e.jsx(tk,{open:h,onOpenChange:x,item:g})]})})},nk=()=>{const{selectedSkillName:t,getSkillByName:r,getSkillDetail:s,createSkill:n,updateSkill:o,skills:a,skillDraft:l,setSkillDraft:c,setSelectedSkill:d}=or(),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(gp,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[g,b]=i.useState(""),[y,v]=i.useState("user"),[S,N]=i.useState(""),[w,k]=i.useState(""),[A,j]=i.useState([]),[M,C]=i.useState([]),[I,E]=i.useState(!1),[P,D]=i.useState(!1),[T,R]=i.useState(""),[V,G]=i.useState(""),[O,Y]=i.useState(!1),[K,U]=i.useState(""),[Q,W]=i.useState(""),[se,ee]=i.useState(null),[pe,$]=i.useState(!1),[oe,_]=i.useState(""),z=m?g.trim()!==""||S.trim()!==""||w.trim()!==""||M.length>0:S!==T||w!==V,X=se?Q!==oe:K.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&l)b(l.name||""),v(l.scope||"user"),N(l.description||""),k(l.instructions||""),R(""),G(""),j([]),C(l.pendingFiles||[]);else if(t&&u){D(!0);try{const _e=await s(t);if(_e){const te=_e.sources.md;N(te.description||""),k(te.instructions||""),R(te.description||""),G(te.instructions||""),j(te.supportingFiles||[])}}catch(_e){console.error("Failed to load skill details:",_e)}finally{D(!1)}}})()},[u,m,t,a,l,s,p]);const re=async()=>{const he=m?g.trim().replace(/\s+/g,"-").toLowerCase():t?.trim();if(!he){q.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(he)||he.length>64){q.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!S.trim()){q.error("Description is required");return}if(m&&a.some(_e=>_e.name===he)){q.error("A skill with this name already exists");return}E(!0);try{const _e={name:he,description:S.trim(),instructions:w.trim()||void 0,scope:m?y:void 0,supportingFiles:m&&M.length>0?M:void 0};let te;m?(te=await n(_e),te&&(c(null),C([]),d(he))):(te=await o(he,_e),te&&(R(S.trim()),G(w.trim()))),te?q.success(m?"Skill created successfully":"Skill updated successfully"):q.error(m?"Failed to create skill":"Failed to update skill")}catch(_e){console.error("Error saving skill:",_e),q.error("An error occurred while saving")}finally{E(!1)}},ge=()=>{ee(null),U(""),W(""),_(""),Y(!0)},H=async he=>{if(ee(he),U(he),m){const te=M.find(J=>J.path===he)?.content||"";W(te),_(te),Y(!0);return}if(t){$(!0),Y(!0);try{const{readSupportingFile:_e}=or.getState(),te=await _e(t,he);W(te||""),_(te||"")}catch{q.error("Failed to load file content"),W(""),_("")}finally{$(!1)}}},fe=async()=>{if(!K.trim()){q.error("File name is required");return}const he=K.trim(),_e=se!==null;if(m){if(_e)C(ne=>ne.map(ke=>ke.path===se?{path:he,content:Q}:ke)),q.success(`File "${he}" updated`);else{if(M.some(ne=>ne.path===he)){q.error("A file with this name already exists");return}C(ne=>[...ne,{path:he,content:Q}]),q.success(`File "${he}" added`)}Y(!1),ee(null);return}if(!t){q.error("No skill selected");return}const{writeSupportingFile:te}=or.getState();if(await te(t,he,Q)){q.success(_e?`File "${he}" updated`:`File "${he}" created`),Y(!1),ee(null);const ne=await s(t);ne&&j(ne.sources.md.supportingFiles||[])}else q.error(_e?"Failed to update file":"Failed to create file")},we=async he=>{if(m){C(_e=>_e.filter(te=>te.path!==he)),q.success(`File "${he}" removed`);return}if(t&&window.confirm(`Are you sure you want to delete "${he}"?`)){const{deleteSupportingFile:_e}=or.getState();if(await _e(t,he)){q.success(`File "${he}" deleted`);const J=await s(t);J&&j(J.sources.md.supportingFiles||[])}else q.error("Failed to delete file")}};return m&&p==="external"?e.jsx(rk,{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(km,{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"})]})}):P?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(gt,{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(jt,{value:g,onChange:he=>b(he.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(Ls,{value:y,onValueChange:he=>v(he),children:[e.jsxs(Os,{className:"!h-9 w-auto gap-1.5",children:[y==="user"?e.jsx(Ys,{className:"h-4 w-4"}):e.jsx(cr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:y})]}),e.jsxs(_s,{align:"end",children:[e.jsx(rs,{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(Ys,{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(rs,{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(cr,{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:he=>N(he.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:w,onChange:he=>k(he.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(De,{variant:"outline",size:"sm",onClick:ge,className:"gap-1.5",children:[e.jsx(is,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const he=m?M:A;return he.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:he.map(_e=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg border bg-muted/30 hover:bg-muted/50 cursor-pointer transition-colors",onClick:()=>H(_e.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(hr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:_e.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(De,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:te=>{te.stopPropagation(),we(_e.path)},children:e.jsx(Us,{className:"h-3.5 w-3.5"})})]},_e.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(De,{size:"sm",variant:"default",onClick:re,disabled:I||!z,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Wa,{className:"h-3 w-3"}),I?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(xs,{open:O,onOpenChange:he=>{Y(he),he||ee(null)},children:e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(vs,{className:"flex-shrink-0",children:[e.jsx(js,{children:se?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ns,{children:se?"Modify the file content":"Create a new file in the skill directory"})]}),pe?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(jt,{value:K,onChange:he=>U(he.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:se!==null}),!se&&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:Q,onChange:he=>W(he.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(zs,{children:[e.jsx(De,{variant:"ghost",onClick:()=>{Y(!1),ee(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(hn,{onClick:fe,disabled:pe||!X,children:se?"Save Changes":"Create File"})]})]})})]})})},ok="__add_provider__",ak=({onItemSelect:t})=>{const r=at(u=>u.providers),s=at(u=>u.selectedProviderId),n=at(u=>u.setSelectedProvider),{isMobile:o}=Qt(),[a,l]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=i.useMemo(()=>Wt(),[]);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:F("flex h-full flex-col",d),children:[e.jsx("div",{className:F("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(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(ok),t?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(is,{className:"size-4"})})]})}),e.jsx(gt,{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(_n,{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:F("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(ws,{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)})})]})},ik=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Su=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const r=ik.format(t);return r.endsWith(".0")?r.slice(0,-2):r},kn="__add_provider__",Un=t=>typeof t=="object"&&t!==null,ku=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()},lk=t=>{if(!Un(t))return{};const r={};for(const[s,n]of Object.entries(t))Array.isArray(n)&&(r[s]=n.filter(o=>Un(o)));return r},ck=t=>{if(typeof t=="string")return{id:t};if(!Un(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}},dk=t=>{let r=[];Array.isArray(t)?r=t:Un(t)&&(Array.isArray(t.all)?r=t.all:Array.isArray(t.providers)&&(r=t.providers));const s=r.map(o=>ck(o)).filter(o=>!!o),n=new Set;return s.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},uk=()=>{const t=at(H=>H.providers),r=at(H=>H.selectedProviderId),s=at(H=>H.setSelectedProvider),n=at(H=>H.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({}),[v,S]=i.useState({}),[N,w]=i.useState([]),[k,A]=i.useState(!1),[j,M]=i.useState(null),[C,I]=i.useState(""),[E,P]=i.useState(""),[D,T]=i.useState(!1),[R,V]=i.useState({}),[G,O]=i.useState(!1);i.useEffect(()=>{!r&&t.length>0&&s(t[0].id)},[t,r,s]),i.useEffect(()=>{let H=!0;return(async()=>{c(!0);try{const we=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!we.ok)throw new Error(`Auth methods request failed (${we.status})`);const he=await we.json().catch(()=>({}));if(!H)return;a(lk(he))}catch(we){if(!H)return;console.error("Failed to load provider auth methods:",we),q.error("Failed to load provider authentication methods")}finally{H&&c(!1)}})(),()=>{H=!1}},[]),i.useEffect(()=>{let H=!0;return(async()=>{A(!0),M(null);try{const we=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!we.ok)throw new Error(`Provider list request failed (${we.status})`);const he=await we.json().catch(()=>({}));if(!H)return;w(dk(he))}catch(we){if(!H)return;console.error("Failed to load available providers:",we),M("Unable to load provider list")}finally{H&&A(!1)}})(),()=>{H=!1}},[]);const Y=i.useMemo(()=>new Set(t.map(H=>H.id)),[t]),K=i.useMemo(()=>N.filter(H=>!Y.has(H.id)),[N,Y]);i.useEffect(()=>{if(r===kn){if(!C&&K.length>0){I(K[0].id);return}C&&!K.some(H=>H.id===C)&&I(K[0]?.id??"")}},[r,C,K]),i.useEffect(()=>{if(r===kn){O(!0);return}O(!1)},[r]),i.useEffect(()=>{if(!r||r===kn)return;let H=!1;return(async()=>{try{const we=await fetch(`/api/provider/${encodeURIComponent(r)}/source`,{method:"GET",headers:{Accept:"application/json"}}),he=await we.json().catch(()=>null);if(!we.ok)throw new Error(he?.error||"Failed to load provider sources");const _e=he?.sources??he?.data?.sources;!H&&_e&&V(te=>({...te,[r]:_e}))}catch(we){H||console.error("Failed to load provider sources:",we)}})(),()=>{H=!0}},[r]);const U=t.find(H=>H.id===r),Q=r?R[r]:void 0,W=async H=>{const fe=d[H]?.trim()??"";if(!fe){q.error("API key is required");return}const we=`api:${H}`;f(we);try{const he=await fetch(`/api/auth/${encodeURIComponent(H)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:fe})}),_e=await he.json().catch(()=>null);if(!he.ok){const te=_e?.error||"Failed to save API key";throw new Error(te)}q.success("API key saved"),u(te=>({...te,[H]:""})),await lo({scopes:["providers"],mode:"active"}),s(H)}catch(he){console.error("Failed to save API key:",he),q.error("Failed to save API key")}finally{f(null)}},se=async(H,fe)=>{const we=`oauth:${H}:${fe}`;f(we);try{const he=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:fe})}),_e=await he.json().catch(()=>null);if(!he.ok){const de=_e?.error||"Failed to start OAuth flow";throw new Error(de)}const te=Un(_e)?_e:{},J=Un(te.data)?te.data:te,ne=typeof J.url=="string"&&J.url||typeof J.verification_uri_complete=="string"&&J.verification_uri_complete||typeof J.verification_uri=="string"&&J.verification_uri||void 0,ke=typeof J.instructions=="string"&&J.instructions||typeof J.message=="string"&&J.message||void 0,Z=typeof J.user_code=="string"&&J.user_code||typeof J.code=="string"&&J.code||typeof J.userCode=="string"&&J.userCode||void 0;if(!ne&&!ke&&!Z)throw new Error("No OAuth details returned");const ye=`${H}:${fe}`;S(de=>({...de,[ye]:{url:ne,instructions:ke,userCode:Z}})),ne&&window.open(ne,"_blank","noopener,noreferrer"),g({providerId:H,methodIndex:fe}),q.message("Complete the OAuth flow in your browser")}catch(he){console.error("Failed to start OAuth flow:",he),q.error("Failed to start OAuth flow")}finally{f(null)}},ee=async(H,fe)=>{const we=`${H}:${fe}`,he=b[we]?.trim(),_e=`oauth-complete:${H}:${fe}`;f(_e);try{const te={method:fe};he&&(te.code=he);const J=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(te)}),ne=await J.json().catch(()=>null);if(!J.ok){const ke=ne?.error||"Failed to complete OAuth flow";throw new Error(ke)}q.success("OAuth connection completed"),y(ke=>({...ke,[we]:""})),g(null),await lo({scopes:["providers"],mode:"active"}),s(H)}catch(te){console.error("Failed to complete OAuth flow:",te),q.error("Failed to complete OAuth flow")}finally{f(null)}},pe=async H=>{try{await navigator.clipboard.writeText(H),q.success("OAuth link copied")}catch(fe){console.error("Failed to copy OAuth link:",fe),q.error("Failed to copy OAuth link")}},$=async H=>{try{await navigator.clipboard.writeText(H),q.success("Device code copied")}catch(fe){console.error("Failed to copy device code:",fe),q.error("Failed to copy device code")}},oe=async H=>{const fe=`disconnect:${H}`;f(fe);try{const we=await fetch(`/api/provider/${encodeURIComponent(H)}/auth?scope=all`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),he=await we.json().catch(()=>null);if(!we.ok){const _e=he?.error||"Failed to disconnect provider";throw new Error(_e)}q.success("Provider disconnected"),await lo({scopes:["providers"],mode:"active"})}catch(we){console.error("Failed to disconnect provider:",we),q.error("Failed to disconnect provider")}finally{f(null)}},_=r===kn;if(!_&&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(_n,{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(_)return e.jsx(gt,{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."})]}),k?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:j}):K.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(es,{open:D,onOpenChange:H=>{T(H),H||P("")},children:[e.jsx(ts,{asChild:!0,children:e.jsxs("button",{type:"button",className:F("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:C?"text-foreground":"text-muted-foreground",children:C?K.find(H=>H.id===C)?.name||C:"Select provider"}),e.jsx(Ot,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(ss,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:H=>H.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:H=>H.stopPropagation(),children:[e.jsx(lr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:E,onChange:H=>P(H.target.value),onKeyDown:H=>H.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(gt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const H=K.filter(fe=>{const we=E.toLowerCase();return(fe.name||fe.id).toLowerCase().includes(we)||fe.id.toLowerCase().includes(we)});return H.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):H.map(fe=>e.jsxs(Nt,{onSelect:()=>{I(fe.id),T(!1),P("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:fe.name||fe.id}),C===fe.id&&e.jsx(Gt,{className:"h-4 w-4 text-primary"})]},fe.id))})()})]})]})]}),C&&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(jt,{type:"password",value:d[C]??"",onChange:H=>u(fe=>({...fe,[C]:H.target.value})),placeholder:"sk-..."}),e.jsx(De,{size:"sm",onClick:()=>W(C),disabled:m===`api:${C}`,className:"h-8",children:m===`api:${C}`?"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 fe=(o[C]??[]).filter(we=>ku(we)==="oauth");return fe.length===0?null:e.jsx("div",{className:"space-y-3",children:fe.map((we,he)=>{const _e=we.label||we.name||`OAuth method ${he+1}`,te=`${C}:${he}`,J=x?.providerId===C&&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:_e}),(we.description||we.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(we.description||we.help)})]}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>se(C,he),disabled:m===`oauth:${C}:${he}`,className:"h-8",children:"Connect"})]}),v[te]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[te]?.instructions}),v[te]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[te]?.userCode,readOnly:!0}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>$(v[te]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[te]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[te]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(De,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[te]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>pe(v[te]?.url??""),className:"h-8",children:"Copy link"})]})]}),J&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:b[te]??"",onChange:ne=>y(ke=>({...ke,[te]:ne.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(De,{size:"sm",onClick:()=>ee(C,he),disabled:m===`oauth-complete:${C}:${he}`,className:"h-8",children:m===`oauth-complete:${C}:${he}`?"Saving…":"Complete"})]})]},`${C}-${_e}`)})})})()]})]})]})});if(!U)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(_n,{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 z=Array.isArray(U.models)?U.models:[],re=(o[U.id]??[]).filter(H=>ku(H)==="oauth"),ge=z.filter(H=>{const fe=typeof H?.name=="string"?H.name:"",we=typeof H?.id=="string"?H.id:"",he=p.trim().toLowerCase();return he?fe.toLowerCase().includes(he)||we.toLowerCase().includes(he):!0});return e.jsx(gt,{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(ws,{providerId:U.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:U.name||U.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",U.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!==kn&&e.jsx(De,{size:"sm",variant:"outline",onClick:()=>O(H=>!H),className:"h-8",children:G?"Hide":"Reconnect"})]}),!G&&r!==kn?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(jt,{type:"password",value:d[U.id]??"",onChange:H=>u(fe=>({...fe,[U.id]:H.target.value})),placeholder:"sk-..."}),e.jsx(De,{size:"sm",onClick:()=>W(U.id),disabled:m===`api:${U.id}`,className:"h-8",children:m===`api:${U.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."})]}),re.length>0&&e.jsx("div",{className:"space-y-3",children:re.map((H,fe)=>{const we=H.label||H.name||`OAuth method ${fe+1}`,he=`${U.id}:${fe}`,_e=x?.providerId===U.id&&x?.methodIndex===fe;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:we}),(H.description||H.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(H.description||H.help)})]}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>se(U.id,fe),disabled:m===`oauth:${U.id}:${fe}`,className:"h-8",children:"Connect"})]}),v[he]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[he]?.instructions}),v[he]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[he]?.userCode,readOnly:!0}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>$(v[he]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[he]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[he]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(De,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[he]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>pe(v[he]?.url??""),className:"h-8",children:"Copy link"})]})]}),_e&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:b[he]??"",onChange:te=>y(J=>({...J,[he]:te.target.value})),placeholder:"Paste authorization code"}),e.jsx(De,{size:"sm",onClick:()=>ee(U.id,fe),disabled:m===`oauth-complete:${U.id}:${fe}`,className:"h-8",children:m===`oauth-complete:${U.id}:${fe}`?"Saving…":"Complete"})]})]},`${U.id}-${we}`)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Connection"}),Q&&(Q.auth.exists||Q.user.exists||Q.project.exists||Q.custom?.exists)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Configured in: ",[Q.auth.exists?"auth credentials":null,Q.user.exists?"user config":null,Q.project.exists?"project config":null,Q.custom?.exists?"custom config":null].filter(Boolean).join(", ")]}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>oe(U.id),disabled:m===`disconnect:${U.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${U.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(jt,{value:p,onChange:H=>h(H.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:ge.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):ge.map(H=>{const fe=typeof H?.id=="string"?H.id:"",we=typeof H?.name=="string"?H.name:fe,he=fe?n(U.id,fe):void 0,_e=Su(he?.limit?.context),te=Su(he?.limit?.output),J=[];return he?.tool_call&&J.push({key:"tools",icon:Ba,label:"Tool calling"}),he?.reasoning&&J.push({key:"reasoning",icon:wr,label:"Reasoning"}),he?.attachment&&J.push({key:"image",icon:vr,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:we}),(_e||te)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[_e?`${_e} ctx`:"",_e&&te?" · ":"",te?`${te} out`:""]}),J.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:J.map(({key:ne,icon:ke,label:Z})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Z,"aria-label":Z,children:e.jsx(ke,{className:"h-3 w-3"})},ne))})]},fe)})})]})]})})},mk={branch:Ht,briefcase:Fl,house:Tl,graduation:Pl,code:Qs,heart:mm},fk={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},pk=({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}=Hn(),{setSidebarOpen:h}=Ce(),{isMobile:x}=Qt(),[g,b]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||b(typeof window.opencodeDesktop<"u")},[]);const v=p();i.useEffect(()=>{c(),d(),u(),m()},[c,d,u,m]);const S=j=>{a(`import:${j.host}:${j.username}`),t?.(),x&&h(!1)},N=g?"bg-transparent":y?"bg-background":"bg-sidebar",w=()=>{a("new"),t?.(),x&&h(!1)},k=async j=>{window.confirm(`Are you sure you want to delete profile "${j.name}"?`)&&(await l(j.id)?q.success(`Profile "${j.name}" deleted successfully`):q.error("Failed to delete profile"))},A=async j=>{const M=s===j?null:j;if(!await f(M)){q.error("Failed to update default identity");return}q.success(M?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:F("flex h-full flex-col",N),children:[e.jsx("div",{className:F("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(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,"aria-label":"Create new profile",children:e.jsx(is,{className:"size-4"})})]})}),e.jsxs(gt,{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(Nu,{profile:o,isSelected:r==="global",isDefault:s==="global",onSelect:()=>{a("global"),t?.(),x&&h(!1)},onToggleDefault:()=>A("global"),onDelete:void 0,isReadOnly:!0})]}),n.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),n.length===0&&!o&&v.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ht,{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(j=>e.jsx(Nu,{profile:j,isSelected:r===j.id,isDefault:s===j.id,onSelect:()=>{a(j.id),t?.(),x&&h(!1)},onToggleDefault:()=>A(j.id),onDelete:()=>k(j)},j.id))}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Discovered Credentials"}),e.jsx("p",{className:"px-2 pb-2 typography-micro text-muted-foreground/60",children:"Found in ~/.git-credentials"}),v.map(j=>e.jsx(gk,{credential:j,onImport:()=>S(j)},`${j.host}-${j.username}`))]})]})]})},Nu=({profile:t,isSelected:r,isDefault:s=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:l=!1})=>{const c=mk[t.icon||"branch"]||Ht,d=fk[t.color||""],u=t.authType||"ssh";return e.jsx("div",{className:F("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(De,{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(Gr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(Nt,{onClick:m=>{m.stopPropagation(),o()},children:s?"Unset default":"Set as default"}),!l&&a&&e.jsxs(Nt,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},hk=t=>{const r=t.split("/");return r.length>=3?r[r.length-1]:t},gk=({credential:t,onImport:r})=>{const s=hk(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(De,{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(Hr,{className:"h-3 w-3"}),"Import"]})]})})},Cu=[{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)"}],xk=[{key:"branch",Icon:Ht,label:"Branch"},{key:"briefcase",Icon:Fl,label:"Work"},{key:"house",Icon:Tl,label:"Personal"},{key:"graduation",Icon:Pl,label:"School"},{key:"code",Icon:Qs,label:"Code"}],yk=()=>{const{selectedProfileId:t,getProfileById:r,createProfile:s,updateProfile:n,deleteProfile:o}=Hn(),a=i.useMemo(()=>{if(t?.startsWith("import:")){const[,D,T]=t.split(":");return{host:D,username:T}}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,v]=i.useState(""),[S,N]=i.useState(""),[w,k]=i.useState("keyword"),[A,j]=i.useState("branch"),[M,C]=i.useState(!1);i.useEffect(()=>{if(a){const D=a.host.split("/"),T=D.length>=3?D[D.length-1]:a.host;m(T),p(a.username),x(""),b("token"),v(""),N(a.host),k("string"),j("code")}else c?(m(""),p(""),x(""),b("ssh"),v(""),N(""),k("keyword"),j("branch")):l&&(m(l.name),p(l.userName),x(l.userEmail),b(l.authType||"ssh"),v(l.sshKey||""),N(l.host||""),k(l.color||"keyword"),j(l.icon||"branch"))},[l,c,t,a]);const I=async()=>{if(!f.trim()||!h.trim()){q.error("User name and email are required");return}if(g==="token"&&!S.trim()){q.error("Host is required for token-based authentication");return}C(!0);try{const D={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:w,icon:A};let T;if(c)T=await s(D);else if(t)T=await n(t,D);else return;T?q.success(c?"Profile created successfully":"Profile updated successfully"):q.error(c?"Failed to create profile":"Failed to update profile")}catch(D){console.error("Error saving profile:",D),q.error("An error occurred while saving")}finally{C(!1)}},E=async()=>{if(!(!t||c)&&confirm("Are you sure you want to delete this profile?"))try{await o(t)?q.success("Profile deleted successfully"):q.error("Failed to delete profile")}catch(D){console.error("Error deleting profile:",D),q.error("An error occurred while deleting")}},P=i.useMemo(()=>Cu.find(T=>T.key===w)?.cssVar||"var(--syntax-keyword)",[w]);return t?e.jsx(gt,{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(jt,{value:u,onChange:D=>m(D.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:Cu.map(D=>e.jsx("button",{onClick:()=>k(D.key),className:F("w-8 h-8 rounded-lg border-2 transition-all",w===D.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:D.cssVar},title:D.label},D.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:xk.map(D=>{const T=D.Icon;return e.jsx("button",{onClick:()=>j(D.key),className:F("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",A===D.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:D.label,children:e.jsx(T,{className:"w-4 h-4",style:{color:P}})},D.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(jt,{value:f,onChange:D=>p(D.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(jt,{type:"email",value:h,onChange:D=>x(D.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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:F("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(tx,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>b("token"),className:F("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(sx,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(jt,{value:y,onChange:D=>v(D.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(jt,{value:S,onChange:D=>N(D.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(De,{size:"sm",variant:"destructive",onClick:E,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Us,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:F("flex gap-2",c&&"ml-auto"),children:e.jsxs(De,{size:"sm",variant:"default",onClick:I,disabled:M,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Wa,{className:"h-3 w-3"}),M?"Saving...":"Save Profile"]})})]})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ys,{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 Oi(t,r,s){return Math.min(s,Math.max(r,t))}const nn=Te.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=Te.useRef(null);Te.useImperativeHandle(f,()=>p.current);const[h,x]=Te.useState(()=>String(t));Te.useEffect(()=>{document.activeElement!==p.current&&x(String(t))},[t]);const g=Te.useCallback(()=>{p.current?.focus()},[]),b=Te.useCallback(C=>{const I=Oi(C,s,n);r(I),x(String(I))},[n,s,r]),y=Te.useCallback(()=>{const C=Number(h);return Number.isFinite(C)?C:t},[h,t]),v=Te.useCallback(()=>{b(y()+o),g()},[b,y,g,o]),S=Te.useCallback(()=>{b(y()-o),g()},[b,y,g,o]),N=C=>{const I=C.target.value;x(I);const E=Number(I);Number.isFinite(E)&&r(Oi(E,s,n))},w=C=>{const I=Number(h);if(!Number.isFinite(I))x(String(t));else{const E=Oi(I,s,n);E!==I&&r(E),x(String(E))}c?.(C)},k=C=>{if(C.key==="ArrowUp"){C.preventDefault(),v();return}if(C.key==="ArrowDown"){C.preventDefault(),S();return}d?.(C)},A=y(),j=u||A<=s,M=u||A>=n;return e.jsxs("div",{className:F("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:N,onBlur:w,onKeyDown:k,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:F("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:M,onClick:v,className:F("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(_a,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:j,onClick:S,className:F("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(Ot,{className:"h-3.5 w-3.5"})})]})]})});nn.displayName="NumberInput";const bk=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Mu=[{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"}],Du=[{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."}],Au=[{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."}],uc=({visibleSettings:t})=>{const{isMobile:r}=Qt(),s=Mo(),n=Ce(j=>j.showReasoningTraces),o=Ce(j=>j.setShowReasoningTraces),a=Ce(j=>j.toolCallExpansion),l=Ce(j=>j.setToolCallExpansion),c=Ce(j=>j.fontSize),d=Ce(j=>j.setFontSize),u=Ce(j=>j.padding),m=Ce(j=>j.setPadding),f=Ce(j=>j.cornerRadius),p=Ce(j=>j.setCornerRadius),h=Ce(j=>j.inputBarOffset),x=Ce(j=>j.setInputBarOffset),g=Ce(j=>j.diffLayoutPreference),b=Ce(j=>j.setDiffLayoutPreference),y=Ce(j=>j.diffViewMode),v=Ce(j=>j.setDiffViewMode),S=pr(j=>j.queueModeEnabled),N=pr(j=>j.setQueueMode),{themeMode:w,setThemeMode:k}=Xr(),A=j=>t?t.includes(j):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[A("theme")&&!Wt()&&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:bk.map(j=>e.jsx(Ms,{variant:w===j.value?"default":"outline",className:F(w===j.value?void 0:"text-foreground"),onClick:()=>k(j.value),children:j.label},j.value))})]}),A("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:c,onChange:j=>d(Number(j.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(nn,{value:c,onValueChange:d,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Ms,{type:"button",variant:"ghost",onClick:()=>d(100),disabled:c===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(Is,{className:"h-3.5 w-3.5"})})]})]}),A("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:u,onChange:j=>m(Number(j.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:u}),e.jsx(Ms,{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 spacing",title:"Reset",children:e.jsx(Is,{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:u,onChange:j=>m(Number(j.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(nn,{value:u,onValueChange:m,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Ms,{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 spacing",title:"Reset",children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]})]}),A("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:f,onChange:j=>p(Number(j.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:[f,"px"]}),e.jsx(Ms,{type:"button",variant:"ghost",onClick:()=>p(12),disabled:f===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(Is,{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:f,onChange:j=>p(Number(j.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(nn,{value:f,onValueChange:p,min:0,max:32,step:1,"aria-label":"Corner radius in pixels"}),e.jsx(Ms,{type:"button",variant:"ghost",onClick:()=>p(12),disabled:f===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(Is,{className:"h-3.5 w-3.5"})})]})]}),A("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:h,onChange:j=>x(Number(j.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:[h,"px"]}),e.jsx(Ms,{type:"button",variant:"ghost",onClick:()=>x(0),disabled:h===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(Is,{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:h,onChange:j=>x(Number(j.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(nn,{value:h,onValueChange:x,min:0,max:100,step:5,"aria-label":"Input bar offset in pixels"}),e.jsx(Ms,{type:"button",variant:"ghost",onClick:()=>x(0),disabled:h===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(Is,{className:"h-3.5 w-3.5"})})]})]}),A("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:Mu.find(j=>j.value===a)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Mu.map(j=>e.jsx(Ms,{variant:a===j.value?"default":"outline",className:F(a===j.value?void 0:"text-foreground"),onClick:()=>l(j.value),children:j.label},j.value))})]}),A("diffLayout")&&!r&&!Wt()&&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:Du.map(j=>e.jsx(Ms,{variant:g===j.id?"default":"outline",className:F(g===j.id?void 0:"text-foreground"),onClick:()=>b(j.id),children:j.label},j.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Du.find(j=>j.id===g)?.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:Au.map(j=>e.jsx(Ms,{variant:y===j.id?"default":"outline",className:F(y===j.id?void 0:"text-foreground"),onClick:()=>v(j.id),children:j.label},j.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Au.find(j=>j.id===y)?.description})]})]}),A("dotfiles")&&!Wt()&&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(j=>e.jsx(Ms,{variant:s===j.value?"default":"outline",className:F(s===j.value?void 0:"text-foreground"),onClick:()=>Af(j.value),children:j.label},j.id))})})]}),A("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:j=>o(j.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),A("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:S,onChange:j=>N(j.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:S?`Enter queues messages, ${Xt()}+Enter sends immediately.`:`Enter sends immediately, ${Xt()}+Enter queues messages.`})]})]})},Eu="https://github.com/btriapitsyn/openchamber",wk=800,xp=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),o=Ha(),{isMobile:a}=Qt(),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&&(q.success("You are on the latest version"),c.current=!1)},wk);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:()=>lo(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Is,{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:F("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(Hr,{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:Eu,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ji,{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(Nm,{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(Zi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(ul,{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(Zo,{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:F("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(Hr,{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:F("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:Eu,target:"_blank",rel:"noopener noreferrer",className:F("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Ji,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:F("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Zi,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(ul,{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})]})},vk=1440*60*1e3,yp=5,Iu=1440*60*1e3,_i=t=>t.time?.updated??t.time?.created??0,Pu=({sessions:t,currentSessionId:r,cutoffDays:s,keepRecent:n=yp,now:o=Date.now()})=>{if(!Array.isArray(t)||s<=0)return[];const a=o-s*vk,l=[...t].sort((d,u)=>_i(u)-_i(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=_i(d);return u?u<a:!1}).map(d=>d.id)},bp=t=>{const r=t?.autoRun!==!1,s=me(g=>g.sessions),n=me(g=>g.currentSessionId),o=me(g=>g.isLoading),a=me(g=>g.deleteSessions),l=Ce(g=>g.autoDeleteEnabled),c=Ce(g=>g.autoDeleteAfterDays),d=Ce(g=>g.autoDeleteLastRunAt),u=Ce(g=>g.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),h=i.useMemo(()=>c<=0?[]:Pu({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<Iu)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(s.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const y=Pu({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<Iu||x()},[c,l,d,r,o,s.length,x]),{candidates:h,isRunning:m,runCleanup:x,keepRecentCount:yp}},$i=1,Bi=365,wp=()=>{const{isMobile:t}=Qt(),r=Ce(p=>p.autoDeleteEnabled),s=Ce(p=>p.autoDeleteAfterDays),n=Ce(p=>p.setAutoDeleteEnabled),o=Ce(p=>p.setAutoDeleteAfterDays),[a,l]=i.useState(String(s));i.useEffect(()=>{l(String(s))},[s]);const{candidates:c,isRunning:d,runCleanup:u}=bp({autoRun:!1}),m=c.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){q.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&q.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&q.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(Bi,Math.max($i,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(Bi,Math.max($i,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(nn,{value:s,onValueChange:o,min:$i,max:Bi,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(Ms,{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]})]})},jk=10,Sk=500,kk=20,Nk=500,Ck=30,Mk=1e3,Dk=()=>{const{isMobile:t}=Qt(),r=Ce(h=>h.memoryLimitHistorical),s=Ce(h=>h.memoryLimitViewport),n=Ce(h=>h.memoryLimitActiveSession),o=Ce(h=>h.setMemoryLimitHistorical),a=Ce(h=>h.setMemoryLimitViewport),l=Ce(h=>h.setMemoryLimitActiveSession),[c,d]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let x=null;if(ls())x=await Pr();else{const g=As()?.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 us({[h]:x}),!ls()){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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(zi,{label:"Initial load limit",description:"Messages loaded when opening a session",value:r,defaultValue:rn.HISTORICAL_MESSAGES,min:jk,max:Sk,onChange:m,isMobile:t}),e.jsx(zi,{label:"Background trim limit",description:"Max messages kept when switching away",value:s,defaultValue:rn.VIEWPORT_MESSAGES,min:kk,max:Nk,onChange:f,isMobile:t}),e.jsx(zi,{label:"Active session limit",description:"Max messages for active session",value:n,defaultValue:nl,min:Ck,max:Mk,onChange:p,isMobile:t})]})]})},zi=({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(nn,{value:s,onValueChange:l,min:o,max:a,step:10,"aria-label":t})]})]})})},Tu="opencode",Fu="big-pickle",Ak=(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===Tu)?.models.some(o=>o.id===Fu))return{providerId:Tu,modelId:Fu};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},vp=()=>{const t=at(I=>I.setProvider),r=at(I=>I.setModel),s=at(I=>I.setAgent),n=at(I=>I.setCurrentVariant),o=at(I=>I.setSettingsDefaultModel),a=at(I=>I.setSettingsDefaultVariant),l=at(I=>I.setSettingsDefaultAgent),c=at(I=>I.settingsAutoCreateWorktree),d=at(I=>I.setSettingsAutoCreateWorktree),u=at(I=>I.providers),[m,f]=i.useState(),[p,h]=i.useState(),[x,g]=i.useState(),[b,y]=i.useState(!0),v=i.useMemo(()=>Ak(m,u),[m,u]),S=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{(async()=>{try{let E=null;if(ls())E=await Pr();else{const P=As()?.settings;if(P)try{const T=(await P.load())?.settings;T&&(E={defaultModel:typeof T.defaultModel=="string"?T.defaultModel:void 0,defaultVariant:typeof T.defaultVariant=="string"?T.defaultVariant:void 0,defaultAgent:typeof T.defaultAgent=="string"?T.defaultAgent:void 0})}catch{}if(!E){const D=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});D.ok&&(E=await D.json())}}if(E){const P=typeof E.defaultModel=="string"&&E.defaultModel.trim().length>0?E.defaultModel.trim():void 0,D=typeof E.defaultVariant=="string"&&E.defaultVariant.trim().length>0?E.defaultVariant.trim():void 0,T=typeof E.defaultAgent=="string"&&E.defaultAgent.trim().length>0?E.defaultAgent.trim():void 0;P!==void 0&&f(P),D!==void 0&&h(D),T!==void 0&&g(T)}}catch(E){console.warn("Failed to load defaults settings:",E)}finally{y(!1)}})()},[]);const N=i.useCallback(async(I,E)=>{const P=I&&E?`${I}/${E}`:void 0;f(P),h(void 0),a(void 0),n(void 0),o(P),I&&E&&u.find(T=>T.id===I)&&(t(I),r(E));try{if(await us({defaultModel:P??"",defaultVariant:""}),!ls()){const D=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:P})});D.ok||console.warn("Failed to save default model to server:",D.status,D.statusText)}}catch(D){console.warn("Failed to save default model:",D)}},[u,n,t,r,o,a]),w="__default__",k=i.useCallback(async I=>{const E=I===w?void 0:I||void 0;h(E),a(E),n(E);try{await us({defaultVariant:E??""})}catch(P){console.warn("Failed to save default variant:",P)}},[n,a]),A=i.useCallback(async I=>{const E=I||void 0;g(E),l(E),I&&s(I);try{await us({defaultAgent:E??""})}catch(P){console.warn("Failed to save default agent:",P)}},[s,l]),j=i.useMemo(()=>{if(!v.providerId||!v.modelId)return[];const P=u.find(D=>D.id===v.providerId)?.models.find(D=>D.id===v.modelId)?.variants;return P?Object.keys(P):[]},[v.modelId,v.providerId,u]),M=j.length>0;i.useEffect(()=>{!M&&p&&(h(void 0),a(void 0),n(void 0),us({defaultVariant:""}).catch(()=>{}))},[p,n,a,M]);const C=i.useCallback(async I=>{const E=I.target.checked;d(E);try{await us({autoCreateWorktree:E})}catch(P){console.warn("Failed to save auto create worktree setting:",P)}},[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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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(dc,{providerId:v.providerId,modelId:v.modelId,onChange:N})]}),M&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default thinking"}),e.jsxs(Ls,{value:p??w,onValueChange:k,children:[e.jsx(Os,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(pn,{placeholder:"Thinking"})}),e.jsxs(_s,{children:[e.jsx(rs,{value:w,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),j.map(I=>e.jsx(rs,{value:I,className:"pr-2 [&>span:first-child]:hidden",children:I},I))]})]})]}),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(hp,{agentName:x||"",onChange:A})]})]}),(v.providerId||x)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",v.providerId&&e.jsxs("span",{className:"text-foreground",children:[v.providerId,"/",v.modelId,M?` (${p??"default"})`:""]}),v.providerId&&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:C}),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): ${Xt()} + N • New session (Standard): Shift + ${Xt()} + N`:`New session (Standard): ${Xt()} + N • New session (Worktree): Shift + ${Xt()} + N`})]})]})},Ek=()=>{const t=at(l=>l.settingsGitmojiEnabled),r=at(l=>l.setSettingsGitmojiEnabled),s=ei(),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let c=null;if(ls())c=await Pr();else{const d=As()?.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 us({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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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=>bv(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."})]})})]})},Ik=()=>{const t=Vt($=>$.getActiveProject()),r=Vt($=>$.updateWorktreeDefaults),s=t?.path??null,n=t?.worktreeDefaults,o=Vl(s),a=df(s),{sessions:l,getWorktreeMetadata:c}=me(),[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),[v,S]=i.useState(null),[N,w]=i.useState(null),[k,A]=i.useState([]),[j,M]=i.useState(!1),C=".openchamber",I=i.useCallback(($,oe)=>{const _=$.replace(/\\/g,"/").replace(/\/+$/,""),z=!_||_==="/"?`/${C}`:`${_}/${C}`;return oe?`${z}/${oe}`:z},[]),E=i.useCallback(async()=>{if(!(!s||v===!1))try{const oe=(await $n(s)).map(re=>Bn(s,re)),z=`${I(s,"")}/`,X=oe.filter(re=>re.path.startsWith(z));A(X)}catch{}},[s,v,I]);i.useEffect(()=>{if(!s)return;let $=!1;return y(!0),M(!0),S(null),w(null),A([]),(async()=>{try{const oe=await Yr(s);if($)return;if(S(oe),oe){const[_,z]=await Promise.all([qa(s),$n(s).catch(()=>[])]);if(!$){_&&w({all:_.all,current:_.current});const X=z.map(fe=>Bn(s,fe)),ge=`${`${s.replace(/\\/g,"/").replace(/\/+$/,"")}/${C}`}/`,H=X.filter(fe=>fe.path.startsWith(ge));A(H)}}}catch{}finally{$||(y(!1),M(!1))}})(),()=>{$=!0}},[s]),i.useEffect(()=>{if(!s)return;let $=!1;return g(!0),(async()=>{try{const oe=await Qn(s);$||h(oe.length>0?oe:[""])}catch{$||h([""])}finally{$||g(!1)}})(),()=>{$=!0}},[s]),i.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const P=N??a,D=v??o,T=i.useMemo(()=>{const $=[],oe=P?.current?`Current (HEAD: ${P.current})`:"Current (HEAD)";return $.push({value:"HEAD",label:oe,group:"special"}),P&&(P.all.filter(X=>!X.startsWith("remotes/")).sort((X,re)=>X.localeCompare(re)).forEach(X=>{$.push({value:X,label:X,group:"local"})}),P.all.filter(X=>X.startsWith("remotes/")).map(X=>X.replace(/^remotes\//,"")).sort((X,re)=>X.localeCompare(re)).forEach(X=>{$.push({value:X,label:X,group:"remote"})})),$},[P]),R=i.useRef(null),V=i.useCallback($=>{u($),R.current=$},[]),G=i.useCallback($=>{t?.id&&(r(t.id,{branchPrefix:$}),R.current=null)},[t?.id,r]),O=i.useCallback(()=>{G(d)},[d,G]);i.useEffect(()=>()=>{R.current!==null&&t?.id&&r(t.id,{branchPrefix:R.current})},[t?.id,r]);const Y=i.useCallback($=>{f($),t?.id&&r(t.id,{baseBranch:$})},[t?.id,r]),K=i.useCallback(($,oe)=>{h(_=>{const z=[..._];return z[$]=oe,z})},[]),U=i.useCallback(()=>{h($=>[...$,""])},[]),Q=i.useCallback($=>{h(oe=>oe.filter((_,z)=>z!==$))},[]),W=i.useCallback(async()=>{if(!s)return;const $=p.filter(oe=>oe.trim().length>0);await Ym(s,$)},[s,p]),se=i.useCallback(()=>{W()},[W]),ee=i.useCallback($=>{const oe=$.path.replace(/\\/g,"/").replace(/\/+$/,""),_=l.filter(fe=>{if(c(fe.id)?.path===$.path)return!0;const he=fe.directory;return!!(he&&he.replace(/\\/g,"/").replace(/\/+$/,"")===oe)}),z=new Set(_.map(fe=>fe.id)),X=fe=>{const we=l.filter(_e=>{const te=_e.parentID;return te&&fe.has(te)});if(we.length===0)return[];const he=new Set(we.map(_e=>_e.id));return[...we,...X(he)]},re=X(z),ge=new Set,H=[..._,...re].filter(fe=>ge.has(fe.id)?!1:(ge.add(fe.id),!0));Wn.requestDelete({sessions:H,mode:"worktree",worktree:$})},[l,c]),pe=i.useMemo(()=>l.map($=>$.id).join(","),[l]);return i.useEffect(()=>{v&&s&&E()},[pe,v,s,E]),s?b?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):D===!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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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(jt,{value:d,onChange:$=>V($.target.value),onBlur:O,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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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(Ls,{value:m,onValueChange:Y,children:[e.jsx(Os,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(pn,{placeholder:"Select a branch"})}),e.jsxs(_s,{children:[e.jsxs(cn,{children:[e.jsx(Rn,{children:"Default"}),T.filter($=>$.group==="special").map($=>e.jsx(rs,{value:$.value,children:$.label},$.value))]}),T.some($=>$.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(Pa,{}),e.jsxs(cn,{children:[e.jsx(Rn,{children:"Local branches"}),T.filter($=>$.group==="local").map($=>e.jsx(rs,{value:$.value,children:$.label},$.value))]})]}),T.some($=>$.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(Pa,{}),e.jsxs(cn,{children:[e.jsx(Rn,{children:"Remote branches"}),T.filter($=>$.group==="remote").map($=>e.jsx(rs,{value:$.value,children:$.label},$.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(($,oe)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:$,onChange:_=>K(oe,_.target.value),onBlur:se,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{Q(oe),setTimeout(W,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(Zt,{className:"h-4 w-4"})})]},oe)),e.jsxs("button",{type:"button",onClick:U,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(is,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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"})]}),j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):k.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:k.map($=>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:$.label||$.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:$.relativePath||$.path})]}),e.jsx("button",{type:"button",onClick:()=>ee($),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 ${$.branch||$.label}`,children:e.jsx(Us,{className:"h-4 w-4"})})]},$.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},Pk=()=>{const t=Ce(k=>k.nativeNotificationsEnabled),r=Ce(k=>k.setNativeNotificationsEnabled),s=Ce(k=>k.notificationMode),n=Ce(k=>k.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 k=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;c(k),(async()=>{if(!k){u(!1);return}try{const j=await navigator.serviceWorker.getRegistration();if(!j){u(!1);return}const M=await j.pushManager.getSubscription();u(!!M)}catch{u(!1)}})()},[]);const p=async k=>{if(k&&typeof Notification<"u"&&Notification.permission==="default")try{const A=await Notification.requestPermission();a(A),A==="granted"?r(!0):q.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(A){console.error("Failed to request notification permission:",A),q.error("Failed to request notification permission")}else r(!!(k&&o==="granted"))},h=typeof Notification<"u"&&Notification.permission==="granted",x=k=>{const A="=".repeat((4-k.length%4)%4),j=(k+A).replace(/-/g,"+").replace(/_/g,"/"),M=atob(j),C=new Uint8Array(M.length);for(let I=0;I<M.length;I+=1)C[I]=M.charCodeAt(I);return C},g=async(k,A,j)=>{let M=null;const C=new Promise((I,E)=>{M=setTimeout(()=>{E(new Error(j))},A)});try{return await Promise.race([k,C])}finally{M&&clearTimeout(M)}},b=async k=>{if(k.active)return;const A=k.installing||k.waiting;A&&A.state!=="activated"&&await g(new Promise(j=>{const M=()=>{A.state==="activated"&&(A.removeEventListener("statechange",M),j())};A.addEventListener("statechange",M),M()}),15e3,"Service worker activation timed out")},y=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const k=[{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 A=null;for(const j of k)try{const M=j.opts?navigator.serviceWorker.register("/sw.js",j.opts):navigator.serviceWorker.register("/sw.js");return await g(M,1e4,`Service worker registration timed out (${j.label})`)}catch(M){A=M}throw A instanceof Error?A:new Error("Service worker registration failed")},v=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const k=await navigator.serviceWorker.getRegistration();if(k)return k;const A=await y();try{await A.update()}catch{}return await b(A),A},S=k=>{const A=k,j=[`type=${typeof k}`,`toString=${String(k)}`,`name=${String(A?.name??"")}`,`message=${String(A?.message??"")}`];let M="";try{M=JSON.stringify(k)}catch{}return{summary:j.filter(Boolean).join(" | "),json:M,stack:typeof A?.stack=="string"?A.stack:""}},N=async()=>{if(!l){q.error("Push notifications not supported");return}const k=As();if(!k?.push){q.error("Push API not available");return}f(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const D=await Notification.requestPermission();if(a(D),D!=="granted"){q.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){q.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}const A=await k.push.getVapidPublicKey();if(!A?.publicKey){q.error("Failed to load push key");return}const j=await v();await b(j);const M=await j.pushManager.getSubscription();if(!("pushManager"in j)||!j.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const I=(M??await g(j.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x(A.publicKey)}),15e3,"Push subscription timed out")).toJSON(),E=I.keys;if(!I.endpoint||!E?.p256dh||!E.auth)throw new Error("Push subscription missing keys");if(!(await g(k.push.subscribe({endpoint:I.endpoint,keys:{p256dh:E.p256dh,auth:E.auth},origin:typeof window<"u"?window.location.origin:void 0}),15e3,"Push subscribe request timed out"))?.ok){q.error("Failed to enable background notifications");return}u(!0),q.success("Background notifications enabled")}catch(A){console.error("[Push] Enable failed:",A);const j=S(A);q.error("Failed to enable background notifications",{description:j.summary})}finally{f(!1)}},w=async()=>{if(!l){u(!1);return}const k=As();if(!k?.push){q.error("Push API not available");return}f(!0);try{const j=await(await v()).pushManager.getSubscription();if(!j){u(!1);return}const M=j.endpoint;await j.unsubscribe(),await k.push.unsubscribe({endpoint:M}),u(!1),q.success("Background notifications disabled")}finally{f(!1)}};return gr()?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(mo,{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(mo,{checked:s==="always",onCheckedChange:k=>n(k?"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(Nf,{size:"sm"})}),e.jsx(mo,{checked:d,disabled:m,onCheckedChange:k=>{k?N():w()},className:"data-[state=checked]:bg-status-info"})]})]})]}):null},Tk=({section:t})=>{const{isMobile:r}=Qt(),s=r&&gr();if(!t)return e.jsxs(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-3 p-3 sm:space-y-6 sm:p-6",children:[e.jsx(uc,{}),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(wp,{})}),s&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(xp,{})})]});const n=()=>{switch(t){case"visual":return e.jsx(Fk,{});case"chat":return e.jsx(Rk,{});case"sessions":return e.jsx(Lk,{});case"git":return e.jsx(Ok,{});case"notifications":return e.jsx(_k,{});default:return null}};return e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},Fk=()=>e.jsx(uc,{visibleSettings:["theme","fontSize","spacing","cornerRadius","inputBarOffset"]}),Rk=()=>e.jsx(uc,{visibleSettings:["toolOutput","diffLayout","dotfiles","reasoning","queueMode"]}),Lk=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(vp,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(wp,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Dk,{})})]}),Ok=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ek,{}),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(Ik,{})]})]}),_k=()=>e.jsx(Pk,{}),$k=[{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:"notifications",label:"Notifications",items:["Native"],webOnly:!0}],Bk=({selectedSection:t,onSelectSection:r})=>{const{isMobile:s}=Qt(),n=s&&gr(),[o,a]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=i.useMemo(()=>Wt(),[]),c=i.useMemo(()=>gr(),[]);i.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=i.useMemo(()=>$k.filter(m=>!(m.webOnly&&!c||m.hideInVSCode&&l)),[c,l]),u=o?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:F("flex h-full flex-col",u),children:[e.jsx(gt,{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:F("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(xp,{})})]})},zk=t=>{let r=fp.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},Wi=200,Hi=500,Wk=264,Hk=940,jl=({onClose:t,forceMobile:r})=>{const s=Qt(),n=r??s.isMobile,o=Ce(_=>_.sidebarSection),a=Ce(_=>_.setSidebarSection),l=i.useMemo(()=>o!=="sessions"?o:"settings",[o]),c=i.useCallback(_=>{a(_)},[a]),[d,u]=i.useState("visual"),[m,f]=i.useState(!1),[p,h]=i.useState(()=>typeof window<"u"?Math.min(Hi,Math.max(Wi,Math.floor(window.innerWidth*.2))):Wk),[x,g]=i.useState(!1),[b,y]=i.useState(!1),[v,S]=i.useState(0),N=i.useRef(null),w=i.useRef(0),k=i.useRef(p),[A,j]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),M=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),C=i.useMemo(()=>Wt(),[]),I=i.useMemo(()=>zk(C),[C]);i.useEffect(()=>{typeof window>"u"||j(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{const _=N.current;if(!_)return;const z=new ResizeObserver(X=>{for(const re of X)S(re.contentRect.width)});return z.observe(_),S(_.clientWidth),()=>z.disconnect()},[]);const E=Vt(_=>_.projects),P=Vt(_=>_.activeProjectId),D=Vt(_=>_.setActiveProject),T=i.useMemo(()=>[...E].sort((_,z)=>(_.label||_.path).localeCompare(z.label||z.path)),[E]),R=i.useMemo(()=>T.length===0?null:T.find(_=>_.id===P)??T[0],[P,T]),V=i.useCallback(_=>_.replace(/[-_]/g," ").replace(/\b\w/g,z=>z.toUpperCase()),[]),G=i.useMemo(()=>{if(!R)return"Project";const _=R.label&&R.label.trim().length>0?R.label:R.path.split("/").filter(Boolean).pop()||R.path;return V(_)},[R,V]),O=T.length>0&&!C,Y=v===0||v>=Hk;i.useEffect(()=>{if(l==="agents"){setTimeout(()=>{Qr.getState().loadAgents()},0);return}if(l==="commands"){setTimeout(()=>{Kr.getState().loadCommands()},0);return}l==="skills"&&(or.getState().loadSkills(),ko.getState().loadCatalog())},[P,l]),i.useEffect(()=>{if(typeof window>"u")return;const _=()=>{if(!x){const z=Math.min(Hi,Math.max(Wi,Math.floor(window.innerWidth*.2)));h(z)}};return window.addEventListener("resize",_),()=>window.removeEventListener("resize",_)},[x]),i.useEffect(()=>{if(!b)return;const _=X=>{const re=X.clientX-w.current,ge=Math.min(Hi,Math.max(Wi,k.current+re));h(ge),g(!0)},z=()=>y(!1);return window.addEventListener("pointermove",_),window.addEventListener("pointerup",z,{once:!0}),()=>{window.removeEventListener("pointermove",_),window.removeEventListener("pointerup",z)}},[b]);const K=_=>{y(!0),w.current=_.clientX,k.current=p,_.preventDefault()},U=i.useCallback(async _=>{if(!_.target.closest("button, a, input, select, textarea")&&_.button===0&&A)try{const{getCurrentWindow:z}=await bs(async()=>{const{getCurrentWindow:re}=await import("./vendor-.bun-BrcdMJ39.js").then(ge=>ge.dd);return{getCurrentWindow:re}},__vite__mapDeps([0,1]));await z().startDragging()}catch(z){console.error("Failed to start window dragging:",z)}},[A]),Q=i.useCallback(async _=>{if(_.button===0&&A)try{const{getCurrentWindow:z}=await bs(async()=>{const{getCurrentWindow:re}=await import("./vendor-.bun-BrcdMJ39.js").then(ge=>ge.dd);return{getCurrentWindow:re}},__vite__mapDeps([0,1]));await z().startDragging()}catch(z){console.error("Failed to start window dragging:",z)}},[A]),W=i.useCallback(_=>{c(_),f(!1)},[c]),se=i.useCallback(()=>{n&&f(!0)},[n]),ee=()=>{switch(l){case"settings":return e.jsx(Bk,{selectedSection:d,onSelectSection:_=>{u(_),se()}});case"agents":return e.jsx(_S,{onItemSelect:se});case"commands":return e.jsx(qS,{onItemSelect:se});case"skills":return e.jsx(QS,{onItemSelect:se});case"providers":return e.jsx(ak,{onItemSelect:se});case"git-identities":return e.jsx(pk,{onItemSelect:se});default:return null}},pe=()=>{switch(l){case"agents":return e.jsx(GS,{});case"commands":return e.jsx(KS,{});case"skills":return e.jsx(nk,{});case"providers":return e.jsx(uk,{});case"git-identities":return e.jsx(yk,{});case"settings":return e.jsx(Tk,{section:d});default:return null}},$=Xt(),oe=i.useMemo(()=>A&&M?"pl-[5.75rem]":"",[A,M]);return e.jsxs("div",{ref:N,className:F("flex h-full flex-col overflow-hidden",A?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:U,className:F("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&oe,A?"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(Cl,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:F("flex items-center",n?"gap-1":"h-full"),children:e.jsx("div",{className:F("flex items-center gap-1",!n&&"p-1 bg-background/50 rounded-lg"),children:I.map(({id:_,label:z,icon:X})=>{const re=l===_,ge=X;return n?e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{onClick:()=>W(_),className:F("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",re?"bg-secondary text-foreground shadow-sm":"text-muted-foreground"),"aria-pressed":re,"aria-label":z,children:e.jsx(ge,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(it,{children:e.jsx("p",{children:z})})]},_):e.jsxs("button",{onClick:()=>W(_),onMouseDown:re?Q:void 0,className:F("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",re?"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":re,"aria-label":z,children:[e.jsx(ge,{className:"h-4 w-4",weight:"regular"}),Y&&e.jsx("span",{children:z})]},_)})})}),(t||O)&&e.jsxs("div",{className:F("flex items-center gap-2",n?"":"pr-3"),children:[O&&e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:G,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(cr,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:G,className:F("flex h-9 max-w-[18rem] items-center gap-1.5 bg-transparent px-2 text-foreground outline-none hover:text-foreground/80 focus-visible:ring-2 focus-visible:ring-ring",!n&&"app-region-no-drag"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:G}),e.jsx(Ot,{className:"size-4 opacity-50"})]})}),e.jsx(ss,{align:"end",className:"w-auto",children:e.jsx(Ma,{value:R?.id??"",onValueChange:_=>{_&&D(_)},children:T.map(_=>{const z=_.label?.trim()?_.label.trim():_.path.split("/").filter(Boolean).pop()||_.path,X=V(z);return e.jsx(Da,{value:_.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:X})},_.id)})})})]}),t&&e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,"aria-label":"Close settings",className:F("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(Zt,{className:"h-5 w-5"})})}),e.jsx(it,{children:e.jsxs("p",{children:["Close Settings (",$,"+,)"]})})]})]})]}),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(fs,{children:pe()})}):e.jsx("div",{className:F("flex-1 overflow-hidden",C?"bg-background":"bg-sidebar"),children:e.jsx(fs,{children:ee()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:F("relative overflow-hidden border-r",A?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":C?"bg-background":"bg-sidebar",b?"transition-none":""),style:{width:`${p}px`,minWidth:`${p}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:F("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:K,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(fs,{children:ee()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(fs,{children:pe()})})]})})]})},Uk=()=>{const{isSidebarOpen:t,activeMainTab:r,setIsMobile:s,isSessionSwitcherOpen:n,isSettingsDialogOpen:o,setSettingsDialogOpen:a,isMultiRunLauncherOpen:l,setMultiRunLauncherOpen:c,multiRunLauncherPrefillPrompt:d}=Ce(),{isMobile:u}=Qt(),[m,f]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");i.useEffect(()=>{typeof window>"u"||f(typeof window.opencodeDesktop<"u")},[]),hv({enabled:!0});const p=Ha(b=>b.checkForUpdates);i.useEffect(()=>{const b=setTimeout(()=>{p()},3e3);return()=>clearTimeout(b)},[p]),i.useEffect(()=>{Ce.getState().isMobile!==u&&s(u)},[u,s]),i.useEffect(()=>{if(typeof window>"u")return;let b;const y=()=>{b!==void 0&&window.clearTimeout(b),b=window.setTimeout(()=>{Ce.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",y),()=>{window.removeEventListener("resize",y),b!==void 0&&window.clearTimeout(b)}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const b=document.documentElement;let y=0,v=!1,S=0,N=null;const w=Ce.getState().setKeyboardOpen,k=()=>{N&&(N.style.setProperty("--oc-keyboard-avoid-offset","0px"),N.removeAttribute("data-keyboard-avoid-active"),N=null)},A=P=>{if(!P)return null;const D=P.closest("[data-keyboard-avoid]");if(D)return D;if(P.classList.contains("overlay-scrollbar-container")){const T=P.parentElement;if(T instanceof HTMLElement)return T}return P},j=()=>{y=0,v=!0,b.style.setProperty("--oc-keyboard-inset","0px"),w(!1)},M=()=>{const P=window.visualViewport,D=P?Math.round(P.height):window.innerHeight,T=P?Math.max(0,Math.round(P.offsetTop)):0;b.style.setProperty("--oc-visual-viewport-offset-top",`${T}px`);const R=document.activeElement,V=R?.tagName,O=V==="INPUT"||V==="TEXTAREA"||V==="SELECT"||!!R?.isContentEditable,Y=Math.round(b.clientHeight||window.innerHeight),K=D+T,U=Math.max(0,Y-K),W=U>=(O?120:180)?U:0;if(v)W===0&&(v=!1),y=0;else if(y===0)W>0&&O&&(y=W);else{const $=!O&&D>S+6;W===0?(y=0,w(!1)):$?j():(W>0&&O||W>y)&&(y=W,w(!0))}b.style.setProperty("--oc-keyboard-inset",`${y}px`),S=D;const ee=/iPad|iPhone|iPod/.test(navigator.userAgent)&&y>0?34:0;b.style.setProperty("--oc-keyboard-home-indicator",`${ee}px`);const pe=O?A(R):null;if(!u||!pe||!R)k();else{pe!==N&&(k(),N=pe);const $=T+D,_=R.getBoundingClientRect().bottom-$,z=8,X=Math.max(y,W),re=_>z&&X>0?Math.min(_,X):0,ge=N;ge&&(ge.style.setProperty("--oc-keyboard-avoid-offset",`${re}px`),ge.setAttribute("data-keyboard-avoid-active","true"))}if(u&&O){const $=document.scrollingElement;$&&$.scrollTop!==0&&($.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};M();const C=window.visualViewport;C?.addEventListener("resize",M),C?.addEventListener("scroll",M),window.addEventListener("resize",M),window.addEventListener("orientationchange",M);const I=P=>{const D=P.target;if(!D)return;const T=D.tagName;(T==="INPUT"||T==="TEXTAREA"||T==="SELECT"||D.isContentEditable)&&(v=!1),M()};document.addEventListener("focusin",I,!0);const E=P=>{const D=P.target;if(!D)return;const T=D.tagName;if(T==="INPUT"||T==="TEXTAREA"||T==="SELECT"||D.isContentEditable){const V=P.relatedTarget,G=V?.tagName;if(G==="INPUT"||G==="TEXTAREA"||G==="SELECT"||V?.isContentEditable)return;j()}};return document.addEventListener("focusout",E,!0),()=>{C?.removeEventListener("resize",M),C?.removeEventListener("scroll",M),window.removeEventListener("resize",M),window.removeEventListener("orientationchange",M),document.removeEventListener("focusin",I,!0),document.removeEventListener("focusout",E,!0),k()}},[u]);const h=i.useMemo(()=>{switch(r){case"git":return e.jsx(sS,{});case"diff":return e.jsx(Dw,{});case"terminal":return e.jsx(pS,{});case"files":return e.jsx(PS,{});default:return null}},[r]),x=r==="chat",g=o&&!u;return e.jsx(ov,{children:e.jsxs("div",{className:F("main-content-safe-area h-[100dvh]",u?"flex flex-col":"flex",m?"bg-transparent":"bg-background"),children:[e.jsx(Hw,{}),e.jsx(Gw,{}),e.jsx(ev,{}),u?e.jsxs(e.Fragment,{children:[!(o||l)&&e.jsx(ud,{}),e.jsx("div",{className:F("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(fs,{children:e.jsx(Ia,{mobileVariant:!0})})}):e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:F("absolute inset-0",!x&&"invisible"),children:e.jsx(fs,{children:e.jsx(po,{})})}),h&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(fs,{children:h})})]})}),l&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(fs,{children:e.jsx(Ad,{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(fs,{children:e.jsx(jl,{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:F("absolute inset-0 flex flex-col",(g||l)&&"invisible"),children:[e.jsx(ud,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx(_w,{isOpen:t,isMobile:u,children:e.jsx(Ia,{})}),e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:F("absolute inset-0",!x&&"invisible"),children:e.jsx(fs,{children:e.jsx(po,{})})}),h&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(fs,{children:h})})]})]})]}),l&&e.jsx("div",{className:F("absolute inset-0 z-10",m?"bg-transparent":"bg-background"),children:e.jsx(fs,{children:e.jsx(Ad,{initialPrompt:d,onCreated:()=>c(!1),onCancel:()=>c(!1)})})})]}),g&&e.jsx("div",{className:F("absolute inset-0 z-10",m?"bg-transparent":"bg-background"),children:e.jsx(fs,{children:e.jsx(jl,{onClose:()=>a(!1)})})})]})]})})},Vk=550,Gk=1400,qk=280,Kk=()=>{const t=Fr(),r=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),s=i.useMemo(()=>{const P=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof P=="string"&&P.trim().length>0?P.trim():null},[]),n=i.useRef(!1),[o,a]=i.useState("sessions"),[l,c]=i.useState(0),d=i.useRef(null),u=me(P=>P.currentSessionId),m=me(P=>P.sessions),f=i.useMemo(()=>u?m.find(P=>P.id===u)?.title||"Session":null,[u,m]),p=me(P=>!!P.newSessionDraft?.open),h=me(P=>P.openNewSessionDraft),[x,g]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),b=at(P=>P.isInitialized),y=at(P=>P.initializeApp),v=me(P=>P.loadSessions),S=me(P=>P.loadMessages),N=me(P=>P.messages),[w,k]=i.useState(()=>b),[A,j]=i.useState(!1),M=i.useRef(0);i.useEffect(()=>{u&&a("chat")},[u]),i.useEffect(()=>{const P=t.vscode;P&&P.executeCommand("openchamber.setActiveSession",u,f)},[f,u,t.vscode]),i.useEffect(()=>{r!=="editor"&&!u&&!p&&o==="chat"&&a("sessions")},[u,p,o,r]);const C=i.useCallback(()=>{a("sessions")},[]);i.useEffect(()=>{const P=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(P==="connected"||P==="connecting"||P==="error"||P==="disconnected")&&g(P);const D=T=>{const V=T.detail?.status;(V==="connected"||V==="connecting"||V==="error"||V==="disconnected")&&g(V)};return window.addEventListener("openchamber:connection-status",D),()=>window.removeEventListener("openchamber:connection-status",D)},[]),i.useEffect(()=>{const P=D=>{const R=D.detail?.view;R==="settings"?a("settings"):R==="chat"?a("chat"):R==="sessions"&&a("sessions")};return window.addEventListener("openchamber:navigate",P),()=>window.removeEventListener("openchamber:navigate",P)},[]),i.useEffect(()=>{(async()=>{if(A||w||x!=="connected")return;const D=Date.now();if(!(D-M.current<750)){M.current=D,j(!0);try{const T=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();T&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:b}),b||await y();const R=at.getState();if(!R.isInitialized||!R.isConnected||R.providers.length===0||R.agents.length===0)return;await v();const V=me.getState().error;if(T&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:R.providers.length,agents:R.agents.length,sessions:me.getState().sessions.length,sessionsError:V}),typeof V=="string"&&V.length>0)return;k(!0)}catch{}finally{j(!1)}}})()},[x,b,w,y,A,v]),i.useEffect(()=>{if(r==="editor"&&!n.current&&!(!w||x!=="connected")){if(!s){n.current=!0,h();return}m.some(P=>P.id===s)&&(n.current=!0,me.getState().setCurrentSession(s))}},[x,w,s,h,m,r]),i.useEffect(()=>{(async()=>{if(!w||x!=="connected"||o!=="chat"||p||!u)return;if(!(N.has(u)&&(N.get(u)?.length||0)>0))try{await S(u)}catch{}})()},[x,u,o,w,S,N,p]),i.useEffect(()=>{const P=d.current;if(!P)return;const D=new ResizeObserver(T=>{for(const R of T)c(R.contentRect.width)});return D.observe(P),c(P.clientWidth),()=>D.disconnect()},[]);const I=l>0&&l<Vk,E=l>=Gk;return i.useEffect(()=>{E&&o==="sessions"&&r==="sidebar"&&a("chat")},[E,o,r]),e.jsx("div",{ref:d,className:"h-full w-full bg-background text-foreground flex flex-col",children:r==="editor"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Yo,{title:m.find(P=>P.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(fs,{children:e.jsx(po,{})})})]}):o==="settings"?e.jsx(jl,{onClose:()=>a(E?"chat":"sessions"),forceMobile:I}):E?e.jsxs("div",{className:"flex h-full",children:[e.jsx("div",{className:"h-full border-r border-border overflow-hidden flex-shrink-0",style:{width:qk},children:e.jsx(Ia,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(Yo,{title:p&&!u?"New session":m.find(P=>P.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(fs,{children:e.jsx(po,{})})})]})]}):o==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Yo,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ia,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>a("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Yo,{title:p&&!u?"New session":m.find(P=>P.id===u)?.title||"Chat",showBack:!0,onBack:C,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(fs,{children:e.jsx(po,{})})})]})})},Yo=({title:t,showBack:r,onBack:s,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:l,showContextUsage:c})=>{const{getCurrentModel:d}=at(),u=me(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(fm,{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(is,{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(go,{className:"h-5 w-5"})}),l&&e.jsx(dl,{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(un,{className:"h-5 w-5"})}),c&&x&&x.totalTokens>0&&e.jsx(il,{totalTokens:x.totalTokens,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit??0,size:"compact"})]})},Sl=".openchamber",Xo=t=>{const r=Vt.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"?Bt(t):"",a=`/${Sl}/`,l=o.indexOf(a);return l>0?o.slice(0,l):t?Bt(t):null},Bt=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Ru=t=>{const r=Bt(t);return!r||r==="/"?`/${Sl}`:`${r}/${Sl}`},Qk=(t,r)=>{const s=Bt(t);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const l=Bt(o);if(l)return l}const a=typeof n.name=="string"?n.name.trim():"";return!a||!s?null:`${s}/${a}`}).filter(n=>!!n)},Yk=async t=>{const r=Bt(t);if(!r)return[];try{const n=(await Fe.listLocalDirectory(r)).filter(o=>o.isDirectory);return Qk(r,n)}catch{return[]}},_r=(t,r)=>{const s=Bt(t),n=Bt(r);if(!s||!n)return!1;if(s===n)return!0;const o=n==="/"?"/":`${n}/`;return s.startsWith(o)},jp=async(t,r)=>{const s=Bt(r);if(!s)return s;try{const n=await t.path.get({directory:s});return Bt(n.data?.directory??"")||s}catch{return s}},Sp=async(t,r)=>{const s=Bt(r);if(!s)return[];const n=await jp(t,s),o=l=>l.filter(c=>{const d=Bt(c.directory??"");return d?_r(d,s)||n!==s&&_r(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[]}},Xk=async(t,r)=>{const s=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&s.set(Bt(o.path),o.worktreeMetadata)});const n=Array.from(new Set(t.sessions.map(o=>Bt(o.path)))).filter(Boolean).filter(o=>!s.has(o));if(n.length===0)return s;try{const o=await $n(r),a=new Map(o.map(l=>[Bt(l.worktree),l]));n.forEach(l=>{const c=a.get(l);c&&s.set(l,Bn(r,c))})}catch{}return s},Ui=async t=>{const{apiClient:r,group:s,projectDirectory:n,worktreePaths:o}=t,a=await Xk(s,n),l=me.getState(),c=Array.from(new Set(o.map(p=>Bt(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(v=>Bt(v.path)===p).map(v=>v.id),x=l.getSessionsByDirectory(p),g=Array.isArray(x)?x.map(v=>v.id):[];let b=[];if(g.length===0)try{b=(await Sp(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 Jk(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 zr=ns()(cs((t,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const s=bt.getState().currentDirectory,n=Xo(s);if(!n){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Bt(n),a=Ru(o),l=r().groups;t({isLoading:!0,error:null});try{const c=Fe.getApiClient(),d=await jp(c,o),u=Ru(d);let m=new Map,f=[];try{f=await $n(o),m=new Map(f.map(S=>[Bt(S.worktree),S]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const N=await c.session.list({directory:o}),w=Array.isArray(N.data)?N.data:[];if(w.some(k=>{const A=Bt(k.directory??"");return _r(A,a)||_r(A,u)}))return w}catch{}const S=await c.session.list(void 0);return Array.isArray(S.data)?S.data:[]},h=async S=>{const N=new Map,w=5;let k=0;const A=async()=>{for(;k<S.length;){const j=S[k];k+=1;const M=Bt(j);if(M)try{(await Sp(c,M)).forEach(I=>N.set(I.id,I))}catch(C){console.debug("Failed to fetch sessions from worktree:",M,C)}}};return await Promise.all(Array.from({length:Math.min(w,S.length)},A)),Array.from(N.values())};let g=(await p()).filter(S=>{const N=Bt(S.directory??"");return N?_r(N,a)||_r(N,u):!1});if(g.length===0){const S=new Set;f.map(w=>Bt(w.worktree)).filter(w=>_r(w,a)||_r(w,u)).forEach(w=>S.add(w));const N=Array.from(new Set([a,u].map(w=>Bt(w)).filter(Boolean)));await Promise.all(N.map(async w=>{(await Yk(w)).forEach(A=>S.add(A))})),S.size>0&&(g=await h(Array.from(S)))}const b=new Map;for(const S of g){const N=S.time?.updated??0;b.set(S.id,typeof N=="number"?N:0)}const y=new Map;for(const S of g){const N=Jk(S.title);if(!N)continue;const w=Bt(S.directory),k=m.get(w),A={id:S.id,path:w,providerId:N.provider,modelId:N.model,instanceNumber:N.index,branch:k?.branch??"",displayLabel:`${N.provider}/${N.model}`,worktreeMetadata:k?Bn(o,k):void 0},j=y.get(N.groupSlug);j?j.push(A):y.set(N.groupSlug,[A])}const v=Array.from(y.entries()).map(([S,N])=>{const w=N.reduce((k,A)=>{const j=b.get(A.id)??0;return Math.max(k,j)},0);return{name:S,sessions:N.sort((k,A)=>{const j=k.providerId.localeCompare(A.providerId);if(j!==0)return j;const M=k.modelId.localeCompare(A.modelId);return M!==0?M:k.instanceNumber-A.instanceNumber}),lastActive:w||Date.now(),sessionCount:N.length}});v.sort((S,N)=>S.name.localeCompare(N.name)),t({groups:v,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=bt.getState().currentDirectory,a=Xo(o);if(!a)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const l=Fe.getApiClient(),c=await Ui({apiClient:l,group:n,projectDirectory:Bt(a),worktreePaths:n.sessions.map(f=>f.path)}),d=me.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=Bt(n);if(!a)return!1;const l=bt.getState().currentDirectory,c=Xo(l);if(!c)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const d=Fe.getApiClient(),u=await Ui({apiClient:d,group:o,projectDirectory:Bt(c),worktreePaths:[a]}),m=me.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=Bt(n);if(!a)return!1;const c=Array.from(new Set(o.sessions.map(m=>Bt(m.path)).filter(Boolean))).filter(m=>m!==a);if(c.length===0)return!0;const d=bt.getState().currentDirectory,u=Xo(d);if(!u)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const m=Fe.getApiClient(),f=await Ui({apiClient:m,group:o,projectDirectory:Bt(u),worktreePaths:c}),p=me.getState(),h=new Set;f.forEach(({worktreePath:g,sessionIds:b,metadata:y})=>{b.forEach(v=>{h.add(v),y&&(p.setWorktreeMetadata(v,y),p.setSessionDirectory(v,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=>Bt(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"})),Zk=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`},eN=({group:t,isSelected:r,onSelect:s})=>{const[n,o]=i.useState(!1),[a,l]=i.useState(!1),[c,d]=i.useState(!1),u=zr(f=>f.deleteGroup),m=i.useCallback(async()=>{if(c)return;if(d(!0),q.info(`Deleting "${t.name}"...`),await u(t.name))q.success(`Deleted "${t.name}"`);else{const p=zr.getState().error;q.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:F("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(Ht,{className:"h-3 w-3"}),t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:Zk(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:F("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(Gr,{className:"h-3.5 w-3.5"})})}),e.jsx(ss,{align:"end",className:"min-w-[140px]",children:e.jsx(Nt,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),l(!0)},children:"Delete"})})]})})]})}),e.jsx(xs,{open:a,onOpenChange:l,children:e.jsxs(ys,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(vs,{children:[e.jsx(js,{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(zs,{children:[e.jsx(De,{variant:"outline",onClick:()=>l(!1),disabled:c,children:"Cancel"}),e.jsx(De,{variant:"destructive",onClick:()=>{m()},disabled:c,children:c?"Deleting…":"Delete"})]})]})})]})},tN=({className:t,selectedGroupName:r,onGroupSelect:s,onNewAgent:n})=>{const[o,a]=i.useState(""),[l,c]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=zr(),f=bt(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:F("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(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{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(De,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(is,{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(Ot,{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(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[x.map(b=>e.jsx(eN,{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"})]})]})]})},sN=10*1024*1024,rN=5,nN=({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,v]=i.useState([]),[S,N]=i.useState(!1),[w,k]=i.useState(!1),A=i.useRef(null),j=i.useRef(null),M=bt(ee=>ee.currentDirectory??null),{isGitRepository:C,isLoading:I}=ac(M),E=i.useMemo(()=>{if(typeof window>"u")return null;const ee=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof ee=="string"&&ee.trim().length>0?ee.trim():null},[]),P=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),D=Vt(ee=>ee.activeProjectId),T=Vt(ee=>ee.projects),R=i.useMemo(()=>{if(P&&E)return E;if(D){const _=T.find(z=>z.id===D);if(_?.path)return _.path}const ee=M??E;if(!ee)return null;const pe=ee.replace(/\\/g,"/").replace(/\/+$/,"")||ee,oe=pe.indexOf("/.openchamber/");return oe>0?pe.slice(0,oe):pe.endsWith("/.openchamber")?pe.slice(0,pe.length-13):pe},[D,T,M,E,P]);i.useEffect(()=>{if(!R)return;let ee=!1;return k(!0),(async()=>{try{const pe=await Qn(R);ee||v(pe)}catch{}finally{ee||k(!1)}})(),()=>{ee=!0}},[R]);const V=i.useCallback(ee=>{c.length>=rN||d(pe=>[...pe,ee])},[c.length]),G=i.useCallback(ee=>{d(pe=>pe.filter(($,oe)=>oe!==ee))},[]),O=i.useCallback((ee,pe)=>{d($=>$.map((oe,_)=>_===ee?pe:oe))},[]),Y=async ee=>{const pe=ee.target.files;if(!pe)return;let $=0;for(let oe=0;oe<pe.length;oe++){const _=pe[oe];if(_.size>sN){q.error(`File "${_.name}" is too large (max 10MB)`);continue}try{const z=await new Promise((re,ge)=>{const H=new FileReader;H.onload=()=>re(H.result),H.onerror=ge,H.readAsDataURL(_)}),X={id:Ta(),filename:_.name,mimeType:_.type||"application/octet-stream",size:_.size,dataUrl:z};x(re=>[...re,X]),$++}catch(z){console.error("File attach failed",z),q.error(`Failed to attach "${_.name}"`)}}$>0&&q.success(`Attached ${$} file${$>1?"s":""}`),A.current&&(A.current.value="")},K=ee=>{x(pe=>pe.filter($=>$.id!==ee))},U=g||s,Q=!!(n.trim()&&a.trim()&&c.length>=1&&C&&!I),W=async ee=>{if(ee.preventDefault(),!(!Q||U)){b(!0);try{const pe=c.map(({providerID:_,modelID:z,displayName:X,variant:re})=>({providerID:_,modelID:z,displayName:X,variant:re})),$=h.length>0?h.map(_=>({mime:_.mimeType,filename:_.filename,url:_.dataUrl})):void 0,oe=y.filter(_=>_.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:pe,agent:u||void 0,worktreeBaseBranch:f,files:$,setupCommands:oe.length>0?oe:void 0}),o(""),l(""),d([]),m(""),x([]),p("HEAD")}catch(pe){console.error("Failed to create agent group:",pe),q.error("Failed to create agent group")}finally{b(!1)}}},se=ee=>{nc(ee)||ee.key==="Enter"&&!ee.shiftKey&&(ee.preventDefault(),Q&&!U&&W(ee))};return e.jsx("div",{className:F("flex flex-col items-center justify-center h-full w-full p-4",t),children:e.jsxs("form",{onSubmit:W,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(jt,{id:"group-name",value:n,onChange:ee=>o(ee.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(Ht,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(Tf,{directory:M,value:f,onChange:p}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from ",e.jsx("code",{className:"font-mono text-xs",children:f})]})]}),e.jsxs(No,{open:S,onOpenChange:N,children:[e.jsxs(Qa,{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(ee=>ee.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",y.filter(ee=>ee.trim()).length," configured)"]})]}),e.jsx(Ot,{className:F("h-4 w-4 text-muted-foreground transition-transform duration-200",S&&"rotate-180")})]}),e.jsx(Co,{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."]}),w?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[y.map((ee,pe)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:ee,onChange:$=>{const oe=[...y];oe[pe]=$.target.value,v(oe)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const $=y.filter((oe,_)=>_!==pe);v($)},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(Zt,{className:"h-4 w-4"})})]},pe)),e.jsxs("button",{type:"button",onClick:()=>v([...y,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(is,{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(Ff,{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(Pf,{selectedModels:c,onAdd:V,onRemove:G,onUpdate:O,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:j,id:"prompt",value:a,onChange:ee=>l(ee.target.value),onKeyDown:se,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(ee=>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:[ee.mimeType.startsWith("image/")?e.jsx(vr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(hr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:ee.filename,children:ee.filename}),e.jsx("button",{type:"button",onClick:()=>K(ee.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Zt,{className:"h-3.5 w-3.5"})})]},ee.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:A,type:"file",multiple:!0,className:"hidden",onChange:Y,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>A.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(lm,{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:!Q||U,className:F("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",Q?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:U?e.jsx(rx,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Oa,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},oN=({group:t,className:r})=>{const{selectedSessionId:s,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=zr(),{setCurrentSession:l,currentSessionId:c}=me(),[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(N=>N.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){q.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{q.success("Worktree path copied")}).catch(()=>{q.error("Failed to copy path")})},[p?.path]),b=i.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),y=i.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),v=i.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(q.info("Removing worktree..."),await o(t.name,d.path))q.success("Worktree removed");else{const N=zr.getState().error;q.error(N||"Failed to remove worktree");return}else if(q.info("Removing other worktrees..."),await a(t.name,d.path))q.success("Removed other worktrees");else{const N=zr.getState().error;q.error(N||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,t.name,m,a,d]);return e.jsxs("div",{className:F("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(Ht,{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(De,{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(ws,{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(Ot,{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(Nt,{onClick:()=>h(S),className:"flex items-center gap-2 py-2",children:[e.jsx(ws,{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(Ht,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:S.worktreeMetadata?.label||S.branch})]})]}),p?.id===S.id&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},S.id))})]})}),e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsx(De,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Gr,{className:"h-4 w-4"})})}),e.jsxs(ss,{align:"end",className:"min-w-[220px]",children:[e.jsx(Nt,{onSelect:S=>{S.preventDefault(),b()},variant:"destructive",children:"Remove this worktree"}),e.jsx(Nt,{onSelect:S=>{S.preventDefault(),y()},children:"Leave this one, remove others"}),e.jsxs(Nt,{onClick:S=>{S.stopPropagation(),g()},disabled:!p?.path,children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(xs,{open:!!d,onOpenChange:S=>{S||u(null)},children:e.jsxs(ys,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(vs,{children:[e.jsx(js,{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(zs,{children:[e.jsx(De,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(De,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{v()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?x?e.jsx(rp,{sessionId:p.id,children:e.jsx(sp,{})}):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(ws,{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"})})})]})},aN=({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=at(S=>S.isInitialized),a=at(S=>S.initializeApp),l=me(S=>S.loadSessions),c=bt(S=>S.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=zr(),{createMultiRun:h,isLoading:x}=fo();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 N=w=>{const A=w.detail?.status;(A==="connected"||A==="connecting"||A==="error"||A==="disconnected")&&n(A)};return window.addEventListener("openchamber:connection-status",N),()=>window.removeEventListener("openchamber:connection-status",N)},[r]),i.useEffect(()=>{if(!r||s!=="connected")return;const S=Date.now();if(S-d.current<750)return;d.current=S;const N=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof N=="string"&&N.trim().length>0)try{c(N,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const k=at.getState();if(!k.isInitialized||!k.isConnected||k.providers.length===0||k.agents.length===0)return;await l(),ds()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:k.providers.length,agents:k.agents.length,sessions:me.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=>{q.info(`Creating agent group "${S.name}" with ${S.models.length} model(s)...`);const N=await h(S);if(N){q.success(`Agent group "${S.name}" created with ${N.sessionIds.length} session(s)`);const w=N.groupSlug,k=async(A=6)=>{for(let j=0;j<A;j+=1){if(await p(),zr.getState().groups.some(C=>C.name===w))return!0;await new Promise(C=>setTimeout(C,500))}return!1};try{await me.getState().loadSessions()}catch{}await k(),m(w)}else{const w=fo.getState().error;q.error(w||"Failed to create agent group")}},[h,p,m]),v=f();return e.jsxs("div",{className:F("flex h-full w-full bg-background",t),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(tN,{selectedGroupName:u,onGroupSelect:g,onNewAgent:b})}),e.jsx("div",{className:"flex-1 min-w-0",children:v?e.jsx(oN,{group:v}):e.jsx(nN,{onCreateGroup:y,isCreating:x})})]})},iN=(t=5e3)=>{const[r,s]=Te.useState(null);return Te.useEffect(()=>{if(!ls())return;let n=!1,o=null;const a=async()=>{const l=await kx();n||(s(l),o=setTimeout(a,t))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[t]),r},lN=({onClose:t})=>{const{sessions:r,messages:s,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:l}=me(),c=iN(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(Zl,{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(nx,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),t&&e.jsx(De,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:t,children:e.jsx(Zt,{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," / ",kr.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:[kr.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:[kr.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:[kr.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(gt,{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(ox,{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>kr.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Us,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(it,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{l()},children:"Evict LRU"})}),e.jsx(it,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(De,{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(it,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},cN="openchamber-message-cursors",Vn="cursors",dN=1,kp="openchamber.messageCursors",mc=()=>typeof window<"u",fc=()=>mc()&&typeof indexedDB<"u",Np=()=>fc()?new Promise((t,r)=>{const s=indexedDB.open(cN,dN);s.onupgradeneeded=()=>{const n=s.result;n.objectStoreNames.contains(Vn)||n.createObjectStore(Vn)},s.onerror=()=>{r(s.error??new Error("Failed to open IndexedDB"))},s.onsuccess=()=>{t(s.result)}}):Promise.reject(new Error("IndexedDB not supported")),Cp=()=>{if(!mc())return{};try{const t=window.localStorage.getItem(kp);if(!t)return{};const r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},uN=t=>{if(mc())try{window.localStorage.setItem(kp,JSON.stringify(t))}catch{}},mN=async(t,r,s)=>{if(!t||!r)return;if(fc())try{const o=await Np();await new Promise((a,l)=>{const c=o.transaction(Vn,"readwrite");c.objectStore(Vn).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=Cp();n[t]={messageId:r,completedAt:s},uN(n)},fN=async t=>{if(!t)return null;if(fc())try{const s=await Np(),n=await new Promise((o,a)=>{const l=s.transaction(Vn,"readonly"),d=l.objectStore(Vn).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 Cp()[t]??null},pN=50,hN=750,Lu=new WeakMap,Ou=t=>{if(!t||!Array.isArray(t))return 0;const r=Lu.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 Lu.set(t,s),s},gN=10,_u=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<gN?null:n},$u=(t,r)=>{const s=_u(t),n=_u(r);return!s||!n||s.length!==n.length?!0:s>n},kl=new Map,Bu=(t,r)=>{const s=`${t}:${r}`,n=kl.get(s);if(n&&n.sessionId===t)return n.message;const l=(me.getState().messages.get(t)||[]).find(c=>c.info.id===r)||null;return kl.set(s,{sessionId:t,message:l}),l},xN=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(" ")},yN=()=>{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}=me(),{checkConnection:x}=at(),g=Ce(Ae=>Ae.nativeNotificationsEnabled),b=Ce(Ae=>Ae.notificationMode),y=bt(Ae=>Ae.currentDirectory),v=i.useMemo(()=>{if(!c)return;try{const Ue=u?.(c);if(Ue?.path)return Ue.path}catch(Ue){console.warn("Failed to inspect worktree metadata for session directory:",Ue)}const ae=me.getState().sessions.find(Ue=>Ue.id===c);if(ae&&typeof ae.directory=="string"&&ae.directory.trim().length>0)return ae.directory.trim()},[c,u]),S=i.useMemo(()=>{if(v&&v.length>0)return v;if(typeof y=="string"&&y.trim().length>0)return y.trim()},[v,y]);i.useEffect(()=>{let Ae=!1;const ae=async()=>{try{const Se=await Fe.listPendingPermissions();if(Ae||Se.length===0)return;for(const Ne of Se)o(Ne)}catch{}},Ue=async()=>{try{const Ne=Vt.getState().projects.map(Ye=>Ye.path),rt=me.getState().sessions.map(Ye=>Ye.directory),Ke=[S,...Ne,...rt],Le=await Fe.listPendingQuestions({directories:Ke});if(Ae||Le.length===0)return;for(const Ye of Le)a(Ye)}catch{}};return ae(),Ue(),()=>{Ae=!0}},[o,a,S]);const N=i.useCallback(Ae=>{if(typeof Ae!="string")return null;const ae=Ae.trim();if(!ae)return null;const Ue=ae.replace(/\\/g,"/");return Ue.length>1?Ue.replace(/\/+$/,""):Ue},[]),w=i.useCallback(Ae=>{if(!Ae)return null;try{const Se=u?.(Ae),Ne=N(Se?.path??null);if(Ne)return Ne}catch{}const Ue=me.getState().sessions.find(Se=>Se.id===Ae);return N(Ue?.directory??null)},[u,N]),k=Ce(Ae=>Ae.setEventStreamStatus),A=i.useRef(null),j=i.useCallback((Ae,ae)=>{const Ue=ae??null,Se=A.current;if(!(Se&&Se.status===Ae&&Se.hint===Ue)){if(A.current={status:Ae,hint:Ue},ds()){const Ge={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[Ae]??"[INFO]",rt=Ue?`${Ge} SSE ${Ae}: ${Ue}`:`${Ge} SSE ${Ae}`;console.info(rt)}k(Ae,Ue)}},[k]),M=i.useCallback((Ae,ae,Ue)=>{if(!Ae)return Promise.resolve();const Se=Date.now();if(O.current)return O.current;if(Se-Y.current<hN)return Promise.resolve();const Ne=m(Ae,Ue).catch(Ge=>{console.warn(`[useEventStream] Failed to resync messages (${ae}):`,Ge)}).finally(()=>{O.current=null,Y.current=Date.now()});return O.current=Ne,Ne},[m]),C=i.useCallback(async Ae=>{ds()&&console.info("[useEventStream] Bootstrapping state:",Ae);try{await Promise.all([f(),c?M(c,Ae,1/0):Promise.resolve()])}catch(ae){console.warn("[useEventStream] Bootstrap failed:",Ae,ae)}},[c,f,M]),I=i.useCallback((Ae,ae,Ue)=>{ds()&&console.debug(`[MessageTracker] ${Ae}: ${ae}`,Ue)},[]),E=i.useCallback(Ae=>{ds()&&console.debug(`[MessageTracker] ${Ae}: reported`)},[]),P=i.useRef(null),D=i.useRef(null),T=i.useRef(0);i.useRef(new Set);const R=i.useRef(new Map),V=i.useRef(null),G=i.useRef(!1),O=i.useRef(null),Y=i.useRef(0),K=i.useRef(new Set),U=i.useRef(new Set),Q=i.useRef(new Set),W=i.useRef(new Set),se=i.useCallback(()=>{if(typeof document>"u")return"visible";const Ae=document.visibilityState;return Ae==="hidden"&&document.hasFocus()?"visible":Ae},[]),ee=i.useRef(se()),pe=i.useRef(typeof navigator>"u"?!0:navigator.onLine),$=i.useRef(!1),oe=i.useRef(null),_=i.useRef(null),z=i.useRef(Date.now()),X=i.useRef(!1),re=i.useCallback(Ae=>{const ae=Date.now();ae-z.current>25e3&&(C(Ae),z.current=ae)},[C]);i.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(X.current=!0)},[]);const ge=i.useRef(new Map),H=i.useRef(new Map),fe=i.useRef(0),we=i.useRef(null),he=i.useRef(c),_e=i.useRef(null),te=i.useRef(null);i.useEffect(()=>{he.current=c},[c]);const J=i.useCallback((Ae,ae)=>{if(!Ae)return;const Ue=Date.now(),Se=R.current,Ne=Se.get(Ae);if(Ne&&Ue-Ne<3e3)return;Se.set(Ae,Ue);const Ge=rt=>{if(typeof ae=="string"&&ae.trim().length>0)return ae.trim();try{const Ye=u?.(rt);if(Ye?.path)return Ye.path}catch{}const Le=me.getState().sessions.find(Ye=>Ye.id===rt);return Le&&typeof Le.directory=="string"&&Le.directory.trim().length>0?Le.directory.trim():null};setTimeout(async()=>{try{const rt=Ge(Ae),Ke=rt?await Fe.withDirectory(rt,()=>Fe.getSession(Ae)):await Fe.getSession(Ae);if(Ke){const Le={};typeof Ke.title=="string"&&Ke.title.length>0&&(Le.title=Ke.title),Ke.summary!==void 0&&(Le.summary=Ke.summary),Object.keys(Le).length>0&&d(Ae,Le)}}catch(rt){console.warn("Failed to refresh session metadata:",rt)}},100)},[d,u]),ne=i.useCallback((Ae,ae)=>{if(me.getState().sessionActivityPhase?.get(Ae)===ae){H.current=new Map(me.getState().sessionActivityPhase??new Map);return}const Se=ge.current.get(Ae);Se&&(clearTimeout(Se),ge.current.delete(Ae));const Ne=new Map(me.getState().sessionActivityPhase??new Map);if(Ne.set(Ae,ae),H.current=Ne,me.setState({sessionActivityPhase:Ne}),ae==="cooldown"){const Ge=setTimeout(()=>{if(ge.current.delete(Ae),me.getState().sessionActivityPhase?.get(Ae)==="cooldown"){const Ke=new Map(me.getState().sessionActivityPhase??new Map);Ke.set(Ae,"idle"),H.current=Ke,me.setState({sessionActivityPhase:Ke})}},2e3);ge.current.set(Ae,Ge)}},[]),ke=i.useCallback(async()=>{const Ae=Date.now();if(we.current)return we.current;if(Ae-fe.current<1500)return;fe.current=Ae;const ae=Se=>{const Ne=new Set,Ge=me.getState().sessions,rt=new Set(Ge.map(Le=>Le.id));for(const[Le,Ye]of Object.entries(Se)){if(!Le||!Ye)continue;Ne.add(Le);const xt=Ye.type==="busy"||Ye.type==="retry"?"busy":"idle";ne(Le,xt)}const Ke=me.getState().sessionActivityPhase;if(Ke)for(const[Le,Ye]of Ke.entries())rt.has(Le)&&(Ye==="busy"||Ye==="cooldown")&&!Ne.has(Le)&&ne(Le,"idle")},Ue=(async()=>{try{const Se=await Fe.getGlobalSessionStatus();if(Se&&Object.keys(Se).length>0){ae(Se);return}const Ne=new Set,Ge=me.getState().sessions;for(const xt of Ge){const nt=w(xt.id);nt&&Ne.add(nt)}const rt=N(S??null);rt&&Ne.add(rt);const Ke=Array.from(Ne);if(Ke.length===0){const xt=await Fe.getSessionStatus();xt&&ae(xt);return}const Le=await Promise.allSettled(Ke.map(xt=>Fe.getSessionStatusForDirectory(xt))),Ye={};for(const xt of Le)xt.status!=="fulfilled"||!xt.value||Object.assign(Ye,xt.value);if(Object.keys(Ye).length===0&&Array.from(me.getState().sessionActivityPhase?.values?.()??[]).some(nt=>nt==="busy"||nt==="cooldown")&&!await Fe.checkHealth().catch(()=>!1))return;ae(Ye)}catch{}})().finally(()=>{we.current=null});return we.current=Ue,Ue},[S,N,w,ne]);i.useEffect(()=>{const Ae=c??null,ae=_e.current,Ue=w(Ae),Se=te.current;ae&&Ae&&ae!==Ae&&Se&&Ue&&Se!==Ue&&ke(),_e.current=Ae,te.current=Ue},[c,ke,w]);const Z=i.useCallback(Ae=>{if(z.current=Date.now(),ds()&&console.debug("[useEventStream] Received event:",Ae.type,Ae.properties),!Ae.properties)return;const ae=Ae.properties;if(!new Set(["session.abort","session.error"]).has(Ae.type)){const Se=(typeof ae.session=="object"&&ae.session!==null?ae.session:null)||(typeof ae.sessionInfo=="object"&&ae.sessionInfo!==null?ae.sessionInfo:null);if(Se){const Ne=Se,Ge=typeof Ne.id=="string"&&Ne.id.length>0?Ne.id:typeof Ne.sessionID=="string"&&Ne.sessionID.length>0?Ne.sessionID:typeof ae.sessionID=="string"&&ae.sessionID.length>0?ae.sessionID:typeof ae.id=="string"&&ae.id.length>0?ae.id:void 0;if(Ge){const rt=typeof Ne.title=="string"?Ne.title:typeof ae.title=="string"?ae.title:void 0,Ke=typeof Ne.summary=="object"&&Ne.summary!==null?Ne.summary:typeof ae.summary=="object"&&ae.summary!==null?ae.summary:void 0;if(rt!==void 0||Ke!==void 0){const Le={};rt!==void 0&&(Le.title=rt),Ke!==void 0&&(Le.summary=Ke),d(Ge,Le)}}}}switch(Ae.type){case"server.connected":x();break;case"global.disposed":case"server.instance.disposed":{C("server_disposed_event");break}case"openchamber:session-activity":{const Se=typeof ae.sessionId=="string"?ae.sessionId:null,Ne=typeof ae.phase=="string"?ae.phase:null;Se&&(Ne==="idle"||Ne==="busy"||Ne==="cooldown")&&(ne(Se,Ne),J(Se,typeof ae.directory=="string"?ae.directory:null));break}case"mcp.tools.changed":{const Se=typeof ae.directory=="string"?ae.directory:S;no.getState().refresh({directory:Se??null,silent:!0});break}case"session.status":if(X.current)break;{const Se=typeof ae.sessionID=="string"?ae.sessionID:null,Ne=typeof ae.status=="object"&&ae.status!==null?ae.status:null,Ge=typeof Ne?.type=="string"?Ne.type:null;Se&&Ge&&(ne(Se,Ge==="busy"||Ge==="retry"?"busy":"idle"),J(Se,typeof ae.directory=="string"?ae.directory:null))}break;case"message.part.updated":{const Se=typeof ae.part=="object"&&ae.part!==null?ae.part:null;if(!Se)break;const Ne=Se,Ge=typeof ae.info=="object"&&ae.info!==null?ae.info:ae,rt=typeof Ge.sessionID=="string"?Ge.sessionID:null,Ke=typeof Ne.sessionID=="string"&&Ne.sessionID.length>0?Ne.sessionID:typeof rt=="string"&&rt.length>0?rt:typeof ae.sessionID=="string"&&ae.sessionID.length>0?ae.sessionID:null,Le=typeof Ge.id=="string"?Ge.id:null,Ye=typeof Ne.messageID=="string"&&Ne.messageID.length>0?Ne.messageID:typeof Le=="string"&&Le.length>0?Le:typeof ae.messageID=="string"&&ae.messageID.length>0?ae.messageID:null;if(!Ke||!Ye){ds()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:Ne.sessionID??rt??ae.sessionID,messageID:Ne.messageID??Le??ae.messageID});break}const xt=Ke,nt=Ye,It=me.getState().sessionMemoryState.get(xt)?.trimmedHeadMaxId;if(It&&!$u(nt,It)){ds()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:xt,messageId:nt,trimmedHeadMaxId:It});break}let Pt="assistant";if(Ge&&typeof Ge.role=="string")Pt=Ge.role;else{const We=Bu(xt,nt);if(We){const ut=We.info.role;typeof ut=="string"&&(Pt=ut)}}if(I(nt,"part_received",{role:Pt}),Pt==="user"&&Ne.synthetic===!0){I(nt,"skipped_synthetic_user_part");break}const zt={...Se,type:Se.type||"text"};I(nt,"addStreamingPart_called"),t(xt,nt,zt,Pt);break}case"message.updated":{const Se=typeof ae.info=="object"&&ae.info!==null?ae.info:ae,Ne=Se,Ge=typeof Ne.sessionID=="string"&&Ne.sessionID.length>0?Ne.sessionID:typeof ae.sessionID=="string"&&ae.sessionID.length>0?ae.sessionID:null,rt=typeof Ne.id=="string"&&Ne.id.length>0?Ne.id:typeof ae.messageID=="string"&&ae.messageID.length>0?ae.messageID:null;if(!Ge||!rt){ds()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:Ne.sessionID??ae.sessionID,messageID:Ne.id??ae.messageID});break}const Ke=Ge,Le=rt,Ye=me.getState().sessionMemoryState.get(Ke)?.trimmedHeadMaxId;if(Ye&&!$u(Le,Ye)){ds()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Ke,messageId:Le,trimmedHeadMaxId:Ye});break}if(X.current&&ds())try{const Rt=ae.parts||Ne.parts||[],be=(Array.isArray(Rt)?Rt.filter(Ee=>Ee?.type==="text"):[]).map(Ee=>{const B=Ee;return typeof B?.text=="string"?B.text:typeof B?.content=="string"?B.content:""}).join(`
137
- `);console.info("[STREAM-TRACE] message.updated",{messageId:Le,role:Ne.role,status:Ne.status,textLen:be.length,textPreview:be.slice(0,120),partsCount:Array.isArray(Rt)?Rt.length:0})}catch{}if(I(Le,"message_updated",{role:Ne.role}),Ne.role==="user"){const Rt=ae.parts||Ne.parts,qt=Array.isArray(Rt)?Rt:[],be={...Se,userMessageMarker:!0,clientRole:"user"};if(s(Ke,Le,be),qt.length>0)for(let Ee=0;Ee<qt.length;Ee++){const B=qt[Ee];if(B.synthetic===!0)continue;const ue={...B,type:B?.type||"text",sessionID:B?.sessionID||Ke,messageID:B?.messageID||Le};t(Ke,Le,ue,"user")}I(Le,"user_message_created_from_event",{partsCount:qt.length});break}const xt=Bu(Ke,Le),nt=Ou(xt?.parts||[]),It=xt?.info?.finish==="stop",Pt=ae.parts||Ne.parts,zt=Array.isArray(Pt)?Pt:[],We=zt.length>0,vt=typeof(Ne.time||{})?.completed=="number";if(!We&&!vt)break;const dt=Se.finish,Tt=typeof dt=="string"?dt:null,Ct=Tt==="stop";if(Ne.role==="assistant"&&We){const Rt=Ou(zt);if(nt>0&&Rt+pN<nt&&!Ct){I(Le,"skipped_shrinking_update",{incomingLen:Rt,existingLen:nt});break}if(X.current){const be=nt>0&&Rt<nt,Ee=zt.some(ue=>{if(!ue||ue.type!=="text")return!1;const ve=ue;return typeof ve.text=="string"&&ve.text.length>0});if(be&&!(Ct&&Ee)){I(Le,"desktop_shrinking_update_suppressed",{incomingLen:Rt,existingLen:nt});break}}}if(s(Ke,Le,Se),We&&Ne.role!=="user"){const be=(me.getState().messages.get(Ke)||[]).find(ue=>ue.info.id===Le),Ee=!be||be.parts.length===0;I(Le,Ee?"server_parts_injected":"server_parts_refreshed",{count:zt.length});const B=X.current&&Ne.role==="assistant"?zt.filter(ue=>ue?.type!=="text"):zt;for(let ue=0;ue<B.length;ue++){const ve=B[ue],Be={...ve,type:ve?.type||"text",sessionID:ve?.sessionID||Ke,messageID:ve?.messageID||Le};t(Ke,Le,Be,Ne.role),I(Le,`server_part_${ue}`)}}const os=Se.time,St=os?.completed,Lt=typeof St=="number"&&Number.isFinite(St),Ft=Tt==="stop"||It;if(Se.role==="assistant"&&(Lt||Ft)&&Se.role==="assistant"){const qt=me.getState().messages.get(Ke)||[];let be=null,Ee="";for(let tt=0;tt<qt.length;tt++){const Me=qt[tt];Me.info.role==="assistant"&&Me.info.id>Ee&&(Ee=Me.info.id,be=Me.info.id)}if(c===Ke&&Le!==be)break;if(!Ft&&X.current){I(Le,"desktop_completion_without_stop");break}const ue=Lt?St:Date.now();if(Lt||s(Ke,Le,{...Se,time:{...os??{},completed:ue}}),I(Le,"completed",{timeCompleted:ue}),E(Le),mN(Ke,Le,ue),r(Ke,Le),Tt==="stop"&&gr()&&g&&(b==="always"||ee.current==="hidden")){const Me=Q.current;if(!Me.has(Le)){Me.add(Le);const qe=As();if(qe?.notifications){const et=Ne.mode||"agent",ot=Ne.modelID||"assistant",_t=`${et.charAt(0).toUpperCase()+et.slice(1)} agent is ready`,$t=`${xN(ot)} completed the task`;qe.notifications.notifyAgentCompletion({title:_t,body:$t,tag:Le})}}}X.current||Tt==="stop"&&me.getState().sessionActivityPhase?.get(Ke)==="busy"&&ne(Ke,"cooldown");const ve=Se.sessionID,Be=typeof ve=="string"&&ve.length>0?ve:Ke;J(Be,typeof ae.directory=="string"?ae.directory:null),Se.summary&&typeof Be=="string"&&n(Be,null)}break}case"session.created":case"session.updated":{const Se=typeof ae.info=="object"&&ae.info!==null?ae.info:typeof ae.sessionInfo=="object"&&ae.sessionInfo!==null?ae.sessionInfo:typeof ae.session=="object"&&ae.session!==null?ae.session:ae,Ne=typeof Se.id=="string"&&Se.id.length>0?Se.id:typeof Se.sessionID=="string"&&Se.sessionID.length>0?Se.sessionID:typeof ae.sessionID=="string"&&ae.sessionID.length>0?ae.sessionID:typeof ae.id=="string"&&ae.id.length>0?ae.id:void 0;if(Ne){const Ge=typeof Se.time=="object"&&Se.time!==null?Se.time:typeof ae.time=="object"&&ae.time!==null?ae.time:null,rt=Ge&&typeof Ge.compacting=="number"?Ge.compacting:null;n(Ne,rt);const Ke=typeof Se.directory=="string"?Se.directory:typeof ae.directory=="string"?ae.directory:null,Le={...Se,id:Ne,...Ke?{directory:Ke}:{}};p(Le)}break}case"session.deleted":{const Se=typeof ae.sessionID=="string"?ae.sessionID:typeof ae.id=="string"?ae.id:null;Se&&h(Se);break}case"session.abort":{const Se=typeof ae.sessionID=="string"&&ae.sessionID.length>0?ae.sessionID:null,Ne=typeof ae.messageID=="string"&&ae.messageID.length>0?ae.messageID:null;Se&&Ne&&r(Se,Ne);break}case"permission.asked":{if(!("sessionID"in ae)||typeof ae.sessionID!="string")break;const Se=ae;o(Se);const Ne=`${Se.sessionID}:${Se.id}`;K.current.has(Ne)||setTimeout(()=>{if(he.current===Se.sessionID||!me.getState().permissions.get(Se.sessionID)?.some(Le=>Le.id===Se.id))return;K.current.add(Ne);const Ke=me.getState().sessions.find(Le=>Le.id===Se.sessionID)?.title||"Session";if(bs(async()=>{const{toast:Le}=await import("./vendor-.bun-BrcdMJ39.js").then(Ye=>Ye.db);return{toast:Le}},__vite__mapDeps([0,1])).then(({toast:Le})=>{Le.warning("Permission required",{description:Ke,action:{label:"Open",onClick:()=>{Ce.getState().setActiveMainTab("chat"),me.getState().setCurrentSession(Se.sessionID)}}})}),gr()&&g&&(b==="always"||ee.current==="hidden")){const Ye=As();Ye?.notifications&&Ye.notifications.notifyAgentCompletion({title:"Permission required",body:Ke,tag:`permission-${Ne}`})}},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in ae)||typeof ae.sessionID!="string")break;const Se=ae;a(Se);const Ne=`${Se.sessionID}:${Se.id}`;if(gr()&&g&&(b==="always"||ee.current==="hidden")){const rt=W.current;if(!rt.has(Ne)){rt.add(Ne);const Ke=As();Ke?.notifications&&Ke.notifications.notifyAgentCompletion({title:"Input needed",body:"Agent is waiting for your response",tag:Ne})}}U.current.has(Ne)||setTimeout(()=>{if(he.current===Se.sessionID||!me.getState().questions.get(Se.sessionID)?.some(Le=>Le.id===Se.id))return;U.current.add(Ne);const Ke=me.getState().sessions.find(Le=>Le.id===Se.sessionID)?.title||"Session";bs(async()=>{const{toast:Le}=await import("./vendor-.bun-BrcdMJ39.js").then(Ye=>Ye.db);return{toast:Le}},__vite__mapDeps([0,1])).then(({toast:Le})=>{Le.info("Input needed",{description:Ke,action:{label:"Open",onClick:()=>{Ce.getState().setActiveMainTab("chat"),me.getState().setCurrentSession(Se.sessionID)}}})})},0);break}case"question.replied":{const Se=typeof ae.sessionID=="string"?ae.sessionID:null,Ne=typeof ae.requestID=="string"?ae.requestID:null;Se&&Ne&&l(Se,Ne);break}case"todo.updated":{const Se=typeof ae.sessionID=="string"?ae.sessionID:null,Ne=Array.isArray(ae.todos)?ae.todos:null;Se&&Ne&&Rv(Se,Ne);break}}},[c,g,b,t,r,s,o,a,l,x,J,n,d,I,E,ne,p,h,C,S]),ye=i.useCallback(()=>{const Ae=se();return ee.current=Ae,Ae==="visible"&&pe.current},[se]),de=i.useCallback(()=>{ds()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:X.current,hasUnsubscribe:!!P.current,currentSessionId:he.current,effectiveDirectory:S,onlineStatus:pe.current,visibilityState:ee.current,lastEventTimestamp:z.current,reconnectAttempts:T.current})},[S]),je=i.useCallback(async()=>!0,[]),ie=i.useCallback(()=>{if(G.current){ds()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(G.current=!0,D.current&&(clearTimeout(D.current),D.current=null),P.current){const Ae=P.current;P.current=null;try{Ae()}catch(ae){console.warn("[useEventStream] Error during unsubscribe:",ae)}}G.current=!1},[]),Xe=i.useCallback(async Ae=>{if(de(),!ye()){$.current=!0,pe.current?j("paused","Paused while hidden"):j("offline","Waiting for network");return}X.current&&(await je()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),Ae?.resetAttempts&&(T.current=0),ie(),z.current=Date.now(),j("connecting",null),ds()&&console.info("[useEventStream] Starting event stream...");const ae=Se=>{console.warn("Event stream error:",Se)},Ue=()=>{const Se=$.current;if(T.current=0,$.current=!1,z.current=Date.now(),j("connected",null),x(),ke(),Se)C("sse_reconnected");else{const Ne=he.current;Ne&&setTimeout(()=>{M(Ne,"sse_reconnected",1/0).then(()=>J(Ne)).catch(Ge=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Ge)})},0)}};if(ds()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:S,isCleaningUp:G.current}),G.current){ds()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Se=Fe.subscribeToGlobalEvents(Ge=>{const rt=Ge.payload,Ke=Ge.payload,Le=typeof Ke.properties=="object"&&Ke.properties!==null?Ke.properties:{},Ye=Ge.directory&&Ge.directory!=="global"?{...Le,directory:Ge.directory}:Le;Z({type:typeof rt.type=="string"?rt.type:"",properties:Ye})},ae,Ue),Ne=()=>{try{Se()}catch(Ge){console.warn("[useEventStream] Error during unsubscribe:",Ge)}};G.current?Ne():P.current=Ne}catch(Se){console.error("[useEventStream] Error during subscription:",Se),ae(Se)}},[ye,ie,j,x,M,J,Z,S,ke,je,de,C]),mt=i.useCallback(Ae=>{if(!ye()){$.current=!0,ie(),pe.current?j("paused","Paused while hidden"):j("offline","Waiting for network");return}const ae=T.current+1;T.current=ae;const Ue=Ae??`Retrying (${ae})`;j("reconnecting",Ue);const Se=ae<=3?Math.min(1e3*Math.pow(2,ae-1),8e3):Math.min(2e3*Math.pow(2,ae-3),32e3),Ne=Math.floor(Math.random()*250),Ge=Se+Ne;D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{Xe({resetAttempts:!1})},Ge)},[ye,ie,j,Xe]);i.useEffect(()=>{const Ae=ge.current;typeof window<"u"&&(window.__messageTracker=I);let ae=null;X.current&&typeof window<"u"&&(ae=Ye=>{const xt=typeof Ye.detail?.sessionId=="string"?Ye.detail.sessionId:null,nt=typeof Ye.detail?.phase=="string"?Ye.detail.phase:null;xt&&(nt==="idle"||nt==="busy"||nt==="cooldown")&&(ne(xt,nt),J(xt))},window.addEventListener("openchamber:session-activity",ae));const Ue=()=>{oe.current&&(clearTimeout(oe.current),oe.current=null)},Se=()=>{oe.current||(oe.current=setTimeout(()=>{const Ye=se();ee.current=Ye,Ye!=="visible"?(ie(),$.current=!0,j("paused","Paused while hidden")):Ue()},5e3))},Ne=()=>{if(ee.current=se(),ee.current==="visible"){if(Ue(),re("visibility_restore"),$.current||!P.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ye=he.current;Ye&&(M(Ye,"visibility_restore",ol()).catch(()=>{}),J(Ye)),ke(),j("connecting","Resuming stream"),Xe({resetAttempts:!0})}}else j("paused","Paused while hidden"),Se()},Ge=()=>{if(ee.current=se(),ee.current==="visible"&&(Ue(),re("window_focus"),$.current||!P.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ye=he.current;Ye&&(J(Ye),M(Ye,"window_focus",ol()).then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(xt=>console.warn("[useEventStream] Failed to refresh messages:",xt))),ke(),j("connecting","Resuming stream"),Xe({resetAttempts:!0})}},rt=()=>{pe.current=!0,re("network_restored"),($.current||!P.current)&&(j("connecting","Network restored"),Xe({resetAttempts:!0}))},Ke=()=>{pe.current=!1,$.current=!0,j("offline","Waiting for network"),ie()};typeof document<"u"&&document.addEventListener("visibilitychange",Ne),typeof window<"u"&&(window.addEventListener("online",rt),window.addEventListener("offline",Ke),window.addEventListener("focus",Ge));const Le=setTimeout(()=>{Xe({resetAttempts:!0})},100);return _.current&&clearInterval(_.current),_.current=setInterval(()=>{if(!ye())return;const Ye=Date.now();Array.from(me.getState().sessionActivityPhase?.values?.()??[]).some(nt=>nt==="busy"||nt==="cooldown")&&ke(),Ye-z.current>45e3&&Promise.resolve().then(async()=>{try{await Fe.checkHealth()?z.current=Date.now():mt("Refreshing stalled stream")}catch(nt){console.warn("Health check after stale stream failed:",nt),mt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Le),ae&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",ae),typeof document<"u"&&document.removeEventListener("visibilitychange",Ne),typeof window<"u"&&(window.removeEventListener("online",rt),window.removeEventListener("offline",Ke),window.removeEventListener("focus",Ge)),Ue(),_.current&&(clearInterval(_.current),_.current=null),Ae.forEach(Ye=>clearTimeout(Ye)),Ae.clear(),kl.clear(),Q.current.clear(),W.current.clear(),$.current=!1,ee.current=se(),pe.current=typeof navigator>"u"?!0:navigator.onLine,ie(),V.current&&(clearTimeout(V.current),V.current=null),j("idle",null)}},[S,I,se,ie,j,Xe,mt,m,J,ne,ke,ye,f,re,M])},bN=()=>{const{openNewSessionDraft:t,abortCurrentOperation:r,armAbortPrompt:s,clearAbortPrompt:n,currentSessionId:o}=me(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=Ce(),{themeMode:p,setThemeMode:h}=Xr(),{working:x}=Gf(),g=i.useRef(null),b=i.useRef(null),y=i.useRef(!1),v=i.useCallback(()=>{b.current&&(clearTimeout(b.current),b.current=null),g.current=null,n()},[n]);i.useEffect(()=>{const S=N=>{if(Ts(N)&&N.key==="k"&&(N.preventDefault(),a()),Ts(N)&&N.shiftKey&&N.key.toLowerCase()==="l"){const k=As()?.diagnostics;if(!k||(N.preventDefault(),y.current))return;y.current=!0,k.downloadLogs().then(({fileName:A,content:j})=>{const M=A||"openchamber.log",C=new Blob([j],{type:"text/plain;charset=utf-8"}),I=URL.createObjectURL(C),E=document.createElement("a");E.href=I,E.download=M,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(I)}).finally(()=>{y.current=!1});return}if(Ts(N)&&N.key==="."&&(N.preventDefault(),l()),Ts(N)&&N.key.toLowerCase()==="n"){N.preventDefault();const w=Wt(),k=at.getState().settingsAutoCreateWorktree;if(w?!1:k?!N.shiftKey:N.shiftKey){u("chat"),d(!1),Xa();return}u("chat"),d(!1),t()}if(Ts(N)&&N.key==="/"){N.preventDefault();const w=["light","dark","system"],A=(w.indexOf(p)+1)%w.length;h(w[A])}if(Ts(N)&&!N.shiftKey&&N.key.toLowerCase()==="t"){N.preventDefault();const{isTimelineDialogOpen:w,setTimelineDialogOpen:k}=Ce.getState();k(!w);return}if(Ts(N)&&!N.shiftKey&&N.key===","){N.preventDefault();const{isSettingsDialogOpen:w}=Ce.getState();m(!w);return}if(Ts(N)&&!N.shiftKey&&N.key.toLowerCase()==="l"){N.preventDefault();const{isMobile:w,isSessionSwitcherOpen:k}=Ce.getState();w?d(!k):c();return}if(Ts(N)&&!N.shiftKey&&N.key.toLowerCase()==="i"){N.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Ts(N)&&N.shiftKey&&N.key.toLowerCase()==="m"){const{isSettingsDialogOpen:w,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:j,isAboutDialogOpen:M,activeMainTab:C,isModelSelectorOpen:I}=Ce.getState();if(w||k||A||j||M||!(C==="chat"))return;N.preventDefault(),f(!I);return}if(Ts(N)&&N.shiftKey&&N.key.toLowerCase()==="t"){const{isSettingsDialogOpen:w,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:j,isAboutDialogOpen:M,activeMainTab:C}=Ce.getState();if(w||k||A||j||M||!(C==="chat"))return;const P=at.getState();if(P.getCurrentModelVariants().length===0)return;N.preventDefault(),P.cycleCurrentVariant();const T=at.getState().currentVariant,R=me.getState(),V=R.currentSessionId,G=at.getState().currentAgentName,O=at.getState().currentProviderId,Y=at.getState().currentModelId;V&&G&&O&&Y&&R.saveAgentModelVariantForSession(V,G,O,Y,T);return}if(N.key==="Escape"){const{isSettingsDialogOpen:w,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:j,isAboutDialogOpen:M,activeMainTab:C}=Ce.getState();if(w){N.preventDefault(),m(!1),v();return}if(k||A||j||M||!(C==="chat")){v();return}const P=o;if(!(x.canAbort&&!!P)){v();return}const T=Date.now(),R=g.current;if(R&&T<R){N.preventDefault(),v(),r();return}N.preventDefault();const V=s(3e3)??T+3e3;g.current=V,b.current&&clearTimeout(b.current);const G=Math.max(V-T,0);b.current=setTimeout(()=>{g.current&&Date.now()>=g.current&&v()},G||0);return}};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[t,r,a,l,c,d,u,m,f,h,p,x,s,v,o]),i.useEffect(()=>()=>{v()},[v])},zu="openchamber:menu-action",wN=t=>{const{openNewSessionDraft:r}=me(),{toggleCommandPalette:s,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=Ce(),{addProject:u}=Vt(),{requestAccess:m,startAccessing:f}=Ja(),{setThemeMode:p}=Xr(),h=i.useRef(!1),x=i.useCallback(()=>{ls()?m("").then(async g=>{if(!g.success||!g.path){g.error&&g.error!=="Directory selection cancelled"&&q.error("Failed to select directory",{description:g.error});return}const b=await f(g.path);if(!b.success){q.error("Failed to open directory",{description:b.error||"Desktop could not grant file access."});return}u(g.path,{id:g.projectId})||q.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(g=>{console.error("Desktop: Error selecting directory:",g),q.error("Failed to select directory")}):Wn.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),Xa();break;case"change-workspace":x();break;case"open-git-tab":{const{activeMainTab:v}=Ce.getState();l(v==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:v}=Ce.getState();l(v==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:v}=Ce.getState();l(v==="terminal"?"chat":"terminal");break}case"theme-light":p("light");break;case"theme-dark":p("dark");break;case"theme-system":p("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":t?.();break;case"help-dialog":n();break;case"download-logs":{const S=As()?.diagnostics;if(!S||h.current)break;h.current=!0,S.downloadLogs().then(({fileName:N,content:w})=>{const k=N||"openchamber.log",A=new Blob([w],{type:"text/plain;charset=utf-8"}),j=URL.createObjectURL(A),M=document.createElement("a");M.href=j,M.download=k,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(j),q.success("Logs saved",{description:`Downloaded to ~/Downloads/${k}`})}).catch(()=>{q.error("Failed to download logs")}).finally(()=>{h.current=!1});break}}};return window.addEventListener(zu,g),()=>window.removeEventListener(zu,g)},[r,s,n,o,a,l,c,d,p,t,x])},vN=t=>t.role==="assistant",Wu=t=>{const r=t.info;if(!vN(r))return;const s=r.time?.completed;return typeof s=="number"?s:void 0},ha=t=>{if(!t)return!1;if(t.role==="user")return!0;const r=t;return r.clientRole==="user"?!0:!!r.userMessageMarker},Hu=t=>(Array.isArray(t?.parts)?t.parts:[]).map(n=>co(n)).join(" ").replace(/\s+/g," ").trim(),jN=(t,r)=>{if(!t||!ha(t.info))return-1;const s=Hu(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(!ha(l.info))return;const d=Hu(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(!ha(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},SN=()=>{const{currentSessionId:t,messages:r,streamingMessageIds:s}=me(),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=me.getState().sessionMemoryState.get(t),m=Sa(),f=u?.isStreaming?m.VIEWPORT_MESSAGES:m.HISTORICAL_MESSAGES,p=f+m.FETCH_BUFFER,h=await Fe.getSessionMessages(t,p),x=await fN(t);if(!h)return;const g=d[d.length-1];if(g){const b=h.findIndex(S=>S.info.id===g.info.id),v=b===-1?jN(g,h):b;if(v!==-1)if(v<h.length-1){const S=h.slice(v+1);console.log(`[SYNC] Found ${S.length} new messages to append`);const N=[...d,...S],{syncMessages:w}=me.getState();w(t,N)}else{const S=h[v],N=d[d.length-1],w=Wu(S),k=Wu(N);if(w&&!k){console.log("[SYNC] Last message completed on server");const A=[...d.slice(0,-1),S],{syncMessages:j}=me.getState();j(t,A)}}else if(ha(g.info)){const S=h.slice(-f);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:N}=me.getState();N(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 v=h.slice(b+1).slice(-f);if(v.length>0){console.log(`[SYNC] Restoring ${v.length} messages after cursor`);const{syncMessages:S}=me.getState();S(t,v)}}}else if(h.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const y=h.slice(-f),{syncMessages:v}=me.getState();v(t,y)}}else if(h.length>0){const b=h.slice(-f);console.log(`[SYNC] Loading last ${b.length} messages`);const{syncMessages:y}=me.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])},kN=()=>{i.useEffect(()=>{let t=!1;return(async()=>{try{const s=await Fe.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&&me.setState({sessionActivityPhase:n})}catch{}})(),()=>{t=!0}},[])},NN=["chat","git","diff","terminal","files"],CN=["settings","agents","commands","skills","providers","git-identities"],qs={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function Uu(t){const r=MN();return{sessionId:DN(r),tab:AN(r),settingsSection:EN(r),diffFile:IN(r)}}function MN(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function DN(t){const r=t.get(qs.SESSION);return!r||r.trim().length===0?null:r.trim()}function AN(t){const r=t.get(qs.TAB);if(!r)return null;const s=r.toLowerCase().trim();return NN.includes(s)?s:null}function EN(t){const r=t.get(qs.SETTINGS);if(!r)return null;const s=r.toLowerCase().trim();return CN.includes(s)?s:s==="openchamber"||s==="general"||s==="preferences"?"settings":null}function IN(t){const r=t.get(qs.FILE);if(!r||r.trim().length===0)return null;try{return decodeURIComponent(r.trim())}catch{return r.trim()}}function Vu(){if(typeof window>"u")return!1;try{const t=new URLSearchParams(window.location.search);return t.has(qs.SESSION)||t.has(qs.TAB)||t.has(qs.SETTINGS)||t.has(qs.FILE)}catch{return!1}}const PN="chat";function Mp(t){const r=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&r.set(qs.SESSION,t.sessionId),t.isSettingsOpen){const s=t.settingsSection==="sessions"?"settings":t.settingsSection;return r.set(qs.SETTINGS,s),r}return t.tab!==PN&&r.set(qs.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&r.set(qs.FILE,t.diffFile),r}function TN(t,r){const s=typeof window<"u"?window.location.pathname:"/",n=t.toString();return n?`${s}?${n}`:s}function FN(t){if(typeof window>"u")return!0;try{const r=new URLSearchParams(window.location.search),s=Mp(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 RN(t,r={}){if(!(typeof window>"u")&&!LN()&&!(!r.force&&FN(t)))try{const s=Mp(t),n=TN(s);r.replace?window.history.replaceState({...window.history.state,route:t},"",n):window.history.pushState({route:t},"",n)}catch{}}function LN(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function ON(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function _N(){const t=i.useMemo(()=>ON(),[]),r=i.useRef(!1),s=i.useRef(!1),n=me(f=>f.setCurrentSession),o=Ce(f=>f.setActiveMainTab),a=Ce(f=>f.setSettingsDialogOpen),l=Ce(f=>f.setSidebarSection),c=Ce(f=>f.navigateToDiff),d=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=me.getState().currentSessionId;f.sessionId!==p&&await n(f.sessionId)}if(f.settingsSection){l(f.settingsSection),a(!0);return}Ce.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=me.getState(),p=Ce.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();RN(p,f)},[t,u]);i.useEffect(()=>{if(r.current||(r.current=!0,!Vu()))return;const f=Uu();(async()=>(await d(f),t||m({replace:!0})))()},[d,t,m]),i.useEffect(()=>{if(t)return;let f=me.getState().currentSessionId;return me.subscribe(h=>{const x=h.currentSessionId;x===f||s.current||(f=x,m())})},[t,m]),i.useEffect(()=>{if(t)return;let f=Ce.getState().activeMainTab,p=Ce.getState().isSettingsDialogOpen,h=Ce.getState().sidebarSection,x=Ce.getState().pendingDiffFile;return Ce.subscribe(b=>{if(s.current)return;const y=b.activeMainTab!==f,v=b.isSettingsDialogOpen!==p,S=b.sidebarSection!==h,N=b.pendingDiffFile!==x&&b.activeMainTab==="diff";f=b.activeMainTab,p=b.isSettingsDialogOpen,h=b.sidebarSection,x=b.pendingDiffFile,(y||v||S||N)&&m()})},[t,m]),i.useEffect(()=>{if(typeof window>"u"||t)return;const f=()=>{const p=Uu();if(Vu())d(p);else{const h=Ce.getState();h.isSettingsDialogOpen&&a(!1),h.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[d,t,o,a])}const $N=1e4,Gu=()=>{if(typeof document>"u")return"visible";const t=document.visibilityState;return t==="hidden"&&document.hasFocus()?"visible":t},qu=t=>{if(!gr())return;const r=As();r?.push?.setVisibility&&r.push.setVisibility({visible:t})},BN=()=>{i.useEffect(()=>{if(!gr()||typeof document>"u")return;const t=()=>{qu(Gu()==="visible")},r=()=>{Gu()==="visible"&&qu(!0)};t();const s=window.setInterval(r,$N);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 zN(){const{git:t}=Fr(),r=bt(m=>m.currentDirectory),{currentSessionId:s,sessions:n,worktreeMetadata:o}=me(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=as(),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 WN({children:t}){return zN(),e.jsx(e.Fragment,{children:t})}const HN=()=>{const[{isUpdating:t,message:r},s]=i.useState(()=>Vx());return i.useEffect(()=>Ux(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(lc,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Dp={getLastAssistantMessage(){const t=me.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=me.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=bt.getState(),r=me.getState(),s=Vt.getState(),n=t.currentDirectory||null,o=Fe.getDirectory()??null,a=r.sessions||[],l=new Set,c={};a.forEach(j=>{const M=j.directory;typeof M=="string"&&M.trim().length>0?(l.add(M),c[M]=(c[M]??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(j){return{available:!1,error:j instanceof Error?j.message:String(j)}}})(),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 j=>{try{return await j.json()}catch{return null}},h=async j=>{try{return await j.text()}catch{return null}},x=async j=>{try{const M=await fetch(j);return M.ok?await p(M):{status:M.status}}catch(M){return{error:M instanceof Error?M.message:String(M)}}};let g=null,b=null,y=null,v=null;const S=n?`/api/path?directory=${encodeURIComponent(n)}`:"/api/path";g=await x(S);const N=n?`/api/project/current?directory=${encodeURIComponent(n)}`:"/api/project/current";b=await x(N),y=await x("/api/config/settings");try{const j=await fetch("/api/health"),M=j.headers.get("content-type")||"",C=await h(j);v={status:j.status,ok:j.ok,contentType:M,type:M.includes("application/json")?"json":"html",preview:C?C.slice(0,120):null}}catch(j){v={error:j instanceof Error?j.message:String(j)}}let w={isGitRepo:null};if(n)try{w.isGitRepo=await Yr(n)}catch(j){w={isGitRepo:null,error:j instanceof Error?j.message:String(j)}}const k=s.projects.map(j=>({id:j.id,path:j.path,label:j.label})),A={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:k},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:w,localStorage:d,opencode:{pathInfo:g,projectInfo:b,health:v},openchamber:{settingsInfo:y}};return console.log("[DEBUG] App status snapshot:",A),A},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=me.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=me.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:
138
- `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
139
- `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
140
- `),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)
141
- `),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=me.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),v=y!==null,S=g.filter(E=>E.type==="tool"),N=g.filter(E=>E.type==="reasoning"),w=m(S.map(E=>u(E.state?.time?.end??E.state?.time?.start))),k=m(N.map(E=>u(E.time?.end??E.time?.start))),A=m([w,k].filter(E=>E!==null)),j=S.some(E=>["pending","running","started"].includes(E.state?.status)),M=N.some(E=>typeof E.time?.end!="number");S.length>0&&(d.withTools+=1),N.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const C=!!(v&&typeof w=="number"&&y<w);C&&(d.completedBeforeTool+=1);const I=!!(v&&typeof k=="number"&&y<k);return I&&(d.completedBeforeReasoning+=1),v&&j&&(d.runningToolsWhenCompleted+=1),v&&M&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:x.id,role:x.role,completedAt:y,latestToolTimestamp:w,latestReasoningTimestamp:k,latestPartTimestamp:A,completed_missing:!v,completed_before_tool:C,completed_before_reasoning:I,running_tools_when_completed:!!(v&&j),reasoning_open_when_completed:!!(v&&M),has_tools:S.length>0,has_reasoning:N.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=me.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=Dp,ds()&&(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 UN=({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 Dp.copyDiagnosticsReport()).ok?(c(!0),q.success("Diagnostics copied")):q.error("Copy failed")}catch(m){q.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 bs(async()=>{const{getVersion:x}=await import("./vendor-.bun-BrcdMJ39.js").then(g=>g.de);return{getVersion:x}},__vite__mapDeps([0,1])),h=await p();n(h)}catch{n("1.5.5")}})():n("1.5.5")},[t]);const u=s;return e.jsx(xs,{open:t,onOpenChange:r,children:e.jsx(ys,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(lc,{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:F("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(Ji,{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(Nm,{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(Zi,{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 Vi({apis:t,children:r}){return e.jsx(ql.Provider,{value:t,children:r})}const VN="curl -fsSL https://opencode.ai/install | bash",GN=3e3;function qN({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(Xs,{className:"h-4 w-4"})})]})}const KN=3e4;function QN({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),KN);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 bs(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-BrcdMJ39.js").then(x=>x.dd);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(VN),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,GN);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(ga,{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(Gt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(qN,{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(ga,{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 YN=()=>{const{isAboutDialogOpen:t,setAboutDialogOpen:r}=Ce();return e.jsx(UN,{open:t,onOpenChange:r})};function XN({apis:t}){const{initializeApp:r,isInitialized:s,isConnected:n}=at(),{error:o,clearError:a,loadSessions:l}=me(),c=bt(w=>w.currentDirectory),d=bt(w=>w.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=dp(),[h,x]=i.useState(()=>t.runtime.isDesktop),[g,b]=i.useState(()=>t.runtime.isVSCode),[y,v]=i.useState(()=>t.runtime.isDesktop?Nx():!0);i.useEffect(()=>{x(t.runtime.isDesktop),b(t.runtime.isVSCode)},[t.runtime.isDesktop,t.runtime.isVSCode]),i.useEffect(()=>(Ec(t),()=>Ec(null)),[t]),i.useEffect(()=>{if(typeof document>"u")return;const w=document.documentElement,k=cu[f]?.stack??cu[aS].stack,A=tn[p]?.stack??tn[fa].stack;w.style.setProperty("--font-sans",k),w.style.setProperty("--font-heading",k),w.style.setProperty("--font-family-sans",k),w.style.setProperty("--font-mono",A),w.style.setProperty("--font-family-mono",A),w.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=k)},[f,p]),i.useEffect(()=>{if(s){const k=setTimeout(()=>{const A=document.getElementById("initial-loading");A&&(A.classList.add("fade-out"),setTimeout(()=>{A.remove()},300))},150);return()=>clearTimeout(k)}},[s]),i.useEffect(()=>{const w=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&!s&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},5e3);return()=>clearTimeout(w)},[s]),i.useEffect(()=>{(async()=>g||await r())()},[r,g]),i.useEffect(()=>{if(d)return;(async()=>g||n&&(Fe.setDirectory(c),await l()))()},[c,d,l,n,g]),yN(),BN(),_N(),bN();const S=i.useCallback(()=>{m(w=>!w)},[]);wN(S),SN(),kN(),bp(),i.useEffect(()=>{const w=k=>{Ts(k)&&k.shiftKey&&k.key==="D"&&(k.preventDefault(),m(A=>!A))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=i.useCallback(()=>{v(!0),window.location.reload()},[]);return h&&!y?e.jsx(fs,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(QN,{onCliAvailable:N})})}):g?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(fs,{children:e.jsx(Vi,{apis:t,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(aN,{}),e.jsx(Si,{})]})})}):e.jsx(fs,{children:e.jsx(Vi,{apis:t,children:e.jsx(ru,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Kk,{}),e.jsx(Si,{})]})})})}):e.jsx(fs,{children:e.jsx(Vi,{apis:t,children:e.jsx(WN,{children:e.jsx(ru,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx(Uk,{}),e.jsx(Si,{}),e.jsx(HN,{}),e.jsx(YN,{}),u&&e.jsx(lN,{onClose:()=>m(!1)})]})})})})})}const Ap=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=bt.getState();t&&s.homeDirectory!==t&&s.synchronizeHomeDirectory(t),r&&!Wt()&&s.setDirectory(r,{showOverlay:!1})},Ep="/auth/session",JN=async()=>fetch(Ep,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Ku=async t=>fetch(Ep,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:t})}),pc=({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})]}),ZN=({message:t="Preparing workspace…"})=>e.jsx(pc,{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})})}),eC=({onRetry:t})=>e.jsx(pc,{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(De,{type:"button",onClick:t,className:"w-full max-w-xs",children:"Retry"})]})}),tC=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},sC=()=>{try{const t=new URL(window.location.href);t.searchParams.delete("token"),window.history.replaceState({},"",t.toString())}catch{}},rC=({children:t})=>{const r=i.useMemo(()=>ls(),[]),s=i.useMemo(()=>Wt(),[]),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 JN();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=tC();y&&(x.current=!0,sC(),u(!0),f(""),Ku(y).then(v=>{if(v.ok){c(""),a("authenticated");return}if(v.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(v=>{console.warn("Failed to submit URL token:",v),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),i.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await Tm(),await Fm(),await Ap()))())},[n,o]);const b=async y=>{if(y.preventDefault(),!(!l||d)){u(!0),f("");try{const v=await Ku(l);if(v.ok){c(""),a("authenticated");return}if(v.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(v){console.warn("Failed to submit UI password:",v),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(ZN,{}):o==="error"?e.jsx(eC,{onRetry:()=>{g()}}):o==="locked"?e.jsx(pc,{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(jt,{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(De,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(ix,{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})},Gi=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 nC{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(`
142
- `)}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=Gi(r.colors.surface.muted),o=Gi(r.colors.surface.subtle),a=Gi(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 {
143
- ${s}
144
- }
145
-
146
- .dark {
147
- ${s}
148
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
149
- ${s}
150
- }
151
-
152
- :root:not(.dark) {
153
- ${s}
154
- }`,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=Wt()?Rx:Rl;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 hc={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"}}},gc={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"}}},jo=[hc,gc];function Ra(t){return jo.find(r=>r.metadata.id===t)}const Ip=hc.metadata.id,Pp=gc.metadata.id,oC=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Tp=t=>t==="dark"?gc:hc,aC=t=>(jo.find(s=>s.metadata.variant===t)??Tp(t)).metadata.id,Jo=(t,r)=>{const s=Ra(t);return s&&s.metadata.variant===r?s:jo.find(o=>o.metadata.variant===r)??Tp(r)},iC=typeof window<"u"?i.useLayoutEffect:i.useEffect,La=(t,r)=>{if(!t)return r==="light"?Ip:Pp;const s=Ra(t);return s&&s.metadata.variant===r?s.metadata.id:aC(r)},lC=t=>{let r=Ip,s=Pp,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=Ra(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=La(a,"light"),s=La(l,"dark")}if(t){const o=Ra(t);o&&(o.metadata.variant==="light"?r=o.metadata.id:s=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:s}};function cC({children:t,defaultThemeId:r}){const s=Te.useMemo(()=>new nC,[]),[n,o]=Te.useState(()=>lC(r)),[a,l]=Te.useState(()=>oC()),[c,d]=Te.useState(()=>typeof window>"u"||!Wt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Te.useMemo(()=>Wt(),[]),m=Te.useMemo(()=>u&&c?c:n.themeMode==="light"?Jo(n.lightThemeId,"light"):n.themeMode==="dark"||a?Jo(n.darkThemeId,"dark"):Jo(n.lightThemeId,"light"),[u,n,a,c]),f=Te.useMemo(()=>u&&c?[c,...jo]:jo,[u,c]);Te.useEffect(()=>{if(!u)return;const N=A=>{d(A);const j=A.metadata.variant==="dark"?"dark":"light",M=Ce.getState();M.theme!==j&&M.setTheme(j)},w=A=>{const j=A.detail;j?.theme&&N(j.theme)},k=window.__OPENCHAMBER_VSCODE_THEME__;return k&&N(k),window.addEventListener("openchamber:vscode-theme",w),()=>window.removeEventListener("openchamber:vscode-theme",w)},[u]);const p=Te.useCallback(N=>{if(typeof document>"u")return;const w=N.colors.surface.background;ls()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=w;let k=document.querySelector('meta[name="theme-color"]');k||(k=document.createElement("meta"),k.setAttribute("name","theme-color"),document.head.appendChild(k)),k.setAttribute("content",w);const A=N.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let j=document.querySelector(`meta[name="theme-color"][media="${A}"]`);j||(j=document.createElement("meta"),j.setAttribute("name","theme-color"),j.setAttribute("media",A),document.head.appendChild(j)),j.setAttribute("content",w)},[]),h=Te.useCallback(N=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",N)},[]);iC(()=>{if(typeof window>"u")return;s.apply(m),h(u),p(m);const N=document.documentElement;N.classList.remove("light","dark"),N.classList.add(m.metadata.variant)},[h,s,m,u,p]),Te.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const N=window.matchMedia("(prefers-color-scheme: dark)"),w=k=>{l(k.matches)};return l(N.matches),N.addEventListener("change",w),()=>N.removeEventListener("change",w)},[n.themeMode]),Te.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]),Te.useEffect(()=>{us({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]),Te.useEffect(()=>{if(typeof window>"u")return;const N=w=>{const k=w.detail;k&&o(A=>{let j=A.themeMode;k.useSystemTheme===!0?j="system":k.useSystemTheme===!1&&(k.themeVariant==="dark"||k.themeVariant==="light")&&(j=k.themeVariant);let M=A.lightThemeId;typeof k.lightThemeId=="string"&&k.lightThemeId.length>0&&(M=La(k.lightThemeId,"light"));let C=A.darkThemeId;return typeof k.darkThemeId=="string"&&k.darkThemeId.length>0&&(C=La(k.darkThemeId,"dark")),j===A.themeMode&&M===A.lightThemeId&&C===A.darkThemeId?A:{themeMode:j,lightThemeId:M,darkThemeId:C}})};return window.addEventListener("openchamber:settings-synced",N),()=>window.removeEventListener("openchamber:settings-synced",N)},[]);const x=Te.useCallback(N=>{const w=f.find(k=>k.metadata.id===N);w&&o(k=>w.metadata.variant==="dark"?k.darkThemeId===w.metadata.id&&k.themeMode==="dark"?k:{...k,darkThemeId:w.metadata.id,themeMode:"dark"}:k.lightThemeId===w.metadata.id&&k.themeMode==="light"?k:{...k,lightThemeId:w.metadata.id,themeMode:"light"})},[f]),g=Te.useCallback(N=>{o(w=>w.themeMode===N?w:{...w,themeMode:N})},[]),b=Te.useCallback(N=>{if(N){o(k=>k.themeMode==="system"?k:{...k,themeMode:"system"});return}const w=m.metadata.variant==="dark"?"dark":"light";o(k=>k.themeMode===w?k:{...k,themeMode:w})},[m.metadata.variant]),y=Te.useCallback(N=>{const w=f.find(k=>k.metadata.id===N&&k.metadata.variant==="light");w&&o(k=>k.lightThemeId===w.metadata.id?k:{...k,lightThemeId:w.metadata.id})},[f]),v=Te.useCallback(N=>{const w=f.find(k=>k.metadata.id===N&&k.metadata.variant==="dark");w&&o(k=>k.darkThemeId===w.metadata.id?k:{...k,darkThemeId:w.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:v};return e.jsx(Kl.Provider,{value:S,children:t})}const dC=({children:t})=>{const{theme:r,applyTheme:s,fontSize:n,applyTypography:o,padding:a,applyPadding:l}=Ce();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 Qu=!1;const uC=()=>{if(Qu||typeof window>"u")return;Qu=!0;let t={showReasoningTraces:Ce.getState().showReasoningTraces,autoDeleteEnabled:Ce.getState().autoDeleteEnabled,autoDeleteAfterDays:Ce.getState().autoDeleteAfterDays},r=null,s=null;const n=()=>{const a=r;r=null,s=null,a&&Object.keys(a).length>0&&us(a)},o=a=>{r={...r??{},...a},!s&&(s=setTimeout(n,150))};Ce.subscribe(a=>{const l={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},c={};l.showReasoningTraces!==t.showReasoningTraces&&(c.showReasoningTraces=l.showReasoningTraces),l.autoDeleteEnabled!==t.autoDeleteEnabled&&(c.autoDeleteEnabled=l.autoDeleteEnabled),l.autoDeleteAfterDays!==t.autoDeleteAfterDays&&(c.autoDeleteAfterDays=l.autoDeleteAfterDays),t=l,Object.keys(c).length>0&&o(c)})};let Yu=!1;const Xu="openchamber-typography-base",mC=()=>{if(typeof document>"u")return;const r=`:root {
155
- ${Object.entries(Rl).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
156
- `)}
157
- }
158
- `,s=document.getElementById(Xu);if(s){s.textContent=r;return}const n=document.createElement("style");n.id=Xu,n.textContent=r,document.head.appendChild(n)},fC=()=>{Yu||typeof window>"u"||(Yu=!0,mC())},pC=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await Tm();await Fm();uC();fC();await Ap();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 Fp=document.getElementById("root");if(!Fp)throw new Error("Root element not found");lx.createRoot(Fp).render(e.jsx(Te.StrictMode,{children:e.jsx(cC,{children:e.jsx(dC,{children:e.jsx(rC,{children:e.jsx(XN,{apis:pC})})})})}));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 xC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{xs as D,dn as S,ys as a,ff as b,F as c,xj as d,yj as e,Qd as f,Tr as g,bj as h,vj as i,xC as m,Yf as p,wj as r,ta as t};