@openchamber/web 1.5.0 → 1.5.1
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,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-CqCnPJev.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-
|
|
2
|
-
import{t as Vf,c as Gf,F as qf,j as e,R as Kf,T as Qf,P as Yf,C as Xf,A as Jf,a as Zf,b as Vt,d as Jt,p as Es,e as Is,f as ep,_ as as,g as i,r as bu,i as Ht,I as tp,k as sp,l as rp,m as np,n as op,L as ap,o as ip,q as lp,s as cp,u as _t,S as dp,v as up,w as vu,x as mp,y as fp,z as pp,B as hp,D as gp,E as xp,G as Ae,H as Ql,J as te,K as Fi,M as Yl,N as Sa,O as Ft,Q as Rs,U as rs,V as il,W as wu,X as ju,Y as yp,Z as jr,$ as bp,a0 as _s,a1 as Hs,a2 as _r,a3 as zt,a4 as ka,a5 as vp,a6 as en,a7 as an,a8 as tn,a9 as Ri,aa as Fs,ab as Su,ac as wp,ad as jp,ae as Sp,af as kp,ag as Np,ah as Cp,ai as Mp,aj as Lo,ak as Dp,al as ku,am as ta,an as Fr,ao as is,ap as lr,aq as ln,ar as co,as as Xt,at as cr,au as Ap,av as Ep,aw as Nu,ax as ll,ay as sn,az as Cu,aA as dr,aB as Mu,aC as Cn,aD as Ip,aE as Na,aF as Va,aG as Pp,aH as Or,aI as xr,aJ as Ys,aK as Tp,aL as Xs,aM as Fp,aN as Xl,aO as Rp,aP as _p,aQ as Op,aR as $p,aS as Lp,aT as Bp,aU as zp,aV as Wp,aW as Hp,aX as Up,aY as Ga,aZ as Vp,a_ as ur,a$ as cl,b0 as dl,b1 as Gp,b2 as qp,b3 as Kp,b4 as Qp,b5 as Yp,b6 as Xp,b7 as Jp,b8 as Zp,b9 as eh,ba as th,bb as sh,bc as rh,bd as nh,be as oh,bf as ah,bg as ih,bh as yr,bi as sa,bj as mr,bk as nr,bl as lh,bm as ch,bn as Ca,bo as dh,bp as ul,bq as uh,br as mh,bs as fh,bt as Zn,bu as ph,bv as hh,bw as gh,bx as xh,by as yh,bz as eo,bA as Bo,bB as Ma,bC as bh,bD as vh,bE as wn,bF as xn,bG as Du,bH as wh,bI as jh,bJ as Os,bK as Au,bL as Sh,bM as Eu,bN as kh,bO as Nh,bP as _i,bQ as Iu,bR as Pu,bS as Ch,bT as or,bU as to,bV as Mh,bW as Jl,bX as Dh,bY as Oi,bZ as uo,b_ as Fn,b$ as Ah,c0 as Tu,c1 as ml,c2 as fl,c3 as pl,c4 as Eh,c5 as Ih,c6 as Ph,c7 as Zl,c8 as Fu,c9 as Th,ca as Fh,cb as Rh,cc as _h,cd as Ru,ce as so,cf as _u,cg as Ou,ch as qa,ci as Da,cj as $u,ck as Oh,cl as $h,cm as Lh,cn as $i,co as Lu,cp as Li,cq as Bh,cr as zh,cs as Wh,ct as Hh,cu as Uh,cv as Vh,cw as Gh,cx as qh}from"./vendor-.bun-CqCnPJev.js";import{c as Kh,l as Qh,g as Yh,r as Xh,d as Jh,a as Zh,b as eg,e as tg,u as sg,f as rg,h as ng,i as og,j as ag,k as ig,m as lg}from"./index-B5OwFsqC.js";const es=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Wt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,rn=()=>typeof window>"u"?!1:!es()&&!Wt(),$r=()=>es()?window.opencodeDesktop??null:null,Bu=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const s=window.opencodeDesktop;return s?.getSettings&&s?.updateSettings?{getSettings:s.getSettings.bind(s),updateSettings:s.updateSettings.bind(s)}:null},zu=async()=>{const s=$r();if(typeof window<"u"){const r=window.__OPENCHAMBER_HOME__;if(r&&r.length>0)return r}if(!s)return null;if(typeof s.homeDirectory=="string"&&s.homeDirectory.length>0)return s.homeDirectory;try{if(!s.getHomeDirectory)return null;const r=await s.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},cg=async()=>{const s=$r();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},dg=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Lr=async()=>{const s=Bu();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},ug=async s=>{const r=Bu();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},mg=async s=>{const r=$r();if(!r||!r.requestDirectoryAccess)return{success:!0,path:s};try{return await r.requestDirectoryAccess(s)}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},fg=async s=>{const r=$r();if(!r||!r.startAccessingDirectory)return{success:!0};try{return await r.startAccessingDirectory(s)}catch(t){return console.warn("Failed to start accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},pg=async s=>{const r=$r();if(!r||!r.stopAccessingDirectory)return{success:!0};try{return await r.stopAccessingDirectory(s)}catch(t){return console.warn("Failed to stop accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},hg=async()=>{const s=$r();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},gg=async s=>{const r=$r();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},xg=async()=>{const s=$r();if(!s||!s.restartToUpdate)return!1;try{return await s.restartToUpdate(),!0}catch(r){return console.warn("Failed to restart for update",r),!1}};function _(...s){return Vf(Gf(s))}const Wu=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Ds=s=>Wu()&&es()?s.metaKey:s.ctrlKey,Yt=()=>Wu()&&es()?"⌘":"Ctrl",Hu=(s,r)=>{const t=s??"",n=Math.max(16,r?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;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}`},ra=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function Yr(s,r){if(!s)return"";const t=ra(s);if(t==="/")return"/";const n=r?ra(r):void 0;if(n&&n!=="/"){if(t===n)return"~";if(t.startsWith(`${n}/`)){const o=t.slice(n.length+1);return o?`~/${o}`:"~"}}return t}function ec(s,r){if(!s)return"/";const t=ra(s);if(!t||t==="/")return"/";const n=r?ra(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Ts(s,r){return r?s?s.toLowerCase().includes(r.toLowerCase())?!0:new qf([s],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function yg({delayDuration:s=0,...r}){return e.jsx(Zf,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function dt({delayDuration:s=0,...r}){return e.jsx(yg,{delayDuration:s,children:e.jsx(Kf,{"data-slot":"tooltip",...r})})}function ut({...s}){return e.jsx(Qf,{"data-slot":"tooltip-trigger",...s})}function lt({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(Yf,{children:e.jsxs(Xf,{"data-slot":"tooltip-content",sideOffset:r,className:_("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",s),...n,children:[t,e.jsx(Jf,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Ka=null;const tc=()=>{const s=new Map;return{getItem:r=>s.get(r)??null,setItem:(r,t)=>{s.set(r,t)},removeItem:r=>{s.delete(r)},clear:()=>{s.clear()},key:r=>Array.from(s.keys())[r]??null,get length(){return s.size}}},bg=()=>{if(typeof window>"u"||!window.localStorage)return tc();const s=window.localStorage,r=tc();let t=!0;const n=()=>{t=!1};return{getItem:u=>{if(t)try{const m=s.getItem(u);if(m!==null)return m}catch{n()}return r.getItem(u)},setItem:(u,m)=>{if(t)try{s.setItem(u,m),r.removeItem(u);return}catch{n()}r.setItem(u,m)},removeItem:u=>{if(t)try{s.removeItem(u)}catch{n()}r.removeItem(u)},clear:()=>{if(t)try{s.clear()}catch{n()}r.clear()},key:u=>{if(t)try{return s.key(u)}catch{n()}return r.key(u)},get length(){if(t)try{return s.length+r.length}catch{n()}return r.length}}},ds=()=>(Ka||(Ka=bg()),Ka),hl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},vg={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function sc(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const br={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)"}}},zo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...br.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:zo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...br.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:zo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...br.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:zo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...br.tool.inline})},$e=Vt()(Jt(Es((s,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",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,toolCallExpansion:"collapsed",fontSize:100,padding:100,inputBarOffset:0,favoriteModels:[],recentModels:[],diffLayoutPreference:"dynamic",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"single",isTimelineDialogOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",setTheme:t=>{s({theme:t}),r().applyTheme()},toggleSidebar:()=>{s(t=>{const n=!t.isSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:n,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:n}})},setSidebarOpen:t=>{s(()=>{if(t&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:t,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:t}})},setSidebarWidth:t=>{s({sidebarWidth:t,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:t=>{s({isSessionSwitcherOpen:t})},setActiveMainTab:t=>{s({activeMainTab:t})},setPendingDiffFile:t=>{s({pendingDiffFile:t})},navigateToDiff:t=>{s({pendingDiffFile:t,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:t}=r();return t&&s({pendingDiffFile:null}),t},setIsMobile:t=>{s({isMobile:t})},toggleCommandPalette:()=>{s(t=>({isCommandPaletteOpen:!t.isCommandPaletteOpen}))},setCommandPaletteOpen:t=>{s({isCommandPaletteOpen:t})},toggleHelpDialog:()=>{s(t=>({isHelpDialogOpen:!t.isHelpDialogOpen}))},setHelpDialogOpen:t=>{s({isHelpDialogOpen:t})},setAboutDialogOpen:t=>{s({isAboutDialogOpen:t})},setSessionCreateDialogOpen:t=>{s({isSessionCreateDialogOpen:t})},setSettingsDialogOpen:t=>{s({isSettingsDialogOpen:t})},setModelSelectorOpen:t=>{s({isModelSelectorOpen:t})},setSidebarSection:t=>{s({sidebarSection:t})},setEventStreamStatus:(t,n)=>{s({eventStreamStatus:t,eventStreamHint:n??null})},setShowReasoningTraces:t=>{s({showReasoningTraces:t})},setAutoDeleteEnabled:t=>{s({autoDeleteEnabled:t})},setAutoDeleteAfterDays:t=>{const n=Math.max(1,Math.min(365,t));s({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:t=>{s({autoDeleteLastRunAt:t})},setToolCallExpansion:t=>{s({toolCallExpansion:t})},setFontSize:t=>{const n=Math.max(50,Math.min(200,t));s({fontSize:n}),r().applyTypography()},setPadding:t=>{const n=Math.max(50,Math.min(200,t));s({padding:n}),r().applyPadding()},applyTypography:()=>{const{fontSize:t}=r(),n=document.documentElement,o=t/100,a=Object.entries(hl);if(o===1){for(const[l]of a)n.style.removeProperty(sc(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(sc(l),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=r(),n=document.documentElement,o=t/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:t=>{s({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{s(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{s({diffWrapLines:t})},setDiffViewMode:t=>{s({diffViewMode:t})},setInputBarOffset:t=>{s({inputBarOffset:t})},setKeyboardOpen:t=>{s({isKeyboardOpen:t})},toggleFavoriteModel:(t,n)=>{s(o=>o.favoriteModels.some(l=>l.providerID===t&&l.modelID===n)?{favoriteModels:o.favoriteModels.filter(l=>!(l.providerID===t&&l.modelID===n))}:{favoriteModels:[{providerID:t,modelID:n},...o.favoriteModels]})},isFavoriteModel:(t,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===t&&a.modelID===n)},addRecentModel:(t,n)=>{s(o=>{const a=o.recentModels.filter(l=>!(l.providerID===t&&l.modelID===n));return{recentModels:[{providerID:t,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||s(t=>{const n={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:t}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(t)},setMultiRunLauncherOpen:t=>{s(n=>({isMultiRunLauncherOpen:t,multiRunLauncherPrefillPrompt:t?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:t=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:t,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:t=>{s({isTimelineDialogOpen:t})},setNativeNotificationsEnabled:t=>{s({nativeNotificationsEnabled:t})},setNotificationMode:t=>{s({notificationMode:t})}}),{name:"ui-store",storage:Is(()=>ds()),partialize:s=>({theme:s.theme,isSidebarOpen:s.isSidebarOpen,sidebarWidth:s.sidebarWidth,isSessionSwitcherOpen:s.isSessionSwitcherOpen,activeMainTab:s.activeMainTab,sidebarSection:s.sidebarSection,isSessionCreateDialogOpen:s.isSessionCreateDialogOpen,isSettingsDialogOpen:s.isSettingsDialogOpen,showReasoningTraces:s.showReasoningTraces,autoDeleteEnabled:s.autoDeleteEnabled,autoDeleteAfterDays:s.autoDeleteAfterDays,autoDeleteLastRunAt:s.autoDeleteLastRunAt,toolCallExpansion:s.toolCallExpansion,fontSize:s.fontSize,padding:s.padding,favoriteModels:s.favoriteModels,recentModels:s.recentModels,diffLayoutPreference:s.diffLayoutPreference,diffWrapLines:s.diffWrapLines,diffViewMode:s.diffViewMode,nativeNotificationsEnabled:s.nativeNotificationsEnabled,notificationMode:s.notificationMode})}),{name:"ui-store"}));async function wg(){try{const s=await fetch("/api/openchamber/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)throw new Error(`Server responded with ${s.status}`);const r=await s.json();return{available:r.available??!1,version:r.version,currentVersion:r.currentVersion??"unknown",body:r.body,packageManager:r.packageManager,updateCommand:r.updateCommand}}catch(s){return console.warn("Failed to check for web updates:",s),null}}function jg(){return es()?"desktop":rn()?"web":null}const rc={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Aa=Vt()((s,r)=>({...rc,checkForUpdates:async()=>{const t=jg();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await hg():t==="web"&&(n=await wg()),s({checking:!1,available:n?.available??!1,info:n,lastChecked:Date.now()})}catch(n){s({checking:!1,error:n instanceof Error?n.message:"Failed to check for updates"})}}},downloadUpdate:async()=>{const{available:t,runtimeType:n}=r();if(!(n!=="desktop"||!t)){s({downloading:!0,error:null,progress:null});try{await gg(o=>{s({progress:o})}),s({downloading:!1,downloaded:!0})}catch(o){s({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:t,runtimeType:n}=r();if(!(n!=="desktop"||!t))try{await xg()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(rc)}})),Sg="/api",kg=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Ng=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(kg.test(r)||typeof window>"u")return r;const t=window.location?.href||window.location?.origin;if(!t)return r;try{return new URL(r,t).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),r}},Cg=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_DESKTOP_SERVER__,r=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!s||!r)return null;const t=typeof s.origin=="string"&&s.origin.length>0?s.origin:null;return t?`${t}/api`:null},xo=s=>s.replace(/\\/g,"/"),Qa=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class Mg{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=Sg){const n=Cg()||r;this.baseUrl=Ng(n),this.client=ep({baseUrl:this.baseUrl})}normalizeCandidatePath(r){if(typeof r!="string")return null;const t=r.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const t=r.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[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,t){if(r==null)return t();const n=this.currentDirectory;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,t=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&&(t(a.directory),t(a.worktree),t(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);t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(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 t=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(r){const t=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,t){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:t});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||[]}async getSessionTodos(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/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 t=r.toLowerCase();return t.startsWith("text/")&&t!=="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(t)}isHeicMime(r){if(!r)return!1;const t=r.toLowerCase();return t==="image/heic"||t==="image/heif"}async compressImage(r,t,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=t;t==="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 t=(await as(async()=>{const{default:f}=await import("./vendor-.bun-CqCnPJev.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 t({blob:c,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const g=new FileReader;g.onload=()=>f(g.result),g.onerror=p,g.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(t){return console.warn("Failed to convert HEIC to JPEG:",t),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 t=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);t=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:t}}async sendMessage(r){const t=Date.now(),n=r.messageId??`temp_${t}_${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,t,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const t=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Failed to unrevert session");return t.data}async forkSession(r,t){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t});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 t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/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 t=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(t?{directory:t}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(r,t,n){return(await this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:t,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async replyToQuestion(r,t){const n=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t];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 t=[],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[]}};t.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)t.push(n(d));const a=await Promise.all(t),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 t=`${this.baseUrl}/config`,n=await fetch(t,{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 t=await this.getConfig(),n=r(t);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 t=r.split(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-CqCnPJev.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-CM8zam_u.js","assets/index-C7GBt0ia.js","assets/index-DXflA-iU.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as Vf,c as Gf,F as qf,j as e,R as Kf,T as Qf,P as Yf,C as Xf,A as Jf,a as Zf,b as Vt,d as Jt,p as Es,e as Is,f as ep,_ as as,g as i,r as bu,i as Ht,I as tp,k as sp,l as rp,m as np,n as op,L as ap,o as ip,q as lp,s as cp,u as _t,S as dp,v as up,w as vu,x as mp,y as fp,z as pp,B as hp,D as gp,E as xp,G as Ae,H as Ql,J as te,K as Fi,M as Yl,N as Sa,O as Ft,Q as Rs,U as rs,V as il,W as wu,X as ju,Y as yp,Z as jr,$ as bp,a0 as _s,a1 as Hs,a2 as _r,a3 as zt,a4 as ka,a5 as vp,a6 as en,a7 as an,a8 as tn,a9 as Ri,aa as Fs,ab as Su,ac as wp,ad as jp,ae as Sp,af as kp,ag as Np,ah as Cp,ai as Mp,aj as Lo,ak as Dp,al as ku,am as ta,an as Fr,ao as is,ap as lr,aq as ln,ar as co,as as Xt,at as cr,au as Ap,av as Ep,aw as Nu,ax as ll,ay as sn,az as Cu,aA as dr,aB as Mu,aC as Cn,aD as Ip,aE as Na,aF as Va,aG as Pp,aH as Or,aI as xr,aJ as Ys,aK as Tp,aL as Xs,aM as Fp,aN as Xl,aO as Rp,aP as _p,aQ as Op,aR as $p,aS as Lp,aT as Bp,aU as zp,aV as Wp,aW as Hp,aX as Up,aY as Ga,aZ as Vp,a_ as ur,a$ as cl,b0 as dl,b1 as Gp,b2 as qp,b3 as Kp,b4 as Qp,b5 as Yp,b6 as Xp,b7 as Jp,b8 as Zp,b9 as eh,ba as th,bb as sh,bc as rh,bd as nh,be as oh,bf as ah,bg as ih,bh as yr,bi as sa,bj as mr,bk as nr,bl as lh,bm as ch,bn as Ca,bo as dh,bp as ul,bq as uh,br as mh,bs as fh,bt as Zn,bu as ph,bv as hh,bw as gh,bx as xh,by as yh,bz as eo,bA as Bo,bB as Ma,bC as bh,bD as vh,bE as wn,bF as xn,bG as Du,bH as wh,bI as jh,bJ as Os,bK as Au,bL as Sh,bM as Eu,bN as kh,bO as Nh,bP as _i,bQ as Iu,bR as Pu,bS as Ch,bT as or,bU as to,bV as Mh,bW as Jl,bX as Dh,bY as Oi,bZ as uo,b_ as Fn,b$ as Ah,c0 as Tu,c1 as ml,c2 as fl,c3 as pl,c4 as Eh,c5 as Ih,c6 as Ph,c7 as Zl,c8 as Fu,c9 as Th,ca as Fh,cb as Rh,cc as _h,cd as Ru,ce as so,cf as _u,cg as Ou,ch as qa,ci as Da,cj as $u,ck as Oh,cl as $h,cm as Lh,cn as $i,co as Lu,cp as Li,cq as Bh,cr as zh,cs as Wh,ct as Hh,cu as Uh,cv as Vh,cw as Gh,cx as qh}from"./vendor-.bun-CqCnPJev.js";import{c as Kh,l as Qh,g as Yh,r as Xh,d as Jh,a as Zh,b as eg,e as tg,u as sg,f as rg,h as ng,i as og,j as ag,k as ig,m as lg}from"./index-C7GBt0ia.js";const es=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Wt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,rn=()=>typeof window>"u"?!1:!es()&&!Wt(),$r=()=>es()?window.opencodeDesktop??null:null,Bu=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const s=window.opencodeDesktop;return s?.getSettings&&s?.updateSettings?{getSettings:s.getSettings.bind(s),updateSettings:s.updateSettings.bind(s)}:null},zu=async()=>{const s=$r();if(typeof window<"u"){const r=window.__OPENCHAMBER_HOME__;if(r&&r.length>0)return r}if(!s)return null;if(typeof s.homeDirectory=="string"&&s.homeDirectory.length>0)return s.homeDirectory;try{if(!s.getHomeDirectory)return null;const r=await s.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},cg=async()=>{const s=$r();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},dg=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Lr=async()=>{const s=Bu();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},ug=async s=>{const r=Bu();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},mg=async s=>{const r=$r();if(!r||!r.requestDirectoryAccess)return{success:!0,path:s};try{return await r.requestDirectoryAccess(s)}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},fg=async s=>{const r=$r();if(!r||!r.startAccessingDirectory)return{success:!0};try{return await r.startAccessingDirectory(s)}catch(t){return console.warn("Failed to start accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},pg=async s=>{const r=$r();if(!r||!r.stopAccessingDirectory)return{success:!0};try{return await r.stopAccessingDirectory(s)}catch(t){return console.warn("Failed to stop accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},hg=async()=>{const s=$r();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},gg=async s=>{const r=$r();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},xg=async()=>{const s=$r();if(!s||!s.restartToUpdate)return!1;try{return await s.restartToUpdate(),!0}catch(r){return console.warn("Failed to restart for update",r),!1}};function _(...s){return Vf(Gf(s))}const Wu=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Ds=s=>Wu()&&es()?s.metaKey:s.ctrlKey,Yt=()=>Wu()&&es()?"⌘":"Ctrl",Hu=(s,r)=>{const t=s??"",n=Math.max(16,r?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;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}`},ra=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function Yr(s,r){if(!s)return"";const t=ra(s);if(t==="/")return"/";const n=r?ra(r):void 0;if(n&&n!=="/"){if(t===n)return"~";if(t.startsWith(`${n}/`)){const o=t.slice(n.length+1);return o?`~/${o}`:"~"}}return t}function ec(s,r){if(!s)return"/";const t=ra(s);if(!t||t==="/")return"/";const n=r?ra(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Ts(s,r){return r?s?s.toLowerCase().includes(r.toLowerCase())?!0:new qf([s],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function yg({delayDuration:s=0,...r}){return e.jsx(Zf,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function dt({delayDuration:s=0,...r}){return e.jsx(yg,{delayDuration:s,children:e.jsx(Kf,{"data-slot":"tooltip",...r})})}function ut({...s}){return e.jsx(Qf,{"data-slot":"tooltip-trigger",...s})}function lt({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(Yf,{children:e.jsxs(Xf,{"data-slot":"tooltip-content",sideOffset:r,className:_("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",s),...n,children:[t,e.jsx(Jf,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Ka=null;const tc=()=>{const s=new Map;return{getItem:r=>s.get(r)??null,setItem:(r,t)=>{s.set(r,t)},removeItem:r=>{s.delete(r)},clear:()=>{s.clear()},key:r=>Array.from(s.keys())[r]??null,get length(){return s.size}}},bg=()=>{if(typeof window>"u"||!window.localStorage)return tc();const s=window.localStorage,r=tc();let t=!0;const n=()=>{t=!1};return{getItem:u=>{if(t)try{const m=s.getItem(u);if(m!==null)return m}catch{n()}return r.getItem(u)},setItem:(u,m)=>{if(t)try{s.setItem(u,m),r.removeItem(u);return}catch{n()}r.setItem(u,m)},removeItem:u=>{if(t)try{s.removeItem(u)}catch{n()}r.removeItem(u)},clear:()=>{if(t)try{s.clear()}catch{n()}r.clear()},key:u=>{if(t)try{return s.key(u)}catch{n()}return r.key(u)},get length(){if(t)try{return s.length+r.length}catch{n()}return r.length}}},ds=()=>(Ka||(Ka=bg()),Ka),hl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},vg={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function sc(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const br={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)"}}},zo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...br.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:zo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...br.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:zo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...br.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:zo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...br.tool.inline})},$e=Vt()(Jt(Es((s,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",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,toolCallExpansion:"collapsed",fontSize:100,padding:100,inputBarOffset:0,favoriteModels:[],recentModels:[],diffLayoutPreference:"dynamic",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"single",isTimelineDialogOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",setTheme:t=>{s({theme:t}),r().applyTheme()},toggleSidebar:()=>{s(t=>{const n=!t.isSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:n,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:n}})},setSidebarOpen:t=>{s(()=>{if(t&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:t,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:t}})},setSidebarWidth:t=>{s({sidebarWidth:t,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:t=>{s({isSessionSwitcherOpen:t})},setActiveMainTab:t=>{s({activeMainTab:t})},setPendingDiffFile:t=>{s({pendingDiffFile:t})},navigateToDiff:t=>{s({pendingDiffFile:t,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:t}=r();return t&&s({pendingDiffFile:null}),t},setIsMobile:t=>{s({isMobile:t})},toggleCommandPalette:()=>{s(t=>({isCommandPaletteOpen:!t.isCommandPaletteOpen}))},setCommandPaletteOpen:t=>{s({isCommandPaletteOpen:t})},toggleHelpDialog:()=>{s(t=>({isHelpDialogOpen:!t.isHelpDialogOpen}))},setHelpDialogOpen:t=>{s({isHelpDialogOpen:t})},setAboutDialogOpen:t=>{s({isAboutDialogOpen:t})},setSessionCreateDialogOpen:t=>{s({isSessionCreateDialogOpen:t})},setSettingsDialogOpen:t=>{s({isSettingsDialogOpen:t})},setModelSelectorOpen:t=>{s({isModelSelectorOpen:t})},setSidebarSection:t=>{s({sidebarSection:t})},setEventStreamStatus:(t,n)=>{s({eventStreamStatus:t,eventStreamHint:n??null})},setShowReasoningTraces:t=>{s({showReasoningTraces:t})},setAutoDeleteEnabled:t=>{s({autoDeleteEnabled:t})},setAutoDeleteAfterDays:t=>{const n=Math.max(1,Math.min(365,t));s({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:t=>{s({autoDeleteLastRunAt:t})},setToolCallExpansion:t=>{s({toolCallExpansion:t})},setFontSize:t=>{const n=Math.max(50,Math.min(200,t));s({fontSize:n}),r().applyTypography()},setPadding:t=>{const n=Math.max(50,Math.min(200,t));s({padding:n}),r().applyPadding()},applyTypography:()=>{const{fontSize:t}=r(),n=document.documentElement,o=t/100,a=Object.entries(hl);if(o===1){for(const[l]of a)n.style.removeProperty(sc(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(sc(l),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=r(),n=document.documentElement,o=t/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:t=>{s({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{s(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{s({diffWrapLines:t})},setDiffViewMode:t=>{s({diffViewMode:t})},setInputBarOffset:t=>{s({inputBarOffset:t})},setKeyboardOpen:t=>{s({isKeyboardOpen:t})},toggleFavoriteModel:(t,n)=>{s(o=>o.favoriteModels.some(l=>l.providerID===t&&l.modelID===n)?{favoriteModels:o.favoriteModels.filter(l=>!(l.providerID===t&&l.modelID===n))}:{favoriteModels:[{providerID:t,modelID:n},...o.favoriteModels]})},isFavoriteModel:(t,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===t&&a.modelID===n)},addRecentModel:(t,n)=>{s(o=>{const a=o.recentModels.filter(l=>!(l.providerID===t&&l.modelID===n));return{recentModels:[{providerID:t,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||s(t=>{const n={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:t}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(t)},setMultiRunLauncherOpen:t=>{s(n=>({isMultiRunLauncherOpen:t,multiRunLauncherPrefillPrompt:t?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:t=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:t,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:t=>{s({isTimelineDialogOpen:t})},setNativeNotificationsEnabled:t=>{s({nativeNotificationsEnabled:t})},setNotificationMode:t=>{s({notificationMode:t})}}),{name:"ui-store",storage:Is(()=>ds()),partialize:s=>({theme:s.theme,isSidebarOpen:s.isSidebarOpen,sidebarWidth:s.sidebarWidth,isSessionSwitcherOpen:s.isSessionSwitcherOpen,activeMainTab:s.activeMainTab,sidebarSection:s.sidebarSection,isSessionCreateDialogOpen:s.isSessionCreateDialogOpen,isSettingsDialogOpen:s.isSettingsDialogOpen,showReasoningTraces:s.showReasoningTraces,autoDeleteEnabled:s.autoDeleteEnabled,autoDeleteAfterDays:s.autoDeleteAfterDays,autoDeleteLastRunAt:s.autoDeleteLastRunAt,toolCallExpansion:s.toolCallExpansion,fontSize:s.fontSize,padding:s.padding,favoriteModels:s.favoriteModels,recentModels:s.recentModels,diffLayoutPreference:s.diffLayoutPreference,diffWrapLines:s.diffWrapLines,diffViewMode:s.diffViewMode,nativeNotificationsEnabled:s.nativeNotificationsEnabled,notificationMode:s.notificationMode})}),{name:"ui-store"}));async function wg(){try{const s=await fetch("/api/openchamber/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)throw new Error(`Server responded with ${s.status}`);const r=await s.json();return{available:r.available??!1,version:r.version,currentVersion:r.currentVersion??"unknown",body:r.body,packageManager:r.packageManager,updateCommand:r.updateCommand}}catch(s){return console.warn("Failed to check for web updates:",s),null}}function jg(){return es()?"desktop":rn()?"web":null}const rc={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Aa=Vt()((s,r)=>({...rc,checkForUpdates:async()=>{const t=jg();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await hg():t==="web"&&(n=await wg()),s({checking:!1,available:n?.available??!1,info:n,lastChecked:Date.now()})}catch(n){s({checking:!1,error:n instanceof Error?n.message:"Failed to check for updates"})}}},downloadUpdate:async()=>{const{available:t,runtimeType:n}=r();if(!(n!=="desktop"||!t)){s({downloading:!0,error:null,progress:null});try{await gg(o=>{s({progress:o})}),s({downloading:!1,downloaded:!0})}catch(o){s({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:t,runtimeType:n}=r();if(!(n!=="desktop"||!t))try{await xg()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(rc)}})),Sg="/api",kg=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Ng=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(kg.test(r)||typeof window>"u")return r;const t=window.location?.href||window.location?.origin;if(!t)return r;try{return new URL(r,t).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),r}},Cg=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_DESKTOP_SERVER__,r=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!s||!r)return null;const t=typeof s.origin=="string"&&s.origin.length>0?s.origin:null;return t?`${t}/api`:null},xo=s=>s.replace(/\\/g,"/"),Qa=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class Mg{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=Sg){const n=Cg()||r;this.baseUrl=Ng(n),this.client=ep({baseUrl:this.baseUrl})}normalizeCandidatePath(r){if(typeof r!="string")return null;const t=r.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const t=r.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[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,t){if(r==null)return t();const n=this.currentDirectory;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,t=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&&(t(a.directory),t(a.worktree),t(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);t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(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 t=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(r){const t=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,t){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:t});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||[]}async getSessionTodos(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/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 t=r.toLowerCase();return t.startsWith("text/")&&t!=="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(t)}isHeicMime(r){if(!r)return!1;const t=r.toLowerCase();return t==="image/heic"||t==="image/heif"}async compressImage(r,t,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=t;t==="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 t=(await as(async()=>{const{default:f}=await import("./vendor-.bun-CqCnPJev.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 t({blob:c,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const g=new FileReader;g.onload=()=>f(g.result),g.onerror=p,g.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(t){return console.warn("Failed to convert HEIC to JPEG:",t),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 t=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);t=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:t}}async sendMessage(r){const t=Date.now(),n=r.messageId??`temp_${t}_${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,t,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const t=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Failed to unrevert session");return t.data}async forkSession(r,t){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t});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 t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/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 t=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(t?{directory:t}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(r,t,n){return(await this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:t,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async replyToQuestion(r,t){const n=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t];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 t=[],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[]}};t.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)t.push(n(d));const a=await Promise.all(t),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 t=`${this.baseUrl}/config`,n=await fetch(t,{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 t=await this.getConfig(),n=r(t);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 t=r.split(`
|
|
3
3
|
`),n=[];let o;for(const l of t)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
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 t=r,n=typeof t.directory=="string"?t.directory:typeof t.properties=="object"&&t.properties!==null?t.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof t.type=="string")return{directory:o&&o.length>0?o:"global",payload:t};const a=t.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 t of this.globalSseListeners)try{t(r)}catch(n){console.warn("[OpencodeClient] Global SSE listener error:",n)}}notifyGlobalSseOpen(){for(const r of this.globalSseOpenListeners)try{r()}catch(t){console.warn("[OpencodeClient] Global SSE open handler error:",t)}}notifyGlobalSseError(r){for(const t of this.globalSseErrorListeners)try{t(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(t=>{t?.name==="AbortError"||r.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",t)}).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 t=`${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(t,{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
5
|
`);const g=u.split(`
|
|
@@ -109,7 +109,7 @@ ${qe}`)}const Me=ce.map(qe=>{if(!qe?.dataUrl)return null;try{const[Ke,Fe]=qe.dat
|
|
|
109
109
|
`).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
|
|
110
110
|
`).trim(),Sw=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=i.useMemo(()=>jw(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Bl,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},kw=i.memo(Sw),Nw=s=>{const r={tools:s.filter(n=>n.kind==="tool").length,reasoning:s.filter(n=>n.kind==="reasoning").length,justifications:s.filter(n=>n.kind==="justification").length},t=[];return r.tools>0&&t.push(`${r.tools} tool${r.tools>1?"s":""}`),r.reasoning>0&&t.push(`${r.reasoning} reasoning`),r.justifications>0&&t.push(`${r.justifications} justification${r.justifications>1?"s":""}`),t.join(", ")},Sd=s=>[...s].sort((r,t)=>{const n=typeof r.endedAt=="number"?r.endedAt:void 0,o=typeof t.endedAt=="number"?t.endedAt:void 0;return n===void 0&&o===void 0?0:n===void 0?1:o===void 0?-1:n-o}),Cw=s=>{const r={},t=s.filter(n=>n.kind==="tool");return t.forEach((n,o)=>{const a=n.part.id;a&&(r[a]={hasPrev:o>0,hasNext:o<t.length-1})}),r},Mw=({parts:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:l,onContentChange:c,isWorking:d,previewedPartIds:u,diffStats:m})=>{const f=i.useRef(r),[p,g]=i.useState(0);i.useEffect(()=>{if(f.current===r)return;const b=f.current===!1;f.current=r,c?.("structural"),r&&b&&g(v=>v+1)},[r,c]);const y=i.useMemo(()=>Sd(d?s.filter(b=>b.part.id&&u.has(b.id)):s),[s,d,u]),h=Nw(y),j=Cw(y);return y.length===0?null:e.jsx(gs,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:_("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl cursor-pointer"),onClick:t,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:_("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(to,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:_("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(Ft,{className:"h-3.5 w-3.5"}):e.jsx(Rs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(h||m)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[h&&e.jsx("span",{className:"truncate block",children:h}),m&&(m.additions>0||m.deletions>0)&&e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,m.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,m.deletions)]})]})]})]}),r&&e.jsx("div",{className:_("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:y.map((b,v)=>{const w=b.part.id||`group-part-${v}`,N=j[w],x=`${w}-exp${p}`;switch(b.kind){case"tool":return e.jsx(gs,{children:e.jsx(Xo,{part:b.part,isExpanded:a.has(w),onToggle:l,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:N?.hasPrev??!1,hasNextTool:N?.hasNext??!1})},x);case"reasoning":return e.jsx(gs,{children:e.jsx(uf,{part:b.part,messageId:b.messageId,onContentChange:c})},x);case"justification":return e.jsx(gs,{children:e.jsx(kw,{part:b.part,messageId:b.messageId,onContentChange:c})},x);default:return null}})})]})})},Dw=i.memo(Mw),Aw=({isMigrating:s,children:r,className:t})=>e.jsx("div",{className:_("w-full overflow-hidden",s&&"pointer-events-none",t),style:s?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:r}),yi=i.memo(Aw),pf=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},hf=s=>{if(s.type!=="text")return!1;const r=pf(s);return!r||r.trim().length===0},Ew=(s,r={})=>{const{includeReasoning:t=!0}=r,n=s.some(o=>!o.synthetic);return s.filter(o=>!!o.synthetic&&n||!t&&o.type==="reasoning"?!1:!(o.type==="patch"))},Iw=s=>{const r=s/1e3;if(r<60)return`${r.toFixed(1)}s`;const t=Math.floor(r/60),n=Math.round(r%60);return`${t}m ${n}s`},Pw=(s,r)=>{const t=i.useRef(null),n=i.useRef(null),[o,a]=i.useState(!1),l=i.useRef(s);l.current=s;const c=i.useRef(r);c.current=r;const d=i.useRef(!1),u=r.size>0;return i.useEffect(()=>{s&&s.isWorking&&u&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const m=l.current;if(!m)return;const f=Array.from(c.current);f.length>0&&m.markPartsPreviewed(f)},300)},1e3)))},[u,s]),i.useEffect(()=>{s&&(!s.isWorking||!u)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[u,s]),i.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},Tw=new Set(["task"]),gn=s=>typeof s=="string"&&Tw.has(s.toLowerCase()),Fw=({messageId:s,parts:r,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:l,onShowPopup:c,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=i.useState(!1),g=i.useRef(null),y=i.useMemo(()=>r.filter(C=>C.type!=="text"?!1:!hf(C)),[r]),h=d?.token;let j=!1;const b=!!a,v=!!l,w=!!(n??t),N=!!o,x=i.useCallback(()=>{g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null)},[]),k=i.useCallback(()=>{!w||!b||!N||typeof window>"u"||(x(),p(!0),g.current=window.setTimeout(()=>{p(!1),g.current=null},1800))},[b,x,N,w]);i.useEffect(()=>{N||(p(!1),x())},[x,N]);const A=i.useCallback(C=>{!a||!N||(C.stopPropagation(),C.preventDefault(),a(),w&&k())},[N,w,a,k]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:w&&b&&N?k:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:y.map((C,M)=>{let S;return d&&h&&!j&&pf(C).includes(h)&&(S=d,j=!0),e.jsx(gs,{children:e.jsx(tw,{part:C,messageId:s,isMobile:t,agentMention:S})},`user-text-${M}`)})}),e.jsx(qm,{files:r,onShowPopup:c}),b&&N||u||m?e.jsxs("div",{className:_("mt-1 flex items-center justify-end 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",f&&"opacity-100 pointer-events-auto"),children:[u&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:C=>C.stopPropagation(),onClick:C=>{C.stopPropagation(),u()},children:e.jsx(Zn,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:C=>C.stopPropagation(),onClick:C=>{C.stopPropagation(),m()},children:e.jsx(zt,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Fork from here"})]}),b&&N&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:C=>C.stopPropagation(),onClick:A,onFocus:()=>p(!0),onBlur:()=>{v||p(!1)},children:v?e.jsx(_t,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ys,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy message"})]})]}):null]})},Rw=({messageId:s,parts:r,isMessageCompleted:t,messageFinish:n,messageCompletedAt:o,syntaxTheme:a,isMobile:l,hasTouchInput:c,expandedTools:d,onToggleTool:u,onShowPopup:m,streamPhase:f,allowAnimation:p,onContentChange:g,hasTextContent:y=!1,onCopyMessage:h,copiedMessage:j=!1,onAuxiliaryContentComplete:b,showReasoningTraces:v=!1,turnGroupingContext:w,errorMessage:N})=>{const[x,k]=i.useState(!1),A=i.useRef(null),C=!!h,M=!!j,S=!!(c??l),D=!t,E=i.useMemo(()=>r.filter(ie=>!hf(ie)).filter(ie=>ie.type!=="compaction"),[r]),T=i.useMemo(()=>E.filter(ie=>ie.type==="tool"),[E]),I=i.useMemo(()=>E.filter(ie=>ie.type==="text"),[E]),P=he(ie=>ie.createSessionFromAssistantMessage),O=$e(ie=>ie.openMultiRunLauncherWithPrompt),U=w?.isLastAssistantInTurn??!1,Q=n==="stop",W=T.length>0,L=i.useMemo(()=>T.some(ie=>{const We=(ie.state??{})?.status;return We==="pending"||We==="running"||We==="started"}),[T]),H=i.useCallback(ie=>{const de=ie.state??{},We=de?.status;if(We==="pending"||We==="running"||We==="started")return!1;const Ge=de?.time??{},bt=typeof Ge?.end=="number"?Ge.end:void 0,Z=typeof Ge?.start=="number"?Ge.start:void 0;return!(typeof bt!="number"||typeof Z=="number"&&bt<Z)},[]),q=i.useMemo(()=>T.length===0?!0:L?!1:T.every(ie=>H(ie)),[T,L,H]),X=i.useMemo(()=>I.length===0?!0:I.every(ie=>typeof ie.time?.end=="number"),[I]),Y=i.useMemo(()=>E.filter(ie=>ie.type==="reasoning"),[E]),re=i.useMemo(()=>Y.length===0?!0:Y.every(ie=>typeof ie.time?.end=="number"),[Y]),K=typeof n!="string",ae=Y.length>0&&W&&(L||K||!q),F=i.useMemo(()=>W?I.length===0?K||L||!q:!0:I.length>0?ae:!1,[I.length,K,L,W,ae,q]),$=D||F&&(!X||!q||L||K)||ae,R=D||W&&(L||K||!q),B=D||ae,z=W||Y.length>0,G=I.length===0,ge=z&&G&&!R&&!B&&q&&re,oe=i.useRef(!1),me=i.useRef(!1);i.useEffect(()=>{me.current=!1},[s]),i.useEffect(()=>{if(!ge){oe.current=!1;return}oe.current||(oe.current=!0,b?.())},[ge,b]),i.useEffect(()=>{if(D){me.current=!1;return}if(W){me.current=!1;return}Y.length!==0&&(B||!re||me.current||(me.current=!0,g?.("structural")))},[D,W,g,re,Y.length,B]);const Ne=!!y&&!D,Ce=i.useCallback(()=>{A.current!==null&&typeof window<"u"&&(window.clearTimeout(A.current),A.current=null)},[]),Be=i.useCallback(()=>{!S||!C||!Ne||typeof window>"u"||(Ce(),k(!0),A.current=window.setTimeout(()=>{k(!1),A.current=null},1800))},[C,Ce,Ne,S]);i.useEffect(()=>{Ne||(k(!1),Ce())},[Ce,Ne]);const V=i.useCallback(ie=>{!h||!Ne||(ie.stopPropagation(),ie.preventDefault(),h(),S&&Be())},[Ne,S,h,Be]),J=i.useCallback(ie=>{ie.stopPropagation(),ie.preventDefault(),P&&P(s)},[P,s]),ee=i.useCallback(ie=>{ie.stopPropagation(),ie.preventDefault();const de=Sl(I);if(!de.trim())return;const We=`${Zx}
|
|
111
111
|
|
|
112
|
-
${de}`;O(We)},[I,O]);i.useEffect(()=>()=>{Ce()},[Ce]);const xe=i.useMemo(()=>{const ie={},de=T.filter(We=>gn(We.tool)||R?!1:H(We));return de.forEach((We,Ge)=>{ie[We.id]={hasPrev:Ge>0,hasNext:Ge<de.length-1}}),ie},[T,R,H]),fe=i.useMemo(()=>w?.activityParts??[],[w]),Oe=i.useMemo(()=>w?fe.filter(ie=>ie.messageId===s):[],[fe,s,w]),Se=i.useMemo(()=>w?w.activityGroupSegments.filter(ie=>ie.anchorMessageId===s):[],[s,w]),Le=i.useMemo(()=>{const ie=new Map;return Oe.forEach(de=>{ie.set(de.part,de)}),ie},[Oe]),pe=i.useMemo(()=>w?(v?fe:fe.filter(de=>de.kind==="tool")).filter(de=>{if(de.kind!=="tool")return!0;const We=de.part.tool;return!gn(We)}):[],[fe,v,w]),[it,xt]=i.useState(!1);i.useEffect(()=>{if(!w)return;const ie=w.activityGroupSegments.some(de=>de.afterToolPartId!==null);(pe.length>1||ie&&pe.length>0)&&xt(!0)},[w,pe.length]);const Mt=!!(w&&it),De=i.useMemo(()=>{if(!w)return[];if(!Mt)return[];if(!w.isWorking)return[];const ie=[];return Oe.forEach(de=>{if(w.previewedPartIds.has(de.id)||!v&&de.kind!=="tool")return;const We=de.part;if(de.kind==="tool"){const Ge=We;if(gn(Ge.tool)||R||!H(Ge))return}else if(de.kind==="reasoning"){if(!v||B||typeof We.time?.end!="number")return}else if(de.kind==="justification"&&(!v||$||typeof We.time?.end!="number"))return;ie.push(de)}),ie},[Oe,H,$,B,R,v,Mt,w]),ne=i.useMemo(()=>{const ie=new Set;return De.forEach(de=>{ie.add(de.id)}),ie},[De]),{isAnimating:rt}=Pw(w,ne),be=!!(w&&Mt&&pe.length>0&&Se.length>0),ke=i.useMemo(()=>T.filter(ie=>gn(ie.tool)),[T]),Qe=i.useMemo(()=>{const ie=[],de=Ge=>{!w||!be||Se.filter(bt=>(bt.afterToolPartId??null)===Ge).forEach(bt=>{const Z=v?bt.parts:bt.parts.filter(we=>we.kind==="tool");Z.length!==0&&ie.push(e.jsx(Dw,{parts:Z,isExpanded:w.isGroupExpanded,onToggle:w.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:g,isWorking:w.isWorking,previewedPartIds:w.previewedPartIds,diffStats:w.diffStats},`progressive-group-${bt.id}`))})};de(null),ke.forEach(Ge=>{ie.push(e.jsx(gs,{children:e.jsx(Xo,{part:Ge,isExpanded:d.has(Ge.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:g,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Ge.id}`)),de(Ge.id)});const We=[];return E.forEach((Ge,bt)=>{const Z=Le.get(Ge);if(!Z||!w)return;let we=null,ve=null;if(!Mt){if(Z.kind==="tool"){const _e=Ge;if(gn(_e.tool))return;const pt=_e.state?.time,ft=H(_e);if(!(!R&&ft))return;const At=xe[_e.id];ve=e.jsx(gs,{children:e.jsx(Xo,{part:_e,isExpanded:d.has(_e.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:g,hasPrevTool:At?.hasPrev??!1,hasNextTool:At?.hasNext??!1})},`tool-${_e.id}`),we=ft&&typeof pt?.end=="number"?pt.end:null}ve&&We.push({part:Ge,index:bt,endTime:we,element:ve});return}if(!w.isWorking||w.isGroupExpanded||w.previewedPartIds.has(Z.id)||!v&&Z.kind!=="tool")return;const Ue=ne.has(Z.id);switch(Z.kind){case"tool":{const _e=Ge;if(gn(_e.tool))break;const pt=_e.state?.time,ft=H(_e);if(!(!R&&ft))break;const At=xe[_e.id],Te=e.jsx(gs,{children:e.jsx(Xo,{part:_e,isExpanded:d.has(_e.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:g,hasPrevTool:At?.hasPrev??!1,hasNextTool:At?.hasNext??!1})},`tool-${_e.id}`);ve=Ue?e.jsx(yi,{isMigrating:rt,children:Te},`migrating-tool-${_e.id}`):Te,we=ft&&typeof pt?.end=="number"?pt.end:null;break}case"reasoning":{if(!v)break;const _e=Ge.time,et=typeof _e?.end=="number";if(!(et&&!B))break;const ft=e.jsx(gs,{children:e.jsx(uf,{part:Ge,messageId:s,onContentChange:g})},`reasoning-${bt}`);ve=Ue?e.jsx(yi,{isMigrating:rt,children:ft},`migrating-reasoning-${bt}`):ft,we=et?_e?.end??null:null;break}case"justification":{if(!v)break;const _e=Ge.time,et=typeof _e?.end=="number";if(!(et&&!$))break;const ft=e.jsx(gs,{children:e.jsx(Jv,{part:Ge,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:g,renderAsReasoning:!0})},`assistant-text-${bt}`);ve=Ue?e.jsx(yi,{isMigrating:rt,children:ft},`migrating-text-${bt}`):ft,we=et?_e?.end??null:null;break}}ve&&We.push({part:Ge,index:bt,endTime:we,element:ve})}),We.sort((Ge,bt)=>Ge.endTime===null&&bt.endTime===null?Ge.index-bt.index:Ge.endTime===null?1:bt.endTime===null?-1:Ge.endTime-bt.endTime),We.forEach(({element:Ge})=>{ie.push(Ge)}),ie},[Le,Se,d,rt,l,H,s,g,m,u,ne,$,B,R,Mt,v,a,xe,w,E,ke,be]),tt=w?.turnId,He=he(ie=>ie.currentSessionId),Re=St(ie=>{if(!tt||!He)return;const de=ie.messages.get(He);if(!de)return;const We=de.find(Z=>Z.info?.id===tt);if(!We)return;const bt=We.info.summary?.body;return typeof bt=="string"&&bt.trim().length>0?bt:void 0}),nt=typeof w?.summaryBody=="string"&&w.summaryBody.trim().length>0?w.summaryBody:Re,yt=i.useRef(void 0);nt&&nt.trim().length>0&&(yt.current=nt);const ct=i.useRef(tt);ct.current!==tt&&(ct.current=tt,yt.current=void 0);const It=yt.current,Tt=w?.isLastAssistantInTurn&&It&&It.trim().length>0,je=!!N,ze=U&&y&&(Q||!!N),[Ze,Ye]=i.useState(!1),mt=i.useMemo(()=>{if(!U||!Q)return;const ie=w?.userMessageCreatedAt;if(!(typeof ie!="number"||typeof o!="number")&&!(o<=ie))return Iw(o-ie)},[U,Q,w?.userMessageCreatedAt,o]),ye=e.jsxs(e.Fragment,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:ie=>ie.stopPropagation(),onClick:J,children:e.jsx(Mh,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:ie=>ie.stopPropagation(),onClick:ee,children:e.jsx(Bm,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),h&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{type:"button",variant:"ghost",size:"icon","data-visible":x||M?"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",!Ne&&"opacity-50"),disabled:!Ne,"aria-label":"Copy message text","aria-hidden":!Ne,onPointerDown:ie=>ie.stopPropagation(),onClick:V,onFocus:()=>{Ne&&k(!0)},onBlur:()=>{M||k(!1)},children:M?e.jsx(_t,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ys,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:_("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&C&&Ne?Be:void 0,children:e.jsxs("div",{className:"px-3",children:[e.jsxs("div",{className:"leading-normal overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Qe,je&&e.jsx(gs,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Zr,{content:N??""})})},"assistant-error"),Tt&&e.jsx(gs,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Ye(!0),onMouseLeave:()=>Ye(!1),children:[e.jsx(Zr,{content:It}),ze&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[mt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),mt]}):e.jsx("span",{}),e.jsx("div",{className:_("flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",Ze&&"opacity-100 pointer-events-auto"),children:ye})]})]})},"summary-body")]}),e.jsx(qm,{files:r,onShowPopup:m}),!Tt&&ze&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[mt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),mt]}):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:ye})]})]})})},_w=({isUser:s,...r})=>s?e.jsx(Fw,{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(Rw,{...r}),kd=i.memo(_w),bi=s=>{const r=s,t=r?.clientRole,n=r?.role;return r?.userMessageMarker===!0||t==="user"||n==="user"||r?.origin==="user"||r?.source==="user"?{role:"user",isUser:!0}:{role:t||n||"assistant",isUser:!1}},Ow=i.lazy(()=>as(()=>import("./ToolOutputDialog-D8JjsNSh.js"),__vite__mapDeps([2,0,1,3,4]))),$w=new Set(["task","edit","multiedit","write","bash"]),Nd=s=>typeof s=="string"&&$w.has(s.toLowerCase());function vi(s){const r=i.useRef({hasValue:!1,value:void 0});return!r.current.hasValue&&s!==void 0&&s!==null&&(r.current={hasValue:!0,value:s}),r.current.hasValue?r.current.value:s}const sr=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},Lw=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:l})=>{const{isMobile:c,hasTouchInput:d}=$t(),{currentTheme:u}=Wr(),m=i.useRef(null),f=he(ul(Te=>({lifecyclePhase:Te.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const st=s.info.sessionID??Te.currentSessionId??null;return st?(Te.streamingMessageIds.get(st)??null)===s.info.id:!1})(),currentSessionId:Te.currentSessionId,getCurrentAgent:Te.getCurrentAgent,getSessionAgentSelection:Te.getSessionAgentSelection,getAgentModelForSession:Te.getAgentModelForSession,getSessionModelSelection:Te.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:g,currentSessionId:y,getCurrentAgent:h,getSessionAgentSelection:j,getAgentModelForSession:b,getSessionModelSelection:v}=f,w=at(Te=>Te.providers),N=$e(Te=>Te.showReasoningTraces),x=$e(Te=>Te.toolCallExpansion);i.useEffect(()=>{y&&Pr.getInstance().recordSessionStart(y)},[y]);const[k,A]=i.useState(null),[C,M]=i.useState(!1),[S,D]=i.useState(new Set),[E,T]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{D(new Set)},[s.info.id,x]);const P=i.useMemo(()=>bi(s.info),[s.info]).isUser,O=i.useMemo(()=>P?s.parts.map(Te=>Te.type==="compaction"?{type:"text",text:"/compact"}:Te):s.parts,[P,s.parts]),U=i.useMemo(()=>{if(P||!r)return null;const Te=sr(r.info,"clientRole"),st=sr(r.info,"role");if((typeof Te=="string"?Te:typeof st=="string"?st:void 0)!=="user")return null;const Xe=sr(r.info,"mode"),kt=sr(r.info,"providerID"),Lt=sr(r.info,"modelID"),ts=sr(r.info,"variant"),ns=typeof Xe=="string"&&Xe.trim().length>0?Xe:void 0,ps=typeof kt=="string"&&kt.trim().length>0?kt:void 0,pr=typeof Lt=="string"&&Lt.trim().length>0?Lt:void 0,Bt=typeof ts=="string"&&ts.trim().length>0?ts:void 0;return!ns&&!ps&&!pr&&!Bt?null:{agentName:ns,providerId:ps,modelId:pr,variant:Bt}},[P,r]),Q=i.useMemo(()=>{if(P)return;const Te=sr(s.info,"mode");if(typeof Te=="string"&&Te.trim().length>0)return Te;if(U?.agentName)return U.agentName;const st=s.info.sessionID;if(!st)return;const Ve=h(st);return Ve||(j(st)??void 0)},[P,s.info,U,h,j]),W=s.info.sessionID,L=P?null:sr(s.info,"providerID"),H=P?null:sr(s.info,"modelID"),q=i.useMemo(()=>{if(P||!W)return null;if(U?.providerId&&U?.modelId)return{providerId:U.providerId,modelId:U.modelId};if(Q){const st=b(W,Q);if(st?.providerId&&st?.modelId)return st}const Te=v(W);return Te?.providerId&&Te?.modelId?Te:null},[P,W,Q,U,b,v]),X=i.useMemo(()=>P?null:typeof L=="string"&&L.trim().length>0?L:q?.providerId??null,[P,L,q]),Y=i.useMemo(()=>P?null:typeof H=="string"&&H.trim().length>0?H:q?.modelId??null,[P,H,q]),re=i.useMemo(()=>{if(!P&&X&&Y&&w.length>0){const Te=w.find(st=>st.id===X);if(Te?.models&&Array.isArray(Te.models)){const Xe=Te.models.find(kt=>kt.id===Y)?.name;return typeof Xe=="string"?Xe:void 0}}},[P,X,Y,w]),K=i.useMemo(()=>{if(P||!X||!Y)return!1;const Te=w.find(Xe=>Xe.id===X);if(!Te?.models||!Array.isArray(Te.models))return!1;const Ve=Te.models.find(Xe=>Xe.id===Y)?.variants;return!!(Ve&&Object.keys(Ve).length>0)},[P,Y,X,w]),ae=vi(Q),F=vi(X??void 0),$=vi(re),R=ae??void 0,B=F??null,z=$??void 0,G=i.useMemo(()=>{const Te=s.info.time;return typeof Te?.completed=="number"?Te.completed:null},[s.info.time]),ge=i.useMemo(()=>P?!0:!!(G&&G>0),[P,G]),oe=i.useMemo(()=>{const Te=s.info.finish;return typeof Te=="string"?Te:void 0},[s.info]),me=i.useMemo(()=>Ew(O,{includeReasoning:N}),[O,N]),Ne=i.useMemo(()=>P||ge?me:[],[P,ge,me]),Ce=i.useMemo(()=>P?[]:me.filter(Te=>Te.type==="text"),[P,me]),Be=i.useMemo(()=>P?[]:me.filter(st=>st.type==="tool"),[P,me]),V=i.useMemo(()=>{if(x==="collapsed"||x==="activity")return S;const Te=new Set;for(const Ve of Be){const Xe=Ve.tool;Ve.id&&Nd(Xe)&&Te.add(Ve.id)}if(l?.isFirstAssistantInTurn)for(const Ve of l.activityParts){if(Ve.kind!=="tool")continue;const Xe=Ve.part;Xe.id&&Nd(Xe.tool)&&Te.add(Xe.id)}const st=new Set(Te);for(const Ve of S)st.has(Ve)?st.delete(Ve):st.add(Ve);return st},[S,x,Be,l]),J=i.useMemo(()=>{if(!P)return;const Te=s.parts.find(kt=>kt.type==="agent");if(!Te)return;const st=Te,Ve=typeof st.name=="string"?st.name:void 0;if(!Ve)return;const Xe=st.source&&typeof st.source.value=="string"&&st.source.value.trim().length>0?st.source.value:`#${Ve}`;return{name:Ve,token:Xe}},[P,s.parts]),ee=typeof oe!="string",xe=i.useMemo(()=>P?!1:Ce.length===0||Be.length===0?ee:!0,[Ce.length,Be.length,ee,P]),fe=u?.metadata.variant,Oe=i.useMemo(()=>fe?fe==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[fe]),Se=i.useMemo(()=>u?Ll(u):Oe?Ov:$v,[u,Oe]),Le=i.useMemo(()=>P?!1:Pr.getInstance().shouldAnimateMessage(s.info,y||s.info.sessionID),[s.info,y,P]),pe=i.useRef(!1),it=i.useMemo(()=>r?bi(r.info):null,[r]),xt=i.useMemo(()=>t?bi(t.info):null,[t]),Mt=i.useMemo(()=>P||!xt?!1:!xt.isUser&&xt.role==="assistant",[P,xt]),De=i.useMemo(()=>ge?"completed":p||(g?"streaming":"completed"),[ge,p,g]),ne=i.useMemo(()=>{if(P)return!0;const Te=l?.headerMessageId;if(Te){if(s.info.id===Te){if(De==="completed")return!0;const Ve=De==="streaming"||De==="cooldown",Xe=pe.current;return Ve&&!Xe&&(pe.current=!0),Xe||Ve}return!1}return it?it.isUser:!0},[P,it,l,De,s.info]),rt=i.useCallback(Te=>{navigator.clipboard.writeText(Te),A(Te),setTimeout(()=>A(null),2e3)},[]),be=l?.turnId,ke=St(Te=>{if(!be)return;const st=s.info.sessionID;if(!st)return;const Ve=Te.messages.get(st);if(!Ve)return;const Xe=Ve.find(ts=>ts.info?.id===be);if(!Xe)return;const Lt=Xe.info.summary?.body;return typeof Lt=="string"&&Lt.trim().length>0?Lt:void 0}),Qe=St(Te=>{if(!be)return;const st=s.info.sessionID;if(!st)return;const Ve=Te.messages.get(st);if(!Ve)return;const Xe=Ve.find(Lt=>Lt.info?.id===be);if(!Xe)return;const kt=Xe.info.variant;return typeof kt=="string"&&kt.trim().length>0?kt:void 0}),tt=P?void 0:Qe??U?.variant,He=!P&&K?tt??"Default":void 0,Re=typeof l?.summaryBody=="string"&&l.summaryBody.trim().length>0?l.summaryBody:ke,nt=i.useRef(void 0);Re&&Re.trim().length>0&&(nt.current=Re);const yt=i.useRef(be);yt.current!==be&&(yt.current=be,nt.current=void 0);const ct=nt.current,It=i.useMemo(()=>{if(P)return;const Te=s.info?.error;if(!Te)return;const st=typeof Te.data?.message=="string"?Te.data.message:void 0,Ve=typeof Te.message=="string"?Te.message:void 0,Xe=typeof Te.name=="string"?Te.name:void 0,kt=st||Ve||Xe;if(kt)return`Opencode failed to send message with error:
|
|
112
|
+
${de}`;O(We)},[I,O]);i.useEffect(()=>()=>{Ce()},[Ce]);const xe=i.useMemo(()=>{const ie={},de=T.filter(We=>gn(We.tool)||R?!1:H(We));return de.forEach((We,Ge)=>{ie[We.id]={hasPrev:Ge>0,hasNext:Ge<de.length-1}}),ie},[T,R,H]),fe=i.useMemo(()=>w?.activityParts??[],[w]),Oe=i.useMemo(()=>w?fe.filter(ie=>ie.messageId===s):[],[fe,s,w]),Se=i.useMemo(()=>w?w.activityGroupSegments.filter(ie=>ie.anchorMessageId===s):[],[s,w]),Le=i.useMemo(()=>{const ie=new Map;return Oe.forEach(de=>{ie.set(de.part,de)}),ie},[Oe]),pe=i.useMemo(()=>w?(v?fe:fe.filter(de=>de.kind==="tool")).filter(de=>{if(de.kind!=="tool")return!0;const We=de.part.tool;return!gn(We)}):[],[fe,v,w]),[it,xt]=i.useState(!1);i.useEffect(()=>{if(!w)return;const ie=w.activityGroupSegments.some(de=>de.afterToolPartId!==null);(pe.length>1||ie&&pe.length>0)&&xt(!0)},[w,pe.length]);const Mt=!!(w&&it),De=i.useMemo(()=>{if(!w)return[];if(!Mt)return[];if(!w.isWorking)return[];const ie=[];return Oe.forEach(de=>{if(w.previewedPartIds.has(de.id)||!v&&de.kind!=="tool")return;const We=de.part;if(de.kind==="tool"){const Ge=We;if(gn(Ge.tool)||R||!H(Ge))return}else if(de.kind==="reasoning"){if(!v||B||typeof We.time?.end!="number")return}else if(de.kind==="justification"&&(!v||$||typeof We.time?.end!="number"))return;ie.push(de)}),ie},[Oe,H,$,B,R,v,Mt,w]),ne=i.useMemo(()=>{const ie=new Set;return De.forEach(de=>{ie.add(de.id)}),ie},[De]),{isAnimating:rt}=Pw(w,ne),be=!!(w&&Mt&&pe.length>0&&Se.length>0),ke=i.useMemo(()=>T.filter(ie=>gn(ie.tool)),[T]),Qe=i.useMemo(()=>{const ie=[],de=Ge=>{!w||!be||Se.filter(bt=>(bt.afterToolPartId??null)===Ge).forEach(bt=>{const Z=v?bt.parts:bt.parts.filter(we=>we.kind==="tool");Z.length!==0&&ie.push(e.jsx(Dw,{parts:Z,isExpanded:w.isGroupExpanded,onToggle:w.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:g,isWorking:w.isWorking,previewedPartIds:w.previewedPartIds,diffStats:w.diffStats},`progressive-group-${bt.id}`))})};de(null),ke.forEach(Ge=>{ie.push(e.jsx(gs,{children:e.jsx(Xo,{part:Ge,isExpanded:d.has(Ge.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:g,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Ge.id}`)),de(Ge.id)});const We=[];return E.forEach((Ge,bt)=>{const Z=Le.get(Ge);if(!Z||!w)return;let we=null,ve=null;if(!Mt){if(Z.kind==="tool"){const _e=Ge;if(gn(_e.tool))return;const pt=_e.state?.time,ft=H(_e);if(!(!R&&ft))return;const At=xe[_e.id];ve=e.jsx(gs,{children:e.jsx(Xo,{part:_e,isExpanded:d.has(_e.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:g,hasPrevTool:At?.hasPrev??!1,hasNextTool:At?.hasNext??!1})},`tool-${_e.id}`),we=ft&&typeof pt?.end=="number"?pt.end:null}ve&&We.push({part:Ge,index:bt,endTime:we,element:ve});return}if(!w.isWorking||w.isGroupExpanded||w.previewedPartIds.has(Z.id)||!v&&Z.kind!=="tool")return;const Ue=ne.has(Z.id);switch(Z.kind){case"tool":{const _e=Ge;if(gn(_e.tool))break;const pt=_e.state?.time,ft=H(_e);if(!(!R&&ft))break;const At=xe[_e.id],Te=e.jsx(gs,{children:e.jsx(Xo,{part:_e,isExpanded:d.has(_e.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:g,hasPrevTool:At?.hasPrev??!1,hasNextTool:At?.hasNext??!1})},`tool-${_e.id}`);ve=Ue?e.jsx(yi,{isMigrating:rt,children:Te},`migrating-tool-${_e.id}`):Te,we=ft&&typeof pt?.end=="number"?pt.end:null;break}case"reasoning":{if(!v)break;const _e=Ge.time,et=typeof _e?.end=="number";if(!(et&&!B))break;const ft=e.jsx(gs,{children:e.jsx(uf,{part:Ge,messageId:s,onContentChange:g})},`reasoning-${bt}`);ve=Ue?e.jsx(yi,{isMigrating:rt,children:ft},`migrating-reasoning-${bt}`):ft,we=et?_e?.end??null:null;break}case"justification":{if(!v)break;const _e=Ge.time,et=typeof _e?.end=="number";if(!(et&&!$))break;const ft=e.jsx(gs,{children:e.jsx(Jv,{part:Ge,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:g,renderAsReasoning:!0})},`assistant-text-${bt}`);ve=Ue?e.jsx(yi,{isMigrating:rt,children:ft},`migrating-text-${bt}`):ft,we=et?_e?.end??null:null;break}}ve&&We.push({part:Ge,index:bt,endTime:we,element:ve})}),We.sort((Ge,bt)=>Ge.endTime===null&&bt.endTime===null?Ge.index-bt.index:Ge.endTime===null?1:bt.endTime===null?-1:Ge.endTime-bt.endTime),We.forEach(({element:Ge})=>{ie.push(Ge)}),ie},[Le,Se,d,rt,l,H,s,g,m,u,ne,$,B,R,Mt,v,a,xe,w,E,ke,be]),tt=w?.turnId,He=he(ie=>ie.currentSessionId),Re=St(ie=>{if(!tt||!He)return;const de=ie.messages.get(He);if(!de)return;const We=de.find(Z=>Z.info?.id===tt);if(!We)return;const bt=We.info.summary?.body;return typeof bt=="string"&&bt.trim().length>0?bt:void 0}),nt=typeof w?.summaryBody=="string"&&w.summaryBody.trim().length>0?w.summaryBody:Re,yt=i.useRef(void 0);nt&&nt.trim().length>0&&(yt.current=nt);const ct=i.useRef(tt);ct.current!==tt&&(ct.current=tt,yt.current=void 0);const It=yt.current,Tt=w?.isLastAssistantInTurn&&It&&It.trim().length>0,je=!!N,ze=U&&y&&(Q||!!N),[Ze,Ye]=i.useState(!1),mt=i.useMemo(()=>{if(!U||!Q)return;const ie=w?.userMessageCreatedAt;if(!(typeof ie!="number"||typeof o!="number")&&!(o<=ie))return Iw(o-ie)},[U,Q,w?.userMessageCreatedAt,o]),ye=e.jsxs(e.Fragment,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:ie=>ie.stopPropagation(),onClick:J,children:e.jsx(Mh,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:ie=>ie.stopPropagation(),onClick:ee,children:e.jsx(Bm,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),h&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{type:"button",variant:"ghost",size:"icon","data-visible":x||M?"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",!Ne&&"opacity-50"),disabled:!Ne,"aria-label":"Copy message text","aria-hidden":!Ne,onPointerDown:ie=>ie.stopPropagation(),onClick:V,onFocus:()=>{Ne&&k(!0)},onBlur:()=>{M||k(!1)},children:M?e.jsx(_t,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ys,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:_("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&C&&Ne?Be:void 0,children:e.jsxs("div",{className:"px-3",children:[e.jsxs("div",{className:"leading-normal overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Qe,je&&e.jsx(gs,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Zr,{content:N??""})})},"assistant-error"),Tt&&e.jsx(gs,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Ye(!0),onMouseLeave:()=>Ye(!1),children:[e.jsx(Zr,{content:It}),ze&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[mt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),mt]}):e.jsx("span",{}),e.jsx("div",{className:_("flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",Ze&&"opacity-100 pointer-events-auto"),children:ye})]})]})},"summary-body")]}),e.jsx(qm,{files:r,onShowPopup:m}),!Tt&&ze&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[mt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),mt]}):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:ye})]})]})})},_w=({isUser:s,...r})=>s?e.jsx(Fw,{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(Rw,{...r}),kd=i.memo(_w),bi=s=>{const r=s,t=r?.clientRole,n=r?.role;return r?.userMessageMarker===!0||t==="user"||n==="user"||r?.origin==="user"||r?.source==="user"?{role:"user",isUser:!0}:{role:t||n||"assistant",isUser:!1}},Ow=i.lazy(()=>as(()=>import("./ToolOutputDialog-CM8zam_u.js"),__vite__mapDeps([2,0,1,3,4]))),$w=new Set(["task","edit","multiedit","write","bash"]),Nd=s=>typeof s=="string"&&$w.has(s.toLowerCase());function vi(s){const r=i.useRef({hasValue:!1,value:void 0});return!r.current.hasValue&&s!==void 0&&s!==null&&(r.current={hasValue:!0,value:s}),r.current.hasValue?r.current.value:s}const sr=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},Lw=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:l})=>{const{isMobile:c,hasTouchInput:d}=$t(),{currentTheme:u}=Wr(),m=i.useRef(null),f=he(ul(Te=>({lifecyclePhase:Te.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const st=s.info.sessionID??Te.currentSessionId??null;return st?(Te.streamingMessageIds.get(st)??null)===s.info.id:!1})(),currentSessionId:Te.currentSessionId,getCurrentAgent:Te.getCurrentAgent,getSessionAgentSelection:Te.getSessionAgentSelection,getAgentModelForSession:Te.getAgentModelForSession,getSessionModelSelection:Te.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:g,currentSessionId:y,getCurrentAgent:h,getSessionAgentSelection:j,getAgentModelForSession:b,getSessionModelSelection:v}=f,w=at(Te=>Te.providers),N=$e(Te=>Te.showReasoningTraces),x=$e(Te=>Te.toolCallExpansion);i.useEffect(()=>{y&&Pr.getInstance().recordSessionStart(y)},[y]);const[k,A]=i.useState(null),[C,M]=i.useState(!1),[S,D]=i.useState(new Set),[E,T]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{D(new Set)},[s.info.id,x]);const P=i.useMemo(()=>bi(s.info),[s.info]).isUser,O=i.useMemo(()=>P?s.parts.map(Te=>Te.type==="compaction"?{type:"text",text:"/compact"}:Te):s.parts,[P,s.parts]),U=i.useMemo(()=>{if(P||!r)return null;const Te=sr(r.info,"clientRole"),st=sr(r.info,"role");if((typeof Te=="string"?Te:typeof st=="string"?st:void 0)!=="user")return null;const Xe=sr(r.info,"mode"),kt=sr(r.info,"providerID"),Lt=sr(r.info,"modelID"),ts=sr(r.info,"variant"),ns=typeof Xe=="string"&&Xe.trim().length>0?Xe:void 0,ps=typeof kt=="string"&&kt.trim().length>0?kt:void 0,pr=typeof Lt=="string"&&Lt.trim().length>0?Lt:void 0,Bt=typeof ts=="string"&&ts.trim().length>0?ts:void 0;return!ns&&!ps&&!pr&&!Bt?null:{agentName:ns,providerId:ps,modelId:pr,variant:Bt}},[P,r]),Q=i.useMemo(()=>{if(P)return;const Te=sr(s.info,"mode");if(typeof Te=="string"&&Te.trim().length>0)return Te;if(U?.agentName)return U.agentName;const st=s.info.sessionID;if(!st)return;const Ve=h(st);return Ve||(j(st)??void 0)},[P,s.info,U,h,j]),W=s.info.sessionID,L=P?null:sr(s.info,"providerID"),H=P?null:sr(s.info,"modelID"),q=i.useMemo(()=>{if(P||!W)return null;if(U?.providerId&&U?.modelId)return{providerId:U.providerId,modelId:U.modelId};if(Q){const st=b(W,Q);if(st?.providerId&&st?.modelId)return st}const Te=v(W);return Te?.providerId&&Te?.modelId?Te:null},[P,W,Q,U,b,v]),X=i.useMemo(()=>P?null:typeof L=="string"&&L.trim().length>0?L:q?.providerId??null,[P,L,q]),Y=i.useMemo(()=>P?null:typeof H=="string"&&H.trim().length>0?H:q?.modelId??null,[P,H,q]),re=i.useMemo(()=>{if(!P&&X&&Y&&w.length>0){const Te=w.find(st=>st.id===X);if(Te?.models&&Array.isArray(Te.models)){const Xe=Te.models.find(kt=>kt.id===Y)?.name;return typeof Xe=="string"?Xe:void 0}}},[P,X,Y,w]),K=i.useMemo(()=>{if(P||!X||!Y)return!1;const Te=w.find(Xe=>Xe.id===X);if(!Te?.models||!Array.isArray(Te.models))return!1;const Ve=Te.models.find(Xe=>Xe.id===Y)?.variants;return!!(Ve&&Object.keys(Ve).length>0)},[P,Y,X,w]),ae=vi(Q),F=vi(X??void 0),$=vi(re),R=ae??void 0,B=F??null,z=$??void 0,G=i.useMemo(()=>{const Te=s.info.time;return typeof Te?.completed=="number"?Te.completed:null},[s.info.time]),ge=i.useMemo(()=>P?!0:!!(G&&G>0),[P,G]),oe=i.useMemo(()=>{const Te=s.info.finish;return typeof Te=="string"?Te:void 0},[s.info]),me=i.useMemo(()=>Ew(O,{includeReasoning:N}),[O,N]),Ne=i.useMemo(()=>P||ge?me:[],[P,ge,me]),Ce=i.useMemo(()=>P?[]:me.filter(Te=>Te.type==="text"),[P,me]),Be=i.useMemo(()=>P?[]:me.filter(st=>st.type==="tool"),[P,me]),V=i.useMemo(()=>{if(x==="collapsed"||x==="activity")return S;const Te=new Set;for(const Ve of Be){const Xe=Ve.tool;Ve.id&&Nd(Xe)&&Te.add(Ve.id)}if(l?.isFirstAssistantInTurn)for(const Ve of l.activityParts){if(Ve.kind!=="tool")continue;const Xe=Ve.part;Xe.id&&Nd(Xe.tool)&&Te.add(Xe.id)}const st=new Set(Te);for(const Ve of S)st.has(Ve)?st.delete(Ve):st.add(Ve);return st},[S,x,Be,l]),J=i.useMemo(()=>{if(!P)return;const Te=s.parts.find(kt=>kt.type==="agent");if(!Te)return;const st=Te,Ve=typeof st.name=="string"?st.name:void 0;if(!Ve)return;const Xe=st.source&&typeof st.source.value=="string"&&st.source.value.trim().length>0?st.source.value:`#${Ve}`;return{name:Ve,token:Xe}},[P,s.parts]),ee=typeof oe!="string",xe=i.useMemo(()=>P?!1:Ce.length===0||Be.length===0?ee:!0,[Ce.length,Be.length,ee,P]),fe=u?.metadata.variant,Oe=i.useMemo(()=>fe?fe==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[fe]),Se=i.useMemo(()=>u?Ll(u):Oe?Ov:$v,[u,Oe]),Le=i.useMemo(()=>P?!1:Pr.getInstance().shouldAnimateMessage(s.info,y||s.info.sessionID),[s.info,y,P]),pe=i.useRef(!1),it=i.useMemo(()=>r?bi(r.info):null,[r]),xt=i.useMemo(()=>t?bi(t.info):null,[t]),Mt=i.useMemo(()=>P||!xt?!1:!xt.isUser&&xt.role==="assistant",[P,xt]),De=i.useMemo(()=>ge?"completed":p||(g?"streaming":"completed"),[ge,p,g]),ne=i.useMemo(()=>{if(P)return!0;const Te=l?.headerMessageId;if(Te){if(s.info.id===Te){if(De==="completed")return!0;const Ve=De==="streaming"||De==="cooldown",Xe=pe.current;return Ve&&!Xe&&(pe.current=!0),Xe||Ve}return!1}return it?it.isUser:!0},[P,it,l,De,s.info]),rt=i.useCallback(Te=>{navigator.clipboard.writeText(Te),A(Te),setTimeout(()=>A(null),2e3)},[]),be=l?.turnId,ke=St(Te=>{if(!be)return;const st=s.info.sessionID;if(!st)return;const Ve=Te.messages.get(st);if(!Ve)return;const Xe=Ve.find(ts=>ts.info?.id===be);if(!Xe)return;const Lt=Xe.info.summary?.body;return typeof Lt=="string"&&Lt.trim().length>0?Lt:void 0}),Qe=St(Te=>{if(!be)return;const st=s.info.sessionID;if(!st)return;const Ve=Te.messages.get(st);if(!Ve)return;const Xe=Ve.find(Lt=>Lt.info?.id===be);if(!Xe)return;const kt=Xe.info.variant;return typeof kt=="string"&&kt.trim().length>0?kt:void 0}),tt=P?void 0:Qe??U?.variant,He=!P&&K?tt??"Default":void 0,Re=typeof l?.summaryBody=="string"&&l.summaryBody.trim().length>0?l.summaryBody:ke,nt=i.useRef(void 0);Re&&Re.trim().length>0&&(nt.current=Re);const yt=i.useRef(be);yt.current!==be&&(yt.current=be,nt.current=void 0);const ct=nt.current,It=i.useMemo(()=>{if(P)return;const Te=s.info?.error;if(!Te)return;const st=typeof Te.data?.message=="string"?Te.data.message:void 0,Ve=typeof Te.message=="string"?Te.message:void 0,Xe=typeof Te.name=="string"?Te.name:void 0,kt=st||Ve||Xe;if(kt)return`Opencode failed to send message with error:
|
|
113
113
|
\`${kt}\``},[P,s.info]),Tt=i.useMemo(()=>P?Ne.filter(Ve=>Ve.type==="text").map(Ve=>(Ve.text||Ve.content||"").trim()).filter(Ve=>Ve.length>0).join(`
|
|
114
114
|
`).replace(/\n\s*\n+/g,`
|
|
115
115
|
`):It&&It.trim().length>0?It:ct&&ct.trim().length>0?ct:Sl(Ne),[It,ct,Ne,P]),je=Tt.length>0,ze=i.useCallback(()=>{navigator.clipboard.writeText(Tt),M(!0),setTimeout(()=>M(!1),2e3)},[Tt]),Ze=he(Te=>Te.revertToMessage),Ye=he(Te=>Te.forkFromMessage),mt=i.useCallback(()=>{!W||!s.info.id||Ze(W,s.info.id)},[W,s.info.id,Ze]),ye=i.useCallback(()=>{!W||!s.info.id||Ye(W,s.info.id)},[W,s.info.id,Ye]),ie=i.useCallback(Te=>{D(st=>{const Ve=new Set(st);return Ve.has(Te)?Ve.delete(Te):Ve.add(Te),Ve})},[]),de=o??null,We=i.useRef(!1),Ge=i.useRef(!1),bt=i.useRef(!1),Z=i.useRef(!1),we=i.useRef(!1);i.useEffect(()=>{Ge.current=!1,bt.current=!1,Z.current=!1,we.current=!1,We.current=!1},[s.info.id]);const ve=i.useCallback(()=>{P||We.current||(We.current=!0,n?.("structural"))},[P,n]),Ue=i.useCallback(Te=>{Te.image&&T(Te)},[]),_e=i.useCallback(Te=>{T(st=>({...st,open:Te}))},[]),et=!!sr(s.info,"animationSettled"),pt=De==="streaming",ft=i.useMemo(()=>P?!1:me.some(Te=>Te.type==="reasoning"),[P,me]),Pt=Le&&!et&&!pt,At=!P&&Le&&Ce.length>0&&!xe;return i.useEffect(()=>{if(de?.onStreamingCandidate){if(!At){bt.current&&(ft&&de?.onReasoningBlock?de.onReasoningBlock():de?.onReservationCancelled&&de.onReservationCancelled(),bt.current=!1);return}we.current||(we.current=!0,de.onStreamingCandidate(),bt.current=!0)}},[de,At,ft]),i.useEffect(()=>{de?.onAnimationStart&&Pt&&(Z.current||(de.onAnimationStart(),Z.current=!0))},[de,Pt]),i.useEffect(()=>{if(P)return;const Te=de?.onAnimatedHeightChange;if(!Te||!(Pt||At))return;const Ve=m.current;if(!Ve)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Te(Ve.getBoundingClientRect().height);return}let Xe=null;const kt=ts=>{if(typeof window>"u"){Te(ts);return}Xe!==null&&window.cancelAnimationFrame(Xe),Xe=window.requestAnimationFrame(()=>{Te(ts)})},Lt=new ResizeObserver(ts=>{const ns=ts[0];ns&&kt(ns.contentRect.height)});return Lt.observe(Ve),kt(Ve.getBoundingClientRect().height),()=>{Xe!==null&&(window.cancelAnimationFrame(Xe),Xe=null),Lt.disconnect()}},[Pt,P,de,At]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:_("group w-full",ne?"pt-2":"pt-0",P?"pb-2":Mt?"pb-0":"pb-2"),"data-message-id":s.info.id,ref:m,style:a?{visibility:"hidden"}:void 0,children:e.jsx("div",{className:"chat-column",children:P?e.jsx(gs,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-xl rounded-br-xs bg-primary/10 dark:bg-primary/8 px-3.5 pt-2.5 pb-1.5",children:e.jsx(kd,{messageId:s.info.id,parts:me,isUser:P,isMessageCompleted:ge,messageFinish:oe,syntaxTheme:Se,isMobile:c,hasTouchInput:d,copiedCode:k,onCopyCode:rt,expandedTools:S,onToggleTool:ie,onShowPopup:Ue,streamPhase:De,allowAnimation:Pt,onContentChange:n,shouldShowHeader:!1,hasTextContent:je,onCopyMessage:ze,copiedMessage:C,showReasoningTraces:N,onAuxiliaryContentComplete:ve,agentMention:J,onRevert:mt,onFork:P?ye:void 0,errorMessage:It})})})}):e.jsxs("div",{children:[ne&&e.jsx(Bv,{isUser:P,providerID:B,agentName:R,modelName:z,variant:He,isDarkTheme:Oe}),e.jsx(kd,{messageId:s.info.id,parts:me,isUser:P,isMessageCompleted:ge,messageFinish:oe,messageCompletedAt:G??void 0,syntaxTheme:Se,isMobile:c,hasTouchInput:d,copiedCode:k,onCopyCode:rt,expandedTools:V,onToggleTool:ie,onShowPopup:Ue,streamPhase:De,allowAnimation:Pt,onContentChange:n,shouldShowHeader:ne,hasTextContent:je,onCopyMessage:ze,copiedMessage:C,onAuxiliaryContentComplete:ve,showReasoningTraces:N,agentMention:J,turnGroupingContext:l,errorMessage:It})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(Ow,{popup:E,onOpenChange:_e,syntaxTheme:Se,isMobile:c})})]})},Bw=i.memo(Lw),zw=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:mf(s).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||t?.split("/").pop()||"file"} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,l)=>e.jsxs("div",{className:_("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(or,{style:r,language:fr(t||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))}),Ww=({content:s,syntaxTheme:r,filePath:t})=>{const n=s.split(`
|
|
@@ -132,7 +132,7 @@ ${q}`;X(""),H(null),oe("chat");try{await K(bt,Ze,Ye,je,void 0,void 0,void 0,mt)}
|
|
|
132
132
|
Use $ARGUMENTS to reference user input.
|
|
133
133
|
Use !\`shell command\` to inject shell output.
|
|
134
134
|
Use @filename to include file contents.`,rows:12,className:"font-mono typography-meta"}),e.jsxs("div",{className:"typography-meta text-muted-foreground/80 space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Template Features:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 ml-2",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"$ARGUMENTS"}),e.jsx("span",{children:"- User input after command"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Replaced with everything the user types after the command name.",e.jsx("br",{}),'Example: "/deploy staging" makes $ARGUMENTS = "staging"']})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"!`command`"}),e.jsx("span",{children:"- Inject shell command output"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Executes shell command and replaces this placeholder with its output.",e.jsx("br",{}),"Example: !`git branch --show-current` gets current branch name"]})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"@filename"}),e.jsx("span",{children:"- Include file contents"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Replaces with the full contents of the specified file.",e.jsx("br",{}),"Example: @package.json includes the package.json content in the prompt"]})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ie,{size:"sm",variant:"default",onClick:M,disabled:A,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Da,{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(_r,{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"})]})})},Sj=({onItemSelect:s})=>{const[r,t]=i.useState(null),[n,o]=i.useState(""),{selectedSkillName:a,skills:l,setSelectedSkill:c,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=Gs(),{setSidebarOpen:g}=$e(),{isMobile:y}=$t(),[h,j]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||j(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const v=h?"bg-transparent":b?"bg-background":"bg-sidebar",w=()=>{const S="new-skill";let D=S,E=1;for(;l.some(T=>T.name===D);)D=`${S}-${E}`,E++;d({name:D,scope:"user",description:""}),c(D),s?.(),y&&g(!1)},N=async S=>{window.confirm(`Are you sure you want to delete skill "${S.name}"?`)&&(await m(S.name)?te.success(`Skill "${S.name}" deleted successfully`):te.error("Failed to delete skill"))},x=async S=>{const D=S.name;let E=1,T=`${D}-copy`;for(;l.some(P=>P.name===T);)E++,T=`${D}-copy-${E}`;const I=await p(S.name);if(!I){te.error("Failed to load skill details for duplication");return}d({name:T,scope:S.scope||"user",description:(I.sources.md.fields.includes("description"),""),instructions:""}),c(T),y&&g(!1)},k=S=>{o(S.name),t(S)},A=async()=>{if(!r)return;const S=n.trim().replace(/\s+/g,"-").toLowerCase();if(!S){te.error("Skill name is required");return}if(S===r.name){t(null);return}if(l.some(T=>T.name===S)){te.error("A skill with this name already exists");return}if(!await p(r.name)){te.error("Failed to load skill details"),t(null);return}await u({name:S,description:"Renamed skill",scope:r.scope})?await m(r.name)?(te.success(`Skill renamed to "${S}"`),c(S)):te.error("Failed to remove old skill after rename"):te.error("Failed to rename skill"),t(null)},C=l.filter(S=>S.scope==="project"),M=l.filter(S=>S.scope==="user");return e.jsxs("div",{className:_("flex h-full flex-col",v),children:[e.jsx("div",{className:_("border-b px-3",y?"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(Ie,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(Xt,{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($u,{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:[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:"Project Skills"}),C.map(S=>e.jsx(Vd,{skill:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),y&&g(!1)},onRename:()=>k(S),onDelete:()=>N(S),onDuplicate:()=>x(S)},S.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(S=>e.jsx(Vd,{skill:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),y&&g(!1)},onRename:()=>k(S),onDelete:()=>N(S),onDuplicate:()=>x(S)},S.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:S=>!S&&t(null),children:e.jsxs(fs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Rename Skill"}),e.jsxs(Ms,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:S=>o(S.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&A()}}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(on,{onClick:A,children:"Rename"})]})]})})]})},Vd=({skill:s,isSelected:r,onSelect:t,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:_("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:t,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:s.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:s.scope}),s.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(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(Ie,{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(Or,{className:"h-3.5 w-3.5"})})}),e.jsxs(Qt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(Et,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(uo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Et,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(Et,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function Mf({tabs:s,value:r,onValueChange:t,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:g}=m,y=Math.max(0,Math.min(100,p/f*100)),h=Math.max(0,Math.min(100,(p+g)/f*100));u.style.clipPath=`inset(0 ${Number(100-h).toFixed(2)}% 0 ${Number(y).toFixed(2)}% round 8px)`},[]);return i.useLayoutEffect(()=>{d()},[d,r,s.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:_("relative isolate w-full",n),children:[e.jsx("div",{ref:l,"aria-hidden":!0,className:_("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:s.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:s.map(u=>{const m=r===u.value,f=u.icon;return e.jsxs("button",{ref:m?c:null,type:"button",onClick:()=>{o&&t(u.value)},className:_("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:_("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const kj=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,Nj=s=>{const r=s.trim(),t=r.match(/^git@github\.com:([^/\s]+)\/([^\s#]+)$/i);if(t)return`${t[1]}/${t[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},Cj=async()=>{try{if(es())return await Lr();const s=Qs()?.settings;if(s)return(await s.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}},Mj=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=mo(),a=In(S=>S.defaultGitIdentityId),l=In(S=>S.loadDefaultGitIdentityId),[c,d]=i.useState(""),[u,m]=i.useState(""),[f,p]=i.useState(""),[g,y]=i.useState([]),[h,j]=i.useState(null),[b,v]=i.useState(!1),[w,N]=i.useState([]),[x,k]=i.useState(null);i.useEffect(()=>{s&&(d(""),m(""),p(""),j(null),v(!1),N([]),k(null),l(),(async()=>{const S=await Cj(),D=Array.isArray(S?.skillCatalogs)?S?.skillCatalogs:[];y(D||[])})())},[s,l]);const A=i.useMemo(()=>{const S=u.trim(),D=f.trim();return g.some(E=>{const T=(E.source||"").trim(),I=(E.subpath||"").trim();return T===S&&I===D})},[g,u,f]),C=async()=>{const S=u.trim();if(!S){te.error("Repository source is required");return}c.trim()||d(Nj(S)),v(!1),j(null);const D=await t({source:S,subpath:f.trim()||void 0,gitIdentityId:x||void 0});if(!D.ok){if(D.error?.kind==="authRequired"){if(Wt()){te.error("Private repositories are not supported in VS Code yet");return}const T=D.error.identities||[];if(N(T),!x&&T.length>0){const I=a&&a!=="global"&&T.some(P=>P.id===a)?a:T[0].id;k(I)}te.error("Authentication required. Select a Git identity and scan again.");return}te.error(D.error?.message||"Failed to scan repository");return}const E=D.items?.length||0;if(j(E),E===0){te.error("No skills found in this repository"),v(!1);return}N([]),v(!0),te.success(`Found ${E} skill(s)`)},M=async()=>{const S=c.trim(),D=u.trim(),E=f.trim();if(!S){te.error("Catalog name is required");return}if(!D){te.error("Repository source is required");return}if(!b){te.error("Scan the repository before adding this catalog");return}if(A){te.error("This catalog already exists");return}const T={id:kj(),label:S,source:D,...E?{subpath:E}:{},...x?{gitIdentityId:x}:{}},I=[...g,T];try{await ss({skillCatalogs:I}),y(I),te.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(P){te.error(P instanceof Error?P.message:"Failed to save catalog")}};return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Add skills catalog"}),e.jsxs(Ms,{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:S=>d(S.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:S=>{m(S.target.value),v(!1),j(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:S=>{p(S.target.value),v(!1),j(null)},placeholder:"e.g. skills"})]}),w.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(ks,{value:x||"",onValueChange:S=>k(S),children:[e.jsx(Ns,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:w.find(S=>S.id===x)?.name||"Choose identity"})}),e.jsx(Cs,{align:"start",children:w.map(S=>e.jsx(Ut,{value:S.id,className:"pr-2 [&>span:first-child]:hidden",children:S.name},S.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,h!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",h," skill(s) found"]}):null,A?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(Ie,{variant:"outline",onClick:()=>{C()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(Oh,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Ie,{variant:"default",onClick:()=>{M()},disabled:!b||A||!c.trim()||!u.trim(),children:"Add catalog"})]})]})})},Dj=({open:s,onOpenChange:r,conflicts:t,onConfirm:n})=>{const[o,a]=i.useState({});i.useEffect(()=>{if(!s)return;const d={};for(const u of t)d[u.skillName]="skip";a(d)},[s,t]);const l=d=>{const u={};for(const m of t)u[m.skillName]=d;a(u)},c=t.length>0&&t.every(d=>o[d.skillName]);return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-2xl",children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Skills already exist"}),e.jsx(Ms,{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:[t.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{variant:"outline",size:"sm",onClick:()=>l("skip"),children:"Skip all"}),e.jsx(Ie,{variant:"outline",size:"sm",onClick:()=>l("overwrite"),children:"Overwrite all"})]})]}),e.jsx("div",{className:"space-y-2",children:t.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(ks,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Ns,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(Cs,{align:"end",children:[e.jsx(Ut,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Ut,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(on,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},Aj=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=mo(),[a,l]=i.useState("user"),[c,d]=i.useState(!1),[u,m]=i.useState([]),[f,p]=i.useState(null);i.useEffect(()=>{s&&(l("user"),d(!1),m([]),p(null))},[s]);const g=async y=>{const h={skillDir:y.skillDir};t?.clawdhub&&(h.clawdhub={slug:t.clawdhub.slug,version:t.clawdhub.version});const j=await n({source:y.source,subpath:y.subpath,gitIdentityId:t?.gitIdentityId,scope:y.scope,selections:[h],conflictPolicy:"prompt",conflictDecisions:y.conflictDecisions});if(j.ok){te.success("Skill installed successfully"),r(!1);return}if(j.error?.kind==="conflicts"){p({source:y.source,subpath:y.subpath,scope:y.scope,skillDir:y.skillDir}),m(j.error.conflicts),d(!0);return}if(j.error?.kind==="authRequired"){te.error(j.error.message||"Authentication required");return}te.error(j.error?.message||"Failed to install skill")};return t?e.jsxs(e.Fragment,{children:[e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Install skill"}),e.jsxs(Ms,{children:["Install ",e.jsx("span",{className:"font-semibold text-foreground",children:t.skillName})," into user or project scope."]})]}),e.jsx("div",{className:"space-y-3",children:t.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:t.warnings.map(y=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:y},y))})]}):null}),e.jsxs(Js,{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(ks,{value:a,onValueChange:y=>l(y),children:[e.jsx(Ns,{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(Os,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Cs,{align:"start",children:[e.jsx(Ut,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Ut,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ur,{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(Ie,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Ie,{className:"w-full sm:w-auto",variant:"default",disabled:o||!t.installable,onClick:()=>{g({source:t.repoSource,subpath:t.repoSubpath,scope:a,skillDir:t.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(Dj,{open:c,onOpenChange:d,conflicts:u,onConfirm:y=>{f&&(g({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:y}),d(!1))}})]}):null},Ej=async()=>{try{if(es())return await Lr();const s=Qs()?.settings;if(s)return(await s.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}},Ij=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:l,isLoadingCatalog:c,lastCatalogError:d}=mo(),[u,m]=i.useState(""),[f,p]=i.useState(!1),[g,y]=i.useState(!1),[h,j]=i.useState(null),[b,v]=i.useState(!1);i.useEffect(()=>{l()},[l]);const w=i.useMemo(()=>o?n[o]||[]:[],[n,o]),N=i.useMemo(()=>{const C=u.trim().toLowerCase();return C?w.filter(M=>{const S=M.skillName.toLowerCase(),D=(M.description||"").toLowerCase(),E=(M.frontmatterName||"").toLowerCase();return S.includes(C)||D.includes(C)||E.includes(C)}):w},[w,u]),x=i.useMemo(()=>t.find(C=>C.id===o)||null,[t,o]),k=!!(o&&o.startsWith("custom:")),A=async()=>{if(!(!o||!k)&&window.confirm("Remove this catalog?")){v(!0);try{const C=await Ej(),S=(Array.isArray(C?.skillCatalogs)?C?.skillCatalogs:[]).filter(D=>D.id!==o);await ss({skillCatalogs:S}),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(Mf,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:s,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(ks,{value:o||"",onValueChange:C=>a(C),children:[e.jsx(Ns,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:x?.label||"Select source"})}),e.jsx(Cs,{align:"start",children:t.map(C=>e.jsx(Ut,{value:C.id,className:"pr-2 [&>span:first-child]:hidden",children:C.label},C.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ie,{type:"button",variant:"outline",onClick:()=>{l({refresh:!0})},disabled:c,className:"gap-2",children:[e.jsx(jr,{className:"h-4 w-4"}),"Refresh"]}),k?e.jsxs(Ie,{type:"button",variant:"outline",onClick:()=>{A()},disabled:b,className:"gap-2",children:[e.jsx(Xs,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Ie,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(Xt,{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:C=>m(C.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(C=>{const M=C.installed?.isInstalled,S=C.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:C.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 (",S||"unknown",")"]}):null,C.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"})]}),C.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:C.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),C.clawdhub?e.jsxs("div",{className:"typography-micro text-muted-foreground mt-1 flex items-center gap-3",children:[C.clawdhub.owner?e.jsxs("span",{children:["by ",C.clawdhub.owner]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"}),C.clawdhub.downloads?.toLocaleString()??0]}),(C.clawdhub.stars??0)>0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wn,{className:"h-3 w-3"}),C.clawdhub.stars]}):null,e.jsxs("span",{children:["v",C.clawdhub.version]})]}):null,C.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:C.warnings.join(" · ")}):null]}),e.jsx(Ie,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!C.installable,onClick:()=>{j(C),y(!0)},children:"Install"})]})},`${C.sourceId}:${C.skillDir}`)})}),e.jsx(Mj,{open:f,onOpenChange:p}),e.jsx(Aj,{open:g,onOpenChange:y,item:h})]})})},Pj=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:l,setSkillDraft:c,setSelectedSkill:d}=Gs(),u=s?r(s):null,m=!!(l&&l.name===s&&!u),f=!!(s&&!u&&!l),[p,g]=i.useState("manual");i.useEffect(()=>{!m&&p!=="manual"&&g("manual")},[m,p]),i.useEffect(()=>{f&&d(null)},[f,d]);const y=m?e.jsx(Mf,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:g,animate:!1}):null,[h,j]=i.useState(""),[b,v]=i.useState("user"),[w,N]=i.useState(""),[x,k]=i.useState(""),[A,C]=i.useState([]),[M,S]=i.useState([]),[D,E]=i.useState(!1),[T,I]=i.useState(!1),[P,O]=i.useState(""),[U,Q]=i.useState(""),[W,L]=i.useState(!1),[H,q]=i.useState(""),[X,Y]=i.useState(""),[re,K]=i.useState(null),[ae,F]=i.useState(!1),[$,R]=i.useState(""),B=m?h.trim()!==""||w.trim()!==""||x.trim()!==""||M.length>0:w!==P||x!==U,z=re?X!==$:H.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&l)j(l.name||""),v(l.scope||"user"),N(l.description||""),k(l.instructions||""),O(""),Q(""),C([]),S(l.pendingFiles||[]);else if(s&&u){I(!0);try{const Be=await t(s);if(Be){const V=Be.sources.md;N(V.description||""),k(V.instructions||""),O(V.description||""),Q(V.instructions||""),C(V.supportingFiles||[])}}catch(Be){console.error("Failed to load skill details:",Be)}finally{I(!1)}}})()},[u,m,s,a,l,t,p]);const G=async()=>{const Ce=m?h.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!Ce){te.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(Ce)||Ce.length>64){te.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!w.trim()){te.error("Description is required");return}if(m&&a.some(Be=>Be.name===Ce)){te.error("A skill with this name already exists");return}E(!0);try{const Be={name:Ce,description:w.trim(),instructions:x.trim()||void 0,scope:m?b:void 0,supportingFiles:m&&M.length>0?M:void 0};let V;m?(V=await n(Be),V&&(c(null),S([]),d(Ce))):(V=await o(Ce,Be),V&&(O(w.trim()),Q(x.trim()))),V?te.success(m?"Skill created successfully":"Skill updated successfully"):te.error(m?"Failed to create skill":"Failed to update skill")}catch(Be){console.error("Error saving skill:",Be),te.error("An error occurred while saving")}finally{E(!1)}},ge=()=>{K(null),q(""),Y(""),R(""),L(!0)},oe=async Ce=>{if(K(Ce),q(Ce),m){const V=M.find(J=>J.path===Ce)?.content||"";Y(V),R(V),L(!0);return}if(s){F(!0),L(!0);try{const{readSupportingFile:Be}=Gs.getState(),V=await Be(s,Ce);Y(V||""),R(V||"")}catch{te.error("Failed to load file content"),Y(""),R("")}finally{F(!1)}}},me=async()=>{if(!H.trim()){te.error("File name is required");return}const Ce=H.trim(),Be=re!==null;if(m){if(Be)S(ee=>ee.map(xe=>xe.path===re?{path:Ce,content:X}:xe)),te.success(`File "${Ce}" updated`);else{if(M.some(ee=>ee.path===Ce)){te.error("A file with this name already exists");return}S(ee=>[...ee,{path:Ce,content:X}]),te.success(`File "${Ce}" added`)}L(!1),K(null);return}if(!s){te.error("No skill selected");return}const{writeSupportingFile:V}=Gs.getState();if(await V(s,Ce,X)){te.success(Be?`File "${Ce}" updated`:`File "${Ce}" created`),L(!1),K(null);const ee=await t(s);ee&&C(ee.sources.md.supportingFiles||[])}else te.error(Be?"Failed to update file":"Failed to create file")},Ne=async Ce=>{if(m){S(Be=>Be.filter(V=>V.path!==Ce)),te.success(`File "${Ce}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${Ce}"?`)){const{deleteSupportingFile:Be}=Gs.getState();if(await Be(s,Ce)){te.success(`File "${Ce}" deleted`);const J=await t(s);J&&C(J.sources.md.supportingFiles||[])}else te.error("Failed to delete file")}};return m&&p==="external"?e.jsx(Ij,{mode:p,onModeChange:g}):!s&&!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($u,{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"})]})}):T?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?y:null,e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:m?"New Skill":s}),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:h,onChange:Ce=>j(Ce.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(ks,{value:b,onValueChange:Ce=>v(Ce),children:[e.jsxs(Ns,{className:"!h-9 w-auto gap-1.5",children:[b==="user"?e.jsx(Os,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:b})]}),e.jsxs(Cs,{align:"end",children:[e.jsx(Ut,{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(Os,{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(Ut,{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(ur,{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(Ss,{value:w,onChange:Ce=>N(Ce.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(Ss,{value:x,onChange:Ce=>k(Ce.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(Ie,{variant:"outline",size:"sm",onClick:ge,className:"gap-1.5",children:[e.jsx(Xt,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const Ce=m?M:A;return Ce.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:Ce.map(Be=>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:()=>oe(Be.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(nr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:Be.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(Ie,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:V=>{V.stopPropagation(),Ne(Be.path)},children:e.jsx(Xs,{className:"h-3.5 w-3.5"})})]},Be.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ie,{size:"sm",variant:"default",onClick:G,disabled:D||!B,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Da,{className:"h-3 w-3"}),D?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(ms,{open:W,onOpenChange:Ce=>{L(Ce),Ce||K(null)},children:e.jsxs(fs,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(ys,{className:"flex-shrink-0",children:[e.jsx(bs,{children:re?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ms,{children:re?"Modify the file content":"Create a new file in the skill directory"})]}),ae?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:H,onChange:Ce=>q(Ce.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:re!==null}),!re&&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(Ss,{value:X,onChange:Ce=>Y(Ce.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>{L(!1),K(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(on,{onClick:me,disabled:ae||!z,children:re?"Save Changes":"Create File"})]})]})})]})})},Tj="__add_provider__",Fj=({onItemSelect:s})=>{const r=at(u=>u.providers),t=at(u=>u.selectedProviderId),n=at(u=>u.setSelectedProvider),{isMobile:o}=$t(),[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:_("flex h-full flex-col",d),children:[e.jsx("div",{className:_("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(Ie,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(Tj),s?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(Xt,{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(to,{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===t;return e.jsx("div",{className:_("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),s?.()},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(cs,{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)})})]})},Rj=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Gd=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=Rj.format(s);return r.endsWith(".0")?r.slice(0,-2):r},qd="__add_provider__",Pn=s=>typeof s=="object"&&s!==null,Kd=s=>{const r=typeof s.type=="string"?s.type:"",t=`${s.name??""} ${s.label??""}`.toLowerCase(),n=`${r} ${t}`.toLowerCase();return n.includes("oauth")?"oauth":n.includes("api")?"api":r.toLowerCase()},_j=s=>{if(!Pn(s))return{};const r={};for(const[t,n]of Object.entries(s))Array.isArray(n)&&(r[t]=n.filter(o=>Pn(o)));return r},Oj=s=>{if(typeof s=="string")return{id:s};if(!Pn(s))return null;const r=typeof s.id=="string"&&s.id||typeof s.providerID=="string"&&s.providerID||typeof s.slug=="string"&&s.slug||typeof s.name=="string"&&s.name;if(!r)return null;const t=typeof s.name=="string"?s.name:void 0;return{id:r,name:t}},$j=s=>{let r=[];Array.isArray(s)?r=s:Pn(s)&&(Array.isArray(s.all)?r=s.all:Array.isArray(s.providers)&&(r=s.providers));const t=r.map(o=>Oj(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},Lj=()=>{const s=at(R=>R.providers),r=at(R=>R.selectedProviderId),t=at(R=>R.setSelectedProvider),n=at(R=>R.getModelMetadata),[o,a]=i.useState({}),[l,c]=i.useState(!1),[d,u]=i.useState({}),[m,f]=i.useState(null),[p,g]=i.useState(""),[y,h]=i.useState(null),[j,b]=i.useState({}),[v,w]=i.useState({}),[N,x]=i.useState([]),[k,A]=i.useState(!1),[C,M]=i.useState(null),[S,D]=i.useState(""),[E,T]=i.useState(""),[I,P]=i.useState(!1);i.useEffect(()=>{!r&&s.length>0&&t(s[0].id)},[s,r,t]),i.useEffect(()=>{let R=!0;return(async()=>{c(!0);try{const z=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!z.ok)throw new Error(`Auth methods request failed (${z.status})`);const G=await z.json().catch(()=>({}));if(!R)return;a(_j(G))}catch(z){if(!R)return;console.error("Failed to load provider auth methods:",z),te.error("Failed to load provider authentication methods")}finally{R&&c(!1)}})(),()=>{R=!1}},[]),i.useEffect(()=>{let R=!0;return(async()=>{A(!0),M(null);try{const z=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!z.ok)throw new Error(`Provider list request failed (${z.status})`);const G=await z.json().catch(()=>({}));if(!R)return;x($j(G))}catch(z){if(!R)return;console.error("Failed to load available providers:",z),M("Unable to load provider list")}finally{R&&A(!1)}})(),()=>{R=!1}},[]);const O=i.useMemo(()=>new Set(s.map(R=>R.id)),[s]),U=i.useMemo(()=>N.filter(R=>!O.has(R.id)),[N,O]);i.useEffect(()=>{if(r===qd){if(!S&&U.length>0){D(U[0].id);return}S&&!U.some(R=>R.id===S)&&D(U[0]?.id??"")}},[r,S,U]);const Q=s.find(R=>R.id===r),W=async R=>{const B=d[R]?.trim()??"";if(!B){te.error("API key is required");return}const z=`api:${R}`;f(z);try{const G=await fetch(`/api/auth/${encodeURIComponent(R)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:B})}),ge=await G.json().catch(()=>null);if(!G.ok){const oe=ge?.error||"Failed to save API key";throw new Error(oe)}te.success("API key saved"),u(oe=>({...oe,[R]:""})),await qn({scopes:["providers"],mode:"active"}),t(R)}catch(G){console.error("Failed to save API key:",G),te.error("Failed to save API key")}finally{f(null)}},L=async(R,B)=>{const z=`oauth:${R}:${B}`;f(z);try{const G=await fetch(`/api/provider/${encodeURIComponent(R)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:B})}),ge=await G.json().catch(()=>null);if(!G.ok){const J=ge?.error||"Failed to start OAuth flow";throw new Error(J)}const oe=Pn(ge)?ge:{},me=Pn(oe.data)?oe.data:oe,Ne=typeof me.url=="string"&&me.url||typeof me.verification_uri_complete=="string"&&me.verification_uri_complete||typeof me.verification_uri=="string"&&me.verification_uri||void 0,Ce=typeof me.instructions=="string"&&me.instructions||typeof me.message=="string"&&me.message||void 0,Be=typeof me.user_code=="string"&&me.user_code||typeof me.code=="string"&&me.code||typeof me.userCode=="string"&&me.userCode||void 0;if(!Ne&&!Ce&&!Be)throw new Error("No OAuth details returned");const V=`${R}:${B}`;w(J=>({...J,[V]:{url:Ne,instructions:Ce,userCode:Be}})),Ne&&window.open(Ne,"_blank","noopener,noreferrer"),h({providerId:R,methodIndex:B}),te.message("Complete the OAuth flow in your browser")}catch(G){console.error("Failed to start OAuth flow:",G),te.error("Failed to start OAuth flow")}finally{f(null)}},H=async(R,B)=>{const z=`${R}:${B}`,G=j[z]?.trim(),ge=`oauth-complete:${R}:${B}`;f(ge);try{const oe={method:B};G&&(oe.code=G);const me=await fetch(`/api/provider/${encodeURIComponent(R)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(oe)}),Ne=await me.json().catch(()=>null);if(!me.ok){const Ce=Ne?.error||"Failed to complete OAuth flow";throw new Error(Ce)}te.success("OAuth connection completed"),b(Ce=>({...Ce,[z]:""})),h(null),await qn({scopes:["providers"],mode:"active"}),t(R)}catch(oe){console.error("Failed to complete OAuth flow:",oe),te.error("Failed to complete OAuth flow")}finally{f(null)}},q=async R=>{try{await navigator.clipboard.writeText(R),te.success("OAuth link copied")}catch(B){console.error("Failed to copy OAuth link:",B),te.error("Failed to copy OAuth link")}},X=async R=>{try{await navigator.clipboard.writeText(R),te.success("Device code copied")}catch(B){console.error("Failed to copy device code:",B),te.error("Failed to copy device code")}},Y=async R=>{const B=`disconnect:${R}`;f(B);try{const z=await fetch(`/api/provider/${encodeURIComponent(R)}/auth`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),G=await z.json().catch(()=>null);if(!z.ok){const ge=G?.error||"Failed to disconnect provider";throw new Error(ge)}te.success("Provider disconnected"),await qn({scopes:["providers"],mode:"active"})}catch(z){console.error("Failed to disconnect provider:",z),te.error("Failed to disconnect provider")}finally{f(null)}},re=r===qd;if(!re&&s.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(to,{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(re)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…"}):C?e.jsx("p",{className:"typography-meta text-muted-foreground",children:C}):U.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(qt,{open:I,onOpenChange:R=>{P(R),R||T("")},children:[e.jsx(Kt,{asChild:!0,children:e.jsxs("button",{type:"button",className:_("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:S?"text-foreground":"text-muted-foreground",children:S?U.find(R=>R.id===S)?.name||S:"Select provider"}),e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(Qt,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:R=>R.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:R=>R.stopPropagation(),children:[e.jsx(lr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:E,onChange:R=>T(R.target.value),onKeyDown:R=>R.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 R=U.filter(B=>{const z=E.toLowerCase();return(B.name||B.id).toLowerCase().includes(z)||B.id.toLowerCase().includes(z)});return R.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):R.map(B=>e.jsxs(Et,{onSelect:()=>{D(B.id),P(!1),T("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:B.name||B.id}),S===B.id&&e.jsx(_t,{className:"h-4 w-4 text-primary"})]},B.id))})()})]})]})]}),S&&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[S]??"",onChange:R=>u(B=>({...B,[S]:R.target.value})),placeholder:"sk-..."}),e.jsx(Ie,{size:"sm",onClick:()=>W(S),disabled:m===`api:${S}`,className:"h-8",children:m===`api:${S}`?"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 B=(o[S]??[]).filter(z=>Kd(z)==="oauth");return B.length===0?null:e.jsx("div",{className:"space-y-3",children:B.map((z,G)=>{const ge=z.label||z.name||`OAuth method ${G+1}`,oe=`${S}:${G}`,me=y?.providerId===S&&y?.methodIndex===G;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:ge}),(z.description||z.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(z.description||z.help)})]}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>L(S,G),disabled:m===`oauth:${S}:${G}`,className:"h-8",children:"Connect"})]}),v[oe]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[oe]?.instructions}),v[oe]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[oe]?.userCode,readOnly:!0}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>X(v[oe]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[oe]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[oe]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ie,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[oe]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>q(v[oe]?.url??""),className:"h-8",children:"Copy link"})]})]}),me&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:j[oe]??"",onChange:Ne=>b(Ce=>({...Ce,[oe]:Ne.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Ie,{size:"sm",onClick:()=>H(S,G),disabled:m===`oauth-complete:${S}:${G}`,className:"h-8",children:m===`oauth-complete:${S}:${G}`?"Saving…":"Complete"})]})]},`${S}-${ge}`)})})})()]})]})]})});if(!Q)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(to,{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 K=Array.isArray(Q.models)?Q.models:[],F=(o[Q.id]??[]).filter(R=>Kd(R)==="oauth"),$=K.filter(R=>{const B=typeof R?.name=="string"?R.name:"",z=typeof R?.id=="string"?R.id:"",G=p.trim().toLowerCase();return G?B.toLowerCase().includes(G)||z.toLowerCase().includes(G):!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(cs,{providerId:Q.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:Q.name||Q.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",Q.id]})]}),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[Q.id]??"",onChange:R=>u(B=>({...B,[Q.id]:R.target.value})),placeholder:"sk-..."}),e.jsx(Ie,{size:"sm",onClick:()=>W(Q.id),disabled:m===`api:${Q.id}`,className:"h-8",children:m===`api:${Q.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."})]}),e.jsx("div",{className:"pt-2 border-t border-border/40",children:e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>Y(Q.id),disabled:m===`disconnect:${Q.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${Q.id}`?"Disconnecting…":"Disconnect provider"})}),F.length>0&&e.jsx("div",{className:"space-y-3",children:F.map((R,B)=>{const z=R.label||R.name||`OAuth method ${B+1}`,G=`${Q.id}:${B}`,ge=y?.providerId===Q.id&&y?.methodIndex===B;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:z}),(R.description||R.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(R.description||R.help)})]}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>L(Q.id,B),disabled:m===`oauth:${Q.id}:${B}`,className:"h-8",children:"Connect"})]}),v[G]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[G]?.instructions}),v[G]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[G]?.userCode,readOnly:!0}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>X(v[G]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[G]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[G]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ie,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[G]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>q(v[G]?.url??""),className:"h-8",children:"Copy link"})]})]}),ge&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:j[G]??"",onChange:oe=>b(me=>({...me,[G]:oe.target.value})),placeholder:"Paste authorization code"}),e.jsx(Ie,{size:"sm",onClick:()=>H(Q.id,B),disabled:m===`oauth-complete:${Q.id}:${B}`,className:"h-8",children:m===`oauth-complete:${Q.id}:${B}`?"Saving…":"Complete"})]})]},`${Q.id}-${z}`)})})]})]}),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:R=>g(R.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:$.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):$.map(R=>{const B=typeof R?.id=="string"?R.id:"",z=typeof R?.name=="string"?R.name:B,G=B?n(Q.id,B):void 0,ge=Gd(G?.limit?.context),oe=Gd(G?.limit?.output),me=[];return G?.tool_call&&me.push({key:"tools",icon:Ma,label:"Tool calling"}),G?.reasoning&&me.push({key:"reasoning",icon:dr,label:"Reasoning"}),G?.attachment&&me.push({key:"image",icon:mr,label:"Image input"}),e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate flex-1 min-w-0",children:z}),(ge||oe)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[ge?`${ge} ctx`:"",ge&&oe?" · ":"",oe?`${oe} out`:""]}),me.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:me.map(({key:Ne,icon:Ce,label:Be})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Be,"aria-label":Be,children:e.jsx(Ce,{className:"h-3 w-3"})},Ne))})]},B)})})]})]})})},Bj={branch:zt,briefcase:pl,house:fl,graduation:ml,code:_s,heart:Tu},zj={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Wj=({onItemSelect:s})=>{const{selectedProfileId:r,defaultGitIdentityId:t,profiles:n,globalIdentity:o,setSelectedProfile:a,deleteProfile:l,loadProfiles:c,loadGlobalIdentity:d,loadDiscoveredCredentials:u,loadDefaultGitIdentityId:m,setDefaultGitIdentityId:f,getUnimportedCredentials:p}=In(),{setSidebarOpen:g}=$e(),{isMobile:y}=$t(),[h,j]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||j(typeof window.opencodeDesktop<"u")},[]);const v=p();i.useEffect(()=>{c(),d(),u(),m()},[c,d,u,m]);const w=C=>{a(`import:${C.host}:${C.username}`),s?.(),y&&g(!1)},N=h?"bg-transparent":b?"bg-background":"bg-sidebar",x=()=>{a("new"),s?.(),y&&g(!1)},k=async C=>{window.confirm(`Are you sure you want to delete profile "${C.name}"?`)&&(await l(C.id)?te.success(`Profile "${C.name}" deleted successfully`):te.error("Failed to delete profile"))},A=async C=>{const M=t===C?null:C;if(!await f(M)){te.error("Failed to update default identity");return}te.success(M?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:_("flex h-full flex-col",N),children:[e.jsx("div",{className:_("border-b px-3",y?"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(Ie,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:x,children:e.jsx(Xt,{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(Qd,{profile:o,isSelected:r==="global",isDefault:t==="global",onSelect:()=>{a("global"),s?.(),y&&g(!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(zt,{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(C=>e.jsx(Qd,{profile:C,isSelected:r===C.id,isDefault:t===C.id,onSelect:()=>{a(C.id),s?.(),y&&g(!1)},onToggleDefault:()=>A(C.id),onDelete:()=>k(C)},C.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(C=>e.jsx(Uj,{credential:C,onImport:()=>w(C)},`${C.host}-${C.username}`))]})]})]})},Qd=({profile:s,isSelected:r,isDefault:t=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:l=!1})=>{const c=Bj[s.icon||"branch"]||zt,d=zj[s.color||""],u=s.authType||"ssh";return e.jsx("div",{className:_("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:s.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}),t&&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"&&s.host?s.host:s.userEmail})]}),(o||!l&&a)&&e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(Ie,{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(Or,{className:"h-3.5 w-3.5"})})}),e.jsxs(Qt,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(Et,{onClick:m=>{m.stopPropagation(),o()},children:t?"Unset default":"Set as default"}),!l&&a&&e.jsxs(Et,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},Hj=s=>{const r=s.split("/");return r.length>=3?r[r.length-1]:s},Uj=({credential:s,onImport:r})=>{const t=Hj(s.host),n=s.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:t})}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n?s.host:s.username})]}),e.jsxs(Ie,{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(Fr,{className:"h-3 w-3"}),"Import"]})]})})},Yd=[{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)"}],Vj=[{key:"branch",Icon:zt,label:"Branch"},{key:"briefcase",Icon:pl,label:"Work"},{key:"house",Icon:fl,label:"Personal"},{key:"graduation",Icon:ml,label:"School"},{key:"code",Icon:_s,label:"Code"}],Gj=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=In(),a=i.useMemo(()=>{if(s?.startsWith("import:")){const[,I,P]=s.split(":");return{host:I,username:P}}return null},[s]),l=i.useMemo(()=>s&&s!=="new"&&!a?r(s):null,[s,r,a]),c=s==="new"||a!==null,d=s==="global",[u,m]=i.useState(""),[f,p]=i.useState(""),[g,y]=i.useState(""),[h,j]=i.useState("ssh"),[b,v]=i.useState(""),[w,N]=i.useState(""),[x,k]=i.useState("keyword"),[A,C]=i.useState("branch"),[M,S]=i.useState(!1);i.useEffect(()=>{if(a){const I=a.host.split("/"),P=I.length>=3?I[I.length-1]:a.host;m(P),p(a.username),y(""),j("token"),v(""),N(a.host),k("string"),C("code")}else c?(m(""),p(""),y(""),j("ssh"),v(""),N(""),k("keyword"),C("branch")):l&&(m(l.name),p(l.userName),y(l.userEmail),j(l.authType||"ssh"),v(l.sshKey||""),N(l.host||""),k(l.color||"keyword"),C(l.icon||"branch"))},[l,c,s,a]);const D=async()=>{if(!f.trim()||!g.trim()){te.error("User name and email are required");return}if(h==="token"&&!w.trim()){te.error("Host is required for token-based authentication");return}S(!0);try{const I={name:u.trim()||f.trim(),userName:f.trim(),userEmail:g.trim(),authType:h,sshKey:h==="ssh"&&b.trim()||null,host:h==="token"&&w.trim()||null,color:x,icon:A};let P;if(c)P=await t(I);else if(s)P=await n(s,I);else return;P?te.success(c?"Profile created successfully":"Profile updated successfully"):te.error(c?"Failed to create profile":"Failed to update profile")}catch(I){console.error("Error saving profile:",I),te.error("An error occurred while saving")}finally{S(!1)}},E=async()=>{if(!(!s||c)&&confirm("Are you sure you want to delete this profile?"))try{await o(s)?te.success("Profile deleted successfully"):te.error("Failed to delete profile")}catch(I){console.error("Error deleting profile:",I),te.error("An error occurred while deleting")}},T=i.useMemo(()=>Yd.find(P=>P.key===x)?.cssVar||"var(--syntax-keyword)",[x]);return s?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:I=>m(I.target.value),placeholder:"Work Profile, Personal, etc."}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Friendly name to identify this profile (optional, defaults to user name)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Color"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Yd.map(I=>e.jsx("button",{onClick:()=>k(I.key),className:_("w-8 h-8 rounded-lg border-2 transition-all",x===I.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:I.cssVar},title:I.label},I.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Icon"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Vj.map(I=>{const P=I.Icon;return e.jsx("button",{onClick:()=>C(I.key),className:_("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",A===I.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:I.label,children:e.jsx(P,{className:"w-4 h-4",style:{color:T}})},I.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["The name that will appear in Git commit messages.",e.jsx("br",{}),"This is the author name shown in git log and GitHub/GitLab interfaces."]})]})]}),e.jsx(jt,{value:f,onChange:I=>p(I.target.value),placeholder:"John Doe",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.name configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Email ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["The email address for Git commits.",e.jsx("br",{}),"This should match your email in GitHub/GitLab",e.jsx("br",{}),"to ensure proper attribution of commits."]})]})]}),e.jsx(jt,{type:"email",value:g,onChange:I=>y(I.target.value),placeholder:"john@example.com",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Authentication Type",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["SSH: Uses SSH key for authentication",e.jsx("br",{}),"Token: Uses personal access token from ~/.git-credentials"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>j("ssh"),className:_("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",h==="ssh"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx($h,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>j("token"),className:_("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",h==="token"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx(Lh,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"Token (HTTPS)"})]})]})]}),h==="ssh"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["SSH Key Path",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Path to SSH private key used for Git authentication.",e.jsx("br",{}),"This key will be used for SSH Git operations.",e.jsx("br",{}),"Common paths: ~/.ssh/id_rsa, ~/.ssh/id_ed25519"]})]})]}),e.jsx(jt,{value:b,onChange:I=>v(I.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),h==="token"&&!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Host ",e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["The Git host this credential applies to.",e.jsx("br",{}),"Token will be read from ~/.git-credentials for this host.",e.jsx("br",{}),"Examples: github.com, gitlab.com"]})]})]}),e.jsx(jt,{value:w,onChange:I=>N(I.target.value),placeholder:"github.com",required:!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git host for token authentication (from ~/.git-credentials)"})]}),!d&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!c&&e.jsxs(Ie,{size:"sm",variant:"destructive",onClick:E,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Xs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:_("flex gap-2",c&&"ml-auto"),children:e.jsxs(Ie,{size:"sm",variant:"default",onClick:D,disabled:M,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Da,{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(Os,{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 ki(s,r,t){return Math.min(t,Math.max(r,s))}const va=Ae.forwardRef(({value:s,onValueChange:r,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:l,onBlur:c,onKeyDown:d,disabled:u,...m},f)=>{const p=Ae.useRef(null);Ae.useImperativeHandle(f,()=>p.current);const[g,y]=Ae.useState(()=>String(s));Ae.useEffect(()=>{document.activeElement!==p.current&&y(String(s))},[s]);const h=Ae.useCallback(()=>{p.current?.focus()},[]),j=Ae.useCallback(S=>{const D=ki(S,t,n);r(D),y(String(D))},[n,t,r]),b=Ae.useCallback(()=>{const S=Number(g);return Number.isFinite(S)?S:s},[g,s]),v=Ae.useCallback(()=>{j(b()+o),h()},[j,b,h,o]),w=Ae.useCallback(()=>{j(b()-o),h()},[j,b,h,o]),N=S=>{const D=S.target.value;y(D);const E=Number(D);Number.isFinite(E)&&r(ki(E,t,n))},x=S=>{const D=Number(g);if(!Number.isFinite(D))y(String(s));else{const E=ki(D,t,n);E!==D&&r(E),y(String(E))}c?.(S)},k=S=>{if(S.key==="ArrowUp"){S.preventDefault(),v();return}if(S.key==="ArrowDown"){S.preventDefault(),w();return}d?.(S)},A=b(),C=u||A<=t,M=u||A>=n;return e.jsxs("div",{className:_("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(t)?t:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:g,onChange:N,onBlur:x,onKeyDown:k,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:_("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:_("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(Na,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:C,onClick:w,className:_("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(Ft,{className:"h-3.5 w-3.5"})})]})]})});va.displayName="NumberInput";const qj=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Xd=[{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"}],Jd=[{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."}],Zd=[{id:"single",label:"Single file",description:"Show one file at a time in the Diff tab."},{id:"stacked",label:"All files",description:"Stack all changed files together in the Diff tab."}],zl=({visibleSettings:s})=>{const{isMobile:r}=$t(),t=$e(x=>x.showReasoningTraces),n=$e(x=>x.setShowReasoningTraces),o=$e(x=>x.toolCallExpansion),a=$e(x=>x.setToolCallExpansion),l=$e(x=>x.fontSize),c=$e(x=>x.setFontSize),d=$e(x=>x.padding),u=$e(x=>x.setPadding),m=$e(x=>x.inputBarOffset),f=$e(x=>x.setInputBarOffset),p=$e(x=>x.diffLayoutPreference),g=$e(x=>x.setDiffLayoutPreference),y=$e(x=>x.diffViewMode),h=$e(x=>x.setDiffViewMode),j=rr(x=>x.queueModeEnabled),b=rr(x=>x.setQueueMode),{themeMode:v,setThemeMode:w}=Wr(),N=x=>s?s.includes(x):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[N("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:qj.map(x=>e.jsx(Ps,{variant:v===x.value?"default":"outline",className:_(v===x.value?void 0:"text-foreground"),onClick:()=>w(x.value),children:x.label},x.value))})]}),N("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:l,onChange:x=>c(Number(x.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(va,{value:l,onValueChange:c,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Ps,{type:"button",variant:"ghost",onClick:()=>c(100),disabled:l===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(Fs,{className:"h-3.5 w-3.5"})})]})]}),N("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:d,onChange:x=>u(Number(x.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:d}),e.jsx(Ps,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===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(Fs,{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:d,onChange:x=>u(Number(x.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(va,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Ps,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===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(Fs,{className:"h-3.5 w-3.5"})})]})]}),N("inputBarOffset")&&r&&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 for phones with curved screen edges."})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"100",step:"5",value:m,onChange:x=>f(Number(x.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:[m,"px"]}),e.jsx(Ps,{type:"button",variant:"ghost",onClick:()=>f(0),disabled:m===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(Fs,{className:"h-3.5 w-3.5"})})]})]}),N("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:Xd.find(x=>x.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Xd.map(x=>e.jsx(Ps,{variant:o===x.value?"default":"outline",className:_(o===x.value?void 0:"text-foreground"),onClick:()=>a(x.value),children:x.label},x.value))})]}),N("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:Jd.map(x=>e.jsx(Ps,{variant:p===x.id?"default":"outline",className:_(p===x.id?void 0:"text-foreground"),onClick:()=>g(x.id),children:x.label},x.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Jd.find(x=>x.id===p)?.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:Zd.map(x=>e.jsx(Ps,{variant:y===x.id?"default":"outline",className:_(y===x.id?void 0:"text-foreground"),onClick:()=>h(x.id),children:x.label},x.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Zd.find(x=>x.id===y)?.description})]})]}),N("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:t,onChange:x=>n(x.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),N("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:j,onChange:x=>b(x.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:j?`Enter queues messages, ${Yt()}+Enter sends immediately.`:`Enter sends immediately, ${Yt()}+Enter queues messages.`})]})]})},eu="https://github.com/btriapitsyn/openchamber",Kj=800,Df=()=>{const[s,r]=i.useState(!1),[t,n]=i.useState(!1),o=Aa(),{isMobile:a}=$t(),l=o.info?.currentVersion||"unknown",c=i.useRef(!1);i.useEffect(()=>{if(o.checking)n(!0),c.current=!0;else if(t){const u=setTimeout(()=>{n(!1),c.current&&!o.available&&!o.error&&(te.success("You are on the latest version"),c.current=!1)},Kj);return()=>clearTimeout(u)}},[o.checking,t,o.available,o.error]);const d=o.checking||t;return a?e.jsxs("div",{className:"w-full space-y-2",children:[e.jsxs("button",{onClick:()=>qn(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Fs,{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:_("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(Fr,{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($i,{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(Lu,{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(Li,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Qi,{open:s,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(Lo,{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:_("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(Fr,{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:_("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:_("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx($i,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:_("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Li,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Qi,{open:s,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})]})},Qj=1440*60*1e3,Af=5,tu=1440*60*1e3,Ni=s=>s.time?.updated??s.time?.created??0,su=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=Af,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*Qj,l=[...s].sort((d,u)=>Ni(u)-Ni(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=Ni(d);return u?u<a:!1}).map(d=>d.id)},Ef=s=>{const r=s?.autoRun!==!1,t=he(h=>h.sessions),n=he(h=>h.currentSessionId),o=he(h=>h.isLoading),a=he(h=>h.deleteSessions),l=$e(h=>h.autoDeleteEnabled),c=$e(h=>h.autoDeleteAfterDays),d=$e(h=>h.autoDeleteLastRunAt),u=$e(h=>h.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),g=i.useMemo(()=>c<=0?[]:su({sessions:t,currentSessionId:n,cutoffDays:c}),[c,n,t]),y=i.useCallback(async({force:h=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!l||c<=0)&&!h)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const j=Date.now();if(!h&&d&&j-d<tu)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const b=su({sessions:t,currentSessionId:n,cutoffDays:c,now:j});if(b.length===0)return u(j),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(b,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[c,l,d,n,a,o,t,u]);return i.useEffect(()=>{if(!r||!l||c<=0||o||t.length===0)return;const h=Date.now();d&&h-d<tu||y()},[c,l,d,r,o,t.length,y]),{candidates:g,isRunning:m,runCleanup:y,keepRecentCount:Af}},Ci=1,Mi=365,If=()=>{const{isMobile:s}=$t(),r=$e(p=>p.autoDeleteEnabled),t=$e(p=>p.autoDeleteAfterDays),n=$e(p=>p.setAutoDeleteEnabled),o=$e(p=>p.setAutoDeleteAfterDays),[a,l]=i.useState(String(t));i.useEffect(()=>{l(String(t))},[t]);const{candidates:c,isRunning:d,runCleanup:u}=Ef({autoRun:!1}),m=c.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){te.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&te.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&te.error(`Failed to delete ${p.failedIds.length} session${p.failedIds.length===1?"":"s"}`)},[u]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session retention"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Automatically delete inactive sessions based on their last activity.",e.jsx("br",{}),"You can also run a one-time cleanup without enabling auto-cleanup.",e.jsx("br",{}),"Keeps the most recent 5 sessions, and never deletes shared sessions."]})]})]})}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:r,onChange:p=>n(p.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Enable auto-cleanup"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s?e.jsx("input",{type:"number",inputMode:"numeric",value:a,onChange:p=>{const g=p.target.value;if(l(g),g.trim()==="")return;const y=Number(g);if(!Number.isFinite(y))return;const h=Math.min(Mi,Math.max(Ci,Math.round(y)));o(h)},onBlur:()=>{if(a.trim()===""){l(String(t));return}const p=Number(a);if(!Number.isFinite(p)){l(String(t));return}const g=Math.min(Mi,Math.max(Ci,Math.round(p)));o(g),l(String(g))},"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(va,{value:t,onValueChange:o,min:Ci,max:Mi,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(Ps,{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]})]})},ru="opencode",nu="big-pickle",Yj=(s,r)=>{if(s){const o=s.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(r.find(o=>o.id===ru)?.models.some(o=>o.id===nu))return{providerId:ru,modelId:nu};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},Pf=()=>{const s=at(S=>S.setProvider),r=at(S=>S.setModel),t=at(S=>S.setAgent),n=at(S=>S.setCurrentVariant),o=at(S=>S.setSettingsDefaultModel),a=at(S=>S.setSettingsDefaultVariant),l=at(S=>S.setSettingsDefaultAgent),c=at(S=>S.settingsAutoCreateWorktree),d=at(S=>S.setSettingsAutoCreateWorktree),u=at(S=>S.providers),[m,f]=i.useState(),[p,g]=i.useState(),[y,h]=i.useState(),[j,b]=i.useState(!0),v=i.useMemo(()=>Yj(m,u),[m,u]);i.useEffect(()=>{(async()=>{try{let D=null;if(es())D=await Lr();else{const E=Qs()?.settings;if(E)try{const I=(await E.load())?.settings;I&&(D={defaultModel:typeof I.defaultModel=="string"?I.defaultModel:void 0,defaultVariant:typeof I.defaultVariant=="string"?I.defaultVariant:void 0,defaultAgent:typeof I.defaultAgent=="string"?I.defaultAgent:void 0})}catch{}if(!D){const T=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});T.ok&&(D=await T.json())}}if(D){const E=typeof D.defaultModel=="string"&&D.defaultModel.trim().length>0?D.defaultModel.trim():void 0,T=typeof D.defaultVariant=="string"&&D.defaultVariant.trim().length>0?D.defaultVariant.trim():void 0,I=typeof D.defaultAgent=="string"&&D.defaultAgent.trim().length>0?D.defaultAgent.trim():void 0;E!==void 0&&f(E),T!==void 0&&g(T),I!==void 0&&h(I)}}catch(D){console.warn("Failed to load defaults settings:",D)}finally{b(!1)}})()},[]);const w=i.useCallback(async(S,D)=>{const E=S&&D?`${S}/${D}`:void 0;f(E),g(void 0),a(void 0),n(void 0),o(E),S&&D&&u.find(I=>I.id===S)&&(s(S),r(D));try{if(await ss({defaultModel:E??"",defaultVariant:""}),!es()){const T=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:E})});T.ok||console.warn("Failed to save default model to server:",T.status,T.statusText)}}catch(T){console.warn("Failed to save default model:",T)}},[u,n,s,r,o,a]),N="__default__",x=i.useCallback(async S=>{const D=S===N?void 0:S||void 0;g(D),a(D),n(D);try{await ss({defaultVariant:D??""})}catch(E){console.warn("Failed to save default variant:",E)}},[n,a]),k=i.useCallback(async S=>{const D=S||void 0;h(D),l(D),S&&t(S);try{await ss({defaultAgent:D??""})}catch(E){console.warn("Failed to save default agent:",E)}},[t,l]),A=i.useMemo(()=>{if(!v.providerId||!v.modelId)return[];const E=u.find(T=>T.id===v.providerId)?.models.find(T=>T.id===v.modelId)?.variants;return E?Object.keys(E):[]},[v.modelId,v.providerId,u]),C=A.length>0;i.useEffect(()=>{!C&&p&&(g(void 0),a(void 0),n(void 0),ss({defaultVariant:""}).catch(()=>{}))},[p,n,a,C]);const M=i.useCallback(async S=>{const D=S.target.checked;d(D);try{await ss({autoCreateWorktree:D})}catch(E){console.warn("Failed to save auto create worktree setting:",E)}},[d]);return j?null:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session Defaults"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:"Configure default behaviors for new sessions."})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default model"}),e.jsx($a,{providerId:v.providerId,modelId:v.modelId,onChange:w})]}),C&&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(ks,{value:p??N,onValueChange:x,children:[e.jsx(Ns,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(nn,{placeholder:"Thinking"})}),e.jsxs(Cs,{children:[e.jsx(Ut,{value:N,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),A.map(S=>e.jsx(Ut,{value:S,className:"pr-2 [&>span:first-child]:hidden",children:S},S))]})]})]}),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(Cf,{agentName:y||"",onChange:k})]})]}),(v.providerId||y)&&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,C?` (${p??"default"})`:""]}),v.providerId&&y&&" / ",y&&e.jsx("span",{className:"text-foreground",children:y})]}),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:M}),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): ${Yt()} + N • New session (Standard): Shift + ${Yt()} + N`:`New session (Standard): ${Yt()} + N • New session (Worktree): Shift + ${Yt()} + N`})]})]})},Jn="opencode",ou="big-pickle",Xj=(s,r)=>{if(s){const o=s.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(r.find(o=>o.id===Jn)?.models.some(o=>o.id===ou))return{providerId:Jn,modelId:ou};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},Jj=()=>{const s=at(d=>d.settingsCommitMessageModel),r=at(d=>d.setSettingsCommitMessageModel),t=at(d=>d.providers),[n,o]=i.useState(!0),a=i.useMemo(()=>t.filter(d=>d.id===Jn),[t]),l=i.useMemo(()=>{const d=s?.startsWith(`${Jn}/`)?s:void 0;return Xj(d,a)},[s,a]);i.useEffect(()=>{(async()=>{try{let u=null;if(es())u=await Lr();else{const m=Qs()?.settings;if(m)try{const p=(await m.load())?.settings;p&&(u={commitMessageModel:typeof p.commitMessageModel=="string"?p.commitMessageModel:void 0})}catch{}if(!u){const f=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});f.ok&&(u=await f.json())}}if(u){const m=typeof u.commitMessageModel=="string"&&u.commitMessageModel.trim().length>0?u.commitMessageModel.trim():void 0;r(m)}}catch(u){console.warn("Failed to load git settings:",u)}finally{o(!1)}})()},[r]);const c=i.useCallback(async(d,u)=>{const m=d&&u?`${d}/${u}`:void 0;r(m);try{await ss({commitMessageModel:m??""})}catch(f){console.warn("Failed to save commit message model:",f)}},[r]);return n?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:"Commit Messages"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:"Configure how commit messages are generated."})]})]})}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Model for generation"}),e.jsx($a,{providerId:l.providerId,modelId:l.modelId,onChange:c,allowedProviderIds:[Jn]}),e.jsxs("p",{className:"typography-meta text-muted-foreground mt-1",children:["This model will be used to analyze diffs and suggest commit messages.",!s&&e.jsxs(e.Fragment,{children:[" Default: ",e.jsx("span",{className:"text-foreground",children:"opencode/big-pickle"})]})]})]})})]})},Zj=()=>{const s=Ot(F=>F.getActiveProject()),r=Ot(F=>F.updateWorktreeDefaults),t=s?.path??null,n=s?.worktreeDefaults,o=Nl(t),a=jm(t),{sessions:l,getWorktreeMetadata:c}=he(),[d,u]=i.useState(n?.branchPrefix??""),[m,f]=i.useState(n?.baseBranch??"HEAD"),[p,g]=i.useState([]),[y,h]=i.useState(!1),[j,b]=i.useState(!1),[v,w]=i.useState(null),[N,x]=i.useState(null),[k,A]=i.useState([]),[C,M]=i.useState(!1),S=".openchamber",D=i.useCallback((F,$)=>{const R=F.replace(/\\/g,"/").replace(/\/+$/,""),B=!R||R==="/"?`/${S}`:`${R}/${S}`;return $?`${B}/${$}`:B},[]),E=i.useCallback(async()=>{if(!(!t||v===!1))try{const $=(await Mn(t)).map(G=>Dn(t,G)),B=`${D(t,"")}/`,z=$.filter(G=>G.path.startsWith(B));A(z)}catch{}},[t,v,D]);i.useEffect(()=>{if(!t)return;let F=!1;return b(!0),M(!0),w(null),x(null),A([]),(async()=>{try{const $=await cn(t);if(F)return;if(w($),$){const[R,B]=await Promise.all([vl(t),Mn(t).catch(()=>[])]);if(!F){R&&x({all:R.all,current:R.current});const z=B.map(me=>Dn(t,me)),ge=`${`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/${S}`}/`,oe=z.filter(me=>me.path.startsWith(ge));A(oe)}}}catch{}finally{F||(b(!1),M(!1))}})(),()=>{F=!0}},[t]),i.useEffect(()=>{if(!t)return;let F=!1;return h(!0),(async()=>{try{const $=await fo(t);F||g($.length>0?$:[""])}catch{F||g([""])}finally{F||h(!1)}})(),()=>{F=!0}},[t]),i.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const T=N??a,I=v??o,P=i.useMemo(()=>{const F=[],$=T?.current?`Current (HEAD: ${T.current})`:"Current (HEAD)";return F.push({value:"HEAD",label:$,group:"special"}),T&&(T.all.filter(z=>!z.startsWith("remotes/")).sort((z,G)=>z.localeCompare(G)).forEach(z=>{F.push({value:z,label:z,group:"local"})}),T.all.filter(z=>z.startsWith("remotes/")).map(z=>z.replace(/^remotes\//,"")).sort((z,G)=>z.localeCompare(G)).forEach(z=>{F.push({value:z,label:z,group:"remote"})})),F},[T]),O=i.useRef(null),U=i.useCallback(F=>{u(F),O.current=F},[]),Q=i.useCallback(F=>{s?.id&&(r(s.id,{branchPrefix:F}),O.current=null)},[s?.id,r]),W=i.useCallback(()=>{Q(d)},[d,Q]);i.useEffect(()=>()=>{O.current!==null&&s?.id&&r(s.id,{branchPrefix:O.current})},[s?.id,r]);const L=i.useCallback(F=>{f(F),s?.id&&r(s.id,{baseBranch:F})},[s?.id,r]),H=i.useCallback((F,$)=>{g(R=>{const B=[...R];return B[F]=$,B})},[]),q=i.useCallback(()=>{g(F=>[...F,""])},[]),X=i.useCallback(F=>{g($=>$.filter((R,B)=>B!==F))},[]),Y=i.useCallback(async()=>{if(!t)return;const F=p.filter($=>$.trim().length>0);await lm(t,F)},[t,p]),re=i.useCallback(()=>{Y()},[Y]),K=i.useCallback(F=>{const $=F.path.replace(/\\/g,"/").replace(/\/+$/,""),R=l.filter(me=>{if(c(me.id)?.path===F.path)return!0;const Ce=me.directory;return!!(Ce&&Ce.replace(/\\/g,"/").replace(/\/+$/,"")===$)}),B=new Set(R.map(me=>me.id)),z=me=>{const Ne=l.filter(Be=>{const V=Be.parentID;return V&&me.has(V)});if(Ne.length===0)return[];const Ce=new Set(Ne.map(Be=>Be.id));return[...Ne,...z(Ce)]},G=z(B),ge=new Set,oe=[...R,...G].filter(me=>ge.has(me.id)?!1:(ge.add(me.id),!0));En.requestDelete({sessions:oe,mode:"worktree",worktree:F})},[l,c]),ae=i.useMemo(()=>l.map(F=>F.id).join(","),[l]);return i.useEffect(()=>{v&&t&&E()},[ae,v,t,E]),t?j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):I===!1?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Worktree settings are only available for Git repositories."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Branch prefix"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{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:F=>U(F.target.value),onBlur:W,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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:"Default branch to create new worktrees from."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default branch for new worktree branches"})]}),e.jsxs(ks,{value:m,onValueChange:L,children:[e.jsx(Ns,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(nn,{placeholder:"Select a branch"})}),e.jsxs(Cs,{children:[e.jsxs(Jr,{children:[e.jsx(Nn,{children:"Default"}),P.filter(F=>F.group==="special").map(F=>e.jsx(Ut,{value:F.value,children:F.label},F.value))]}),P.some(F=>F.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(xa,{}),e.jsxs(Jr,{children:[e.jsx(Nn,{children:"Local branches"}),P.filter(F=>F.group==="local").map(F=>e.jsx(Ut,{value:F.value,children:F.label},F.value))]})]}),P.some(F=>F.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(xa,{}),e.jsxs(Jr,{children:[e.jsx(Nn,{children:"Remote branches"}),P.filter(F=>F.group==="remote").map(F=>e.jsx(Ut,{value:F.value,children:F.label},F.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."]})]}),y?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[p.map((F,$)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:F,onChange:R=>H($,R.target.value),onBlur:re,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{X($),setTimeout(Y,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(Ht,{className:"h-4 w-4"})})]},$)),e.jsxs("button",{type:"button",onClick:q,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Xt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Existing worktrees"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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"})]}),C?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(F=>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:F.label||F.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:F.relativePath||F.path})]}),e.jsx("button",{type:"button",onClick:()=>K(F),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 ${F.branch||F.label}`,children:e.jsx(Xs,{className:"h-4 w-4"})})]},F.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},eS=()=>{const s=$e(d=>d.nativeNotificationsEnabled),r=$e(d=>d.setNativeNotificationsEnabled),t=$e(d=>d.notificationMode),n=$e(d=>d.setNotificationMode),[o,a]=i.useState("default");i.useEffect(()=>{typeof Notification<"u"&&a(Notification.permission)},[]);const l=async d=>{if(d&&typeof Notification<"u"&&Notification.permission==="default")try{const u=await Notification.requestPermission();a(u),u==="granted"?r(!0):te.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(u){console.error("Failed to request notification permission:",u),te.error("Failed to request notification permission")}else r(!!(d&&o==="granted"))},c=typeof Notification<"u"&&Notification.permission==="granted";return rn()?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:"Native Notifications"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Show browser notifications when an assistant completes a task."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Enable native notifications"}),e.jsx(pa,{checked:s&&c,onCheckedChange:l,className:"data-[state=checked]:bg-status-info"})]}),s&&c&&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:"Always notify"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"When off, only notifies if the window is out of focus."})]}),e.jsx(pa,{checked:t==="always",onCheckedChange:d=>n(d?"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"&&!s&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Notifications are enabled in your browser. Toggle the switch above to activate them."})]}):null},tS=({section:s})=>{const{isMobile:r}=$t(),t=r&&rn();if(!s)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(zl,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Pf,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(If,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Df,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(sS,{});case"chat":return e.jsx(rS,{});case"sessions":return e.jsx(nS,{});case"git":return e.jsx(oS,{});case"notifications":return e.jsx(aS,{});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()})},sS=()=>e.jsx(zl,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),rS=()=>e.jsx(zl,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),nS=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Pf,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(If,{})})]}),oS=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Jj,{}),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(Zj,{})]})]}),aS=()=>e.jsx(eS,{}),iS=[{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}],lS=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=$t(),n=t&&rn(),[o,a]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=i.useMemo(()=>Wt(),[]),c=i.useMemo(()=>rn(),[]);i.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=i.useMemo(()=>iS.filter(m=>!(m.webOnly&&!c||m.hideInVSCode&&l)),[c,l]),u=o?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:_("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=s===m.id;return e.jsx("div",{className:_("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(Df,{})})]})},cS=s=>{let r=kf.filter(o=>o.id!=="sessions");s&&(r=r.filter(o=>o.id!=="git-identities"));const t=r.find(o=>o.id==="settings"),n=r.filter(o=>o.id!=="settings");return t?[t,...n]:r},Di=200,Ai=500,dS=264,uS=940,nl=({onClose:s,forceMobile:r})=>{const t=$t(),n=r??t.isMobile,[o,a]=i.useState("settings"),[l,c]=i.useState("visual"),[d,u]=i.useState(!1),[m,f]=i.useState(()=>typeof window<"u"?Math.min(Ai,Math.max(Di,Math.floor(window.innerWidth*.2))):dS),[p,g]=i.useState(!1),[y,h]=i.useState(!1),[j,b]=i.useState(0),v=i.useRef(null),w=i.useRef(0),N=i.useRef(m),[x,k]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),A=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),C=i.useMemo(()=>Wt(),[]),M=i.useMemo(()=>cS(C),[C]);i.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{const $=v.current;if(!$)return;const R=new ResizeObserver(B=>{for(const z of B)b(z.contentRect.width)});return R.observe($),b($.clientWidth),()=>R.disconnect()},[]);const S=Ot($=>$.projects),D=Ot($=>$.activeProjectId),E=Ot($=>$.setActiveProject),T=i.useMemo(()=>[...S].sort(($,R)=>($.label||$.path).localeCompare(R.label||R.path)),[S]),I=i.useMemo(()=>T.length===0?null:T.find($=>$.id===D)??T[0],[D,T]),P=i.useCallback($=>$.replace(/[-_]/g," ").replace(/\b\w/g,R=>R.toUpperCase()),[]),O=i.useMemo(()=>{if(!I)return"Project";const $=I.label&&I.label.trim().length>0?I.label:I.path.split("/").filter(Boolean).pop()||I.path;return P($)},[I,P]),U=T.length>0&&!C,Q=j===0||j>=uS;i.useEffect(()=>{if(o==="agents"){setTimeout(()=>{zr.getState().loadAgents()},0);return}if(o==="commands"){setTimeout(()=>{Br.getState().loadCommands()},0);return}o==="skills"&&(Gs.getState().loadSkills(),mo.getState().loadCatalog())},[D,o]),i.useEffect(()=>{if(typeof window>"u")return;const $=()=>{if(!p){const R=Math.min(Ai,Math.max(Di,Math.floor(window.innerWidth*.2)));f(R)}};return window.addEventListener("resize",$),()=>window.removeEventListener("resize",$)},[p]),i.useEffect(()=>{if(!y)return;const $=B=>{const z=B.clientX-w.current,G=Math.min(Ai,Math.max(Di,N.current+z));f(G),g(!0)},R=()=>h(!1);return window.addEventListener("pointermove",$),window.addEventListener("pointerup",R,{once:!0}),()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",R)}},[y]);const W=$=>{h(!0),w.current=$.clientX,N.current=m,$.preventDefault()},L=i.useCallback(async $=>{if(!$.target.closest("button, a, input, select, textarea")&&$.button===0&&x)try{const{getCurrentWindow:R}=await as(async()=>{const{getCurrentWindow:z}=await import("./vendor-.bun-CqCnPJev.js").then(G=>G.cA);return{getCurrentWindow:z}},__vite__mapDeps([0,1]));await R().startDragging()}catch(R){console.error("Failed to start window dragging:",R)}},[x]),H=i.useCallback(async $=>{if($.button===0&&x)try{const{getCurrentWindow:R}=await as(async()=>{const{getCurrentWindow:z}=await import("./vendor-.bun-CqCnPJev.js").then(G=>G.cA);return{getCurrentWindow:z}},__vite__mapDeps([0,1]));await R().startDragging()}catch(R){console.error("Failed to start window dragging:",R)}},[x]),q=i.useCallback($=>{a($),u(!1)},[]),X=i.useCallback(()=>{n&&u(!0)},[n]),Y=()=>{switch(o){case"settings":return e.jsx(lS,{selectedSection:l,onSelectSection:$=>{c($),X()}});case"agents":return e.jsx(mj,{onItemSelect:X});case"commands":return e.jsx(wj,{onItemSelect:X});case"skills":return e.jsx(Sj,{onItemSelect:X});case"providers":return e.jsx(Fj,{onItemSelect:X});case"git-identities":return e.jsx(Wj,{onItemSelect:X});default:return null}},re=()=>{switch(o){case"agents":return e.jsx(vj,{});case"commands":return e.jsx(jj,{});case"skills":return e.jsx(Pj,{});case"providers":return e.jsx(Lj,{});case"git-identities":return e.jsx(Gj,{});case"settings":return e.jsx(tS,{section:l});default:return null}},K=Yt(),ae=i.useMemo(()=>x&&A?"pl-[5.75rem]":"",[x,A]),F=x&&A;return e.jsxs("div",{ref:v,className:_("flex h-full flex-col overflow-hidden",x?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:L,className:_("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&ae,x?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80"),style:{borderColor:"var(--interactive-border)"},children:[n&&d&&e.jsx("button",{type:"button",onClick:()=>u(!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(Ru,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:_("flex items-center",n?"gap-1":"h-full"),children:[!n&&F&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),M.map(({id:$,label:R,icon:B})=>{const z=o===$,G=B;return n?e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{onClick:()=>q($),className:_("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",z?"text-foreground":"text-muted-foreground"),"aria-pressed":z,"aria-label":R,children:e.jsx(G,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(lt,{children:e.jsx("p",{children:R})})]},$):e.jsxs(i.Fragment,{children:[e.jsxs("button",{onClick:()=>q($),onMouseDown:z?H:void 0,className:_("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",z?"app-region-drag":"app-region-no-drag","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",z?"text-foreground":"text-muted-foreground"),"aria-pressed":z,"aria-label":R,children:[e.jsx(G,{className:"h-4 w-4",weight:"regular"}),Q&&e.jsx("span",{children:R})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},$)})]}),(s||U)&&e.jsxs("div",{className:_("flex items-center gap-2",n?"":"pr-3"),children:[U&&e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:O,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(ur,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:O,className:_("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:O}),e.jsx(Ft,{className:"size-4 opacity-50"})]})}),e.jsx(Qt,{align:"end",className:"w-auto",children:e.jsx(ua,{value:I?.id??"",onValueChange:$=>{$&&E($)},children:T.map($=>{const R=$.label?.trim()?$.label.trim():$.path.split("/").filter(Boolean).pop()||$.path,B=P(R);return e.jsx(ma,{value:$.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:B})},$.id)})})})]}),s&&e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close settings",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",!n&&"app-region-no-drag"),children:e.jsx(Ht,{className:"h-5 w-5"})})}),e.jsx(lt,{children:e.jsxs("p",{children:["Close Settings (",K,"+,)"]})})]})]})]}),e.jsx("div",{className:"flex flex-1 overflow-hidden",children:n?d?e.jsx("div",{className:"flex-1 overflow-hidden bg-background","data-keyboard-avoid":"true",children:e.jsx(os,{children:re()})}):e.jsx("div",{className:_("flex-1 overflow-hidden",C?"bg-background":"bg-sidebar"),children:e.jsx(os,{children:Y()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:_("relative overflow-hidden border-r",x?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":C?"bg-background":"bg-sidebar",y?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:_("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",y?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:W,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(os,{children:Y()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(os,{children:re()})})]})})]})},mS=()=>{const{isSidebarOpen:s,activeMainTab:r,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:l,isMultiRunLauncherOpen:c,setMultiRunLauncherOpen:d,multiRunLauncherPrefillPrompt:u}=$e(),{isMobile:m}=$t(),[f,p]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");i.useEffect(()=>{typeof window>"u"||p(typeof window.opencodeDesktop<"u")},[]),sv({enabled:!0});const g=Aa(b=>b.checkForUpdates);i.useEffect(()=>{const b=setTimeout(()=>{g()},3e3);return()=>clearTimeout(b)},[g]),i.useEffect(()=>{$e.getState().isMobile!==m&&t(m)},[m,t]),i.useEffect(()=>{if(typeof window>"u")return;let b;const v=()=>{b!==void 0&&window.clearTimeout(b),b=window.setTimeout(()=>{$e.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",v),()=>{window.removeEventListener("resize",v),b!==void 0&&window.clearTimeout(b)}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const b=document.documentElement;let v=0,w=!1,N=0,x=null;const k=$e.getState().setKeyboardOpen,A=()=>{x&&(x.style.setProperty("--oc-keyboard-avoid-offset","0px"),x.removeAttribute("data-keyboard-avoid-active"),x=null)},C=I=>{if(!I)return null;const P=I.closest("[data-keyboard-avoid]");if(P)return P;if(I.classList.contains("overlay-scrollbar-container")){const O=I.parentElement;if(O instanceof HTMLElement)return O}return I},M=()=>{v=0,w=!0,b.style.setProperty("--oc-keyboard-inset","0px"),k(!1)},S=()=>{const I=window.visualViewport,P=I?Math.round(I.height):window.innerHeight,O=I?Math.max(0,Math.round(I.offsetTop)):0;b.style.setProperty("--oc-visual-viewport-offset-top",`${O}px`);const U=document.activeElement,Q=U?.tagName,L=Q==="INPUT"||Q==="TEXTAREA"||Q==="SELECT"||!!U?.isContentEditable,H=Math.round(b.clientHeight||window.innerHeight),q=P+O,X=Math.max(0,H-q),re=X>=(L?120:180)?X:0;if(w)re===0&&(w=!1),v=0;else if(v===0)re>0&&L&&(v=re);else{const $=!L&&P>N+6;re===0?(v=0,k(!1)):$?M():(re>0&&L||re>v)&&(v=re,k(!0))}b.style.setProperty("--oc-keyboard-inset",`${v}px`),N=P;const ae=/iPad|iPhone|iPod/.test(navigator.userAgent)&&v>0?34:0;b.style.setProperty("--oc-keyboard-home-indicator",`${ae}px`);const F=L?C(U):null;if(!m||!F||!U)A();else{F!==x&&(A(),x=F);const $=O+P,B=U.getBoundingClientRect().bottom-$,z=8,G=Math.max(v,re),ge=B>z&&G>0?Math.min(B,G):0,oe=x;oe&&(oe.style.setProperty("--oc-keyboard-avoid-offset",`${ge}px`),oe.setAttribute("data-keyboard-avoid-active","true"))}if(m&&L){const $=document.scrollingElement;$&&$.scrollTop!==0&&($.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};S();const D=window.visualViewport;D?.addEventListener("resize",S),D?.addEventListener("scroll",S),window.addEventListener("resize",S),window.addEventListener("orientationchange",S);const E=I=>{const P=I.target;if(!P)return;const O=P.tagName;(O==="INPUT"||O==="TEXTAREA"||O==="SELECT"||P.isContentEditable)&&(w=!1),S()};document.addEventListener("focusin",E,!0);const T=I=>{const P=I.target;if(!P)return;const O=P.tagName;if(O==="INPUT"||O==="TEXTAREA"||O==="SELECT"||P.isContentEditable){const Q=I.relatedTarget,W=Q?.tagName;if(W==="INPUT"||W==="TEXTAREA"||W==="SELECT"||Q?.isContentEditable)return;M()}};return document.addEventListener("focusout",T,!0),()=>{D?.removeEventListener("resize",S),D?.removeEventListener("scroll",S),window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S),document.removeEventListener("focusin",E,!0),document.removeEventListener("focusout",T,!0),A()}},[m]);const y=i.useMemo(()=>{switch(r){case"git":return e.jsx(O0,{});case"diff":return e.jsx(gb,{});case"terminal":return e.jsx(Q0,{});case"files":return e.jsx(aj,{});default:return null}},[r]),h=r==="chat",j=a&&!m;return e.jsx(Gb,{children:e.jsxs("div",{className:_("main-content-safe-area h-[100dvh]",m?"flex flex-col":"flex",f?"bg-transparent":"bg-background"),children:[e.jsx(Tb,{}),e.jsx(_b,{}),e.jsx(zb,{}),m?e.jsxs(e.Fragment,{children:[!(a||c)&&e.jsx(Lc,{}),e.jsx("div",{className:_("flex flex-1 overflow-hidden bg-background",(a||c)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:_("absolute inset-0",!h&&"invisible"),children:e.jsx(os,{children:e.jsx(Xn,{})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(os,{children:y})})]})}),e.jsx(ws,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(ga,{mobileVariant:!0})}),c&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(os,{children:e.jsx(rd,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})}),a&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(os,{children:e.jsx(nl,{onClose:()=>l(!1)})})})]}):e.jsxs(e.Fragment,{children:[!j&&e.jsx(Db,{isOpen:s,isMobile:m,children:e.jsx(ga,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:_("absolute inset-0 flex flex-col",(j||c)&&"invisible"),children:[e.jsx(Lc,{}),e.jsx("div",{className:"flex flex-1 overflow-hidden bg-background",children:e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:_("absolute inset-0",!h&&"invisible"),children:e.jsx(os,{children:e.jsx(Xn,{})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(os,{children:y})})]})})]}),c&&e.jsx("div",{className:_("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(os,{children:e.jsx(rd,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})})]}),j&&e.jsx("div",{className:_("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(os,{children:e.jsx(nl,{onClose:()=>l(!1)})})})]}),!j&&e.jsx(Sb,{})]})})},fS=550,pS=700,hS=280,gS=()=>{const s=kr(),r=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),t=i.useMemo(()=>{const T=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof T=="string"&&T.trim().length>0?T.trim():null},[]),n=i.useRef(!1),[o,a]=i.useState("sessions"),[l,c]=i.useState(0),d=i.useRef(null),u=he(T=>T.currentSessionId),m=he(T=>T.sessions),f=i.useMemo(()=>u?m.find(T=>T.id===u)?.title||"Session":null,[u,m]),p=he(T=>!!T.newSessionDraft?.open),g=he(T=>T.openNewSessionDraft),[y,h]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),j=at(T=>T.isInitialized),b=at(T=>T.initializeApp),v=he(T=>T.loadSessions),w=he(T=>T.loadMessages),N=he(T=>T.messages),[x,k]=i.useState(()=>j),[A,C]=i.useState(!1),M=i.useRef(0);i.useEffect(()=>{u&&a("chat")},[u]),i.useEffect(()=>{const T=s.vscode;T&&T.executeCommand("openchamber.setActiveSession",u,f)},[f,u,s.vscode]),i.useEffect(()=>{r!=="editor"&&!u&&!p&&o==="chat"&&a("sessions")},[u,p,o,r]);const S=i.useCallback(()=>{a("sessions")},[]);i.useEffect(()=>{const T=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(T==="connected"||T==="connecting"||T==="error"||T==="disconnected")&&h(T);const I=P=>{const U=P.detail?.status;(U==="connected"||U==="connecting"||U==="error"||U==="disconnected")&&h(U)};return window.addEventListener("openchamber:connection-status",I),()=>window.removeEventListener("openchamber:connection-status",I)},[]),i.useEffect(()=>{const T=I=>{const O=I.detail?.view;O==="settings"?a("settings"):O==="chat"?a("chat"):O==="sessions"&&a("sessions")};return window.addEventListener("openchamber:navigate",T),()=>window.removeEventListener("openchamber:navigate",T)},[]),i.useEffect(()=>{(async()=>{if(A||x||y!=="connected")return;const I=Date.now();if(!(I-M.current<750)){M.current=I,C(!0);try{const P=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();P&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:j}),j||await b();const O=at.getState();if(!O.isInitialized||!O.isConnected||O.providers.length===0||O.agents.length===0)return;await v();const U=he.getState().error;if(P&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:O.providers.length,agents:O.agents.length,sessions:he.getState().sessions.length,sessionsError:U}),typeof U=="string"&&U.length>0)return;k(!0)}catch{}finally{C(!1)}}})()},[y,j,x,b,A,v]),i.useEffect(()=>{if(r==="editor"&&!n.current&&!(!x||y!=="connected")){if(!t){n.current=!0,g();return}m.some(T=>T.id===t)&&(n.current=!0,he.getState().setCurrentSession(t))}},[y,x,t,g,m,r]),i.useEffect(()=>{(async()=>{if(!x||y!=="connected"||o!=="chat"||p||!u)return;if(!(N.has(u)&&(N.get(u)?.length||0)>0))try{await w(u)}catch{}})()},[y,u,o,x,w,N,p]),i.useEffect(()=>{const T=d.current;if(!T)return;const I=new ResizeObserver(P=>{for(const O of P)c(O.contentRect.width)});return I.observe(T),c(T.clientWidth),()=>I.disconnect()},[]);const D=l>0&&l<fS,E=l>=pS;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(_o,{title:m.find(T=>T.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:e.jsx(Xn,{})})})]}):o==="settings"?e.jsx(nl,{onClose:()=>a(E?"chat":"sessions"),forceMobile:D}):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:hS},children:e.jsx(ga,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(_o,{title:p&&!u?"New session":m.find(T=>T.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:e.jsx(Xn,{})})})]})]}):o==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(_o,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ga,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>a("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(_o,{title:p&&!u?"New session":m.find(T=>T.id===u)?.title||"Chat",showBack:!0,onBack:S,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:e.jsx(Xn,{})})})]})})},_o=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:l,showContextUsage:c})=>{const{getCurrentModel:d}=at(),u=he(h=>h.getContextUsage),m=d(),f=m?.limit&&typeof m.limit=="object"?m.limit:null,p=typeof f?.context=="number"?f.context:0,g=typeof f?.output=="number"?f.output:0,y=u(p,g);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&&t&&e.jsx("button",{onClick:t,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(Fu,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:s,children:s}),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(Xt,{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(so,{className:"h-5 w-5"})}),l&&e.jsx(Ki,{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(en,{className:"h-5 w-5"})}),c&&y&&y.totalTokens>0&&e.jsx(Vi,{totalTokens:y.totalTokens,percentage:y.percentage,contextLimit:y.contextLimit,outputLimit:y.outputLimit??0,size:"compact"})]})},ol=".openchamber",Oo=s=>{const r=Ot.getState(),t=r.activeProjectId,n=t?r.projects.find(c=>c.id===t)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof s=="string"?Rt(s):"",a=`/${ol}/`,l=o.indexOf(a);return l>0?o.slice(0,l):s?Rt(s):null},Rt=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},au=s=>{const r=Rt(s);return!r||r==="/"?`/${ol}`:`${r}/${ol}`},xS=(s,r)=>{const t=Rt(s);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const l=Rt(o);if(l)return l}const a=typeof n.name=="string"?n.name.trim():"";return!a||!t?null:`${t}/${a}`}).filter(n=>!!n)},yS=async s=>{const r=Rt(s);if(!r)return[];try{const n=(await Ee.listLocalDirectory(r)).filter(o=>o.isDirectory);return xS(r,n)}catch{return[]}},Er=(s,r)=>{const t=Rt(s),n=Rt(r);if(!t||!n)return!1;if(t===n)return!0;const o=n==="/"?"/":`${n}/`;return t.startsWith(o)},Tf=async(s,r)=>{const t=Rt(r);if(!t)return t;try{const n=await s.path.get({directory:t});return Rt(n.data?.directory??"")||t}catch{return t}},Ff=async(s,r)=>{const t=Rt(r);if(!t)return[];const n=await Tf(s,t),o=l=>l.filter(c=>{const d=Rt(c.directory??"");return d?Er(d,t)||n!==t&&Er(d,n):!1}),a=async l=>{const c=await s.session.list({directory:l});return Array.isArray(c.data)?c.data:[]};try{const l=o(await a(t));if(l.length>0)return l}catch{}if(n&&n!==t)try{const l=o(await a(n));if(l.length>0)return l}catch{}try{const l=await s.session.list(void 0),c=Array.isArray(l.data)?l.data:[];return o(c)}catch{return[]}},bS=async(s,r)=>{const t=new Map;s.sessions.forEach(o=>{o.worktreeMetadata&&t.set(Rt(o.path),o.worktreeMetadata)});const n=Array.from(new Set(s.sessions.map(o=>Rt(o.path)))).filter(Boolean).filter(o=>!t.has(o));if(n.length===0)return t;try{const o=await Mn(r),a=new Map(o.map(l=>[Rt(l.worktree),l]));n.forEach(l=>{const c=a.get(l);c&&t.set(l,Dn(r,c))})}catch{}return t},Ei=async s=>{const{apiClient:r,group:t,projectDirectory:n,worktreePaths:o}=s,a=await bS(t,n),l=he.getState(),c=Array.from(new Set(o.map(p=>Rt(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<c.length;){const p=c[u];u+=1;const g=t.sessions.filter(v=>Rt(v.path)===p).map(v=>v.id),y=l.getSessionsByDirectory(p),h=Array.isArray(y)?y.map(v=>v.id):[];let j=[];if(h.length===0)try{j=(await Ff(r,p)).map(w=>w.id)}catch{j=[]}const b=Array.from(new Set([...h,...j,...g].filter(Boolean)));m.push({worktreePath:p,sessionIds:b,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,c.length)},f)),m};function vS(s){if(!s)return null;const r=s.split("/");if(r.length<3)return null;const t=r[0];if(!t||t.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:t,provider:n,model:d,index:l?a:1}}const Tr=Vt()(Jt((s,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const t=vt.getState().currentDirectory,n=Oo(t);if(!n){s({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Rt(n),a=au(o),l=r().groups;s({isLoading:!0,error:null});try{const c=Ee.getApiClient(),d=await Tf(c,o),u=au(d);let m=new Map,f=[];try{f=await Mn(o),m=new Map(f.map(w=>[Rt(w.worktree),w]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const N=await c.session.list({directory:o}),x=Array.isArray(N.data)?N.data:[];if(x.some(k=>{const A=Rt(k.directory??"");return Er(A,a)||Er(A,u)}))return x}catch{}const w=await c.session.list(void 0);return Array.isArray(w.data)?w.data:[]},g=async w=>{const N=new Map,x=5;let k=0;const A=async()=>{for(;k<w.length;){const C=w[k];k+=1;const M=Rt(C);if(M)try{(await Ff(c,M)).forEach(D=>N.set(D.id,D))}catch(S){console.debug("Failed to fetch sessions from worktree:",M,S)}}};return await Promise.all(Array.from({length:Math.min(x,w.length)},A)),Array.from(N.values())};let h=(await p()).filter(w=>{const N=Rt(w.directory??"");return N?Er(N,a)||Er(N,u):!1});if(h.length===0){const w=new Set;f.map(x=>Rt(x.worktree)).filter(x=>Er(x,a)||Er(x,u)).forEach(x=>w.add(x));const N=Array.from(new Set([a,u].map(x=>Rt(x)).filter(Boolean)));await Promise.all(N.map(async x=>{(await yS(x)).forEach(A=>w.add(A))})),w.size>0&&(h=await g(Array.from(w)))}const j=new Map;for(const w of h){const N=w.time?.updated??0;j.set(w.id,typeof N=="number"?N:0)}const b=new Map;for(const w of h){const N=vS(w.title);if(!N)continue;const x=Rt(w.directory),k=m.get(x),A={id:w.id,path:x,providerId:N.provider,modelId:N.model,instanceNumber:N.index,branch:k?.branch??"",displayLabel:`${N.provider}/${N.model}`,worktreeMetadata:k?Dn(o,k):void 0},C=b.get(N.groupSlug);C?C.push(A):b.set(N.groupSlug,[A])}const v=Array.from(b.entries()).map(([w,N])=>{const x=N.reduce((k,A)=>{const C=j.get(A.id)??0;return Math.max(k,C)},0);return{name:w,sessions:N.sort((k,A)=>{const C=k.providerId.localeCompare(A.providerId);if(C!==0)return C;const M=k.modelId.localeCompare(A.modelId);return M!==0?M:k.instanceNumber-A.instanceNumber}),lastActive:x||Date.now(),sessionCount:N.length}});v.sort((w,N)=>w.name.localeCompare(N.name)),s({groups:v,isLoading:!1,error:null})}catch(c){console.error("Failed to load agent groups:",c),s({groups:l.length>0?l:[],isLoading:!1,error:c instanceof Error?c.message:"Failed to load agent groups"})}},selectGroup:t=>{const{groups:n}=r(),o=n.find(a=>a.name===t);s({selectedGroupName:t,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:t=>{s({selectedSessionId:t})},deleteGroup:async t=>{const n=r().groups.find(l=>l.name===t);if(!n)return!1;const o=vt.getState().currentDirectory,a=Oo(o);if(!a)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const l=Ee.getApiClient(),c=await Ei({apiClient:l,group:n,projectDirectory:Rt(a),worktreePaths:n.sessions.map(f=>f.path)}),d=he.getState(),u=new Set;c.forEach(({worktreePath:f,sessionIds:p,metadata:g})=>{p.forEach(y=>{u.add(y),g&&(d.setWorktreeMetadata(y,g),d.setSessionDirectory(y,f))})});const{failedIds:m}=await d.deleteSessions(Array.from(u),{archiveWorktree:!0,silent:!0});return m.length>0&&s({error:"Failed to delete some sessions"}),r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),await r().loadGroups(),m.length===0}catch(l){return s({error:l instanceof Error?l.message:"Failed to delete group"}),!1}finally{s({isLoading:!1})}},deleteGroupWorktree:async(t,n)=>{const o=r().groups.find(d=>d.name===t);if(!o)return!1;const a=Rt(n);if(!a)return!1;const l=vt.getState().currentDirectory,c=Oo(l);if(!c)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const d=Ee.getApiClient(),u=await Ei({apiClient:d,group:o,projectDirectory:Rt(c),worktreePaths:[a]}),m=he.getState(),f=new Set;u.forEach(({worktreePath:y,sessionIds:h,metadata:j})=>{h.forEach(b=>{f.add(b),j&&(m.setWorktreeMetadata(b,j),m.setSessionDirectory(b,y))})});const{failedIds:p}=await m.deleteSessions(Array.from(f),{archiveWorktree:!0,silent:!0});p.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups();const g=r().groups.find(y=>y.name===t);if(!g)return r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===t){const y=r().selectedSessionId,h=new Set(g.sessions.map(j=>j.id));(!y||!h.has(y))&&s({selectedSessionId:g.sessions[0]?.id??null})}return p.length===0}catch(d){return s({error:d instanceof Error?d.message:"Failed to delete worktree"}),!1}finally{s({isLoading:!1})}},keepOnlyGroupWorktree:async(t,n)=>{const o=r().groups.find(m=>m.name===t);if(!o)return!1;const a=Rt(n);if(!a)return!1;const c=Array.from(new Set(o.sessions.map(m=>Rt(m.path)).filter(Boolean))).filter(m=>m!==a);if(c.length===0)return!0;const d=vt.getState().currentDirectory,u=Oo(d);if(!u)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const m=Ee.getApiClient(),f=await Ei({apiClient:m,group:o,projectDirectory:Rt(u),worktreePaths:c}),p=he.getState(),g=new Set;f.forEach(({worktreePath:h,sessionIds:j,metadata:b})=>{j.forEach(v=>{g.add(v),b&&(p.setWorktreeMetadata(v,b),p.setSessionDirectory(v,h))})});const{failedIds:y}=await p.deleteSessions(Array.from(g),{archiveWorktree:!0,silent:!0});if(y.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===t){const h=r().groups.find(b=>b.name===t),j=h?.sessions.find(b=>Rt(b.path)===a)??h?.sessions[0]??null;s({selectedSessionId:j?.id??null})}return y.length===0}catch(m){return s({error:m instanceof Error?m.message:"Failed to remove other worktrees"}),!1}finally{s({isLoading:!1})}},getSelectedGroup:()=>{const{groups:t,selectedGroupName:n}=r();return n?t.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:t}=r(),n=r().getSelectedGroup();return!n||!t?null:n.sessions.find(o=>o.id===t)??null},clearError:()=>{s({error:null})}}),{name:"agent-groups-store"})),wS=s=>{const t=Date.now()-s,n=Math.floor(t/(60*1e3)),o=Math.floor(t/(3600*1e3)),a=Math.floor(t/(1440*60*1e3));return n<1?"now":n<60?`${n}m`:o<24?`${o}h`:`${a}d`},jS=({group:s,isSelected:r,onSelect:t})=>{const[n,o]=i.useState(!1),[a,l]=i.useState(!1),[c,d]=i.useState(!1),u=Tr(f=>f.deleteGroup),m=i.useCallback(async()=>{if(c)return;if(d(!0),te.info(`Deleting "${s.name}"...`),await u(s.name))te.success(`Deleted "${s.name}"`);else{const p=Tr.getState().error;te.error(p||`Failed to delete "${s.name}"`)}d(!1),l(!1)},[u,s.name,c]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:_("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:t,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:s.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(zt,{className:"h-3 w-3"}),s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:wS(s.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(qt,{open:n,onOpenChange:o,children:[e.jsx(Kt,{asChild:!0,children:e.jsx("button",{type:"button",className:_("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(Or,{className:"h-3.5 w-3.5"})})}),e.jsx(Qt,{align:"end",className:"min-w-[140px]",children:e.jsx(Et,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),l(!0)},children:"Delete"})})]})})]})}),e.jsx(ms,{open:a,onOpenChange:l,children:e.jsxs(fs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Delete agent group"}),e.jsxs(Ms,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"outline",onClick:()=>l(!1),disabled:c,children:"Cancel"}),e.jsx(Ie,{variant:"destructive",onClick:()=>{m()},disabled:c,children:c?"Deleting…":"Delete"})]})]})})]})},SS=({className:s,selectedGroupName:r,onGroupSelect:t,onNewAgent:n})=>{const[o,a]=i.useState(""),[l,c]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Tr(),f=vt(j=>j.currentDirectory);i.useEffect(()=>{f&&m()},[f,m]);const p=5,g=i.useMemo(()=>{if(!o.trim())return d;const j=o.toLowerCase();return d.filter(b=>b.name.toLowerCase().includes(j))},[o,d]),y=l?g:g.slice(0,p),h=g.length-p;return e.jsxs("div",{className:_("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",s),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:j=>a(j.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(Ie,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(Xt,{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(Ft,{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:[y.map(j=>e.jsx(jS,{group:j,isSelected:r===j.name,onSelect:()=>t?.(j.name)},j.name)),!l&&h>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 (",h,")"]}),l&&g.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&&g.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"})]})]})]})},kS=10*1024*1024,NS=5,CS=({className:s,onCreateGroup:r,isCreating:t=!1})=>{const[n,o]=i.useState(""),[a,l]=i.useState(""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState("HEAD"),[g,y]=i.useState([]),[h,j]=i.useState(!1),[b,v]=i.useState([]),[w,N]=i.useState(!1),[x,k]=i.useState(!1),A=i.useRef(null),C=i.useRef(null),M=vt(K=>K.currentDirectory??null),{isGitRepository:S,isLoading:D}=_l(M),E=i.useMemo(()=>{if(typeof window>"u")return null;const K=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof K=="string"&&K.trim().length>0?K.trim():null},[]),T=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),I=Ot(K=>K.activeProjectId),P=Ot(K=>K.projects),O=i.useMemo(()=>{if(T&&E)return E;if(I){const R=P.find(B=>B.id===I);if(R?.path)return R.path}const K=M??E;if(!K)return null;const ae=K.replace(/\\/g,"/").replace(/\/+$/,"")||K,$=ae.indexOf("/.openchamber/");return $>0?ae.slice(0,$):ae.endsWith("/.openchamber")?ae.slice(0,ae.length-13):ae},[I,P,M,E,T]);i.useEffect(()=>{if(!O)return;let K=!1;return k(!0),(async()=>{try{const ae=await fo(O);K||v(ae)}catch{}finally{K||k(!1)}})(),()=>{K=!0}},[O]);const U=i.useCallback(K=>{c.length>=NS||d(ae=>[...ae,K])},[c.length]),Q=i.useCallback(K=>{d(ae=>ae.filter((F,$)=>$!==K))},[]),W=i.useCallback((K,ae)=>{d(F=>F.map(($,R)=>R===K?ae:$))},[]),L=async K=>{const ae=K.target.files;if(!ae)return;let F=0;for(let $=0;$<ae.length;$++){const R=ae[$];if(R.size>kS){te.error(`File "${R.name}" is too large (max 10MB)`);continue}try{const B=await new Promise((G,ge)=>{const oe=new FileReader;oe.onload=()=>G(oe.result),oe.onerror=ge,oe.readAsDataURL(R)}),z={id:ya(),filename:R.name,mimeType:R.type||"application/octet-stream",size:R.size,dataUrl:B};y(G=>[...G,z]),F++}catch(B){console.error("File attach failed",B),te.error(`Failed to attach "${R.name}"`)}}F>0&&te.success(`Attached ${F} file${F>1?"s":""}`),A.current&&(A.current.value="")},H=K=>{y(ae=>ae.filter(F=>F.id!==K))},q=h||t,X=!!(n.trim()&&a.trim()&&c.length>=1&&S&&!D),Y=async K=>{if(K.preventDefault(),!(!X||q)){j(!0);try{const ae=c.map(({providerID:R,modelID:B,displayName:z,variant:G})=>({providerID:R,modelID:B,displayName:z,variant:G})),F=g.length>0?g.map(R=>({mime:R.mimeType,filename:R.filename,url:R.dataUrl})):void 0,$=b.filter(R=>R.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:ae,agent:u||void 0,worktreeBaseBranch:f,files:F,setupCommands:$.length>0?$:void 0}),o(""),l(""),d([]),m(""),y([]),p("HEAD")}catch(ae){console.error("Failed to create agent group:",ae),te.error("Failed to create agent group")}finally{j(!1)}}},re=K=>{Fl(K)||K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),X&&!q&&Y(K))};return e.jsx("div",{className:_("flex flex-col items-center justify-center h-full w-full p-4",s),children:e.jsxs("form",{onSubmit:Y,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:K=>o(K.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(zt,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(Vm,{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(po,{open:w,onOpenChange:N,children:[e.jsxs(Ta,{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",b.filter(K=>K.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",b.filter(K=>K.trim()).length," configured)"]})]}),e.jsx(Ft,{className:_("h-4 w-4 text-muted-foreground transition-transform duration-200",w&&"rotate-180")})]}),e.jsx(ho,{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."]}),x?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[b.map((K,ae)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:K,onChange:F=>{const $=[...b];$[ae]=F.target.value,v($)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const F=b.filter(($,R)=>R!==ae);v(F)},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(Ht,{className:"h-4 w-4"})})]},ae)),e.jsxs("button",{type:"button",onClick:()=>v([...b,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Xt,{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(Gm,{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(Um,{selectedModels:c,onAdd:U,onRemove:Q,onUpdate:W,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(Ss,{ref:C,id:"prompt",value:a,onChange:K=>l(K.target.value),onKeyDown:re,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"}),g.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:g.map(K=>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:[K.mimeType.startsWith("image/")?e.jsx(mr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(nr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:K.filename,children:K.filename}),e.jsx("button",{type:"button",onClick:()=>H(K.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})]},K.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:L,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(Du,{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:!X||q,className:_("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",X?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:q?e.jsx(Bh,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Sa,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},MS=({group:s,className:r})=>{const{selectedSessionId:t,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Tr(),{setCurrentSession:l,currentSessionId:c}=he(),[d,u]=i.useState(null),[m,f]=i.useState(!1),p=i.useMemo(()=>t?s.sessions.find(w=>w.id===t)??s.sessions[0]??null:s.sessions[0]??null,[s.sessions,t]),g=i.useCallback(w=>{n(w.id),l(w.id)},[n,l]);i.useEffect(()=>{if(s.sessions.length>0){const w=t?s.sessions.find(N=>N.id===t)??s.sessions[0]:s.sessions[0];w&&(w.id!==c&&l(w.id),t||n(w.id))}},[s.name,s.sessions,t,c,n,l]);const y=p?.id===c,h=i.useCallback(()=>{if(!p?.path){te.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{te.success("Worktree path copied")}).catch(()=>{te.error("Failed to copy path")})},[p?.path]),j=i.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),b=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(te.info("Removing worktree..."),await o(s.name,d.path))te.success("Worktree removed");else{const N=Tr.getState().error;te.error(N||"Failed to remove worktree");return}else if(te.info("Removing other worktrees..."),await a(s.name,d.path))te.success("Removed other worktrees");else{const N=Tr.getState().error;te.error(N||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,s.name,m,a,d]);return e.jsxs("div",{className:_("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:s.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{children:"·"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zt,{className:"h-3.5 w-3.5"}),p?.worktreeMetadata?.label||p?.branch||"No branch"]})]})]})}),s.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(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsxs(Ie,{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(cs,{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(Ft,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Qt,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:s.sessions.map(w=>e.jsxs(Et,{onClick:()=>g(w),className:"flex items-center gap-2 py-2",children:[e.jsx(cs,{providerId:w.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:w.modelId}),w.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",w.instanceNumber]})]}),w.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(zt,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:w.worktreeMetadata?.label||w.branch})]})]}),p?.id===w.id&&e.jsx(_t,{className:"h-4 w-4 text-primary flex-shrink-0"})]},w.id))})]})}),e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(Ie,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Or,{className:"h-4 w-4"})})}),e.jsxs(Qt,{align:"end",className:"min-w-[220px]",children:[e.jsx(Et,{onSelect:w=>{w.preventDefault(),j()},variant:"destructive",children:"Remove this worktree"}),e.jsx(Et,{onSelect:w=>{w.preventDefault(),b()},children:"Leave this one, remove others"}),e.jsxs(Et,{onClick:w=>{w.stopPropagation(),h()},disabled:!p?.path,children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(ms,{open:!!d,onOpenChange:w=>{w||u(null)},children:e.jsxs(fs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(Ms,{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:s.name}),"."]})})]}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Ie,{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?y?e.jsx(yf,{sessionId:p.id,children:e.jsx(xf,{})}):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(cs,{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"})})})]})},DS=({className:s})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[t,n]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=at(w=>w.isInitialized),a=at(w=>w.initializeApp),l=he(w=>w.loadSessions),c=vt(w=>w.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Tr(),{createMultiRun:g,isLoading:y}=Yn();i.useEffect(()=>{if(!r)return;const w=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(w==="connected"||w==="connecting"||w==="error"||w==="disconnected")&&n(w);const N=x=>{const A=x.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||t!=="connected")return;const w=Date.now();if(w-d.current<750)return;d.current=w;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(),Zt()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:k.providers.length,agents:k.agents.length,sessions:he.getState().sessions.length})}catch{}})()},[t,o,a,r,l,c]);const h=i.useCallback(w=>{m(w)},[m]),j=i.useCallback(()=>{m(null)},[m]),b=i.useCallback(async w=>{te.info(`Creating agent group "${w.name}" with ${w.models.length} model(s)...`);const N=await g(w);if(N){te.success(`Agent group "${w.name}" created with ${N.sessionIds.length} session(s)`);const x=N.groupSlug,k=async(A=6)=>{for(let C=0;C<A;C+=1){if(await p(),Tr.getState().groups.some(S=>S.name===x))return!0;await new Promise(S=>setTimeout(S,500))}return!1};try{await he.getState().loadSessions()}catch{}await k(),m(x)}else{const x=Yn.getState().error;te.error(x||"Failed to create agent group")}},[g,p,m]),v=f();return e.jsxs("div",{className:_("flex h-full w-full bg-background",s),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(SS,{selectedGroupName:u,onGroupSelect:h,onNewAgent:j})}),e.jsx("div",{className:"flex-1 min-w-0",children:v?e.jsx(MS,{group:v}):e.jsx(CS,{onCreateGroup:b,isCreating:y})})]})},Ii=({...s})=>{const{theme:r="system"}=zh();return e.jsx(Wh,{theme:r,className:"toaster group",closeButton:!0,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)"},...s})},AS=(s=5e3)=>{const[r,t]=Ae.useState(null);return Ae.useEffect(()=>{if(!es())return;let n=!1,o=null;const a=async()=>{const l=await cg();n||(t(l),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},ES=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:l}=he(),c=AS(4e3),d=i.useMemo(()=>{let f=0;return t.forEach(p=>{f+=p.length}),f},[t]),u=i.useMemo(()=>r.map(f=>{const p=t.get(f.id)?.length||0,g=n.get(f.id);return{id:f.id,title:f.title||"Untitled",messageCount:p,isStreaming:g?.isStreaming||!1,isZombie:g?.isZombie||!1,backgroundCount:g?.backgroundMessageCount||0,lastAccessed:g?.lastAccessedAt||0,isCurrent:f.id===o}}).sort((f,p)=>p.lastAccessed-f.lastAccessed),[r,t,n,o]),m=t.size;return e.jsxs(Tl,{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(Hh,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),s&&e.jsx(Ie,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:s,children:e.jsx(Ht,{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," / ",us.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:[us.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:[us.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:[us.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(Uh,{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>us.VIEWPORT_MESSAGES?"text-warning":""}`,children:[f.messageCount," msgs"]}),f.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",f.backgroundCount]})]})]},f.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(Ie,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Xs,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(lt,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{l()},children:"Evict LRU"})}),e.jsx(lt,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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(t.keys()),memoryStates:Object.fromEntries(n)})},children:"Log State"})}),e.jsx(lt,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},IS="openchamber-message-cursors",Tn="cursors",PS=1,Rf="openchamber.messageCursors",Wl=()=>typeof window<"u",Hl=()=>Wl()&&typeof indexedDB<"u",_f=()=>Hl()?new Promise((s,r)=>{const t=indexedDB.open(IS,PS);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Tn)||n.createObjectStore(Tn)},t.onerror=()=>{r(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{s(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),Of=()=>{if(!Wl())return{};try{const s=window.localStorage.getItem(Rf);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},TS=s=>{if(Wl())try{window.localStorage.setItem(Rf,JSON.stringify(s))}catch{}},FS=async(s,r,t)=>{if(!s||!r)return;if(Hl())try{const o=await _f();await new Promise((a,l)=>{const c=o.transaction(Tn,"readwrite");c.objectStore(Tn).put({messageId:r,completedAt:t},s),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=Of();n[s]={messageId:r,completedAt:t},TS(n)},RS=async s=>{if(!s)return null;if(Hl())try{const t=await _f(),n=await new Promise((o,a)=>{const l=t.transaction(Tn,"readonly"),d=l.objectStore(Tn).get(s);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 t.close(),n}catch{}return Of()[s]??null},_S=50,OS=750,iu=new WeakMap,lu=s=>{if(!s||!Array.isArray(s))return 0;const r=iu.get(s);if(r!==void 0)return r;let t=0;for(let n=0;n<s.length;n++){const o=s[n];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(t+=a.length)}}return iu.set(s,t),t},$S=10,cu=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.indexOf("_"),n=t>=0?r.slice(t+1):r;return!n||n.length<$S?null:n},du=(s,r)=>{const t=cu(s),n=cu(r);return!t||!n||t.length!==n.length?!0:t>n},al=new Map,uu=(s,r)=>{const t=`${s}:${r}`,n=al.get(t);if(n&&n.sessionId===s)return n.message;const l=(he.getState().messages.get(s)||[]).find(c=>c.info.id===r)||null;return al.set(t,{sessionId:s,message:l}),l},LS=s=>{const r=s.split(/[-_]/),t=[];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]}`;t.push(a),n+=2;continue}t.push(o),n+=1}return t.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")},BS=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:l,currentSessionId:c,applySessionMetadata:d,sessions:u,getWorktreeMetadata:m,loadMessages:f,loadSessions:p,updateSession:g,removeSessionFromStore:y}=he(),{checkConnection:h}=at(),j=$e(De=>De.nativeNotificationsEnabled),b=$e(De=>De.notificationMode),v=vt(De=>De.currentDirectory),w=i.useMemo(()=>{if(!c)return;try{const ne=m?.(c);if(ne?.path)return ne.path}catch(ne){console.warn("Failed to inspect worktree metadata for session directory:",ne)}const De=u.find(ne=>ne.id===c);if(De&&typeof De.directory=="string"&&De.directory.trim().length>0)return De.directory.trim()},[c,m,u]),N=i.useMemo(()=>{if(w&&w.length>0)return w;if(typeof v=="string"&&v.trim().length>0)return v.trim()},[w,v]);i.useEffect(()=>{let De=!1;const ne=async()=>{try{const be=await Ee.listPendingPermissions();if(De||be.length===0)return;be.forEach(ke=>{o(ke)})}catch{}},rt=async()=>{try{const ke=Ot.getState().projects.map(Re=>Re.path),Qe=u.map(Re=>Re.directory),tt=[N,...ke,...Qe],He=await Ee.listPendingQuestions({directories:tt});if(De||He.length===0)return;He.forEach(Re=>{a(Re)})}catch{}};return ne(),rt(),()=>{De=!0}},[o,a,N,u]);const x=i.useCallback(De=>{if(typeof De!="string")return null;const ne=De.trim();if(!ne)return null;const rt=ne.replace(/\\/g,"/");return rt.length>1?rt.replace(/\/+$/,""):rt},[]),k=i.useCallback(De=>{if(!De)return null;try{const rt=m?.(De),be=x(rt?.path??null);if(be)return be}catch{}const ne=u.find(rt=>rt.id===De);return x(ne?.directory??null)},[m,x,u]),A=$e(De=>De.setEventStreamStatus),C=i.useRef(null),M=i.useCallback((De,ne)=>{const rt=ne??null,be=C.current;if(!(be&&be.status===De&&be.hint===rt)){if(C.current={status:De,hint:rt},Zt()){const Qe={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[De]??"[INFO]",tt=rt?`${Qe} SSE ${De}: ${rt}`:`${Qe} SSE ${De}`;console.info(tt)}A(De,rt)}},[A]),S=i.useCallback((De,ne)=>{if(!De)return Promise.resolve();const rt=Date.now();if(L.current)return L.current;if(rt-H.current<OS)return Promise.resolve();const be=f(De).catch(ke=>{console.warn(`[useEventStream] Failed to resync messages (${ne}):`,ke)}).finally(()=>{L.current=null,H.current=Date.now()});return L.current=be,be},[f]),D=i.useCallback(async De=>{Zt()&&console.info("[useEventStream] Bootstrapping state:",De);try{await Promise.all([p(),c?S(c,De):Promise.resolve()])}catch(ne){console.warn("[useEventStream] Bootstrap failed:",De,ne)}},[c,p,S]),E=i.useCallback((De,ne,rt)=>{Zt()&&console.debug(`[MessageTracker] ${De}: ${ne}`,rt)},[]),T=i.useCallback(De=>{Zt()&&console.debug(`[MessageTracker] ${De}: reported`)},[]),I=i.useRef(null),P=i.useRef(null),O=i.useRef(0);i.useRef(new Set);const U=i.useRef(new Map),Q=i.useRef(null),W=i.useRef(!1),L=i.useRef(null),H=i.useRef(0),q=i.useRef(new Set),X=i.useRef(new Set),Y=i.useRef(new Set),re=i.useRef(new Set),K=i.useCallback(()=>{if(typeof document>"u")return"visible";const De=document.visibilityState;return De==="hidden"&&document.hasFocus()?"visible":De},[]),ae=i.useRef(K()),F=i.useRef(typeof navigator>"u"?!0:navigator.onLine),$=i.useRef(!1),R=i.useRef(null),B=i.useRef(null),z=i.useRef(Date.now()),G=i.useRef(!1),ge=i.useCallback(De=>{const ne=Date.now();ne-z.current>25e3&&(D(De),z.current=ne)},[D]);i.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(G.current=!0)},[]);const oe=i.useRef(new Map),me=i.useRef(new Map),Ne=i.useRef(0),Ce=i.useRef(null),Be=i.useRef(c),V=i.useRef(null),J=i.useRef(null);i.useEffect(()=>{Be.current=c},[c]);const ee=i.useCallback((De,ne)=>{if(!De)return;const rt=Date.now(),be=U.current,ke=be.get(De);if(ke&&rt-ke<3e3)return;be.set(De,rt);const Qe=tt=>{if(typeof ne=="string"&&ne.trim().length>0)return ne.trim();try{const Re=m?.(tt);if(Re?.path)return Re.path}catch{}const He=u.find(Re=>Re.id===tt);return He&&typeof He.directory=="string"&&He.directory.trim().length>0?He.directory.trim():null};setTimeout(async()=>{try{const tt=Qe(De),He=tt?await Ee.withDirectory(tt,()=>Ee.getSession(De)):await Ee.getSession(De);if(He){const Re={};typeof He.title=="string"&&He.title.length>0&&(Re.title=He.title),He.summary!==void 0&&(Re.summary=He.summary),Object.keys(Re).length>0&&d(De,Re)}}catch(tt){console.warn("Failed to refresh session metadata:",tt)}},100)},[d,m,u]),xe=i.useCallback((De,ne)=>{if(he.getState().sessionActivityPhase?.get(De)===ne){me.current=new Map(he.getState().sessionActivityPhase??new Map);return}const be=oe.current.get(De);be&&(clearTimeout(be),oe.current.delete(De));const ke=new Map(he.getState().sessionActivityPhase??new Map);if(ke.set(De,ne),me.current=ke,he.setState({sessionActivityPhase:ke}),ne==="cooldown"){const Qe=setTimeout(()=>{if(oe.current.delete(De),he.getState().sessionActivityPhase?.get(De)==="cooldown"){const He=new Map(he.getState().sessionActivityPhase??new Map);He.set(De,"idle"),me.current=He,he.setState({sessionActivityPhase:He})}},2e3);oe.current.set(De,Qe)}},[]),fe=i.useCallback(async()=>{const De=Date.now();if(Ce.current)return Ce.current;if(De-Ne.current<1500)return;Ne.current=De;const ne=be=>{const ke=new Set,Qe=new Set(u.map(He=>He.id));Object.entries(be).forEach(([He,Re])=>{if(!He||!Re)return;ke.add(He);const nt=Re.type==="busy"||Re.type==="retry"?"busy":"idle";xe(He,nt)});const tt=he.getState().sessionActivityPhase;if(tt)for(const[He,Re]of tt.entries())Qe.has(He)&&(Re==="busy"||Re==="cooldown")&&!ke.has(He)&&xe(He,"idle")},rt=(async()=>{try{const be=await Ee.getGlobalSessionStatus();if(be&&Object.keys(be).length>0){ne(be);return}const ke=new Set;u.forEach(nt=>{const yt=k(nt.id);yt&&ke.add(yt)});const Qe=x(N??null);Qe&&ke.add(Qe);const tt=Array.from(ke);if(tt.length===0){const nt=await Ee.getSessionStatus();nt&&ne(nt);return}const He=await Promise.allSettled(tt.map(nt=>Ee.getSessionStatusForDirectory(nt))),Re={};if(He.forEach(nt=>{nt.status!=="fulfilled"||!nt.value||Object.assign(Re,nt.value)}),Object.keys(Re).length===0&&Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(yt=>yt==="busy"||yt==="cooldown")&&!await Ee.checkHealth().catch(()=>!1))return;ne(Re)}catch{}})().finally(()=>{Ce.current=null});return Ce.current=rt,rt},[N,x,k,u,xe]);i.useEffect(()=>{const De=c??null,ne=V.current,rt=k(De),be=J.current;ne&&De&&ne!==De&&be&&rt&&be!==rt&&fe(),V.current=De,J.current=rt},[c,fe,k]);const Oe=i.useCallback(De=>{if(z.current=Date.now(),Zt()&&console.debug("[useEventStream] Received event:",De.type,De.properties),!De.properties)return;const ne=De.properties;if(!new Set(["session.abort","session.error"]).has(De.type)){const be=(typeof ne.session=="object"&&ne.session!==null?ne.session:null)||(typeof ne.sessionInfo=="object"&&ne.sessionInfo!==null?ne.sessionInfo:null);if(be){const ke=be,Qe=typeof ke.id=="string"&&ke.id.length>0?ke.id:typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:typeof ne.id=="string"&&ne.id.length>0?ne.id:void 0;if(Qe){const tt=typeof ke.title=="string"?ke.title:typeof ne.title=="string"?ne.title:void 0,He=typeof ke.summary=="object"&&ke.summary!==null?ke.summary:typeof ne.summary=="object"&&ne.summary!==null?ne.summary:void 0;if(tt!==void 0||He!==void 0){const Re={};tt!==void 0&&(Re.title=tt),He!==void 0&&(Re.summary=He),d(Qe,Re)}}}}switch(De.type){case"server.connected":h();break;case"global.disposed":case"server.instance.disposed":{D("server_disposed_event");break}case"openchamber:session-activity":{const be=typeof ne.sessionId=="string"?ne.sessionId:null,ke=typeof ne.phase=="string"?ne.phase:null;be&&(ke==="idle"||ke==="busy"||ke==="cooldown")&&(xe(be,ke),ee(be,typeof ne.directory=="string"?ne.directory:null));break}case"mcp.tools.changed":{const be=typeof ne.directory=="string"?ne.directory:N;Hn.getState().refresh({directory:be??null,silent:!0});break}case"session.status":if(G.current)break;{const be=typeof ne.sessionID=="string"?ne.sessionID:null,ke=typeof ne.status=="object"&&ne.status!==null?ne.status:null,Qe=typeof ke?.type=="string"?ke.type:null;be&&Qe&&(xe(be,Qe==="busy"||Qe==="retry"?"busy":"idle"),ee(be,typeof ne.directory=="string"?ne.directory:null))}break;case"message.part.updated":{const be=typeof ne.part=="object"&&ne.part!==null?ne.part:null;if(!be)break;const ke=be,Qe=typeof ne.info=="object"&&ne.info!==null?ne.info:ne,tt=typeof Qe.sessionID=="string"?Qe.sessionID:null,He=typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof tt=="string"&&tt.length>0?tt:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,Re=typeof Qe.id=="string"?Qe.id:null,nt=typeof ke.messageID=="string"&&ke.messageID.length>0?ke.messageID:typeof Re=="string"&&Re.length>0?Re:typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;if(!He||!nt){Zt()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:ke.sessionID??tt??ne.sessionID,messageID:ke.messageID??Re??ne.messageID});break}const yt=He,ct=nt,It=he.getState().sessionMemoryState.get(yt)?.trimmedHeadMaxId;if(It&&!du(ct,It)){Zt()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:yt,messageId:ct,trimmedHeadMaxId:It});break}let Tt="assistant";if(Qe&&typeof Qe.role=="string")Tt=Qe.role;else{const ze=uu(yt,ct);if(ze){const Ze=ze.info.role;typeof Ze=="string"&&(Tt=Ze)}}if(E(ct,"part_received",{role:Tt}),Tt==="user"&&ke.synthetic===!0){E(ct,"skipped_synthetic_user_part");break}const je={...be,type:be.type||"text"};E(ct,"addStreamingPart_called"),s(yt,ct,je,Tt);break}case"message.updated":{const be=typeof ne.info=="object"&&ne.info!==null?ne.info:ne,ke=be,Qe=typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,tt=typeof ke.id=="string"&&ke.id.length>0?ke.id:typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;if(!Qe||!tt){Zt()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:ke.sessionID??ne.sessionID,messageID:ke.id??ne.messageID});break}const He=Qe,Re=tt,nt=he.getState().sessionMemoryState.get(He)?.trimmedHeadMaxId;if(nt&&!du(Re,nt)){Zt()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:He,messageId:Re,trimmedHeadMaxId:nt});break}if(G.current&&Zt())try{const we=ne.parts||ke.parts||[],Ue=(Array.isArray(we)?we.filter(_e=>_e?.type==="text"):[]).map(_e=>{const et=_e;return typeof et?.text=="string"?et.text:typeof et?.content=="string"?et.content:""}).join(`
|
|
135
|
-
`);console.info("[STREAM-TRACE] message.updated",{messageId:Re,role:ke.role,status:ke.status,textLen:Ue.length,textPreview:Ue.slice(0,120),partsCount:Array.isArray(we)?we.length:0})}catch{}if(E(Re,"message_updated",{role:ke.role}),ke.role==="user"){const we=ne.parts||ke.parts,ve=Array.isArray(we)?we:[],Ue={...be,userMessageMarker:!0,clientRole:"user"};if(t(He,Re,Ue),ve.length>0)for(let _e=0;_e<ve.length;_e++){const et=ve[_e];if(et.synthetic===!0)continue;const pt={...et,type:et?.type||"text",sessionID:et?.sessionID||He,messageID:et?.messageID||Re};s(He,Re,pt,"user")}E(Re,"user_message_created_from_event",{partsCount:ve.length});break}const yt=uu(He,Re),ct=lu(yt?.parts||[]),It=yt?.info?.finish==="stop",Tt=ne.parts||ke.parts,je=Array.isArray(Tt)?Tt:[],ze=je.length>0,Ye=typeof(ke.time||{})?.completed=="number";if(!ze&&!Ye)break;const mt=be.finish,ye=typeof mt=="string"?mt:null,ie=ye==="stop";if(ke.role==="assistant"&&ze){const we=lu(je);if(ct>0&&we+_S<ct&&!ie){E(Re,"skipped_shrinking_update",{incomingLen:we,existingLen:ct});break}if(G.current){const Ue=ct>0&&we<ct,_e=je.some(pt=>{if(!pt||pt.type!=="text")return!1;const ft=pt;return typeof ft.text=="string"&&ft.text.length>0});if(Ue&&!(ie&&_e)){E(Re,"desktop_shrinking_update_suppressed",{incomingLen:we,existingLen:ct});break}}}if(t(He,Re,be),ze&&ke.role!=="user"){const Ue=(he.getState().messages.get(He)||[]).find(pt=>pt.info.id===Re),_e=!Ue||Ue.parts.length===0;E(Re,_e?"server_parts_injected":"server_parts_refreshed",{count:je.length});const et=G.current&&ke.role==="assistant"?je.filter(pt=>pt?.type!=="text"):je;for(let pt=0;pt<et.length;pt++){const ft=et[pt],Pt={...ft,type:ft?.type||"text",sessionID:ft?.sessionID||He,messageID:ft?.messageID||Re};s(He,Re,Pt,ke.role),E(Re,`server_part_${pt}`)}}const de=be.time,We=de?.completed,Ge=typeof We=="number"&&Number.isFinite(We),bt=ye==="stop"||It;if(be.role==="assistant"&&(Ge||bt)&&be.role==="assistant"){const ve=he.getState().messages.get(He)||[];let Ue=null,_e="";for(let Te=0;Te<ve.length;Te++){const st=ve[Te];st.info.role==="assistant"&&st.info.id>_e&&(_e=st.info.id,Ue=st.info.id)}if(c===He&&Re!==Ue)break;if(!bt&&G.current){E(Re,"desktop_completion_without_stop");break}const pt=Ge?We:Date.now();if(Ge||t(He,Re,{...be,time:{...de??{},completed:pt}}),E(Re,"completed",{timeCompleted:pt}),T(Re),FS(He,Re,pt),r(He,Re),ye==="stop"&&rn()&&j&&(b==="always"||ae.current==="hidden")){const st=Y.current;if(!st.has(Re)){st.add(Re);const Ve=Qs();if(Ve?.notifications){const Xe=ke.mode||"agent",kt=ke.modelID||"assistant",Lt=`${Xe.charAt(0).toUpperCase()+Xe.slice(1)} agent is ready`,ts=`${LS(kt)} completed the task`;Ve.notifications.notifyAgentCompletion({title:Lt,body:ts,tag:Re})}}}G.current||ye==="stop"&&he.getState().sessionActivityPhase?.get(He)==="busy"&&xe(He,"cooldown");const ft=be.sessionID,Pt=typeof ft=="string"&&ft.length>0?ft:He;ee(Pt,typeof ne.directory=="string"?ne.directory:null),be.summary&&typeof Pt=="string"&&n(Pt,null)}break}case"session.created":case"session.updated":{const be=typeof ne.info=="object"&&ne.info!==null?ne.info:typeof ne.sessionInfo=="object"&&ne.sessionInfo!==null?ne.sessionInfo:typeof ne.session=="object"&&ne.session!==null?ne.session:ne,ke=typeof be.id=="string"&&be.id.length>0?be.id:typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:typeof ne.id=="string"&&ne.id.length>0?ne.id:void 0;if(ke){const Qe=typeof be.time=="object"&&be.time!==null?be.time:typeof ne.time=="object"&&ne.time!==null?ne.time:null,tt=Qe&&typeof Qe.compacting=="number"?Qe.compacting:null;n(ke,tt);const He=typeof be.directory=="string"?be.directory:typeof ne.directory=="string"?ne.directory:null,Re={...be,id:ke,...He?{directory:He}:{}};g(Re)}break}case"session.deleted":{const be=typeof ne.sessionID=="string"?ne.sessionID:typeof ne.id=="string"?ne.id:null;be&&y(be);break}case"session.abort":{const be=typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,ke=typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;be&&ke&&r(be,ke);break}case"permission.asked":{if(!("sessionID"in ne)||typeof ne.sessionID!="string")break;const be=ne;o(be);const ke=`${be.sessionID}:${be.id}`;q.current.has(ke)||setTimeout(()=>{if(Be.current===be.sessionID||!he.getState().permissions.get(be.sessionID)?.some(Re=>Re.id===be.id))return;q.current.add(ke);const He=he.getState().sessions.find(Re=>Re.id===be.sessionID)?.title||"Session";as(async()=>{const{toast:Re}=await import("./vendor-.bun-CqCnPJev.js").then(nt=>nt.cy);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.warning("Permission required",{description:He,action:{label:"Open",onClick:()=>{$e.getState().setActiveMainTab("chat"),he.getState().setCurrentSession(be.sessionID)}}})})},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in ne)||typeof ne.sessionID!="string")break;const be=ne;a(be);const ke=`${be.sessionID}:${be.id}`;if(rn()&&j&&(b==="always"||ae.current==="hidden")){const tt=re.current;if(!tt.has(ke)){tt.add(ke);const He=Qs();He?.notifications&&He.notifications.notifyAgentCompletion({title:"Input needed",body:"Agent is waiting for your response",tag:ke})}}X.current.has(ke)||setTimeout(()=>{if(Be.current===be.sessionID||!he.getState().questions.get(be.sessionID)?.some(Re=>Re.id===be.id))return;X.current.add(ke);const He=he.getState().sessions.find(Re=>Re.id===be.sessionID)?.title||"Session";as(async()=>{const{toast:Re}=await import("./vendor-.bun-CqCnPJev.js").then(nt=>nt.cy);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.info("Input needed",{description:He,action:{label:"Open",onClick:()=>{$e.getState().setActiveMainTab("chat"),he.getState().setCurrentSession(be.sessionID)}}})})},0);break}case"question.replied":{const be=typeof ne.sessionID=="string"?ne.sessionID:null,ke=typeof ne.requestID=="string"?ne.requestID:null;be&&ke&&l(be,ke);break}case"todo.updated":{const be=typeof ne.sessionID=="string"?ne.sessionID:null,ke=Array.isArray(ne.todos)?ne.todos:null;be&&ke&&vv(be,ke);break}}},[c,j,b,s,r,t,o,a,l,h,ee,n,d,E,T,xe,g,y,D,N]),Se=i.useCallback(()=>{const De=K();return ae.current=De,De==="visible"&&F.current},[K]),Le=i.useCallback(()=>{Zt()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:G.current,hasUnsubscribe:!!I.current,currentSessionId:Be.current,effectiveDirectory:N,onlineStatus:F.current,visibilityState:ae.current,lastEventTimestamp:z.current,reconnectAttempts:O.current})},[N]),pe=i.useCallback(async()=>!0,[]),it=i.useCallback(()=>{if(W.current){Zt()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(W.current=!0,P.current&&(clearTimeout(P.current),P.current=null),I.current){const De=I.current;I.current=null;try{De()}catch(ne){console.warn("[useEventStream] Error during unsubscribe:",ne)}}W.current=!1},[]),xt=i.useCallback(async De=>{if(Le(),!Se()){$.current=!0,F.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}G.current&&(await pe()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),De?.resetAttempts&&(O.current=0),it(),z.current=Date.now(),M("connecting",null),Zt()&&console.info("[useEventStream] Starting event stream...");const ne=be=>{console.warn("Event stream error:",be)},rt=()=>{const be=$.current;if(O.current=0,$.current=!1,z.current=Date.now(),M("connected",null),h(),Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(Qe=>Qe==="busy"||Qe==="cooldown")&&fe(),be)D("sse_reconnected");else{const Qe=Be.current;Qe&&setTimeout(()=>{S(Qe,"sse_reconnected").then(()=>ee(Qe)).catch(tt=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",tt)})},0)}};if(Zt()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:N,isCleaningUp:W.current}),W.current){Zt()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const be=Ee.subscribeToGlobalEvents(Qe=>{const tt=Qe.payload,He=Qe.payload,Re=typeof He.properties=="object"&&He.properties!==null?He.properties:{},nt=Qe.directory&&Qe.directory!=="global"?{...Re,directory:Qe.directory}:Re;Oe({type:typeof tt.type=="string"?tt.type:"",properties:nt})},ne,rt),ke=()=>{try{be()}catch(Qe){console.warn("[useEventStream] Error during unsubscribe:",Qe)}};W.current?ke():I.current=ke}catch(be){console.error("[useEventStream] Error during subscription:",be),ne(be)}},[Se,it,M,h,S,ee,Oe,N,fe,pe,Le,D]),Mt=i.useCallback(De=>{if(!Se()){$.current=!0,it(),F.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}const ne=O.current+1;O.current=ne;const rt=De??`Retrying (${ne})`;M("reconnecting",rt);const be=ne<=3?Math.min(1e3*Math.pow(2,ne-1),8e3):Math.min(2e3*Math.pow(2,ne-3),32e3),ke=Math.floor(Math.random()*250),Qe=be+ke;P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{xt({resetAttempts:!1})},Qe)},[Se,it,M,xt]);i.useEffect(()=>{const De=oe.current;typeof window<"u"&&(window.__messageTracker=E);let ne=null;G.current&&typeof window<"u"&&(ne=nt=>{const yt=typeof nt.detail?.sessionId=="string"?nt.detail.sessionId:null,ct=typeof nt.detail?.phase=="string"?nt.detail.phase:null;yt&&(ct==="idle"||ct==="busy"||ct==="cooldown")&&(xe(yt,ct),ee(yt))},window.addEventListener("openchamber:session-activity",ne));const rt=()=>{R.current&&(clearTimeout(R.current),R.current=null)},be=()=>{R.current||(R.current=setTimeout(()=>{const nt=K();ae.current=nt,nt!=="visible"?(it(),$.current=!0,M("paused","Paused while hidden")):rt()},5e3))},ke=()=>{if(ae.current=K(),ae.current==="visible"){if(rt(),ge("visibility_restore"),$.current||!I.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const nt=Be.current;nt&&(S(nt,"visibility_restore").catch(()=>{}),ee(nt)),fe(),M("connecting","Resuming stream"),xt({resetAttempts:!0})}}else M("paused","Paused while hidden"),be()},Qe=()=>{if(ae.current=K(),ae.current==="visible"&&(rt(),ge("window_focus"),$.current||!I.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const nt=Be.current;nt&&(ee(nt),S(nt,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(yt=>console.warn("[useEventStream] Failed to refresh messages:",yt))),fe(),M("connecting","Resuming stream"),xt({resetAttempts:!0})}},tt=()=>{F.current=!0,ge("network_restored"),($.current||!I.current)&&(M("connecting","Network restored"),xt({resetAttempts:!0}))},He=()=>{F.current=!1,$.current=!0,M("offline","Waiting for network"),it()};typeof document<"u"&&document.addEventListener("visibilitychange",ke),typeof window<"u"&&(window.addEventListener("online",tt),window.addEventListener("offline",He),window.addEventListener("focus",Qe));const Re=setTimeout(()=>{xt({resetAttempts:!0})},100);return B.current&&clearInterval(B.current),B.current=setInterval(()=>{if(!Se())return;const nt=Date.now();Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(ct=>ct==="busy"||ct==="cooldown")&&fe(),nt-z.current>45e3&&Promise.resolve().then(async()=>{try{await Ee.checkHealth()?z.current=Date.now():Mt("Refreshing stalled stream")}catch(ct){console.warn("Health check after stale stream failed:",ct),Mt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Re),ne&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",ne),typeof document<"u"&&document.removeEventListener("visibilitychange",ke),typeof window<"u"&&(window.removeEventListener("online",tt),window.removeEventListener("offline",He),window.removeEventListener("focus",Qe)),rt(),B.current&&(clearInterval(B.current),B.current=null),De.forEach(nt=>clearTimeout(nt)),De.clear(),al.clear(),Y.current.clear(),re.current.clear(),$.current=!1,ae.current=K(),F.current=typeof navigator>"u"?!0:navigator.onLine,it(),Q.current&&(clearTimeout(Q.current),Q.current=null),M("idle",null)}},[N,E,K,it,M,xt,Mt,f,ee,xe,fe,Se,p,ge,S])},zS=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=he(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=$e(),{themeMode:p,setThemeMode:g}=Wr(),{working:y}=rf(),h=i.useRef(null),j=i.useRef(null),b=i.useRef(!1),v=i.useCallback(()=>{j.current&&(clearTimeout(j.current),j.current=null),h.current=null,n()},[n]);i.useEffect(()=>{const w=N=>{if(Ds(N)&&N.key==="k"&&(N.preventDefault(),a()),Ds(N)&&N.shiftKey&&N.key.toLowerCase()==="l"){const k=Qs()?.diagnostics;if(!k||(N.preventDefault(),b.current))return;b.current=!0,k.downloadLogs().then(({fileName:A,content:C})=>{const M=A||"openchamber.log",S=new Blob([C],{type:"text/plain;charset=utf-8"}),D=URL.createObjectURL(S),E=document.createElement("a");E.href=D,E.download=M,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(D)}).finally(()=>{b.current=!1});return}if(Ds(N)&&N.key==="."&&(N.preventDefault(),l()),Ds(N)&&N.key.toLowerCase()==="n"){N.preventDefault();const x=Wt(),k=at.getState().settingsAutoCreateWorktree;if(x?!1:k?!N.shiftKey:N.shiftKey){u("chat"),d(!1),Ra();return}u("chat"),d(!1),s()}if(Ds(N)&&N.key==="/"){N.preventDefault();const x=["light","dark","system"],A=(x.indexOf(p)+1)%x.length;g(x[A])}if(Ds(N)&&!N.shiftKey&&N.key.toLowerCase()==="t"){N.preventDefault();const{isTimelineDialogOpen:x,setTimelineDialogOpen:k}=$e.getState();k(!x);return}if(Ds(N)&&!N.shiftKey&&N.key===","){N.preventDefault();const{isSettingsDialogOpen:x}=$e.getState();m(!x);return}if(Ds(N)&&!N.shiftKey&&N.key.toLowerCase()==="l"){N.preventDefault();const{isMobile:x,isSessionSwitcherOpen:k}=$e.getState();x?d(!k):c();return}if(Ds(N)&&!N.shiftKey&&N.key.toLowerCase()==="i"){N.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Ds(N)&&N.shiftKey&&N.key.toLowerCase()==="m"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S,isModelSelectorOpen:D}=$e.getState();if(x||k||A||C||M||!(S==="chat"))return;N.preventDefault(),f(!D);return}if(Ds(N)&&N.shiftKey&&N.key.toLowerCase()==="t"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=$e.getState();if(x||k||A||C||M||!(S==="chat"))return;const T=at.getState();if(T.getCurrentModelVariants().length===0)return;N.preventDefault(),T.cycleCurrentVariant();const P=at.getState().currentVariant,O=he.getState(),U=O.currentSessionId,Q=at.getState().currentAgentName,W=at.getState().currentProviderId,L=at.getState().currentModelId;U&&Q&&W&&L&&O.saveAgentModelVariantForSession(U,Q,W,L,P);return}if(N.key==="Escape"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=$e.getState();if(x){N.preventDefault(),m(!1),v();return}if(k||A||C||M||!(S==="chat")){v();return}const T=o;if(!(y.canAbort&&!!T)){v();return}const P=Date.now(),O=h.current;if(O&&P<O){N.preventDefault(),v(),r();return}N.preventDefault();const U=t(3e3)??P+3e3;h.current=U,j.current&&clearTimeout(j.current);const Q=Math.max(U-P,0);j.current=setTimeout(()=>{h.current&&Date.now()>=h.current&&v()},Q||0);return}};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[s,r,a,l,c,d,u,m,f,g,p,y,t,v,o]),i.useEffect(()=>()=>{v()},[v])},mu="openchamber:menu-action",WS=s=>{const{openNewSessionDraft:r}=he(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=$e(),{addProject:u}=Ot(),{requestAccess:m,startAccessing:f}=_a(),{setThemeMode:p}=Wr(),g=i.useRef(!1),y=i.useCallback(()=>{es()?m("").then(async h=>{if(!h.success||!h.path){h.error&&h.error!=="Directory selection cancelled"&&te.error("Failed to select directory",{description:h.error});return}const j=await f(h.path);if(!j.success){te.error("Failed to open directory",{description:j.error||"Desktop could not grant file access."});return}u(h.path,{id:h.projectId})||te.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(h=>{console.error("Desktop: Error selecting directory:",h),te.error("Failed to select directory")}):En.requestDirectoryDialog()},[u,m,f]);i.useEffect(()=>{const h=j=>{switch(j.detail){case"about":d(!0);break;case"settings":c(!0);break;case"command-palette":t();break;case"new-session":l("chat"),a(!1),r();break;case"new-worktree-session":l("chat"),a(!1),Ra();break;case"change-workspace":y();break;case"open-git-tab":{const{activeMainTab:v}=$e.getState();l(v==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:v}=$e.getState();l(v==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:v}=$e.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":s?.();break;case"help-dialog":n();break;case"download-logs":{const w=Qs()?.diagnostics;if(!w||g.current)break;g.current=!0,w.downloadLogs().then(({fileName:N,content:x})=>{const k=N||"openchamber.log",A=new Blob([x],{type:"text/plain;charset=utf-8"}),C=URL.createObjectURL(A),M=document.createElement("a");M.href=C,M.download=k,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(C),te.success("Logs saved",{description:`Downloaded to ~/Downloads/${k}`})}).catch(()=>{te.error("Failed to download logs")}).finally(()=>{g.current=!1});break}}};return window.addEventListener(mu,h),()=>window.removeEventListener(mu,h)},[r,t,n,o,a,l,c,d,p,s,y])},HS=s=>s.role==="assistant",fu=s=>{const r=s.info;if(!HS(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},ea=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},pu=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>Kn(n)).join(" ").replace(/\s+/g," ").trim(),US=(s,r)=>{if(!s||!ea(s.info))return-1;const t=pu(s),n=typeof s.info?.time?.created=="number"?s.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((l,c)=>{if(!ea(l.info))return;const d=pu(l),u=!!(t&&d&&d===t),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}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=c,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(l=>{if(!ea(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},VS=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=he(),n=i.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=i.useRef(void 0),a=i.useRef(0),l=i.useCallback(async()=>{if(!s||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=r.get(s)||[],u=await Ee.getSessionMessages(s),m=await RS(s);if(!u)return;const f=d[d.length-1];if(f){const p=u.findIndex(h=>h.info.id===f.info.id),y=p===-1?US(f,u):p;if(y!==-1)if(y<u.length-1){const h=u.slice(y+1);console.log(`[SYNC] Found ${h.length} new messages to append`);const j=[...d,...h],{syncMessages:b}=he.getState();b(s,j)}else{const h=u[y],j=d[d.length-1],b=fu(h),v=fu(j);if(b&&!v){console.log("[SYNC] Last message completed on server");const w=[...d.slice(0,-1),h],{syncMessages:N}=he.getState();N(s,w)}}else if(ea(f.info)){const h=u.slice(-us.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:j}=he.getState();j(s,h)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(m){const p=u.findIndex(g=>g.info.id===m.messageId);if(p!==-1){if(p<u.length-1){const y=u.slice(p+1).slice(-us.VIEWPORT_MESSAGES);if(y.length>0){console.log(`[SYNC] Restoring ${y.length} messages after cursor`);const{syncMessages:h}=he.getState();h(s,y)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const g=u.slice(-us.VIEWPORT_MESSAGES),{syncMessages:y}=he.getState();y(s,g)}}else if(u.length>0){const p=u.slice(-us.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:g}=he.getState();g(s,p)}}catch(d){console.debug("Background sync failed:",d)}}},[s,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(!s||n)return;const c=()=>{document.visibilityState==="visible"&&l(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,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])},GS=()=>{i.useEffect(()=>{let s=!1;return(async()=>{try{const t=await Ee.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).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&&he.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function qS(){const{git:s}=kr(),r=vt(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=he(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=Gt(),u=i.useMemo(()=>{const m=t?o.get(t)??void 0:void 0,p=n.find(g=>g.id===t)?.directory??null;return m?.path??p??r??null},[t,n,o,r]);i.useEffect(()=>{if(!u||!s){c();return}return a(u),d(u,s),l(s),()=>{c()}},[u,s,a,l,c,d])}function KS({children:s}){return qS(),e.jsx(e.Fragment,{children:s})}const QS=()=>{const[{isUpdating:s,message:r},t]=i.useState(()=>Eg());return i.useEffect(()=>Ag(t),[]),s?e.jsxs("div",{className:"fixed inset-0 z-[9999] flex flex-col items-center justify-center gap-6 backdrop-blur-md",children:[e.jsx($l,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},YS=({open:s,onOpenChange:r})=>{const[t,n]=i.useState(null);i.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:c}=await as(async()=>{const{getVersion:u}=await import("./vendor-.bun-CqCnPJev.js").then(m=>m.cB);return{getVersion:u}},__vite__mapDeps([0,1])),d=await c();n(d)}catch{n("1.5.0")}})():n("1.5.0")},[s]);const o=t;return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsx(fs,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx($l,{width:64,height:64}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),o&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",o]})]}),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 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($i,{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(Lu,{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(Li,{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 Pi({apis:s,children:r}){return e.jsx(Ml.Provider,{value:s,children:r})}const XS="curl -fsSL https://opencode.ai/install | bash",JS=3e3;function ZS({onCopy:s}){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:s,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Ys,{className:"h-4 w-4"})})]})}const ek=3e4;function tk({onCliAvailable:s}){const[r,t]=i.useState(!1),[n,o]=i.useState(!1),[a,l]=i.useState(!1);i.useEffect(()=>{const m=setTimeout(()=>o(!0),ek);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 as(async()=>{const{getCurrentWindow:g}=await import("./vendor-.bun-CqCnPJev.js").then(y=>y.cA);return{getCurrentWindow:g}},__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(XS),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return i.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,JS);return m(),()=>clearInterval(f)},[d,s]),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(ta,{className:"h-4 w-4"})]})," ","is required to continue."]})]}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"bg-background/60 backdrop-blur-sm border border-border rounded-lg px-5 py-3 font-mono text-sm w-fit",children:r?e.jsxs("div",{className:"flex items-center justify-center gap-2",style:{color:"var(--status-success)"},children:[e.jsx(_t,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(ZS,{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(ta,{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 sk=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=$e();return e.jsx(YS,{open:s,onOpenChange:r})};function rk({apis:s}){const{initializeApp:r,isInitialized:t,isConnected:n}=at(),{error:o,clearError:a,loadSessions:l}=he(),c=vt(x=>x.currentDirectory),d=vt(x=>x.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=jf(),[g,y]=i.useState(()=>s.runtime.isDesktop),[h,j]=i.useState(()=>s.runtime.isVSCode),[b,v]=i.useState(()=>s.runtime.isDesktop?dg():!0);i.useEffect(()=>{y(s.runtime.isDesktop),j(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),i.useEffect(()=>(oc(s),()=>oc(null)),[s]),i.useEffect(()=>{if(typeof document>"u")return;const x=document.documentElement,k=Od[f]?.stack??Od[z0].stack,A=Kr[p]?.stack??Kr[Jo].stack;x.style.setProperty("--font-sans",k),x.style.setProperty("--font-heading",k),x.style.setProperty("--font-family-sans",k),x.style.setProperty("--font-mono",A),x.style.setProperty("--font-family-mono",A),x.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=k)},[f,p]),i.useEffect(()=>{if(t){const k=setTimeout(()=>{const A=document.getElementById("initial-loading");A&&(A.classList.add("fade-out"),setTimeout(()=>{A.remove()},300))},150);return()=>clearTimeout(k)}},[t]),i.useEffect(()=>{const x=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&!t&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},5e3);return()=>clearTimeout(x)},[t]),i.useEffect(()=>{(async()=>h||await r())()},[r,h]),i.useEffect(()=>{if(d)return;(async()=>h||n&&(Ee.setDirectory(c),await l()))()},[c,d,l,n,h]),BS(),zS();const w=i.useCallback(()=>{m(x=>!x)},[]);WS(w),VS(),GS(),Ef(),i.useEffect(()=>{const x=k=>{Ds(k)&&k.shiftKey&&k.key==="D"&&(k.preventDefault(),m(A=>!A))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=i.useCallback(()=>{v(!0),window.location.reload()},[]);return g&&!b?e.jsx(os,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(tk,{onCliAvailable:N})})}):h?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(os,{children:e.jsx(Pi,{apis:s,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(DS,{}),e.jsx(Ii,{})]})})}):e.jsx(os,{children:e.jsx(Pi,{apis:s,children:e.jsx(Pd,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(gS,{}),e.jsx(Ii,{})]})})})}):e.jsx(os,{children:e.jsx(Pi,{apis:s,children:e.jsx(KS,{children:e.jsx(Pd,{children:e.jsxs("div",{className:`h-full text-foreground ${g?"bg-transparent":"bg-background"}`,children:[e.jsx(mS,{}),e.jsx(Ii,{}),e.jsx(QS,{}),e.jsx(sk,{}),u&&e.jsx(ES,{onClose:()=>m(!1)})]})})})})})}const $f=async()=>{if(typeof window>"u")return;let s=null,r=null;try{s=window.localStorage.getItem("homeDirectory"),r=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const t=vt.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&t.setDirectory(r,{showOverlay:!1})},Lf="/auth/session",nk=async()=>fetch(Lf,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),hu=async s=>fetch(Lf,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),Ul=({children:s})=>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:s})]}),ok=({message:s="Preparing workspace…"})=>e.jsx(Ul,{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:s})})}),ak=({onRetry:s})=>e.jsx(Ul,{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(Ie,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),ik=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},lk=()=>{try{const s=new URL(window.location.href);s.searchParams.delete("token"),window.history.replaceState({},"",s.toString())}catch{}},ck=({children:s})=>{const r=i.useMemo(()=>es(),[]),t=i.useMemo(()=>Wt(),[]),n=r||t,[o,a]=i.useState(()=>n?"authenticated":"pending"),[l,c]=i.useState(""),[d,u]=i.useState(!1),[m,f]=i.useState(""),p=i.useRef(null),g=i.useRef(n),y=i.useRef(!1),h=i.useCallback(async()=>{if(n){a("authenticated");return}a(b=>b==="authenticated"?b:"pending");try{const b=await nk();if(b.ok){a("authenticated"),f("");return}if(b.status===401){a("locked");return}a("error")}catch(b){console.warn("Failed to check session status:",b),a("error")}},[n]);i.useEffect(()=>{n||h()},[h,n]),i.useEffect(()=>{!n&&o==="locked"&&(g.current=!1)},[n,o]),i.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),i.useEffect(()=>{if(n||o!=="locked"||y.current||d)return;const b=ik();b&&(y.current=!0,lk(),u(!0),f(""),hu(b).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"&&!g.current&&(g.current=!0,(async()=>(await qu(),await Ku(),await $f()))())},[n,o]);const j=async b=>{if(b.preventDefault(),!(!l||d)){u(!0),f("");try{const v=await hu(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(ok,{}):o==="error"?e.jsx(ak,{onRetry:()=>{h()}}):o==="locked"?e.jsx(Ul,{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:j,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(Vh,{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:b=>{c(b.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(Ie,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(Gh,{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:s})},Ti=s=>{if(!s||typeof s!="string")return null;const r=s.trim();if(!r.startsWith("#"))return null;let t=r.slice(1);if((t.length===3||t.length===4)&&(t=t.split("").map(c=>c+c).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const n=Number.parseInt(t,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,l=n&255;return`${o} ${a} ${l}`};class dk{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(r){const t=[];return t.push(...this.generateTailwindVariables(r)),t.push(...this.generatePrimaryColors(r.colors.primary)),t.push(...this.generateSurfaceColors(r.colors.surface)),t.push(...this.generateInteractiveColors(r.colors.interactive)),t.push(...this.generateStatusColors(r.colors.status)),t.push(...this.generateSyntaxColors(r.colors.syntax)),t.push(...this.generateComponentColors(r.colors,r)),t.push(...this.generateTypographyVariables()),r.config&&t.push(...this.generateConfigVariables(r.config)),t.join(`
|
|
135
|
+
`);console.info("[STREAM-TRACE] message.updated",{messageId:Re,role:ke.role,status:ke.status,textLen:Ue.length,textPreview:Ue.slice(0,120),partsCount:Array.isArray(we)?we.length:0})}catch{}if(E(Re,"message_updated",{role:ke.role}),ke.role==="user"){const we=ne.parts||ke.parts,ve=Array.isArray(we)?we:[],Ue={...be,userMessageMarker:!0,clientRole:"user"};if(t(He,Re,Ue),ve.length>0)for(let _e=0;_e<ve.length;_e++){const et=ve[_e];if(et.synthetic===!0)continue;const pt={...et,type:et?.type||"text",sessionID:et?.sessionID||He,messageID:et?.messageID||Re};s(He,Re,pt,"user")}E(Re,"user_message_created_from_event",{partsCount:ve.length});break}const yt=uu(He,Re),ct=lu(yt?.parts||[]),It=yt?.info?.finish==="stop",Tt=ne.parts||ke.parts,je=Array.isArray(Tt)?Tt:[],ze=je.length>0,Ye=typeof(ke.time||{})?.completed=="number";if(!ze&&!Ye)break;const mt=be.finish,ye=typeof mt=="string"?mt:null,ie=ye==="stop";if(ke.role==="assistant"&&ze){const we=lu(je);if(ct>0&&we+_S<ct&&!ie){E(Re,"skipped_shrinking_update",{incomingLen:we,existingLen:ct});break}if(G.current){const Ue=ct>0&&we<ct,_e=je.some(pt=>{if(!pt||pt.type!=="text")return!1;const ft=pt;return typeof ft.text=="string"&&ft.text.length>0});if(Ue&&!(ie&&_e)){E(Re,"desktop_shrinking_update_suppressed",{incomingLen:we,existingLen:ct});break}}}if(t(He,Re,be),ze&&ke.role!=="user"){const Ue=(he.getState().messages.get(He)||[]).find(pt=>pt.info.id===Re),_e=!Ue||Ue.parts.length===0;E(Re,_e?"server_parts_injected":"server_parts_refreshed",{count:je.length});const et=G.current&&ke.role==="assistant"?je.filter(pt=>pt?.type!=="text"):je;for(let pt=0;pt<et.length;pt++){const ft=et[pt],Pt={...ft,type:ft?.type||"text",sessionID:ft?.sessionID||He,messageID:ft?.messageID||Re};s(He,Re,Pt,ke.role),E(Re,`server_part_${pt}`)}}const de=be.time,We=de?.completed,Ge=typeof We=="number"&&Number.isFinite(We),bt=ye==="stop"||It;if(be.role==="assistant"&&(Ge||bt)&&be.role==="assistant"){const ve=he.getState().messages.get(He)||[];let Ue=null,_e="";for(let Te=0;Te<ve.length;Te++){const st=ve[Te];st.info.role==="assistant"&&st.info.id>_e&&(_e=st.info.id,Ue=st.info.id)}if(c===He&&Re!==Ue)break;if(!bt&&G.current){E(Re,"desktop_completion_without_stop");break}const pt=Ge?We:Date.now();if(Ge||t(He,Re,{...be,time:{...de??{},completed:pt}}),E(Re,"completed",{timeCompleted:pt}),T(Re),FS(He,Re,pt),r(He,Re),ye==="stop"&&rn()&&j&&(b==="always"||ae.current==="hidden")){const st=Y.current;if(!st.has(Re)){st.add(Re);const Ve=Qs();if(Ve?.notifications){const Xe=ke.mode||"agent",kt=ke.modelID||"assistant",Lt=`${Xe.charAt(0).toUpperCase()+Xe.slice(1)} agent is ready`,ts=`${LS(kt)} completed the task`;Ve.notifications.notifyAgentCompletion({title:Lt,body:ts,tag:Re})}}}G.current||ye==="stop"&&he.getState().sessionActivityPhase?.get(He)==="busy"&&xe(He,"cooldown");const ft=be.sessionID,Pt=typeof ft=="string"&&ft.length>0?ft:He;ee(Pt,typeof ne.directory=="string"?ne.directory:null),be.summary&&typeof Pt=="string"&&n(Pt,null)}break}case"session.created":case"session.updated":{const be=typeof ne.info=="object"&&ne.info!==null?ne.info:typeof ne.sessionInfo=="object"&&ne.sessionInfo!==null?ne.sessionInfo:typeof ne.session=="object"&&ne.session!==null?ne.session:ne,ke=typeof be.id=="string"&&be.id.length>0?be.id:typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:typeof ne.id=="string"&&ne.id.length>0?ne.id:void 0;if(ke){const Qe=typeof be.time=="object"&&be.time!==null?be.time:typeof ne.time=="object"&&ne.time!==null?ne.time:null,tt=Qe&&typeof Qe.compacting=="number"?Qe.compacting:null;n(ke,tt);const He=typeof be.directory=="string"?be.directory:typeof ne.directory=="string"?ne.directory:null,Re={...be,id:ke,...He?{directory:He}:{}};g(Re)}break}case"session.deleted":{const be=typeof ne.sessionID=="string"?ne.sessionID:typeof ne.id=="string"?ne.id:null;be&&y(be);break}case"session.abort":{const be=typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,ke=typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;be&&ke&&r(be,ke);break}case"permission.asked":{if(!("sessionID"in ne)||typeof ne.sessionID!="string")break;const be=ne;o(be);const ke=`${be.sessionID}:${be.id}`;q.current.has(ke)||setTimeout(()=>{if(Be.current===be.sessionID||!he.getState().permissions.get(be.sessionID)?.some(Re=>Re.id===be.id))return;q.current.add(ke);const He=he.getState().sessions.find(Re=>Re.id===be.sessionID)?.title||"Session";as(async()=>{const{toast:Re}=await import("./vendor-.bun-CqCnPJev.js").then(nt=>nt.cy);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.warning("Permission required",{description:He,action:{label:"Open",onClick:()=>{$e.getState().setActiveMainTab("chat"),he.getState().setCurrentSession(be.sessionID)}}})})},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in ne)||typeof ne.sessionID!="string")break;const be=ne;a(be);const ke=`${be.sessionID}:${be.id}`;if(rn()&&j&&(b==="always"||ae.current==="hidden")){const tt=re.current;if(!tt.has(ke)){tt.add(ke);const He=Qs();He?.notifications&&He.notifications.notifyAgentCompletion({title:"Input needed",body:"Agent is waiting for your response",tag:ke})}}X.current.has(ke)||setTimeout(()=>{if(Be.current===be.sessionID||!he.getState().questions.get(be.sessionID)?.some(Re=>Re.id===be.id))return;X.current.add(ke);const He=he.getState().sessions.find(Re=>Re.id===be.sessionID)?.title||"Session";as(async()=>{const{toast:Re}=await import("./vendor-.bun-CqCnPJev.js").then(nt=>nt.cy);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.info("Input needed",{description:He,action:{label:"Open",onClick:()=>{$e.getState().setActiveMainTab("chat"),he.getState().setCurrentSession(be.sessionID)}}})})},0);break}case"question.replied":{const be=typeof ne.sessionID=="string"?ne.sessionID:null,ke=typeof ne.requestID=="string"?ne.requestID:null;be&&ke&&l(be,ke);break}case"todo.updated":{const be=typeof ne.sessionID=="string"?ne.sessionID:null,ke=Array.isArray(ne.todos)?ne.todos:null;be&&ke&&vv(be,ke);break}}},[c,j,b,s,r,t,o,a,l,h,ee,n,d,E,T,xe,g,y,D,N]),Se=i.useCallback(()=>{const De=K();return ae.current=De,De==="visible"&&F.current},[K]),Le=i.useCallback(()=>{Zt()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:G.current,hasUnsubscribe:!!I.current,currentSessionId:Be.current,effectiveDirectory:N,onlineStatus:F.current,visibilityState:ae.current,lastEventTimestamp:z.current,reconnectAttempts:O.current})},[N]),pe=i.useCallback(async()=>!0,[]),it=i.useCallback(()=>{if(W.current){Zt()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(W.current=!0,P.current&&(clearTimeout(P.current),P.current=null),I.current){const De=I.current;I.current=null;try{De()}catch(ne){console.warn("[useEventStream] Error during unsubscribe:",ne)}}W.current=!1},[]),xt=i.useCallback(async De=>{if(Le(),!Se()){$.current=!0,F.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}G.current&&(await pe()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),De?.resetAttempts&&(O.current=0),it(),z.current=Date.now(),M("connecting",null),Zt()&&console.info("[useEventStream] Starting event stream...");const ne=be=>{console.warn("Event stream error:",be)},rt=()=>{const be=$.current;if(O.current=0,$.current=!1,z.current=Date.now(),M("connected",null),h(),Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(Qe=>Qe==="busy"||Qe==="cooldown")&&fe(),be)D("sse_reconnected");else{const Qe=Be.current;Qe&&setTimeout(()=>{S(Qe,"sse_reconnected").then(()=>ee(Qe)).catch(tt=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",tt)})},0)}};if(Zt()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:N,isCleaningUp:W.current}),W.current){Zt()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const be=Ee.subscribeToGlobalEvents(Qe=>{const tt=Qe.payload,He=Qe.payload,Re=typeof He.properties=="object"&&He.properties!==null?He.properties:{},nt=Qe.directory&&Qe.directory!=="global"?{...Re,directory:Qe.directory}:Re;Oe({type:typeof tt.type=="string"?tt.type:"",properties:nt})},ne,rt),ke=()=>{try{be()}catch(Qe){console.warn("[useEventStream] Error during unsubscribe:",Qe)}};W.current?ke():I.current=ke}catch(be){console.error("[useEventStream] Error during subscription:",be),ne(be)}},[Se,it,M,h,S,ee,Oe,N,fe,pe,Le,D]),Mt=i.useCallback(De=>{if(!Se()){$.current=!0,it(),F.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}const ne=O.current+1;O.current=ne;const rt=De??`Retrying (${ne})`;M("reconnecting",rt);const be=ne<=3?Math.min(1e3*Math.pow(2,ne-1),8e3):Math.min(2e3*Math.pow(2,ne-3),32e3),ke=Math.floor(Math.random()*250),Qe=be+ke;P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{xt({resetAttempts:!1})},Qe)},[Se,it,M,xt]);i.useEffect(()=>{const De=oe.current;typeof window<"u"&&(window.__messageTracker=E);let ne=null;G.current&&typeof window<"u"&&(ne=nt=>{const yt=typeof nt.detail?.sessionId=="string"?nt.detail.sessionId:null,ct=typeof nt.detail?.phase=="string"?nt.detail.phase:null;yt&&(ct==="idle"||ct==="busy"||ct==="cooldown")&&(xe(yt,ct),ee(yt))},window.addEventListener("openchamber:session-activity",ne));const rt=()=>{R.current&&(clearTimeout(R.current),R.current=null)},be=()=>{R.current||(R.current=setTimeout(()=>{const nt=K();ae.current=nt,nt!=="visible"?(it(),$.current=!0,M("paused","Paused while hidden")):rt()},5e3))},ke=()=>{if(ae.current=K(),ae.current==="visible"){if(rt(),ge("visibility_restore"),$.current||!I.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const nt=Be.current;nt&&(S(nt,"visibility_restore").catch(()=>{}),ee(nt)),fe(),M("connecting","Resuming stream"),xt({resetAttempts:!0})}}else M("paused","Paused while hidden"),be()},Qe=()=>{if(ae.current=K(),ae.current==="visible"&&(rt(),ge("window_focus"),$.current||!I.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const nt=Be.current;nt&&(ee(nt),S(nt,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(yt=>console.warn("[useEventStream] Failed to refresh messages:",yt))),fe(),M("connecting","Resuming stream"),xt({resetAttempts:!0})}},tt=()=>{F.current=!0,ge("network_restored"),($.current||!I.current)&&(M("connecting","Network restored"),xt({resetAttempts:!0}))},He=()=>{F.current=!1,$.current=!0,M("offline","Waiting for network"),it()};typeof document<"u"&&document.addEventListener("visibilitychange",ke),typeof window<"u"&&(window.addEventListener("online",tt),window.addEventListener("offline",He),window.addEventListener("focus",Qe));const Re=setTimeout(()=>{xt({resetAttempts:!0})},100);return B.current&&clearInterval(B.current),B.current=setInterval(()=>{if(!Se())return;const nt=Date.now();Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(ct=>ct==="busy"||ct==="cooldown")&&fe(),nt-z.current>45e3&&Promise.resolve().then(async()=>{try{await Ee.checkHealth()?z.current=Date.now():Mt("Refreshing stalled stream")}catch(ct){console.warn("Health check after stale stream failed:",ct),Mt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Re),ne&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",ne),typeof document<"u"&&document.removeEventListener("visibilitychange",ke),typeof window<"u"&&(window.removeEventListener("online",tt),window.removeEventListener("offline",He),window.removeEventListener("focus",Qe)),rt(),B.current&&(clearInterval(B.current),B.current=null),De.forEach(nt=>clearTimeout(nt)),De.clear(),al.clear(),Y.current.clear(),re.current.clear(),$.current=!1,ae.current=K(),F.current=typeof navigator>"u"?!0:navigator.onLine,it(),Q.current&&(clearTimeout(Q.current),Q.current=null),M("idle",null)}},[N,E,K,it,M,xt,Mt,f,ee,xe,fe,Se,p,ge,S])},zS=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=he(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=$e(),{themeMode:p,setThemeMode:g}=Wr(),{working:y}=rf(),h=i.useRef(null),j=i.useRef(null),b=i.useRef(!1),v=i.useCallback(()=>{j.current&&(clearTimeout(j.current),j.current=null),h.current=null,n()},[n]);i.useEffect(()=>{const w=N=>{if(Ds(N)&&N.key==="k"&&(N.preventDefault(),a()),Ds(N)&&N.shiftKey&&N.key.toLowerCase()==="l"){const k=Qs()?.diagnostics;if(!k||(N.preventDefault(),b.current))return;b.current=!0,k.downloadLogs().then(({fileName:A,content:C})=>{const M=A||"openchamber.log",S=new Blob([C],{type:"text/plain;charset=utf-8"}),D=URL.createObjectURL(S),E=document.createElement("a");E.href=D,E.download=M,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(D)}).finally(()=>{b.current=!1});return}if(Ds(N)&&N.key==="."&&(N.preventDefault(),l()),Ds(N)&&N.key.toLowerCase()==="n"){N.preventDefault();const x=Wt(),k=at.getState().settingsAutoCreateWorktree;if(x?!1:k?!N.shiftKey:N.shiftKey){u("chat"),d(!1),Ra();return}u("chat"),d(!1),s()}if(Ds(N)&&N.key==="/"){N.preventDefault();const x=["light","dark","system"],A=(x.indexOf(p)+1)%x.length;g(x[A])}if(Ds(N)&&!N.shiftKey&&N.key.toLowerCase()==="t"){N.preventDefault();const{isTimelineDialogOpen:x,setTimelineDialogOpen:k}=$e.getState();k(!x);return}if(Ds(N)&&!N.shiftKey&&N.key===","){N.preventDefault();const{isSettingsDialogOpen:x}=$e.getState();m(!x);return}if(Ds(N)&&!N.shiftKey&&N.key.toLowerCase()==="l"){N.preventDefault();const{isMobile:x,isSessionSwitcherOpen:k}=$e.getState();x?d(!k):c();return}if(Ds(N)&&!N.shiftKey&&N.key.toLowerCase()==="i"){N.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Ds(N)&&N.shiftKey&&N.key.toLowerCase()==="m"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S,isModelSelectorOpen:D}=$e.getState();if(x||k||A||C||M||!(S==="chat"))return;N.preventDefault(),f(!D);return}if(Ds(N)&&N.shiftKey&&N.key.toLowerCase()==="t"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=$e.getState();if(x||k||A||C||M||!(S==="chat"))return;const T=at.getState();if(T.getCurrentModelVariants().length===0)return;N.preventDefault(),T.cycleCurrentVariant();const P=at.getState().currentVariant,O=he.getState(),U=O.currentSessionId,Q=at.getState().currentAgentName,W=at.getState().currentProviderId,L=at.getState().currentModelId;U&&Q&&W&&L&&O.saveAgentModelVariantForSession(U,Q,W,L,P);return}if(N.key==="Escape"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=$e.getState();if(x){N.preventDefault(),m(!1),v();return}if(k||A||C||M||!(S==="chat")){v();return}const T=o;if(!(y.canAbort&&!!T)){v();return}const P=Date.now(),O=h.current;if(O&&P<O){N.preventDefault(),v(),r();return}N.preventDefault();const U=t(3e3)??P+3e3;h.current=U,j.current&&clearTimeout(j.current);const Q=Math.max(U-P,0);j.current=setTimeout(()=>{h.current&&Date.now()>=h.current&&v()},Q||0);return}};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[s,r,a,l,c,d,u,m,f,g,p,y,t,v,o]),i.useEffect(()=>()=>{v()},[v])},mu="openchamber:menu-action",WS=s=>{const{openNewSessionDraft:r}=he(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=$e(),{addProject:u}=Ot(),{requestAccess:m,startAccessing:f}=_a(),{setThemeMode:p}=Wr(),g=i.useRef(!1),y=i.useCallback(()=>{es()?m("").then(async h=>{if(!h.success||!h.path){h.error&&h.error!=="Directory selection cancelled"&&te.error("Failed to select directory",{description:h.error});return}const j=await f(h.path);if(!j.success){te.error("Failed to open directory",{description:j.error||"Desktop could not grant file access."});return}u(h.path,{id:h.projectId})||te.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(h=>{console.error("Desktop: Error selecting directory:",h),te.error("Failed to select directory")}):En.requestDirectoryDialog()},[u,m,f]);i.useEffect(()=>{const h=j=>{switch(j.detail){case"about":d(!0);break;case"settings":c(!0);break;case"command-palette":t();break;case"new-session":l("chat"),a(!1),r();break;case"new-worktree-session":l("chat"),a(!1),Ra();break;case"change-workspace":y();break;case"open-git-tab":{const{activeMainTab:v}=$e.getState();l(v==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:v}=$e.getState();l(v==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:v}=$e.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":s?.();break;case"help-dialog":n();break;case"download-logs":{const w=Qs()?.diagnostics;if(!w||g.current)break;g.current=!0,w.downloadLogs().then(({fileName:N,content:x})=>{const k=N||"openchamber.log",A=new Blob([x],{type:"text/plain;charset=utf-8"}),C=URL.createObjectURL(A),M=document.createElement("a");M.href=C,M.download=k,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(C),te.success("Logs saved",{description:`Downloaded to ~/Downloads/${k}`})}).catch(()=>{te.error("Failed to download logs")}).finally(()=>{g.current=!1});break}}};return window.addEventListener(mu,h),()=>window.removeEventListener(mu,h)},[r,t,n,o,a,l,c,d,p,s,y])},HS=s=>s.role==="assistant",fu=s=>{const r=s.info;if(!HS(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},ea=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},pu=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>Kn(n)).join(" ").replace(/\s+/g," ").trim(),US=(s,r)=>{if(!s||!ea(s.info))return-1;const t=pu(s),n=typeof s.info?.time?.created=="number"?s.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((l,c)=>{if(!ea(l.info))return;const d=pu(l),u=!!(t&&d&&d===t),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}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=c,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(l=>{if(!ea(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},VS=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=he(),n=i.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=i.useRef(void 0),a=i.useRef(0),l=i.useCallback(async()=>{if(!s||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=r.get(s)||[],u=await Ee.getSessionMessages(s),m=await RS(s);if(!u)return;const f=d[d.length-1];if(f){const p=u.findIndex(h=>h.info.id===f.info.id),y=p===-1?US(f,u):p;if(y!==-1)if(y<u.length-1){const h=u.slice(y+1);console.log(`[SYNC] Found ${h.length} new messages to append`);const j=[...d,...h],{syncMessages:b}=he.getState();b(s,j)}else{const h=u[y],j=d[d.length-1],b=fu(h),v=fu(j);if(b&&!v){console.log("[SYNC] Last message completed on server");const w=[...d.slice(0,-1),h],{syncMessages:N}=he.getState();N(s,w)}}else if(ea(f.info)){const h=u.slice(-us.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:j}=he.getState();j(s,h)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(m){const p=u.findIndex(g=>g.info.id===m.messageId);if(p!==-1){if(p<u.length-1){const y=u.slice(p+1).slice(-us.VIEWPORT_MESSAGES);if(y.length>0){console.log(`[SYNC] Restoring ${y.length} messages after cursor`);const{syncMessages:h}=he.getState();h(s,y)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const g=u.slice(-us.VIEWPORT_MESSAGES),{syncMessages:y}=he.getState();y(s,g)}}else if(u.length>0){const p=u.slice(-us.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:g}=he.getState();g(s,p)}}catch(d){console.debug("Background sync failed:",d)}}},[s,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(!s||n)return;const c=()=>{document.visibilityState==="visible"&&l(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,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])},GS=()=>{i.useEffect(()=>{let s=!1;return(async()=>{try{const t=await Ee.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).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&&he.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function qS(){const{git:s}=kr(),r=vt(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=he(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=Gt(),u=i.useMemo(()=>{const m=t?o.get(t)??void 0:void 0,p=n.find(g=>g.id===t)?.directory??null;return m?.path??p??r??null},[t,n,o,r]);i.useEffect(()=>{if(!u||!s){c();return}return a(u),d(u,s),l(s),()=>{c()}},[u,s,a,l,c,d])}function KS({children:s}){return qS(),e.jsx(e.Fragment,{children:s})}const QS=()=>{const[{isUpdating:s,message:r},t]=i.useState(()=>Eg());return i.useEffect(()=>Ag(t),[]),s?e.jsxs("div",{className:"fixed inset-0 z-[9999] flex flex-col items-center justify-center gap-6 backdrop-blur-md",children:[e.jsx($l,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},YS=({open:s,onOpenChange:r})=>{const[t,n]=i.useState(null);i.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:c}=await as(async()=>{const{getVersion:u}=await import("./vendor-.bun-CqCnPJev.js").then(m=>m.cB);return{getVersion:u}},__vite__mapDeps([0,1])),d=await c();n(d)}catch{n("1.5.1")}})():n("1.5.1")},[s]);const o=t;return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsx(fs,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx($l,{width:64,height:64}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),o&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",o]})]}),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 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($i,{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(Lu,{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(Li,{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 Pi({apis:s,children:r}){return e.jsx(Ml.Provider,{value:s,children:r})}const XS="curl -fsSL https://opencode.ai/install | bash",JS=3e3;function ZS({onCopy:s}){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:s,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Ys,{className:"h-4 w-4"})})]})}const ek=3e4;function tk({onCliAvailable:s}){const[r,t]=i.useState(!1),[n,o]=i.useState(!1),[a,l]=i.useState(!1);i.useEffect(()=>{const m=setTimeout(()=>o(!0),ek);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 as(async()=>{const{getCurrentWindow:g}=await import("./vendor-.bun-CqCnPJev.js").then(y=>y.cA);return{getCurrentWindow:g}},__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(XS),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return i.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,JS);return m(),()=>clearInterval(f)},[d,s]),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(ta,{className:"h-4 w-4"})]})," ","is required to continue."]})]}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"bg-background/60 backdrop-blur-sm border border-border rounded-lg px-5 py-3 font-mono text-sm w-fit",children:r?e.jsxs("div",{className:"flex items-center justify-center gap-2",style:{color:"var(--status-success)"},children:[e.jsx(_t,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(ZS,{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(ta,{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 sk=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=$e();return e.jsx(YS,{open:s,onOpenChange:r})};function rk({apis:s}){const{initializeApp:r,isInitialized:t,isConnected:n}=at(),{error:o,clearError:a,loadSessions:l}=he(),c=vt(x=>x.currentDirectory),d=vt(x=>x.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=jf(),[g,y]=i.useState(()=>s.runtime.isDesktop),[h,j]=i.useState(()=>s.runtime.isVSCode),[b,v]=i.useState(()=>s.runtime.isDesktop?dg():!0);i.useEffect(()=>{y(s.runtime.isDesktop),j(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),i.useEffect(()=>(oc(s),()=>oc(null)),[s]),i.useEffect(()=>{if(typeof document>"u")return;const x=document.documentElement,k=Od[f]?.stack??Od[z0].stack,A=Kr[p]?.stack??Kr[Jo].stack;x.style.setProperty("--font-sans",k),x.style.setProperty("--font-heading",k),x.style.setProperty("--font-family-sans",k),x.style.setProperty("--font-mono",A),x.style.setProperty("--font-family-mono",A),x.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=k)},[f,p]),i.useEffect(()=>{if(t){const k=setTimeout(()=>{const A=document.getElementById("initial-loading");A&&(A.classList.add("fade-out"),setTimeout(()=>{A.remove()},300))},150);return()=>clearTimeout(k)}},[t]),i.useEffect(()=>{const x=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&!t&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},5e3);return()=>clearTimeout(x)},[t]),i.useEffect(()=>{(async()=>h||await r())()},[r,h]),i.useEffect(()=>{if(d)return;(async()=>h||n&&(Ee.setDirectory(c),await l()))()},[c,d,l,n,h]),BS(),zS();const w=i.useCallback(()=>{m(x=>!x)},[]);WS(w),VS(),GS(),Ef(),i.useEffect(()=>{const x=k=>{Ds(k)&&k.shiftKey&&k.key==="D"&&(k.preventDefault(),m(A=>!A))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=i.useCallback(()=>{v(!0),window.location.reload()},[]);return g&&!b?e.jsx(os,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(tk,{onCliAvailable:N})})}):h?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(os,{children:e.jsx(Pi,{apis:s,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(DS,{}),e.jsx(Ii,{})]})})}):e.jsx(os,{children:e.jsx(Pi,{apis:s,children:e.jsx(Pd,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(gS,{}),e.jsx(Ii,{})]})})})}):e.jsx(os,{children:e.jsx(Pi,{apis:s,children:e.jsx(KS,{children:e.jsx(Pd,{children:e.jsxs("div",{className:`h-full text-foreground ${g?"bg-transparent":"bg-background"}`,children:[e.jsx(mS,{}),e.jsx(Ii,{}),e.jsx(QS,{}),e.jsx(sk,{}),u&&e.jsx(ES,{onClose:()=>m(!1)})]})})})})})}const $f=async()=>{if(typeof window>"u")return;let s=null,r=null;try{s=window.localStorage.getItem("homeDirectory"),r=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const t=vt.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&t.setDirectory(r,{showOverlay:!1})},Lf="/auth/session",nk=async()=>fetch(Lf,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),hu=async s=>fetch(Lf,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),Ul=({children:s})=>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:s})]}),ok=({message:s="Preparing workspace…"})=>e.jsx(Ul,{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:s})})}),ak=({onRetry:s})=>e.jsx(Ul,{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(Ie,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),ik=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},lk=()=>{try{const s=new URL(window.location.href);s.searchParams.delete("token"),window.history.replaceState({},"",s.toString())}catch{}},ck=({children:s})=>{const r=i.useMemo(()=>es(),[]),t=i.useMemo(()=>Wt(),[]),n=r||t,[o,a]=i.useState(()=>n?"authenticated":"pending"),[l,c]=i.useState(""),[d,u]=i.useState(!1),[m,f]=i.useState(""),p=i.useRef(null),g=i.useRef(n),y=i.useRef(!1),h=i.useCallback(async()=>{if(n){a("authenticated");return}a(b=>b==="authenticated"?b:"pending");try{const b=await nk();if(b.ok){a("authenticated"),f("");return}if(b.status===401){a("locked");return}a("error")}catch(b){console.warn("Failed to check session status:",b),a("error")}},[n]);i.useEffect(()=>{n||h()},[h,n]),i.useEffect(()=>{!n&&o==="locked"&&(g.current=!1)},[n,o]),i.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),i.useEffect(()=>{if(n||o!=="locked"||y.current||d)return;const b=ik();b&&(y.current=!0,lk(),u(!0),f(""),hu(b).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"&&!g.current&&(g.current=!0,(async()=>(await qu(),await Ku(),await $f()))())},[n,o]);const j=async b=>{if(b.preventDefault(),!(!l||d)){u(!0),f("");try{const v=await hu(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(ok,{}):o==="error"?e.jsx(ak,{onRetry:()=>{h()}}):o==="locked"?e.jsx(Ul,{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:j,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(Vh,{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:b=>{c(b.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(Ie,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(Gh,{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:s})},Ti=s=>{if(!s||typeof s!="string")return null;const r=s.trim();if(!r.startsWith("#"))return null;let t=r.slice(1);if((t.length===3||t.length===4)&&(t=t.split("").map(c=>c+c).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const n=Number.parseInt(t,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,l=n&255;return`${o} ${a} ${l}`};class dk{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(r){const t=[];return t.push(...this.generateTailwindVariables(r)),t.push(...this.generatePrimaryColors(r.colors.primary)),t.push(...this.generateSurfaceColors(r.colors.surface)),t.push(...this.generateInteractiveColors(r.colors.interactive)),t.push(...this.generateStatusColors(r.colors.status)),t.push(...this.generateSyntaxColors(r.colors.syntax)),t.push(...this.generateComponentColors(r.colors,r)),t.push(...this.generateTypographyVariables()),r.config&&t.push(...this.generateConfigVariables(r.config)),t.join(`
|
|
136
136
|
`)}generateTailwindVariables(r){const t=[];t.push(` --background: ${r.colors.surface.background} !important;`),t.push(` --foreground: ${r.colors.surface.foreground} !important;`),t.push(` --muted: ${r.colors.surface.muted} !important;`),t.push(` --muted-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --card: ${r.colors.surface.elevated} !important;`),t.push(` --card-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --popover: ${r.colors.surface.elevated} !important;`),t.push(` --popover-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --border: ${r.colors.interactive.border} !important;`),t.push(` --input: ${r.colors.interactive.border} !important;`),t.push(` --primary: ${r.colors.primary.base} !important;`),t.push(` --primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --secondary: ${r.colors.surface.muted} !important;`),t.push(` --secondary-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --accent: ${r.colors.surface.subtle} !important;`),t.push(` --accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --destructive: ${r.colors.status.error} !important;`),t.push(` --destructive-foreground: ${r.colors.status.errorForeground} !important;`),t.push(` --ring: ${r.colors.interactive.focusRing} !important;`),r.config?.radius?.md&&t.push(` --radius: ${r.config.radius.md} !important;`);const n=Ti(r.colors.surface.muted),o=Ti(r.colors.surface.subtle),a=Ti(r.colors.interactive.border);t.push(` --sidebar-base: ${r.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(" --sidebar: var(--sidebar-base) !important;"),t.push(` --sidebar-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${r.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${r.colors.surface.subtle} !important;`),o&&t.push(` --sidebar-accent-base-rgb: ${o} !important;`),t.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),t.push(` --sidebar-accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${r.colors.interactive.border} !important;`),a&&t.push(` --sidebar-border-rgb: ${a} !important;`),t.push(` --sidebar-ring: ${r.colors.interactive.focusRing} !important;`);const l=r.metadata.variant==="dark",c=l?.8:.95,d=l?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=r.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(u,c)} !important;`),t.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)=>{t.push(` --chart-${m+1}: ${u};`)}),r.colors.loading?(t.push(` --loading-spinner: ${r.colors.loading.spinner||r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.loading.spinnerTrack||r.colors.surface.muted};`)):(t.push(` --loading-spinner: ${r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.surface.muted};`)),t}apply(r){const t=this.generate(r),n=document.createElement("style");n.id="opencode-theme-variables";let o="";r.metadata.variant==="dark"?(o=`:root {
|
|
137
137
|
${t}
|
|
138
138
|
}
|