@openchamber/web 1.4.2 → 1.4.4
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.
- package/bin/cli.js +44 -9
- package/dist/assets/{ToolOutputDialog-zILn8Ed6.js → ToolOutputDialog-BXPi0SDL.js} +3 -3
- package/dist/assets/{index-5Ree9Z_i.js → index-CqQbtUxU.js} +2 -2
- package/dist/assets/index-DR2OFuzB.css +1 -0
- package/dist/assets/main-j7ViaNnX.js +127 -0
- package/dist/assets/{vendor-.bun-COPXsM7o.js → vendor-.bun-BEzqubWg.js} +418 -414
- package/dist/index.html +3 -3
- package/package.json +3 -2
- package/server/index.js +880 -90
- package/server/lib/git-service.js +30 -1
- package/server/lib/opencode-config.js +306 -29
- package/dist/assets/index-msMCcGYO.css +0 -1
- package/dist/assets/main-DF2J5RAs.js +0 -122
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-BEzqubWg.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-BXPi0SDL.js","assets/index-CqQbtUxU.js","assets/index-DR2OFuzB.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as ef,c as tf,j as e,R as sf,T as rf,P as nf,C as of,A as af,a as lf,b as Bt,d as Qt,p as Ms,e as Ds,f as cf,_ as ns,g as c,r as df,i as Lt,I as uf,k as mf,l as ff,m as pf,n as hf,o as gf,q as yf,s as xf,u as Ot,v as bf,S as wf,L as vf,w as Od,x as jf,y as Sf,z as kf,B as Me,D as yl,E as ti,F as Nf,G as Ct,K as Mi,H as Cf,U as is,Z as Mf,Y as er,Q as Sr,W as Ft,O as Yo,J as Df,M as Rr,N as $r,V as cn,X as si,$ as ws,a0 as $d,a1 as Af,a2 as Ef,a3 as If,a4 as Pf,a5 as Tf,a6 as Ff,a7 as Rf,a8 as xo,a9 as Of,aa as $f,ab as Po,ac as dn,ad as se,ae as as,af as ur,ag as Lr,ah as Gn,ai as _t,aj as tr,ak as Lf,al as _f,am as Ld,an as Di,ao as xn,ap as _d,aq as un,ar as Bf,as as Xo,at as Ls,au as fa,av as zf,aw as kr,ax as or,ay as Bs,az as Wf,aA as zs,aB as Hf,aC as xl,aD as Uf,aE as Vf,aF as Gf,aG as qf,aH as Kf,aI as Yf,aJ as Xf,aK as Qf,aL as Jf,aM as Zf,aN as sn,aO as Ts,aP as pa,aQ as ep,aR as Ai,aS as Ei,aT as tp,aU as sp,aV as rp,aW as np,aX as op,aY as ap,aZ as ar,a_ as ip,a$ as lp,b0 as cp,b1 as dp,b2 as up,b3 as mp,b4 as fp,b5 as pp,b6 as hp,b7 as gp,b8 as yp,b9 as xp,ba as bp,bb as To,bc as mr,bd as Qs,be as wp,bf as vp,bg as Qo,bh as jp,bi as qn,bj as Ii,bk as Sp,bl as kp,bm as Np,bn as On,bo as Cp,bp as Mp,bq as Dp,br as Ap,bs as Ep,bt as ri,bu as bo,bv as Jo,bw as Ip,bx as Pp,by as $n,bz as Jr,bA as Bd,bB as zd,bC as Tp,bD as Fp,bE as Ss,bF as Wd,bG as Rp,bH as Hd,bI as Op,bJ as $p,bK as ni,bL as Lp,bM as Ud,bN as lr,bO as Ln,bP as _p,bQ as bn,bR as Bp,bS as Zo,bT as Vd,bU as Pi,bV as Ti,bW as Fi,bX as zp,bY as Wp,bZ as Hp,b_ as Up,b$ as bl,c0 as Gd,c1 as Vp,c2 as wl,c3 as _n,c4 as qd,c5 as Kd,c6 as fr,c7 as ha,c8 as ea,c9 as Yd,ca as Gp,cb as oi,cc as Xd,cd as ai,ce as qp,cf as Kp,cg as Yp,ch as Xp,ci as Qp,cj as Jp,ck as Zp,cl as eh,cm as th}from"./vendor-.bun-BEzqubWg.js";import{c as sh,l as rh,g as nh,r as oh,d as ah,a as ih,b as lh,e as ch,u as dh,f as uh,h as mh,i as fh,j as ph,k as hh}from"./index-CqQbtUxU.js";const ss=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Ht=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Ri=()=>typeof window>"u"?!1:!ss()&&!Ht(),Nr=()=>ss()?window.opencodeDesktop??null:null,Qd=()=>{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},Jd=async()=>{const s=Nr();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},gh=async()=>{const s=Nr();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},yh=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,wn=async()=>{const s=Qd();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},xh=async s=>{const r=Qd();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},bh=async s=>{const r=Nr();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)}}},wh=async s=>{const r=Nr();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)}}},vh=async s=>{const r=Nr();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)}}},jh=async()=>{const s=Nr();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},Sh=async s=>{const r=Nr();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},kh=async()=>{const s=Nr();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 R(...s){return ef(tf(s))}const Zd=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),bs=s=>Zd()&&ss()?s.metaKey:s.ctrlKey,Gt=()=>Zd()&&ss()?"⌘":"Ctrl",eu=(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 i=Math.max(0,n-(a.length+2));if(i<=0)return`…/${a}`;let l="";for(const d of o){if(!d)continue;const u=l?`${l}/${d}`:d;if(u.length>i)break;l=u}if(!l){const d=o[0]??"";l=d?d.slice(0,i):""}return l?`${l}…/${a}`:`…/${a}`},Fo=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function Ir(s,r){if(!s)return"";const t=Fo(s);if(t==="/")return"/";const n=r?Fo(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 vl(s,r){if(!s)return"/";const t=Fo(s);if(!t||t==="/")return"/";const n=r?Fo(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Nh({delayDuration:s=0,...r}){return e.jsx(lf,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function nt({delayDuration:s=0,...r}){return e.jsx(Nh,{delayDuration:s,children:e.jsx(sf,{"data-slot":"tooltip",...r})})}function ot({...s}){return e.jsx(rf,{"data-slot":"tooltip-trigger",...s})}function tt({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(nf,{children:e.jsxs(of,{"data-slot":"tooltip-content",sideOffset:r,className:R("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",s),...n,children:[t,e.jsx(af,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let ga=null;const jl=()=>{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}}},Ch=()=>{if(typeof window>"u"||!window.localStorage)return jl();const s=window.localStorage,r=jl();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}}},cs=()=>(ga||(ga=Ch()),ga),Oi={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Mh={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Sl(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const ir={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)"}}},wo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...ir.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:wo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...ir.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:wo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...ir.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:wo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...ir.tool.inline})},Re=Bt()(Qt(Ms((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,isTimelineDialogOpen:!1,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(Oi);if(o===1){for(const[i]of a)n.style.removeProperty(Sl(i));return}for(const[i,l]of a){const d=parseFloat(l);Number.isFinite(d)&&n.style.setProperty(Sl(i),`${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 i=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),n.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:t=>{s({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{s(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{s({diffWrapLines:t})},setInputBarOffset:t=>{s({inputBarOffset:t})},setKeyboardOpen:t=>{s({isKeyboardOpen:t})},toggleFavoriteModel:(t,n)=>{s(o=>o.favoriteModels.some(i=>i.providerID===t&&i.modelID===n)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===t&&i.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(i=>!(i.providerID===t&&i.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})}}),{name:"ui-store",storage:Ds(()=>cs()),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})}),{name:"ui-store"}));async function Dh(){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 Ah(){return ss()?"desktop":Ri()?"web":null}const kl={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},ta=Bt()((s,r)=>({...kl,checkForUpdates:async()=>{const t=Ah();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await jh():t==="web"&&(n=await Dh()),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 Sh(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 kh()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(kl)}})),Eh="/api",Ih=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Ph=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(Ih.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}},Th=()=>{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},Qn=s=>s.replace(/\\/g,"/"),ya=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class Fh{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=Eh){const n=Th()||r;this.baseUrl=Ph(n),this.client=cf({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],l=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return l.length>=2?{homeDirectory:`${a}/${l[0]}/${l[1]}`,username:l[1]}:l.length===1?{homeDirectory:`${a}/${l[0]}`,username:l[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,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 convertHeicToJpeg(r){try{const t=(await ns(async()=>{const{default:f}=await import("./vendor-.bun-BEzqubWg.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),i=new Uint8Array(a.length);for(let f=0;f<a.length;f++)i[f]=a.charCodeAt(f);const l=new Blob([i],{type:r.mime}),d=await t({blob:l,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const h=new FileReader;h.onload=()=>f(h.result),h.onerror=p,h.readAsDataURL(d)});let m=r.filename;return m&&(m=m.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:m,url:u}}catch(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(!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 i=await this.normalizeFilePart(a),l={type:"file",mime:i.mime,filename:i.filename,url:i.url};o.push(l)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text}),a.files&&a.files.length>0)for(const i of a.files){const l=await this.normalizeFilePart(i),d={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,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 i=await a.json().catch(()=>null);return!i||typeof i!="object"?{}:i}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 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
|
+
`),n=[];let o;for(const i of t)if(i.startsWith("data:"))n.push(i.slice(5).replace(/^\s/,""));else if(i.startsWith("id:")){const l=i.slice(3).trim();l&&(o=l)}if(n.length===0)return null;const a=n.join(`
|
|
4
|
+
`).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const 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 i=a;if(typeof i.type=="string")return{directory:o&&o.length>0?o:"global",payload:i}}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 i=await fetch(t,{method:"GET",headers:a,signal:r.signal});if(!i.ok||!i.body)throw new Error(`Global SSE connect failed with status ${i.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const l=i.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await l.read();if(f||r.signal.aborted)break;if(!p||p.length===0)continue;u+=d.decode(p,{stream:!0}).replace(/\r\n/g,`
|
|
5
|
+
`);const h=u.split(`
|
|
6
|
+
|
|
7
|
+
`);u=h.pop()??"";for(const j of h){const g=this.parseSseBlock(j);if(!g)continue;g.id&&(this.globalSseLastEventId=g.id);const b=this.normalizeRoutedSsePayload(g.data);b&&this.emitGlobalSseEvent(b)}}const m=u.trim();if(m&&!r.signal.aborted){const f=this.parseSseBlock(m);f?.id&&(this.globalSseLastEventId=f.id);const p=f?this.normalizeRoutedSsePayload(f.data):null;p&&this.emitGlobalSseEvent(p)}this.globalSseIsConnected=!1}catch(a){if(this.globalSseIsConnected=!1,a?.name==="AbortError"||r.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",a),this.notifyGlobalSseError(a)}if(r.signal.aborted)break;n+=1;const o=Math.min(3e3*Math.pow(2,n),3e4);await new Promise(a=>setTimeout(a,o))}}subscribeToGlobalEvents(r,t,n,o){const a=this.normalizeCandidatePath(o?.directory??null),i=l=>{a&&l.directory!==a||r(l)};return this.globalSseListeners.add(i),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(l){console.warn("[OpencodeClient] Global SSE open handler error:",l)}},0)),t&&this.globalSseErrorListeners.add(t),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(i),n&&this.globalSseOpenListeners.delete(n),t&&this.globalSseErrorListeners.delete(t),this.maybeStopGlobalSse()}}subscribeToEvents(r,t,n,o,a){const i=a?.key??"default",l=a?.scope??"directory",d=this.sseAbortControllers.get(i);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(i,u);let m;if(l==="global"){let p=null;const h=g=>{if(g.directory==="global")return g.payload;const b=g.payload,x=typeof b.properties=="object"&&b.properties!==null?b.properties:{};return x.directory===g.directory?g.payload:{...b,properties:{...x,directory:g.directory}}},j=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i)};return u.signal.addEventListener("abort",j,{once:!0}),p=this.subscribeToGlobalEvents(g=>{u.signal.aborted||r(h(g))},t?g=>{u.signal.aborted||t(g)}:void 0,n?()=>{u.signal.aborted||n()}:void 0),()=>{j(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const h=p;if(typeof h.type=="string")return h;const j=h.payload;if(j&&typeof j=="object"){const g=j;if(typeof g.type=="string"){if(typeof h.directory=="string"&&h.directory.length>0){const x={...(typeof g.properties=="object"&&g.properties!==null?g.properties:null)??{},directory:h.directory};return{...g,properties:x}}return g}}return null};return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const p=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",p??"default");const h=async j=>{try{const g=p?{directory:p}:void 0,b={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:y=>{y instanceof Error&&y.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",y),t&&!u.signal.aborted&&t(y))},onSseEvent:y=>{if(u.signal.aborted)return;y.id&&typeof y.id=="string"&&(m=y.id);const w=y.data,S=f(w);S&&r(S)}};m&&(b.headers={...b.headers||{},"Last-Event-ID":m});const x=await this.client.event.subscribe(g,b);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const y of x.stream)if(u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(g){if(g?.name==="AbortError"||u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",g),t&&t(g);const b=Math.min(3e3*Math.pow(2,j),3e4);await new Promise(x=>setTimeout(x,b)),u.signal.aborted||await h(j+1);return}if(!u.signal.aborted){const g=Math.min(3e3*Math.pow(2,j),3e4);await new Promise(b=>setTimeout(b,g)),await h(j+1)}};try{await h(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i)}})(),()=>{this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i),u.abort()}}async readFile(r){try{const t=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,directory:this.currentDirectory})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return await t.text()}catch{return`// Content of ${r}
|
|
8
|
+
// This would be loaded from the server`}}async listFiles(r){try{const t=r||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model,template:t.template,subtask:t.subtask}))}catch{return[]}}async getCommandDetails(r){try{const t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(t.data){const n=t.data.find(o=>o.name===r);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{let r;const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;t==="/api"?r="/health":t.endsWith("/api")?r=`${t.slice(0,-4)}/health`:r=`${t}/health`;const n=await fetch(r);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(r){const t=ya();if(t?.createDirectory)try{return await t.createDirectory(r)}catch(a){const i=a instanceof Error?a.message:String(a);throw new Error(i||"Failed to create directory")}const n=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!n.ok){const a=await n.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await n.json()}async listLocalDirectory(r){const t=ya();if(t)try{const n=await t.listDirectory(r||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:Qn(o.path),isDirectory:!!o.isDirectory,isFile:!o.isDirectory,isSymbolicLink:!1}))}catch(n){throw console.error("Failed to list directory contents:",n),n}try{const n=new URLSearchParams;r&&r.trim().length>0&&n.set("path",r);const o=n.toString(),a=await fetch(`${this.baseUrl}/fs/list${o?`?${o}`:""}`);if(!a.ok){const l=await a.json().catch(()=>({})),d=typeof l.error=="string"?l.error:"Failed to list directory";throw new Error(d)}const i=await a.json();return!i||!Array.isArray(i.entries)?[]:i.entries}catch(n){throw console.error("Failed to list directory contents:",n),n}}async searchFiles(r,t){const n=ya(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?Qn(o):null;if(n)try{const m=await n.search({directory:o||"",query:r,maxResults:t?.limit});return Array.isArray(m)?m.map(f=>{const p=Qn(f.path),h=p.split("/").filter(Boolean).pop()||p,j=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?Qn(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:j,extension:h.includes(".")?h.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const i=new URLSearchParams;o&&o.length>0&&i.set("directory",o),typeof r=="string"&&i.set("q",r),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&i.set("limit",String(t.limit));const l=`${this.baseUrl}/fs/search${i.toString()?`?${i.toString()}`:""}`,d=await fetch(l,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await Jd();if(r)return r;try{const t=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok){const o=await t.json().catch(()=>({})),a=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(a)}const n=await t.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(t){return console.warn("Failed to resolve filesystem home directory:",t),null}}async setOpenCodeWorkingDirectory(r){if(!r||typeof r!="string"||!r.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",r),null;const t=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",t,"with path:",r);try{const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})}),o=await n.json().catch(()=>null);if(!n.ok){const a=o??{},i=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:r}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const De=new Fh,ii=new Set;function sa(s){return ii.add(s),()=>{ii.delete(s)}}function Js(s,r){const t=Array.isArray(s)?s:[s],n=Array.from(new Set(t));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:r?.source,timestamp:Date.now()};for(const a of ii)try{const i=a(o);i instanceof Promise&&i.catch(l=>{console.error("[ConfigSync] Async listener failed:",l)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function Bn(s,r){return s.scopes.includes("all")||s.scopes.includes(r)}const $i="Updating OpenCode configuration...";let Zs=0,jr=$i;const li=new Set;function Ro(){const s={isUpdating:Zs>0,message:jr};li.forEach(r=>r(s))}function _s(s){Zs+=1,Zs===1?(jr=s||$i,Ro()):s&&(jr=s,Ro())}function xs(){Zs!==0&&(Zs-=1,Zs===0&&(jr=$i,Ro()))}function cr(s){jr===s&&Zs>0||(jr=s,Zs>0&&Ro())}function Rh(s){return li.add(s),s({isUpdating:Zs>0,message:jr}),()=>{li.delete(s)}}function Oh(){return{isUpdating:Zs>0,message:jr}}const qs=Bt()(Qt(Ms((s,r)=>({queuedMessages:{},queueModeEnabled:!1,addToQueue:(t,n)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};s(i=>{const l=i.queuedMessages[t]??[];return{queuedMessages:{...i.queuedMessages,[t]:[...l,a]}}})},removeFromQueue:(t,n)=>{s(o=>{const i=(o.queuedMessages[t]??[]).filter(l=>l.id!==n);if(i.length===0){const{[t]:l,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[t]:i}}})},popToInput:(t,n)=>{const i=(r().queuedMessages[t]??[]).find(l=>l.id===n);return i?(s(l=>{const u=(l.queuedMessages[t]??[]).filter(m=>m.id!==n);if(u.length===0){const{[t]:m,...f}=l.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...l.queuedMessages,[t]:u}}}),i):null},clearQueue:t=>{s(n=>{const{[t]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{s({queuedMessages:{}})},setQueueMode:t=>{s({queueModeEnabled:t}),os({queueModeEnabled:t})},getQueueForSession:t=>r().queuedMessages[t]??[]}),{name:"message-queue-store",storage:Ds(()=>cs()),partialize:s=>({queuedMessages:s.queuedMessages,queueModeEnabled:s.queueModeEnabled})}),{name:"message-queue-store"})),Nl=s=>{if(!s||typeof s!="object")return null;const r={};return typeof s.showReasoningTraces=="boolean"&&(r.showReasoningTraces=s.showReasoningTraces),Object.keys(r).length>0?r:null},$h=s=>!s||typeof s!="object"?null:{showReasoningTraces:s.showReasoningTraces},Lh=s=>{const r=Re.getState();typeof s.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(s.showReasoningTraces)},_h=async()=>{if(typeof window>"u")return null;if(ss()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const t=await r.load();return Nl(typeof t=="object"&&t!==null?t:null)}catch(t){return console.warn("Failed to load appearance preferences from desktop storage:",t),null}}const s=localStorage.getItem("appearance-preferences");if(!s)return null;try{const r=JSON.parse(s),t=$h(r);return Nl(t)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let tu=null;const Cl=s=>{tu=s},_r=()=>tu,vo=s=>{typeof window>"u"||(s.themeId&&localStorage.setItem("selectedThemeId",s.themeId),s.themeVariant&&localStorage.setItem("selectedThemeVariant",s.themeVariant),s.lightThemeId&&localStorage.setItem("lightThemeId",s.lightThemeId),s.darkThemeId&&localStorage.setItem("darkThemeId",s.darkThemeId),typeof s.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(s.useSystemTheme)),s.lastDirectory&&localStorage.setItem("lastDirectory",s.lastDirectory),s.homeDirectory&&(localStorage.setItem("homeDirectory",s.homeDirectory),window.__OPENCHAMBER_HOME__=s.homeDirectory),Array.isArray(s.projects)&&s.projects.length>0?localStorage.setItem("projects",JSON.stringify(s.projects)):localStorage.removeItem("projects"),s.activeProjectId?localStorage.setItem("activeProjectId",s.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(s.pinnedDirectories)&&s.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(s.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"))},Bh=s=>{if(!Array.isArray(s))return;const r=[],t=new Set;for(const n of s){if(!n||typeof n!="object")continue;const o=n,a=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",l=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!i||!l||t.has(a)||(t.add(a),r.push({id:a,label:i,source:l,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},zh=s=>{if(!Array.isArray(s))return;const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const d=l==="/"?l:l.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||t.has(i)||n.has(d))continue;t.add(i),n.add(d);const u={id:i,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&m.branchPrefix.trim()&&(f.branchPrefix=m.branchPrefix.trim()),typeof m.baseBranch=="string"&&m.baseBranch.trim()&&(f.baseBranch=m.baseBranch.trim()),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r.length>0?r:void 0},su=()=>{const s=Re.persist;if(s&&typeof s=="object")return s},ru=()=>_r()?.settings??null,jo=s=>{const r=Re.getState(),t=qs.getState();if(typeof s.showReasoningTraces=="boolean"&&s.showReasoningTraces!==r.showReasoningTraces&&r.setShowReasoningTraces(s.showReasoningTraces),typeof s.autoDeleteEnabled=="boolean"&&s.autoDeleteEnabled!==r.autoDeleteEnabled&&r.setAutoDeleteEnabled(s.autoDeleteEnabled),typeof s.autoDeleteAfterDays=="number"&&Number.isFinite(s.autoDeleteAfterDays)){const n=Math.max(1,Math.min(365,s.autoDeleteAfterDays));n!==r.autoDeleteAfterDays&&r.setAutoDeleteAfterDays(n)}typeof s.queueModeEnabled=="boolean"&&s.queueModeEnabled!==t.queueModeEnabled&&t.setQueueMode(s.queueModeEnabled)},Ml=s=>{if(!s||typeof s!="object")return null;const r=s,t={};typeof r.themeId=="string"&&r.themeId.length>0&&(t.themeId=r.themeId),(r.useSystemTheme===!0||r.useSystemTheme===!1)&&(t.useSystemTheme=r.useSystemTheme),typeof r.themeVariant=="string"&&(r.themeVariant==="light"||r.themeVariant==="dark")&&(t.themeVariant=r.themeVariant),typeof r.lightThemeId=="string"&&r.lightThemeId.length>0&&(t.lightThemeId=r.lightThemeId),typeof r.darkThemeId=="string"&&r.darkThemeId.length>0&&(t.darkThemeId=r.darkThemeId),typeof r.lastDirectory=="string"&&r.lastDirectory.length>0&&(t.lastDirectory=r.lastDirectory),typeof r.homeDirectory=="string"&&r.homeDirectory.length>0&&(t.homeDirectory=r.homeDirectory);const n=zh(r.projects);n&&(t.projects=n),typeof r.activeProjectId=="string"&&r.activeProjectId.length>0&&(t.activeProjectId=r.activeProjectId),Array.isArray(r.approvedDirectories)&&(t.approvedDirectories=r.approvedDirectories.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.securityScopedBookmarks)&&(t.securityScopedBookmarks=r.securityScopedBookmarks.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(a=>typeof a=="string"&&a.length>0)))),typeof r.showReasoningTraces=="boolean"&&(t.showReasoningTraces=r.showReasoningTraces),typeof r.autoDeleteEnabled=="boolean"&&(t.autoDeleteEnabled=r.autoDeleteEnabled),typeof r.autoDeleteAfterDays=="number"&&Number.isFinite(r.autoDeleteAfterDays)&&(t.autoDeleteAfterDays=r.autoDeleteAfterDays),typeof r.defaultModel=="string"&&r.defaultModel.length>0&&(t.defaultModel=r.defaultModel),typeof r.defaultAgent=="string"&&r.defaultAgent.length>0&&(t.defaultAgent=r.defaultAgent),typeof r.autoCreateWorktree=="boolean"&&(t.autoCreateWorktree=r.autoCreateWorktree),typeof r.queueModeEnabled=="boolean"&&(t.queueModeEnabled=r.queueModeEnabled);const o=Bh(r.skillCatalogs);return o&&(t.skillCatalogs=o),t},Wh=async()=>{const s=ru();if(s)try{const r=await s.load();return Ml(r.settings)}catch(r){console.warn("Failed to load shared settings from runtime settings API:",r)}try{const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return null;const t=await r.json().catch(()=>null);return Ml(t)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},nu=async()=>{if(typeof window>"u")return;const s=su(),r=t=>{vo(t);const n=()=>jo(t);if(s?.hasHydrated?.())n();else if(n(),s?.onFinishHydration){const o=s.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))};try{const t=ss()?await wn():await Wh();t&&r(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},os=async s=>{if(typeof window>"u")return;if(ss()){try{const t=await xh(s);t&&(vo(t),jo(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const r=ru();if(r)try{const t=await r.save(s);t&&(vo(t),jo(t));return}catch(t){console.warn("Failed to update settings via runtime settings API:",t)}try{const t=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s)});if(!t.ok){console.warn("Failed to update shared settings via API:",t.status,t.statusText);return}const n=await t.json().catch(()=>null);n&&(vo(n),jo(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},ou=async()=>{if(typeof window>"u")return;const s=su();try{const r=await _h();if(!r)return;const t=()=>Lh(r);if(s?.hasHydrated?.()){t();return}if(t(),s?.onFinishHydration){const n=s.onFinishHydration(()=>{n?.(),t()})}}catch(r){console.warn("Failed to load appearance preferences:",r)}},Hh=3e4,Uh=40,Vh=60,Gh=(s,r,t)=>{const n=s.trim(),o=r.trim().toLowerCase();return`${n}::${o}::${t}`},Li=Bt()(Qt((s,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=Vh){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",l=Gh(a,i,o),d=Date.now(),u=r().cache[l];if(u&&d-u.timestamp<Hh)return u.files;const m=r().inFlight[l];if(m)return m;const f=De.searchFiles(i,{directory:a,limit:o}).then(p=>(s(h=>{const j={...h.cache,[l]:{files:p,timestamp:Date.now()}},g=h.cacheKeys.filter(b=>b!==l);for(g.push(l);g.length>Uh;){const b=g.shift();b&&delete j[b]}return{cache:j,cacheKeys:g}}),p)).finally(()=>{s(p=>{const h={...p.inFlight};return delete h[l],{inFlight:h}})});return s(p=>({inFlight:{...p.inFlight,[l]:f}})),f},invalidateDirectory(t){if(!t||t.trim().length===0){s({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;s(a=>{const i={...a.cache},l=a.cacheKeys.filter(m=>m.startsWith(o)?(delete i[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:i,cacheKeys:l,inFlight:u}})}}),{name:"file-search-store"})),Wt=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var qh={};let $s=null;const Os=cs(),Dl=Os.getItem("lastDirectory"),Kh=typeof Dl=="string"&&Dl.length>0,Jn=s=>{try{Li.getState().invalidateDirectory(s)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},Yh=s=>{const r=s.trim();if(!r)return r;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},Xh=(s,r)=>{const t=s.trim();return t.startsWith("~")?t==="~"?r||t:(t.startsWith("~/")||t.startsWith("~\\"))&&r?`${r}${t.slice(1)}`:t:t},So=(s,r)=>{const t=Xh(s,r);return Yh(t)},Oo=()=>{if(typeof window<"u"){const r=Os.getItem("homeDirectory")||$s||null,t=Os.getItem("lastDirectory");if(t)return So(t,r);if($s)return $s;const n=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:window.opencodeDesktop&&typeof window.opencodeDesktop.homeDirectory=="string"?window.opencodeDesktop.homeDirectory:null;if(n&&n.length>0)return $s=n,Os.setItem("homeDirectory",n),n;if(r)return $s=r,r}const s=typeof process<"u"&&qh?.HOME;return s||process?.cwd?.()||"/"},Qh=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");if(t.length>1){const n=t.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return t==="/"||t.length===0?null:t},Jh=s=>($s=s,typeof window<"u"&&Os.setItem("homeDirectory",s),os({homeDirectory:s}),s),au=async()=>{const s=n=>{const o=Qh(n);return o?Jh(o):null};try{const n=await De.getFilesystemHome(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await De.getSystemInfo(),o=s(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await Jd(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=Oo(),t=s(r);return t||r},Pr=Oo();Pr&&De.setDirectory(Pr);const Zh=!!(Pr&&Pr!=="/"),ft=Bt()(Qt((s,r)=>({currentDirectory:Pr,directoryHistory:[Pr],historyIndex:0,homeDirectory:Pr,hasPersistedDirectory:Kh,isHomeReady:Zh,isSwitchingDirectory:!1,setDirectory:(t,n)=>{const o=$s||r().homeDirectory||Os.getItem("homeDirectory"),a=So(t,o);Wt()&&console.log("[DirectoryStore] setDirectory called with path:",a),De.setDirectory(a),Jn(),s(i=>{const l=[...i.directoryHistory.slice(0,i.historyIndex+1),a];return Os.setItem("lastDirectory",a),os({lastDirectory:a}),{currentDirectory:a,directoryHistory:l,historyIndex:l.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const t=r();if(t.historyIndex>0){const n=t.historyIndex-1,o=t.directoryHistory[n];De.setDirectory(o),Jn(),Os.setItem("lastDirectory",o),os({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const t=r();if(t.historyIndex<t.directoryHistory.length-1){const n=t.historyIndex+1,o=t.directoryHistory[n];De.setDirectory(o),Jn(),Os.setItem("lastDirectory",o),os({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=r(),o=$s||r().homeDirectory||Oo();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const l=$s||Oo();n(l)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=$s||r().homeDirectory||await au();r().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=r(),o=t;$s=o;const a=n.homeDirectory!==o,i=Os.getItem("lastDirectory"),l=typeof i=="string"&&i.length>0,d=!l&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||s({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",m=n.currentDirectory?So(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(g=>So(g,o)),p=f.some((g,b)=>g!==n.directoryHistory[b]),h=!!(m&&m!==n.currentDirectory),j={homeDirectory:o,hasPersistedDirectory:l,isHomeReady:u};if(d?(j.currentDirectory=o,j.directoryHistory=[o],j.historyIndex=0,j.isSwitchingDirectory=!1):(h||p)&&(j.currentDirectory=m,j.directoryHistory=f,j.historyIndex=Math.min(n.historyIndex,f.length-1),j.isSwitchingDirectory=!1),s(()=>j),(d||h)&&u){const g=d?o:m;De.setDirectory(g),Jn(),Os.setItem("lastDirectory",g),os({lastDirectory:g})}os({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&au().then(s=>{ft.getState().synchronizeHomeDirectory(s)});const rn=cs(),iu="projects",ci="activeProjectId",eg=(s,r)=>{const t=s.trim();return!t.startsWith("~")||!r?t:t==="~"?r:t.startsWith("~/")||t.startsWith("~\\")?`${r}${t.slice(1)}`:t},ra=s=>{const r=s.trim();if(!r)return"";const t=rn.getItem("homeDirectory")||ft.getState().homeDirectory||"",o=eg(r,t).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},lu=s=>{const r=ra(s);if(!r||r==="/")return"Root";const t=r.split("/").filter(Boolean);return t[t.length-1]||r},tg=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,cu=s=>{if(!Array.isArray(s))return[];const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const d=ra(l);if(!d||t.has(i)||n.has(d))continue;t.add(i),n.add(d);const u={id:i,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&(f.branchPrefix=m.branchPrefix),typeof m.baseBranch=="string"&&(f.baseBranch=m.baseBranch),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r},sg=()=>{try{const s=rn.getItem(iu);return s?cu(JSON.parse(s)):[]}catch{return[]}},rg=()=>{try{const s=rn.getItem(ci);if(typeof s=="string"&&s.trim().length>0)return s.trim()}catch{return null}return null},_i=(s,r)=>{try{rn.setItem(iu,JSON.stringify(s))}catch{}try{r?rn.setItem(ci,r):rn.removeItem(ci)}catch{}},Gr=(s,r)=>{_i(s,r),os({projects:s,activeProjectId:r??void 0})},ng=sg(),og=()=>{if(typeof window>"u"||!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode)return null;const r=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof r!="string"||r.trim().length===0)return null;const t=ra(r);if(!t)return null;const n=`vscode:${t}`,o={id:n,path:t,label:lu(t),addedAt:Date.now(),lastOpenedAt:Date.now()};return Wt()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},Fs=og(),Bi=Fs?.projects??ng,du=Fs?.activeProjectId??rg()??Bi[0]?.id??null;Fs&&_i(Bi,du);const It=Bt()(Qt((s,r)=>({projects:Bi,activeProjectId:du,validateProjectPath:t=>{if(typeof t!="string"||t.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=ra(t);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(t,n)=>{if(Fs)return null;const{validateProjectPath:o}=r(),a=o(t);if(!a.ok||!a.normalizedPath)return null;const i=a.normalizedPath,l=r().projects.find(j=>j.path===i);if(l)return r().setActiveProject(l.id),l;const d=Date.now(),u=n?.label?.trim()||lu(i),m=n?.id?.trim(),p={id:m&&!r().projects.some(j=>j.id===m)?m:tg(),path:i,label:u,addedAt:d,lastOpenedAt:d},h=[...r().projects,p];return s({projects:h}),Wt()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:t=>{if(Fs)return;const n=r(),o=n.projects.filter(i=>i.id!==t);let a=n.activeProjectId;if(n.activeProjectId===t&&(a=o[0]?.id??null),s({projects:o,activeProjectId:a}),Gr(o,a),a){const i=o.find(l=>l.id===a);i&&(De.setDirectory(i.path),ft.getState().setDirectory(i.path,{showOverlay:!1}))}else ft.getState().goHome()},setActiveProject:t=>{if(Fs)return;const{projects:n,activeProjectId:o}=r();if(o===t)return;const a=n.find(d=>d.id===t);if(!a)return;const i=Date.now(),l=n.map(d=>d.id===t?{...d,lastOpenedAt:i}:d);s({projects:l,activeProjectId:t}),Gr(l,t),De.setDirectory(a.path),ft.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:t=>{if(Fs)return;const{projects:n,activeProjectId:o}=r();if(o===t||!n.find(d=>d.id===t))return;const i=Date.now(),l=n.map(d=>d.id===t?{...d,lastOpenedAt:i}:d);s({projects:l,activeProjectId:t}),Gr(l,t)},renameProject:(t,n)=>{if(Fs)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:i}=r(),l=a.map(d=>d.id===t?{...d,label:o}:d);s({projects:l}),Gr(l,i)},reorderProjects:(t,n)=>{if(Fs)return;const{projects:o,activeProjectId:a}=r();if(t<0||t>=o.length||n<0||n>=o.length||t===n)return;const i=[...o],[l]=i.splice(t,1);i.splice(n,0,l),s({projects:i}),Gr(i,a)},synchronizeFromSettings:t=>{if(Fs)return;const n=cu(t.projects??[]),o=typeof t.activeProjectId=="string"&&t.activeProjectId.trim()?t.activeProjectId.trim():null,a=r(),i=JSON.stringify(a.projects)!==JSON.stringify(n),l=a.activeProjectId!==o;if(!(!i&&!l)&&(s({projects:n,activeProjectId:o}),_i(n,o),o)){const d=n.find(u=>u.id===o);d&&(De.setDirectory(d.path),ft.getState().setDirectory(d.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:t,activeProjectId:n}=r();return n?t.find(o=>o.id===n)??null:null},updateWorktreeDefaults:(t,n)=>{if(Fs)return;const{projects:o,activeProjectId:a}=r(),i=o.find(u=>u.id===t);if(!i)return;const l={...i.worktreeDefaults};n.branchPrefix!==void 0&&(n.branchPrefix.trim()?l.branchPrefix=n.branchPrefix.trim():delete l.branchPrefix),n.baseBranch!==void 0&&(n.baseBranch.trim()?l.baseBranch=n.baseBranch.trim():delete l.baseBranch),n.autoCreateWorktree!==void 0&&(l.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===t?{...u,worktreeDefaults:Object.keys(l).length>0?l:void 0}:u);s({projects:d}),Gr(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",s=>{const r=s.detail;r&&typeof r=="object"&&It.getState().synchronizeFromSettings(r)});const ag=new Set(["init","review"]),Zr=s=>ag.has(s.name),En="useCommandsStore",di=s=>new Promise(r=>setTimeout(r,s)),Zn=()=>{try{const r=It.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=De.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[CommandsStore] Error resolving config directory:",s)}return null},ig=2e4,Al=300,El=4,lg=800,cg=200,dg=2e3,Br=Bt()(Qt(Ms((s,r)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:t=>{s({selectedCommandName:t})},setCommandDraft:t=>{s({commandDraft:t})},loadCommands:async()=>{s({isLoading:!0});const t=r().commands;let n=null;for(let o=0;o<3;o++)try{const a=Zn(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await De.withDirectory(a,()=>De.listCommandsWithDetails()),d=await Promise.all(l.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${i}`,{headers:{"Cache-Control":"no-cache",...a?{"x-opencode-directory":a}:{}}});if(m.ok){const f=await m.json();let p=f.scope;if(!p&&f.sources){const h=f.sources;p=(h.md?.exists?h.md.scope:void 0)??(h.json?.exists?h.json.scope:void 0)??h.md?.scope??h.json?.scope}return p==="project"||p==="user"?{...u,scope:p}:{...u,scope:void 0}}}catch(m){console.warn(`[CommandsStore] Failed to fetch config for command ${u.name}:`,m)}return u}));return JSON.stringify(t)!==JSON.stringify(d)?s({commands:d,isLoading:!1}):s({isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load commands:",n),s({commands:t,isLoading:!1}),!1},createCommand:async t=>{_s("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),t.scope&&(o.scope=t.scope),console.log("[CommandsStore] Command config to save:",o);const a=Zn(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await xa({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&Js("commands",{source:En}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||xs()}},updateCommand:async(t,n)=>{_s("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const i=Zn(),l=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),u?.requiresReload??!0)return o=!0,await xa({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&Js("commands",{source:En}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||xs()}},deleteCommand:async t=>{_s("Deleting command configuration…");let n=!1;try{const o=Zn(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/commands/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const m=l?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),l?.requiresReload??!0)return n=!0,await xa({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&Js("commands",{source:En}),r().selectedCommandName===t&&s({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||xs()}},getCommandByName:t=>{const{commands:n}=r();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:Ds(()=>cs()),partialize:s=>({selectedCommandName:s.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Br);async function ug(s){const r=typeof s=="number"&&s>0?Math.min(s,Al):0;r>0&&await di(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<ig;){n+=1,cr(`Waiting for OpenCode… (attempt ${n})`);try{if(await De.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-t,i=n<=El&&a<1200?Al:Math.min(lg+Math.max(0,n-El)*cg,dg);await di(i)}throw o||new Error("OpenCode did not become ready in time")}async function xa(s={}){const{message:r,delayMs:t}=s;try{cr(r||"Refreshing commands…")}catch{}try{await ug(t),cr("Refreshing commands…"),await Br.getState().loadCommands(),Js("commands",{source:En})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),cr("OpenCode refresh failed. Please retry refreshing configuration manually."),await di(1500)}finally{xs()}}let Il=null;Il||(Il=sa(s=>{if(s.source!==En&&Bn(s,"commands")){const{loadCommands:r}=Br.getState();r()}}));const gr=()=>{const s=De.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},ko="useSkillsStore",Ks=Bt()(Qt(Ms((s,r)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:t=>{s({selectedSkillName:t})},setSkillDraft:t=>{s({skillDraft:t})},loadSkills:async()=>{s({isLoading:!0});const t=r().skills;let n=null;for(let o=0;o<3;o++)try{const a=gr(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills${i}`);if(!l.ok)throw new Error(`Failed to list skills: ${l.status}`);const u=(await l.json()).skills||[];return s({skills:u,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load skills:",n),s({skills:t,isLoading:!1}),!1},getSkillDetail:async t=>{try{const n=gr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async t=>{_s("Creating skill...");try{const n={name:t.name,description:t.description};t.instructions&&(n.instructions=t.instructions),t.scope&&(n.scope=t.scope),t.supportingFiles&&(n.supportingFiles=t.supportingFiles);const o=gr(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(t.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),l=await i.json().catch(()=>null);if(!i.ok){const u=l?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&Js("skills",{source:ko}),d}catch{return!1}finally{xs()}},updateSkill:async(t,n)=>{_s("Updating skill...");try{const o={};n.description!==void 0&&(o.description=n.description),n.instructions!==void 0&&(o.instructions=n.instructions),n.supportingFiles!==void 0&&(o.supportingFiles=n.supportingFiles);const a=gr(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(t)}${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&Js("skills",{source:ko}),u}catch{return!1}finally{xs()}},deleteSkill:async t=>{_s("Deleting skill...");try{const n=gr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`,{method:"DELETE"}),i=await a.json().catch(()=>null);if(!a.ok){const d=i?.error||"Failed to delete skill";throw new Error(d)}const l=await r().loadSkills();return l&&Js("skills",{source:ko}),r().selectedSkillName===t&&s({selectedSkillName:null}),l}catch{return!1}finally{xs()}},getSkillByName:t=>{const{skills:n}=r();return n.find(o=>o.name===t)},readSupportingFile:async(t,n)=>{try{const o=gr(),a=o?`&directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return i.ok?(await i.json()).content??null:null}catch{return null}},writeSupportingFile:async(t,n,o)=>{try{const a=gr(),i=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(t,n)=>{try{const o=gr(),a=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${a}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:Ds(()=>cs()),partialize:s=>({selectedSkillName:s.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=Ks);let Pl=null;Pl||(Pl=sa(s=>{if(s.source!==ko&&Bn(s,"skills")){const{loadSkills:r}=Ks.getState();r()}}));const ba=()=>{const s=De.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Kn=Bt()(Qt((s,r)=>({sources:[],itemsBySource:{},selectedSourceId:null,isLoadingCatalog:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:t=>s({selectedSourceId:t}),loadCatalog:async t=>{s({isLoadingCatalog:!0,lastCatalogError:null});const n={sources:r().sources,itemsBySource:r().itemsBySource};let o=null;try{for(let a=0;a<3;a++)try{const i=ba(),l=t?.refresh?"&refresh=true":"",d=i?`?directory=${encodeURIComponent(i)}${l}`:l?"?refresh=true":"",u=await fetch(`/api/config/skills/catalog${d}`,{method:"GET",headers:{Accept:"application/json"}}),m=await u.json().catch(()=>null);if(!u.ok||!m?.ok){o=m?.error||{kind:"unknown",message:`Failed to load catalog (${u.status})`};const g=200*(a+1);await new Promise(b=>setTimeout(b,g));continue}const f=m.sources||[],p=m.itemsBySource||{},h=r().selectedSourceId,j=h&&f.some(g=>g.id===h)?h:f[0]?.id??null;return s({sources:f,itemsBySource:p,selectedSourceId:j}),!0}catch(i){o={kind:"unknown",message:i instanceof Error?i.message:String(i)};const l=200*(a+1);await new Promise(d=>setTimeout(d,l))}return s({sources:n.sources,itemsBySource:n.itemsBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{s({isLoadingCatalog:!1})}},scanRepo:async t=>{s({isScanning:!0,lastScanError:null,scanResults:null});try{const n=ba(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),i=await a.json().catch(()=>null);if(!a.ok||!i){const l=i?.error||{kind:"unknown",message:"Failed to scan repository"};return s({lastScanError:l}),{ok:!1,error:l}}return i.ok?(s({scanResults:i.items||[]}),i):(s({lastScanError:i.error||{kind:"unknown",message:"Failed to scan repository"}}),i)}finally{s({isScanning:!1})}},installSkills:async t=>{s({isInstalling:!0,lastInstallError:null});try{const n=ba(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/install${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),i=await a.json().catch(()=>null);if(!i){const l={kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:l}),{ok:!1,error:l}}if(!a.ok||!i.ok){const l=i.error||{kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:l}),{ok:!1,error:l}}return Ks.getState().loadSkills(),i}catch(n){const o={kind:"unknown",message:n instanceof Error?n.message:String(n)};return s({lastInstallError:o}),{ok:!1,error:o}}finally{s({isInstalling:!1})}}}),{name:"skills-catalog-store"})),mg=()=>{const s=De.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},eo=()=>{try{const r=It.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=De.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[AgentsStore] Error resolving config directory:",s)}return null},en=s=>{const r=s;return r.native===!0||r.builtIn===!0},uu=s=>{const r=s;return r.hidden===!0||r.options?.hidden===!0},mu=s=>s.filter(r=>!uu(r)),No="useAgentsStore",$o=s=>new Promise(r=>setTimeout(r,s)),fg=2e4,Tl=300,Fl=4,pg=800,hg=200,gg=2e3,zr=Bt()(Qt(Ms((s,r)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:t=>{s({selectedAgentName:t})},setAgentDraft:t=>{s({agentDraft:t})},loadAgents:async()=>{s({isLoading:!0});const t=r().agents;for(let n=0;n<3;n++)try{const o=eo(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await De.withDirectory(o,()=>De.listAgents()),l=await Promise.all(i.map(async d=>{try{const u=await fetch(`/api/config/agents/${encodeURIComponent(d.name)}${a}`,{headers:{"Cache-Control":"no-cache",...o?{"x-opencode-directory":o}:{}}});if(u.ok){const m=await u.json();let f=m.scope;if(!f&&m.sources){const p=m.sources;f=(p.md?.exists?p.md.scope:void 0)??(p.json?.exists?p.json.scope:void 0)??p.md?.scope??p.json?.scope}return f==="project"||f==="user"?{...d,scope:f}:{...d,scope:void 0}}}catch(u){console.warn(`[AgentsStore] Failed to fetch config for agent ${d.name}:`,u)}return d}));return JSON.stringify(t)!==JSON.stringify(l)?s({agents:l,isLoading:!1}):s({isLoading:!1}),!0}catch{}return s({isLoading:!1}),!1},createAgent:async t=>{_s("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",t.name);const o={mode:t.mode||"subagent"};t.description&&(o.description=t.description),t.model&&(o.model=t.model),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.prompt&&(o.prompt=t.prompt),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),t.scope&&(o.scope=t.scope),console.log("[AgentsStore] Agent config to save:",o);const a=eo(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await In({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&Js("agents",{source:No}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||xs()}},updateAgent:async(t,n)=>{_s("Updating agent configuration…");let o=!1;try{const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const i=eo(),l=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update agent";throw new Error(p)}if(u?.requiresReload??!0)return o=!0,await In({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&Js("agents",{source:No}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||xs()}},deleteAgent:async t=>{_s("Deleting agent configuration…");let n=!1;try{const o=eo(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/agents/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const m=l?.error||"Failed to delete agent";throw new Error(m)}if(l?.requiresReload??!0)return n=!0,await In({message:l?.message,delayMs:l?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&Js("agents",{source:No}),r().selectedAgentName===t&&s({selectedAgentName:null}),u}catch{return!1}finally{n||xs()}},getAgentByName:t=>{const{agents:n}=r();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=r();return mu(t)}}),{name:"agents-store",storage:Ds(()=>cs()),partialize:s=>({selectedAgentName:s.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=zr);async function yg(s){const r=typeof s=="number"&&s>0?Math.min(s,Tl):0;r>0&&await $o(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<fg;){n+=1,cr(`Waiting for OpenCode… (attempt ${n})`);try{if(await De.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-t,i=n<=Fl&&a<1200?Tl:Math.min(pg+Math.max(0,n-Fl)*hg,gg);await $o(i)}throw o||new Error("OpenCode did not become ready in time")}const xg=s=>{if(!s||s.length===0)return["all"];const r=Array.from(new Set(s));return r.includes("all")?["all"]:r};async function bg(s={}){const{message:r,delayMs:t}=s,n=xg(s.scopes),o=s.mode??(n.includes("all")?"projects":"active");try{cr(r||"Refreshing configuration…")}catch{}try{await yg(t);const a=at.getState(),i=zr.getState(),l=Br.getState(),d=Ks.getState(),u=Kn.getState(),m=n.includes("all")||n.includes("providers"),f=n.includes("all")||n.includes("agents"),p=n.includes("all")||n.includes("agents"),h=n.includes("all")||n.includes("commands"),j=n.includes("all")||n.includes("skills"),g=mg(),b=o==="projects"?It.getState().projects:[],x=Array.from(new Set([...g?[g]:[],...b.map(S=>S.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&at.setState({directoryScoped:{}});const y=[];for(const S of x)m&&y.push(a.loadProviders({directory:S}).then(()=>{})),f&&y.push(a.loadAgents({directory:S}).then(()=>{}));const w=[];p&&w.push(i.loadAgents().then(()=>{})),h&&w.push(l.loadCommands().then(()=>{})),j&&(w.push(d.loadSkills().then(()=>{})),w.push(u.loadCatalog().then(()=>{}))),cr("Refreshing configuration…"),await Promise.all([...y,...w])}catch{cr("OpenCode refresh failed. Please retry."),await $o(1500)}finally{xs()}}async function In(s){await bg(s)}async function Pn(s){_s(s?.message||"Reloading OpenCode configuration…");try{const r=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),t=await r.json().catch(()=>null);if(!r.ok){const o=t?.error||"Failed to reload configuration";throw new Error(o)}const n={...s,scopes:s?.scopes??["all"],mode:s?.mode??"projects"};t?.requiresReload?await In({...n,message:t.message,delayMs:t.reloadDelayMs}):await In(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),cr("Failed to reload configuration. Please try again."),await $o(2e3),xs(),r}}let Rl=null;Rl||(Rl=sa(s=>{if(s.source!==No&&Bn(s,"agents")){const{loadAgents:r}=zr.getState();r()}}));const wg="https://models.dev/api.json",vg="/api/openchamber/models-metadata",Ol="opencode",$l="big-pickle",jg=async()=>{try{if(ss()){const n=await wn();return{defaultModel:n?.defaultModel,defaultAgent:n?.defaultAgent,autoCreateWorktree:n?.autoCreateWorktree}}const s=_r()?.settings;if(s)try{const o=(await s.load())?.settings;if(o)return{defaultModel:typeof o?.defaultModel=="string"?o.defaultModel:void 0,defaultAgent:typeof o?.defaultAgent=="string"?o.defaultAgent:void 0,autoCreateWorktree:typeof o?.autoCreateWorktree=="boolean"?o.autoCreateWorktree:void 0}}catch{}const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const t=await r.json();return{defaultModel:typeof t?.defaultModel=="string"?t.defaultModel:void 0,defaultAgent:typeof t?.defaultAgent=="string"?t.defaultAgent:void 0,autoCreateWorktree:typeof t?.autoCreateWorktree=="boolean"?t.autoCreateWorktree:void 0}}catch{return{}}},Ll=s=>{if(!s||typeof s!="string")return null;const r=s.split("/");return r.length!==2||!r[0]||!r[1]?null:{providerId:r[0],modelId:r[1]}},Sg=s=>s?.toLowerCase?.()??"",kg=s=>s==="primary"||s==="all"||s===void 0||s===null,zn=s=>typeof s=="object"&&s!==null,Lo=s=>Array.isArray(s)&&s.every(r=>typeof r=="string"),Ng=s=>{if(!zn(s))return!1;const r=s;if(r.modalities){const{input:t,output:n}=r.modalities;if(t&&!Lo(t)||n&&!Lo(n))return!1}return!0},Cg=s=>{if(!zn(s))return!1;const r=s;return r.models===void 0||zn(r.models)},fu=(s,r)=>{const t=Sg(s);return!t||!r?"":`${t}/${r}`},Mg=s=>{const r=new Map;if(!zn(s))return r;for(const[t,n]of Object.entries(s)){if(!Cg(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!zn(a)))for(const[i,l]of Object.entries(a)){if(!Ng(l))continue;const d=typeof i=="string"&&i.length>0?i:l.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof l.id=="string"&&l.id.length>0?l.id:d,providerId:o,name:typeof l.name=="string"?l.name:void 0,tool_call:typeof l.tool_call=="boolean"?l.tool_call:void 0,reasoning:typeof l.reasoning=="boolean"?l.reasoning:void 0,temperature:typeof l.temperature=="boolean"?l.temperature:void 0,attachment:typeof l.attachment=="boolean"?l.attachment:void 0,modalities:l.modalities?{input:Lo(l.modalities.input)?l.modalities.input:void 0,output:Lo(l.modalities.output)?l.modalities.output:void 0}:void 0,cost:l.cost,limit:l.limit,knowledge:typeof l.knowledge=="string"?l.knowledge:void 0,release_date:typeof l.release_date=="string"?l.release_date:void 0,last_updated:typeof l.last_updated=="string"?l.last_updated:void 0},m=fu(o,d);m&&r.set(m,u)}}return r},Dg=async()=>{if(typeof fetch!="function")return new Map;const s=[vg,wg];for(const r of s){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),a={signal:t?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const i=await fetch(r,a);if(!i.ok)throw new Error(`Metadata request to ${r} returned status ${i.status}`);const l=await i.json();return Mg(l)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let wa=null;const Ag=(s,r)=>{s().size>0||wa||(wa=Dg().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{wa=null}))},Eg=s=>new Promise(r=>setTimeout(r,s)),zi="__global__",nn=s=>{const r=typeof s=="string"?s.trim():"";return r.length>0?r:zi},qr=s=>s===zi?null:s,Ig=()=>{if(typeof window>"u")return zi;const s=De.getDirectory()??ft.getState().currentDirectory;return nn(s)},at=Bt()(Qt(Ms((s,r)=>({activeDirectoryKey:Ig(),directoryScoped:{},providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultAgent:void 0,settingsAutoCreateWorktree:!1,activateDirectory:async t=>{const n=nn(t);s(o=>{const a=o.directoryScoped[n];return a?{activeDirectoryKey:n,providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders}:{activeDirectoryKey:n,providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}}}),r().isConnected&&(await r().loadProviders({directory:qr(n)}),await r().loadAgents({directory:qr(n)}))},loadProviders:async t=>{const n=nn(t?.directory??qr(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),i=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let l=null;for(let d=0;d<3;d++)try{Ag(()=>r().modelsMetadata,h=>s({modelsMetadata:h}));const u=await De.withDirectory(qr(n),()=>De.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(h=>{const j=h.models??{},g=Object.keys(j).map(b=>j[b]);return{...h,models:g}});s(h=>{const g={...h.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:p,defaultProviders:f},b={directoryScoped:{...h.directoryScoped,[n]:g}};return h.activeDirectoryKey===n&&(b.providers=p,b.defaultProviders=f),b});return}catch(u){l=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",l),s(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:i},f={directoryScoped:{...d.directoryScoped,[n]:m}};return d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=i),f})},setProvider:t=>{const{providers:n}=r(),o=n.find(l=>l.id===t);if(!o)return;const i=o.models[0]?.id||"";s(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentProviderId:t,currentModelId:i,selectedProviderId:t};return{currentProviderId:t,currentModelId:i,selectedProviderId:t,directoryScoped:{...l.directoryScoped,[d]:m}}})},setModel:t=>{s(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentModelId:t};return{currentModelId:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},setSelectedProvider:t=>{s(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},selectedProviderId:t};return{selectedProviderId:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},saveAgentModelSelection:(t,n,o)=>{s(a=>{const i=a.activeDirectoryKey,l={...a.agentModelSelections,[t]:{providerId:n,modelId:o}},u={...a.directoryScoped[i]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:l};return{agentModelSelections:l,directoryScoped:{...a.directoryScoped,[i]:u}}})},getAgentModelSelection:t=>{const{agentModelSelections:n}=r();return n[t]||null},loadAgents:async t=>{const n=nn(t?.directory??qr(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let i=null;for(let l=0;l<3;l++)try{const[d,u]=await Promise.all([De.withDirectory(qr(n),()=>De.listAgents()),jg()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(s(S=>{const N={...S.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},D={settingsDefaultModel:u.defaultModel,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,directoryScoped:{...S.directoryScoped,[n]:N}};return S.activeDirectoryKey===n&&(D.agents=m),D}),m.length===0)return s(S=>{const N={...S.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},D={directoryScoped:{...S.directoryScoped,[n]:N}};return S.activeDirectoryKey===n&&(D.currentAgentName=void 0),D}),!0;const p=(S,v)=>{const N=f.find(D=>D.id===S);return N?N.models.some(D=>D.id===v):!1},h=m.filter(S=>kg(S.mode));let b=h.find(S=>S.name==="build")||h[0]||m[0];const x={};if(u.defaultAgent){const S=m.find(v=>v.name===u.defaultAgent);S?b=S:x.defaultAgent=""}let y,w;if(u.defaultModel){const S=Ll(u.defaultModel);S&&p(S.providerId,S.modelId)?(y=S.providerId,w=S.modelId):x.defaultModel=""}if(!y&&b?.model?.providerID&&b?.model?.modelID&&p(b.model.providerID,b.model.modelID)&&(y=b.model.providerID,w=b.model.modelID),!y)if(p(Ol,$l))y=Ol,w=$l;else{const S=f[0];S&&S.models[0]&&(y=S.id,w=S.models[0].id)}return s(S=>{const v=S.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},N={...v,providers:f,agents:m,currentAgentName:b.name,currentProviderId:y??v.currentProviderId,currentModelId:w??v.currentModelId},D={directoryScoped:{...S.directoryScoped,[n]:N}};return S.activeDirectoryKey===n&&(D.currentAgentName=b.name,y&&w&&(D.currentProviderId=y,D.currentModelId=w)),D}),Object.keys(x).length>0&&(s({settingsDefaultModel:x.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultAgent:x.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),os(x).catch(()=>{})),!0}catch(d){i=d;const u=200*(l+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",i),s(l=>{const d=l.activeDirectoryKey===n?l.providers:l.directoryScoped[n]?.providers??[],m={...l.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...l.directoryScoped,[n]:m}};return l.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:t=>{const{agents:n,providers:o,settingsDefaultModel:a}=r();if(s(i=>{const l=i.activeDirectoryKey,u={...i.directoryScoped[l]??{providers:i.providers,agents:i.agents,currentProviderId:i.currentProviderId,currentModelId:i.currentModelId,currentAgentName:i.currentAgentName,selectedProviderId:i.selectedProviderId,agentModelSelections:i.agentModelSelections,defaultProviders:i.defaultProviders},currentAgentName:t};return{currentAgentName:t,directoryScoped:{...i.directoryScoped,[l]:u}}}),t&&typeof window<"u"){const i=window.__zustand_session_store__;if(i){const l=i.getState(),{currentSessionId:d,isOpenChamberCreatedSession:u,initializeNewOpenChamberSession:m,getAgentModelForSession:f}=l;d&&i.setState(p=>{const h=new Map(p.currentAgentContext);return h.set(d,t),{currentAgentContext:h}}),d&&u(d)&&(f(d,t)||m(d,n))}}if(t&&typeof window<"u"){const i=window.__zustand_session_store__;if(i){const{currentSessionId:d,getAgentModelForSession:u}=i.getState();if(d&&u(d,t))return}if(a){const d=Ll(a);if(d&&o.find(m=>m.id===d.providerId)?.models.some(m=>m.id===d.modelId)){s(m=>{const f=m.activeDirectoryKey,h={...m.directoryScoped[f]??{providers:m.providers,agents:m.agents,currentProviderId:m.currentProviderId,currentModelId:m.currentModelId,currentAgentName:m.currentAgentName,selectedProviderId:m.selectedProviderId,agentModelSelections:m.agentModelSelections,defaultProviders:m.defaultProviders},currentProviderId:d.providerId,currentModelId:d.modelId};return{currentProviderId:d.providerId,currentModelId:d.modelId,directoryScoped:{...m.directoryScoped,[f]:h}}});return}}const l=n.find(d=>d.name===t);if(l?.model?.providerID&&l?.model?.modelID){const d=o.find(u=>u.id===l.model.providerID);d&&d.models.find(m=>m.id===l.model.modelID)&&s(m=>{const f=m.activeDirectoryKey,h={...m.directoryScoped[f]??{providers:m.providers,agents:m.agents,currentProviderId:m.currentProviderId,currentModelId:m.currentModelId,currentAgentName:m.currentAgentName,selectedProviderId:m.selectedProviderId,agentModelSelections:m.agentModelSelections,defaultProviders:m.defaultProviders},currentProviderId:l.model.providerID,currentModelId:l.model.modelID,selectedProviderId:l.model.providerID};return{currentProviderId:l.model.providerID,currentModelId:l.model.modelID,selectedProviderId:l.model.providerID,directoryScoped:{...m.directoryScoped,[f]:h}}})}}},setSettingsDefaultModel:t=>{s({settingsDefaultModel:t})},setSettingsDefaultAgent:t=>{s({settingsDefaultAgent:t})},setSettingsAutoCreateWorktree:t=>{s({settingsAutoCreateWorktree:t})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await De.checkHealth();return s({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await Eg(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),s({isConnected:!1}),!1},initializeApp:async()=>{try{const t=Wt();t&&console.log("Starting app initialization...");const n=await r().checkConnection();if(t&&console.log("Connection check result:",n),!n){t&&console.log("Server not connected"),s({isConnected:!1});return}t&&console.log("Initializing app..."),await De.initApp(),t&&console.log("Loading providers..."),await r().loadProviders(),t&&console.log("Loading agents..."),await r().loadAgents(),s({isInitialized:!0,isConnected:!0}),t&&console.log("App initialized successfully")}catch(t){console.error("Failed to initialize app:",t),s({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:t,currentProviderId:n}=r();return t.find(o=>o.id===n)},getCurrentModel:()=>{const t=r().getCurrentProvider(),{currentModelId:n}=r();if(t)return t.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:t,currentAgentName:n}=r();if(n)return t.find(o=>o.name===n)},getModelMetadata:(t,n)=>{const o=fu(t,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=r();return mu(t)}}),{name:"config-store",storage:Ds(()=>cs()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=at);let _l=null;_l||(_l=sa(async s=>{const r=[];if(Bn(s,"agents")){const{loadAgents:t}=at.getState();r.push(t().then(()=>{}))}if(Bn(s,"providers")){const{loadProviders:t}=at.getState();r.push(t())}r.length>0&&await Promise.all(r)}));let Bl=null;typeof window<"u"&&!Bl&&(Bl=ft.subscribe((s,r)=>{const t=nn(s.currentDirectory),n=nn(r.currentDirectory);t!==n&&at.getState().activateDirectory(s.currentDirectory)}));const ls={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Pg=180,gs=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function Wr(s){const r=gs();return r?r.checkIsGitRepository(s):sh(s)}async function Tg(s){const r=gs();return r?r.getGitStatus(s):nh(s)}async function Wi(s){const r=gs();return r?r.getGitBranches(s):hh(s)}async function Fg(s,r){const t=gs();return t?t.deleteGitBranch(s,r):ah(s,r)}async function Rg(s,r){const t=gs();return t?t.deleteRemoteBranch(s,r):ih(s,r)}async function Og(s){const r=gs();return r?r.listGitWorktrees(s):rh(s)}async function $g(s,r){const t=gs();return t?t.addGitWorktree(s,r):lh(s,r)}async function pu(s,r){const t=gs();return t?t.removeGitWorktree(s,r):oh(s,r)}async function Lg(s){const r=gs();return r?r.ensureOpenChamberIgnored(s):ph(s)}async function _g(){const s=gs();return s?s.getGitIdentities():fh()}async function Bg(s){const r=gs();return r?r.createGitIdentity(s):uh(s)}async function zg(s,r){const t=gs();return t?t.updateGitIdentity(s,r):dh(s,r)}async function Wg(s){const r=gs();return r?r.deleteGitIdentity(s):ch(s)}async function Hg(s){const r=gs();return r?r.getCurrentGitIdentity(s):mh(s)}const Ug="openchamber.json",hu=".openchamber";function gu(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const Vg=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},ui=(s,r)=>{const t=Vg(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},yu=s=>ui(ui(s,hu),Ug);async function xu(s){const r=yu(s);try{const t=gu();if(t?.readFile)try{const i=await t.readFile(r);if(!i.content.trim())return null;const l=JSON.parse(i.content);return!l||typeof l!="object"?null:l}catch{return null}const n=await fetch(`${wu()}/fs/read?path=${encodeURIComponent(r)}`);if(!n.ok)return n.status===404,null;const o=await n.text();if(!o.trim())return null;const a=JSON.parse(o);return!a||typeof a!="object"?null:a}catch{return null}}async function Gg(s,r){const t=yu(s),n=ui(s,hu);try{await De.createDirectory(n);const o=gu();if(o?.writeFile)try{return(await o.writeFile(t,JSON.stringify(r,null,2))).success}catch(i){return console.error("Failed to write openchamber config via runtime API:",i),!1}return(await fetch(`${wu()}/fs/write`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,content:JSON.stringify(r,null,2)})})).ok}catch(o){return console.error("Failed to write openchamber config:",o),!1}}async function qg(s,r){const n={...await xu(s)||{},...r};return Gg(s,n)}async function Yn(s){return(await xu(s))?.["setup-worktree"]??[]}async function bu(s,r){const t=r.filter(n=>n.trim().length>0);return qg(s,{"setup-worktree":t})}function Kg(s,r){return s.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function wu(){const s="/api";return s.startsWith("/"),s}const Yg=".openchamber",zl="/api";function Xg(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const pr=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Wl=(s,r)=>{const t=pr(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},vu=s=>s?s.startsWith("refs/heads/")?s.substring(11):s.startsWith("heads/")?s.substring(6):s.startsWith("refs/")?s.substring(5):s:"",Qg=async s=>{try{await De.createDirectory(s)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function Jg(s,r){const t=pr(s),n=Wl(t,Yg);return await Qg(n),Wl(n,r)}async function ju(s){const{projectDirectory:r,worktreeSlug:t,branch:n,createBranch:o,startPoint:a}=s,i=pr(r),l=await Jg(i,t),d={path:l,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await $g(i,d),{path:l,branch:n,label:vu(n),projectDirectory:i,relativePath:l.startsWith(`${i}/`)?l.slice(i.length+1):l}}async function Zg(s){const{projectDirectory:r,path:t,force:n}=s,o=pr(r);await pu(o,{path:t,force:n})}async function Su(s){const{projectDirectory:r,path:t,branch:n,force:o,deleteRemote:a,remote:i}=s,l=pr(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await pu(l,{path:t,force:o}),d&&(await Fg(l,{branch:d,force:!0}),a))try{await Rg(l,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function mn(s){const r=pr(s);return Og(r)}async function Hi(s){const r=pr(s),t=await Tg(r);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function fn(s,r){const t=pr(s),n=pr(r.worktree);return{path:n,branch:r.branch??"",label:vu(r.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}async function ku(s,r,t){const n=t??await Yn(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>Kg(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:s,projectDirectory:r,commands:o});try{const a=Xg();if(a?.execCommands){console.log("[worktreeService] Using runtime API for exec");try{const d=await a.execCommands(o,s);return console.log("[worktreeService] Runtime exec result:",d),d}catch(d){return console.error("[worktreeService] Runtime exec error:",d),{success:!1,results:o.map(u=>({command:u,success:!1,error:d instanceof Error?d.message:"Unknown error"}))}}}console.log("[worktreeService] Using web API for exec");const i=await fetch(`${zl}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:o,cwd:s,background:!0})}),l=await i.json().catch(()=>null);if(i.status===202&&l&&typeof l.jobId=="string"){const d=l.jobId,u=800,m=Math.max(5*6e4,o.length*6e4),f=Date.now();for(;Date.now()-f<m;){await new Promise(g=>setTimeout(g,u));const p=await fetch(`${zl}/fs/exec/${d}`,{method:"GET"}),h=await p.json().catch(()=>null);if(!p.ok)return{success:!1,results:o.map(g=>({command:g,success:!1,error:h&&h.error||"Failed to poll exec job"}))};if(h?.status==="done"){const g=Array.isArray(h?.results)?h.results:[];return{success:h?.success===!0,results:g}}}return{success:!1,results:o.map(p=>({command:p,success:!1,error:"Setup commands timed out"}))}}if(!i.ok){const d=l&&l.error||"Request failed";return console.error("[worktreeService] Web exec failed:",l),{success:!1,results:o.map(u=>({command:u,success:!1,error:d}))}}return console.log("[worktreeService] Web exec result:",l),l}catch(a){return console.error("[worktreeService] Exec exception:",a),{success:!1,results:o.map(i=>({command:i,success:!1,error:a instanceof Error?a.message:"Unknown error"}))}}}const Nu=cs(),Cu="oc.sessionSelectionByDirectory",va=".openchamber",ey=()=>{try{const s=Nu.getItem(Cu);if(!s)return{};const r=JSON.parse(s);return!r||typeof r!="object"?{}:Object.entries(r).reduce((t,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(t[n]=o),t),{})}catch{return{}}};let Co=null;const Ui=()=>(Co||(Co=ey()),Co),Mu=s=>{Co=s;try{Nu.setItem(Cu,JSON.stringify(s))}catch{}},Du=s=>{if(!s)return null;const t=Ui()[s];return typeof t=="string"?t:null},sr=(s,r)=>{if(!s)return;const t={...Ui()};r?t[s]=r:delete t[s],Mu(t)},ty=(s,r)=>{if(!s)return;const t=Du(s);if(!t)return;if(!new Set(r).has(t)){const o={...Ui()};delete o[s],Mu(o)}},Hl=async(s,r)=>{const t=s.status??await Hi(s.path).catch(()=>{});await Su({projectDirectory:s.projectDirectory,path:s.path,branch:s.branch,force:!!t?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},bt=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},Ul=()=>{if(typeof window>"u")return null;const s=window.__VSCODE_CONFIG__,r=typeof s?.workspaceFolder=="string"?s.workspaceFolder:null;return bt(r)},sy=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,to=(...s)=>{Wt()&&sy()&&console.log("[OpenChamber][VSCode][sessions]",...s)},yr=s=>{const r=new Map;return s.forEach(t=>{if(!t||typeof t.id!="string"||t.id.length===0)return;const n=r.get(t.id);if(!n){r.set(t.id,t);return}const o=n.time?.updated??0;(t.time?.updated??0)>o&&r.set(t.id,t)}),Array.from(r.values())},Es=s=>{const r=new Map;s.forEach(t=>{const n=bt(t.directory??null);if(!n)return;const o=r.get(n);o?o.push(t):r.set(n,[t])});for(const[t,n]of r.entries())r.set(t,yr(n));return r},Kr=(s,r)=>{const t=s.find(n=>n.id===r);return t?bt(t.directory??null):null},ry=async(s,r,t)=>{const n=bt(r);if(!n||s.length===0)return null;const o=s.map(u=>({id:u.id,directory:bt(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await mn(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const m=new Map(t);return o.forEach(({id:f})=>{m.delete(f)&&(u=!0)}),u?m:null}const i=new Map;a.forEach(u=>{const m=fn(n,u),f=bt(m.path)??m.path;f!==n&&i.set(f,m)});let l=!1;const d=new Map(t);return o.forEach(({id:u,directory:m})=>{const f=i.get(m);if(!f){d.delete(u)&&(l=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),l=!0)}),l?d:null},rt=Bt()(Qt(Ms((s,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,loadSessions:async()=>{s({isLoading:!0,error:null});try{const t=ft.getState(),n=It.getState(),o=De.getApiClient(),a=Ul(),i=!!a;to("loadSessions:start",{workspace:a,currentDirectory:t.currentDirectory,clientDirectory:De.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const l=new Map,d=async H=>{const V=bt(H)??H,J=V,T=l.get(J);if(T)return T;try{const Z=await o.path.get({directory:H}),B=bt(Z.data?.directory??null)??V;return l.set(J,B),B}catch{return l.set(J,V),V}},u=(H,V,J)=>{const T=bt(V);if(!T)return H;const E=J?.includeDescendants===!0?`${T}/`:null,B=J?.includeMissingDirectory===!0;return H.filter(X=>{const re=bt(X.directory??null);return re?!!(re===T||E&&re.startsWith(E)):B})},m=(H,V,J)=>{const T=bt(V);if(!T)return H;const Z=bt(J??null);if(!Z||Z===T)return H.map(X=>bt(X.directory??null)?X:{...X,directory:T});const E=Z==="/"?"/":`${Z}/`,B=T==="/"?"/":`${T}/`;return H.map(X=>{const re=bt(X.directory??null);if(!re)return{...X,directory:T};if(re===Z)return{...X,directory:T};if(E!=="/"&&re.startsWith(E)){const q=re.slice(E.length);return{...X,directory:`${B}${q}`}}return X})},f=async H=>{const V=bt(H);if(!V)try{const re=await o.session.list(void 0);return Array.isArray(re.data)?re.data:[]}catch(re){throw console.debug("Failed to list sessions (global):",re),re}const J=await d(V),T=async()=>{const re=await o.session.list({directory:V});return Array.isArray(re.data)?re.data:[]};let Z=[],E=null,B=!1;try{Z=await T()}catch(re){console.debug("Failed to list sessions for directory:",V,re),E=re,Z=[]}if(Z.length===0){B=!0;try{const re=await o.session.list(void 0),q=Array.isArray(re.data)?re.data:[];Z=u(q,J,{includeDescendants:i,includeMissingDirectory:!1})}catch(re){throw console.debug("Failed to list sessions (global fallback):",re),E||re}}const X=u(Z,J,{includeDescendants:i,includeMissingDirectory:!B});return to("fetchSessionsForDirectory",{requestedDirectory:V,canonicalDirectory:J,fetched:Z.length,filtered:X.length}),m(X,V,J)},p=bt(t.currentDirectory??De.getDirectory()??null),h=n.projects.find(H=>H.id===n.activeProjectId)??null,j=bt(h?.path??null),g=j??p??null,b=n.projects.length>0?n.projects:g?[{id:"legacy",path:g}]:[];if(b.length===0){s({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}const x=await Promise.all(b.map(async H=>{const V=bt(H.path);if(!V)return{projectId:H.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const J=await Wr(V).catch(()=>!1),T=await f(V||null);to("projectSessions",{projectId:H.id,projectPath:V,isGitRepo:J,parentSessions:T.length});const Z=[];let E=[];const B=new Set;if(B.add(V),J){const re=`${V}/${va}`;try{const q=new Set;(await De.listLocalDirectory(V)).some(F=>F.isDirectory&&F.name===va)&&(await De.listLocalDirectory(re)).filter(W=>W.isDirectory).forEach(W=>{const _=/^([A-Za-z]:)?\//.test(W.path)?W.path:`${re}/${W.name}`,ee=bt(_)??_;q.add(ee)});const I=await mn(V);Array.isArray(I)&&(E=I.map(F=>fn(V,F)).filter(F=>F.path.includes(`/${va}/`)),E.forEach(F=>q.add(F.path))),q.forEach(F=>{const W=bt(F)??F;B.add(W)}),q.size>0&&(await Promise.allSettled(Array.from(q).map(W=>f(W)))).forEach(W=>{W.status==="fulfilled"&&Array.isArray(W.value)&&Z.push(...W.value)})}catch{E=[]}}const X=yr([...T,...Z]);return{projectId:H.id,projectPath:V,sessions:X,discoveredWorktrees:E,validPaths:B}})),y=new Map;x.forEach(H=>{H.projectPath&&H.validPaths.forEach(V=>{const J=bt(V)??V,T=H.sessions.filter(Z=>(bt(Z.directory??null)??J)===J);y.set(J,yr(T))})});const w=yr(Array.from(y.values()).flat()),S=r();let v=S.worktreeMetadata;for(const H of x)if(H.projectPath)try{const V=await ry(H.sessions,H.projectPath,v);V&&(v=V)}catch(V){console.debug("Failed to refresh worktree metadata during session load:",V)}const N=new Map;x.forEach(H=>{H.projectPath&&N.set(H.projectPath,H.discoveredWorktrees)});const D=new Set;x.forEach(H=>{H.validPaths.forEach(V=>{const J=bt(V)??V;J&&D.add(J)})});const M=p??j??null,C=M&&D.has(M)?M:j??M,k=C?y.get(C)??[]:w,A=new Set(w.map(H=>H.id));for(const[H,V]of y.entries())ty(H,V.map(J=>J.id));const P=(C??null)!==(S.lastLoadedDirectory??null);let L=S.currentSessionId;if((!L||!A.has(L)||P)&&(L=k[0]?.id??w[0]?.id??null),C){const H=Du(C);H&&A.has(H)&&(L=H)}const U=(()=>{if(!L)return C??null;const H=v.get(L)?.path;if(H)return bt(H)??H;const V=Kr(w,L);return V||(C??null)})();try{De.setDirectory(U??void 0)}catch(H){console.warn("Failed to sync OpenCode directory after session load:",H)}const z=j?x.find(H=>H.projectPath===j)?.discoveredWorktrees??[]:[];s({sessions:w,sessionsByDirectory:y,currentSessionId:L,lastLoadedDirectory:C??null,isLoading:!1,worktreeMetadata:v,availableWorktrees:z,availableWorktreesByProject:N}),C&&sr(C,L),U&&U!==C&&sr(U,L)}catch(t){s({error:t instanceof Error?t.message:"Failed to load sessions",isLoading:!1})}},createSession:async(t,n,o)=>{s({error:null});const a=ft.getState(),i=bt(a.currentDirectory),l=Ul(),d=l??bt(n??De.getDirectory()??i);to("createSession:start",{title:t,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:l});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(g=>g.id)),p={id:u,title:t||"New session",parentID:o??void 0,directory:d??null,projectID:m.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(s(g=>{const b=[p,...g.sessions],x=new Map(g.sessionsByDirectory);if(d){const y=x.get(d)??[];x.set(d,yr([p,...y]))}return{sessions:b,sessionsByDirectory:x,currentSessionId:u,webUICreatedSessions:new Set([...g.webUICreatedSessions,u]),isLoading:!1}}),d)try{De.setDirectory(d)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const h=g=>{const b=d??null,x=b?{...g,directory:b}:g;s(y=>{const w=y.sessions.map(v=>v.id===u?x:v),S=new Map(y.sessionsByDirectory);if(d){const N=(S.get(d)??[]).map(D=>D.id===u?x:D);S.set(d,yr(N))}return{sessions:w,sessionsByDirectory:Es(w),currentSessionId:x.id,webUICreatedSessions:new Set([...Array.from(y.webUICreatedSessions).filter(v=>v!==u),x.id])}}),sr(d??null,x.id)},j=async()=>{const g=De.getApiClient(),b=20;for(let x=0;x<b;x+=1){try{const y=await g.session.list(d?{directory:d}:void 0),S=(Array.isArray(y.data)?y.data:[]).find(v=>!(f.has(v.id)||t&&v.title&&v.title!==t));if(S)return S}catch(y){console.debug("Session poll attempt failed:",y)}await new Promise(y=>setTimeout(y,2e3))}return null};try{const g=()=>De.createSession({title:t,parentID:o??void 0});let b=null;try{b=d?await De.withDirectory(d,g):await g()}catch(x){console.warn("Direct session create failed or timed out, falling back to polling:",x)}return b||(b=await j()),b?(h(b),b):(s(x=>({sessions:x.sessions.filter(y=>y.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(x.webUICreatedSessions).filter(y=>y!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){return s(b=>({sessions:b.sessions.filter(x=>x.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(b.webUICreatedSessions).filter(x=>x!==u)),isLoading:!1,error:g instanceof Error?g.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{s({isLoading:!0,error:null});const o=r().worktreeMetadata.get(t),a=Kr(r().sessions,t),i=o?.path??a;let l=null;try{o&&n?.archiveWorktree&&(await Hl(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),l=o);const d=()=>De.deleteSession(t);if(!(i?await De.withDirectory(i,d):await d()))return s(p=>{const h={isLoading:!1,error:"Failed to delete session"};if(l){const j=new Map(p.worktreeMetadata);j.delete(t),h.worktreeMetadata=j}return h}),!1;let m=null;s(p=>{const h=p.sessions.filter(x=>x.id!==t);m=p.currentSessionId===t?null:p.currentSessionId;const j=new Map(p.worktreeMetadata);j.delete(t);const g=n?.archiveWorktree&&o?p.availableWorktrees.filter(x=>bt(x.path)!==bt(o.path)):p.availableWorktrees,b=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const x=bt(o.projectDirectory)??o.projectDirectory,y=b.get(x)??[];b.set(x,y.filter(w=>bt(w.path)!==bt(o.path)))}return{sessions:h,sessionsByDirectory:Es(h),currentSessionId:m,isLoading:!1,worktreeMetadata:j,availableWorktrees:g,availableWorktreesByProject:b}});const f=i??De.getDirectory()??null;return sr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return s(l?m=>{const f=new Map(m.worktreeMetadata);return f.delete(t),{worktreeMetadata:f,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(t,n)=>{const o=Array.from(new Set(t.filter(b=>typeof b=="string"&&b.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||s({isLoading:!0,error:null});const i=[],l=[],d=new Set,u=[],m=new Set;for(const b of o)try{const x=r().worktreeMetadata.get(b),y=Kr(r().sessions,b),w=x?.path??y;x&&n?.archiveWorktree&&!m.has(x.path)&&(await Hl(x,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(b),u.push({path:x.path,projectDirectory:x.projectDirectory}),m.add(x.path));const S=()=>De.deleteSession(b);(w?await De.withDirectory(w,S):await S())?(i.push(b),x?.path&&!u.some(N=>N.path===x.path)&&u.push({path:x.path,projectDirectory:x.projectDirectory})):l.push(b)}catch{l.push(b)}const f=ft.getState();u.forEach(({path:b,projectDirectory:x})=>{f.currentDirectory===b&&f.setDirectory(x,{showOverlay:!1})});const p=new Set(i),h=l.length>0?l.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let j=null;s(b=>{const x=b.sessions.filter(N=>!p.has(N.id));b.currentSessionId&&p.has(b.currentSessionId)?j=null:j=b.currentSessionId;const y=new Map(b.worktreeMetadata);for(const N of p)y.delete(N);for(const N of d)y.delete(N);const w=new Set(u.map(N=>bt(N.path)).filter(N=>!!N)),S=w.size>0?b.availableWorktrees.filter(N=>!w.has(bt(N.path)??N.path)):b.availableWorktrees,v=new Map(b.availableWorktreesByProject);return u.length>0&&u.reduce((D,M)=>{const C=bt(M.projectDirectory)??M.projectDirectory,k=bt(M.path)??M.path;return D.has(C)||D.set(C,new Set),D.get(C)?.add(k),D},new Map).forEach((D,M)=>{const k=(v.get(M)??[]).filter(A=>!D.has(bt(A.path)??A.path));v.set(M,k)}),{sessions:x,sessionsByDirectory:Es(x),currentSessionId:j,...a?{}:{isLoading:!1,error:h},worktreeMetadata:y,availableWorktrees:S,availableWorktreesByProject:v}});const g=De.getDirectory()??null;return sr(g,j),{deletedIds:i,failedIds:l}},updateSessionTitle:async(t,n)=>{try{const o=Kr(r().sessions,t),a=r().worktreeMetadata.get(t),i=()=>De.updateSession(t,n),l=a?.path??o,d=l?await De.withDirectory(l,i):await i();s(u=>{const m=u.sessions.map(f=>f.id===t?d:f);return{sessions:m,sessionsByDirectory:Es(m)}})}catch(o){s({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=Kr(r().sessions,t),o=De.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,l=async()=>{const u=n??De.getDirectory();return o.session.share({sessionID:t,...u?{directory:u}:{}})},d=i?await De.withDirectory(i,l):await l();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:Es(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const n=Kr(r().sessions,t),o=De.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,l=async()=>{const u=n??De.getDirectory();return o.session.unshare({sessionID:t,...u?{directory:u}:{}})},d=i?await De.withDirectory(i,l):await l();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:Es(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:t=>{s({currentSessionId:t,error:null});const n=De.getDirectory()??null;sr(n,t)},clearError:()=>{s({error:null})},getSessionsByDirectory:t=>{const n=bt(t)??t,{sessionsByDirectory:o,sessions:a}=r(),i=o.get(n);return i||a.filter(l=>(bt(l.directory??null)??n)===n)},getDirectoryForSession:t=>{if(!t)return null;const n=r().worktreeMetadata.get(t);if(n?.path)return bt(n.path)??n.path;const o=r().sessions.find(i=>i.id===t);return bt(o?.directory??null)},applySessionMetadata:(t,n)=>{!t||!n||s(o=>{const a=o.sessions.findIndex(h=>h.id===t);if(a===-1)return o;const i=o.sessions[a],l=n.time?{...i.time,...n.time}:i.time,d=n.summary===void 0?i.summary:n.summary||void 0,u=n.share===void 0?i.share:n.share||void 0,m={...i,...n,time:l,summary:d,share:u},f=m.title!==i.title||m.parentID!==i.parentID||m.directory!==i.directory||m.version!==i.version||m.projectID!==i.projectID||JSON.stringify(m.time)!==JSON.stringify(i.time)||JSON.stringify(m.summary??null)!==JSON.stringify(i.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(i.share??null),p=[...o.sessions];return p[a]=f?m:i,{sessions:p,sessionsByDirectory:Es(p)}})},isOpenChamberCreatedSession:t=>{const{webUICreatedSessions:n}=r();return n.has(t)},markSessionAsOpenChamberCreated:t=>{s(n=>{const o=new Set(n.webUICreatedSessions);return o.add(t),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:t=>{const{markSessionAsOpenChamberCreated:n}=r();n(t)},setWorktreeMetadata:(t,n)=>{t&&s(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(t,n):a.delete(t),{worktreeMetadata:a}})},getWorktreeMetadata:t=>{if(t)return r().worktreeMetadata.get(t)},setSessionDirectory:(t,n)=>{if(!t)return;const o=r().sessions,a=o.findIndex(u=>u.id===t);if(a===-1)return;const l=o[a].directory??null,d=n??void 0;l!==(d??null)&&(s(u=>{const m=[...u.sessions],f={...m[a]};return d!==void 0?f.directory=d:delete f.directory,m[a]=f,{sessions:m,sessionsByDirectory:Es(m)}}),l&&sr(l,null),n&&sr(n,t))},updateSession:t=>{s(n=>{const a=n.sessions.findIndex(l=>l.id===t.id)===-1?[t,...n.sessions]:n.sessions.map(l=>l.id===t.id?t:l),i=yr(a);return{sessions:i,sessionsByDirectory:Es(i)}})},removeSessionFromStore:t=>{t&&s(n=>{const o=n.sessions.find(u=>u.id===t),a=bt(o?.directory??null),i=n.sessions.filter(u=>u.id!==t);if(i.length===n.sessions.length)return n;const l=new Map(n.worktreeMetadata);l.delete(t);const d=n.currentSessionId===t?null:n.currentSessionId;return a&&sr(a,null),{sessions:i,sessionsByDirectory:Es(i),currentSessionId:d,worktreeMetadata:l}})}}),{name:"session-store",storage:Ds(()=>cs()),partialize:s=>({currentSessionId:s.currentSessionId,sessions:s.sessions,lastLoadedDirectory:s.lastLoadedDirectory,webUICreatedSessions:Array.from(s.webUICreatedSessions),worktreeMetadata:Array.from(s.worktreeMetadata.entries()),availableWorktrees:s.availableWorktrees,availableWorktreesByProject:Array.from(s.availableWorktreesByProject.entries())}),merge:(s,r)=>{if(!(p=>typeof p=="object"&&p!==null)(s))return r;const n=Array.isArray(s.sessions)?s.sessions:r.sessions,o=typeof s.currentSessionId=="string"||s.currentSessionId===null?s.currentSessionId:r.currentSessionId,a=Array.isArray(s.webUICreatedSessions)?s.webUICreatedSessions:[],i=Array.isArray(s.worktreeMetadata)?s.worktreeMetadata:[],l=Array.isArray(s.availableWorktrees)?s.availableWorktrees:r.availableWorktrees,d=Array.isArray(s.availableWorktreesByProject)?s.availableWorktreesByProject:[],u=new Map(d),m=typeof s.lastLoadedDirectory=="string"?s.lastLoadedDirectory:r.lastLoadedDirectory??null,f=yr(n);return{...r,...s,sessions:f,sessionsByDirectory:Es(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:l,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),Au="This message comes from an AI assistant in another session. The user wants you to respond according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed. Always clearly state what you understand your task to be, and wait for the user's approval of your conclusions before taking any further actions.",ny="This message bellow comes from an AI agent in another session. I want you to act according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed; if it is a bug description, find the root cause and fix it. Proceed with actions right away based on your understanding of the task. Here is the content of the message: ",ja=s=>typeof s=="string"&&s.trim()===Au.trim(),Sa=(s,r)=>{const t=Date.now(),n=s.get(r),o=new Map(s);return o.set(r,{phase:"streaming",startedAt:n?.startedAt??t,lastUpdateAt:t}),o},Sn=(s,r)=>{const t=Array.from(r);if(!t.some(a=>s.has(a)))return s;const o=new Map(s);return t.forEach(a=>{o.delete(a)}),o},Vl=new Map,Eu=s=>{const r=Vl.get(s);r&&(clearTimeout(r),Vl.delete(s))},Mr=s=>{for(const r of s)Eu(r)},Wn=s=>{if(!s)return"";if(typeof s=="string")return s;if(Array.isArray(s))return s.map(r=>Wn(r)).join("");if(typeof s=="object"){if(typeof s.text=="string")return s.text;if(Array.isArray(s.content))return s.content.map(r=>Wn(r)).join("")}return""},Tn=s=>{if(!s)return"";const r=s;if(typeof r.text=="string")return r.text;if(Array.isArray(r.text))return r.text.map(n=>typeof n=="string"?n:Tn(n)).join("");const t=Wn(r.delta);return t||(typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||Wn(o.delta)||""}return""}).join(""):"")},kn=(s,r)=>{const t={...s};if(t.type=t.type||"text",t.type==="text"){const n=r&&typeof r.text=="string"?r.text:"",o=typeof t.text=="string"?t.text:"",a=Wn(s.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},Gl=10*1024*1024,oy=s=>{const r=(s||"").toLowerCase();switch(r.includes(".")&&r.split(".").pop()||""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";case"bmp":return"image/bmp";case"ico":return"image/x-icon";case"pdf":return"application/pdf";default:return"text/plain"}},ay=s=>{if(s.type&&s.type.trim().length>0)return s.type;const r=(s.name||"").toLowerCase(),t=r.includes(".")&&r.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying"]).has(r))return"text/plain";switch(t){case"md":case"markdown":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"yaml":case"yml":return"application/x-yaml";case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"sh":case"bash":case"zsh":return"text/plain";default:return"application/octet-stream"}},iy=s=>{const r=s.replace(/\s+/g,"");if(!r)return 0;const t=r.endsWith("==")?2:r.endsWith("=")?1:0;return Math.floor(r.length*3/4)-t},ly=s=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let n=0;n<s.length;n+=3){const o=s[n]??0,a=s[n+1],i=s[n+2],l=o<<16|(a??0)<<8|(i??0);t+=r[l>>18&63],t+=r[l>>12&63],t+=typeof a=="number"?r[l>>6&63]:"=",t+=typeof i=="number"?r[l&63]:"="}return t},Ys=Bt()(Qt(Ms((s,r)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=r();if(n.some(j=>j.filename===t.name&&j.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=Gl;if(t.size>a)throw new Error(`File "${t.name}" is too large. Maximum size is 10MB.`);const i=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],l=ay(t);!i.some(j=>l.startsWith(j)||l===j||l==="")&&l!==""&&console.warn(`File type "${l}" might not be supported`);const u=new FileReader,m=await new Promise((j,g)=>{u.onload=()=>j(u.result),u.onerror=g,u.readAsDataURL(t)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${l}`):m,p=j=>{const g=j.replace(/\\/g,"/").split("/");return g[g.length-1]||j},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:f,mimeType:l,filename:p(t.name),size:t.size,source:"local"};s(j=>({attachedFiles:[...j.attachedFiles,h]}))},addServerFile:async(t,n,o)=>{const{attachedFiles:a}=r();if(a.some(x=>x.serverPath===t&&x.source==="server")){console.log(`Server file "${n}" is already attached`);return}let l=o,d,u;if(!l)try{const x=De.getApiClient(),y=t.lastIndexOf("/"),w=y>0?t.substring(0,y):"/",S=y>0?t.substring(y+1):t,v=await x.file.read({path:S,directory:w});v.data&&"content"in v.data?(l=v.data.content,d=v.data.encoding??void 0,u=v.data.mimeType??void 0):l=""}catch(x){console.error("Failed to read server file:",x),l=`[File: ${n}]`}const m=u||oy(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return l||"";const y=new TextEncoder().encode(l||"");return ly(y)})(),h=d==="base64"?iy(p):new TextEncoder().encode(l||"").length;if(h>Gl)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const j=new File([],n,{type:f}),g=`data:${f};base64,${p}`,b={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:j,dataUrl:g,mimeType:f,filename:n,size:h,source:"server",serverPath:t};s(x=>({attachedFiles:[...x.attachedFiles,b]}))},removeAttachedFile:t=>{s(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{s({attachedFiles:[]})}}),{name:"file-store",storage:Ds(()=>cs()),partialize:s=>({attachedFiles:s.attachedFiles})}),{name:"file-store"})),cy=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),dy=s=>s?cy.has(s.toLowerCase()):!1,uy=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},my=s=>{if(s)try{const r=uy();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===s)}catch{}},fy=(s,r)=>{if(!s||s.length===0)return"ask";for(let t=s.length-1;t>=0;t-=1){const n=s[t];if(n.permission===r&&n.pattern==="*")return n.action}for(let t=s.length-1;t>=0;t-=1){const n=s[t];if(n.permission==="*"&&n.pattern==="*")return n.action}return"ask"},Mo=s=>{const r=my(s);return r?fy(r.permission,"edit"):"ask"},ql=s=>{if(!s||typeof s!="object")return 0;const r=s.input??0,t=s.output??0,n=s.reasoning??0,o=s.cache&&typeof s.cache=="object"?s.cache.read??0:0,a=s.cache&&typeof s.cache=="object"?s.cache.write??0:0;return r+t+n+o+a},ka=s=>{const r=s.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return ql(r);const t=s.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:ql(t.tokens)},Na=(s,r,t)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,i=Math.min(o?a:32e3,32e3),l=Math.min(i,n),d=n>0?Math.max(n-l,1):0,u=d>0?s/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:l}},Nn=["ask","allow","full"],vt=Bt()(Qt(Ms((s,r)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{s(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=r();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{s(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=r();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{s(i=>{const l=new Map(i.sessionAgentModelSelections);let d=l.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),l.set(t,d),{sessionAgentModelSelections:l}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(t);return a&&a.get(n)||null},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a}=r(),i=new Map,l=(f,p)=>{if("mode"in f&&f.mode&&typeof f.mode=="string"&&n.find(b=>b.name===f.mode))return f.mode;if(f.providerID&&f.modelID){const g=n.find(b=>b.model?.providerID===f.providerID&&b.model?.modelID===f.modelID);if(g)return g.name}const{currentAgentContext:h}=r(),j=h.get(t);if(j&&n.find(g=>g.name===j))return j;if(p>0&&f.providerID&&f.modelID){const b=(o.get(t)||[]).filter(x=>x.info.role==="assistant").sort((x,y)=>x.info.time.created-y.info.time.created);for(let x=p-1;x>=0;x--){const w=b[x].info;if(w.providerID===f.providerID&&w.modelID===f.modelID){if(w.mode&&typeof w.mode=="string"&&n.find(N=>N.name===w.mode))return w.mode;const S=n.find(v=>v.model?.providerID===w.providerID&&v.model?.modelID===w.modelID);if(S)return S.name}}}return f.providerID&&f.modelID&&n.find(b=>b.name==="build")?"build":null},d=o.get(t)||[],u=d.filter(f=>f.info.role==="assistant"||f.info.role==="user").sort((f,p)=>f.info.time.created-p.info.time.created),m=d.filter(f=>f.info.role==="assistant").sort((f,p)=>f.info.time.created-p.info.time.created);for(let f=0;f<u.length;f++){const p=u[f],{info:h}=p,j=h;if(j.providerID&&j.modelID){const g=l(j,m.indexOf(p));if(g&&n.find(b=>b.name===g)){const b={providerId:j.providerID,modelId:j.modelID,timestamp:h.time.created},x=i.get(g);(!x||b.timestamp>x.timestamp)&&i.set(g,b)}}}for(const[f,p]of i)a(t,f,p.providerId,p.modelId);return i},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=Na(0,n,o),l=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(l===0||u===0)return null;const f=(a.get(t)||[]).filter(w=>w.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],h=p.info.id,j=w=>{const S=()=>{s(v=>{const N=v.sessionContextUsage.get(t);if(N&&N.totalTokens===w.totalTokens&&N.percentage===w.percentage&&N.contextLimit===w.contextLimit&&(N.outputLimit??0)===(w.outputLimit??0)&&(N.normalizedOutput??0)===(w.normalizedOutput??0)&&N.thresholdLimit===w.thresholdLimit&&N.lastMessageId===w.lastMessageId)return v;const D=new Map(v.sessionContextUsage);return D.set(t,w),{sessionContextUsage:D}})};typeof queueMicrotask=="function"?queueMicrotask(S):typeof window<"u"?window.setTimeout(S,0):setTimeout(S,0)},g=r().sessionContextUsage.get(t);if(g&&g.lastMessageId===h){const w=g.normalizedOutput??g.outputLimit??0,S=g.contextLimit!==l||w!==d||g.thresholdLimit!==u;if(S&&g.totalTokens>0){const v=g.totalTokens/u*100,N={totalTokens:g.totalTokens,percentage:Math.min(v,100),contextLimit:l,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return j(N),N}if(!S&&g.totalTokens>0)return g}const b=ka(p);if(b===0)return g||null;const x=Na(b,n,o),y={totalTokens:b,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit,normalizedOutput:x.normalizedOutput,thresholdLimit:x.thresholdLimit,lastMessageId:h};return j(y),y},updateSessionContextUsage:(t,n,o,a)=>{const l=(a.get(t)||[]).filter(f=>f.info.role==="assistant");if(l.length===0)return;const d=l[l.length-1],u=ka(d);if(u===0)return;const m=Na(u,n,o);s(f=>{const p=new Map(f.sessionContextUsage);return p.set(t,{totalTokens:u,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit,normalizedOutput:m.normalizedOutput,thresholdLimit:m.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(t,n,o,a)=>{const l=r().sessionContextUsage.get(t);(!l||l.totalTokens===0)&&r().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let i=0;const l=()=>{i++;const u=(o.get(t)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&ka(u)>0){r().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(l,1e3)};setTimeout(l,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=r();return n.get(t)},getSessionAgentEditMode:(t,n,o=Mo(n))=>!t||!n?o:r().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=Mo(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||Nn.includes(o)&&s(l=>{const d=new Map(l.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===i?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=Mo(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=r().getSessionAgentEditMode(t,n,a),l=Nn.indexOf(i),d=Nn.indexOf(a),m=((l>=0?l:d>=0?d:0)+1)%Nn.length,f=Nn[m];r().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:Ds(()=>cs()),partialize:s=>({sessionModelSelections:Array.from(s.sessionModelSelections.entries()),sessionAgentSelections:Array.from(s.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(s.sessionAgentModelSelections.entries()).map(([r,t])=>[r,Array.from(t.entries())]),currentAgentContext:Array.from(s.currentAgentContext.entries()),sessionContextUsage:Array.from(s.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(s.sessionAgentEditModes.entries()).map(([r,t])=>[r,Array.from(t.entries())])}),merge:(s,r)=>{const t=new Map;s?.sessionAgentModelSelections&&s.sessionAgentModelSelections.forEach(([o,a])=>{t.set(o,new Map(a))});const n=new Map;return s?.sessionAgentEditModes&&s.sessionAgentEditModes.forEach(([o,a])=>{n.set(o,new Map(a))}),{...r,...s,sessionModelSelections:new Map(s?.sessionModelSelections||[]),sessionAgentSelections:new Map(s?.sessionAgentSelections||[]),sessionAgentModelSelections:t,currentAgentContext:new Map(s?.currentAgentContext||[]),sessionContextUsage:new Map(s?.sessionContextUsage||[]),sessionAgentEditModes:n,hasHydrated:!0}}}),{name:"context-store"})),Kl=(s,r)=>{const t=new Map(s);return t.delete(r),t};let Ca=[],Ma=null;const py=50,hy=3e4,Dr=new Map,so=new Map,Yr=new Map,gy=10,_o=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<gy?null:n},ro=(s,r)=>{const t=_o(s),n=_o(r);return!t||!n||t.length!==n.length?!0:t>n},yy=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},tn=s=>!Array.isArray(s)||s.length===0?0:s.reduce((r,t)=>{if(!t||t.type!=="text")return r;const n=t.text??t.content;return typeof n=="string"?r+n.length:r},0),Bo=s=>s?.finish==="stop",Yl=s=>{if(s){if(typeof s.id=="string"&&s.id.length>0)return s.id;if(s.type){const r=s.reason,t=s.callID;return`${s.type}-${r??""}-${t??""}`}}},Xl=new Set,zo=(s=[],r=[])=>{if(!r.length)return[...s];const t=[...s],n=new Set(s.map(Yl).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=Yl(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},xy=(s,r)=>{const t=Array.isArray(s.parts)?s.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=tn(t),a=tn(n),i=Bo(s.info),l=Bo(r.info);let d=n;return i&&o>=a?d=zo(t,n):l&&a>=o?d=zo(n,t):o>=a&&(d=t),{...r,info:{...s.info,...r.info},parts:d}},Da=s=>{const r=[],t=new Map;for(const n of s){const o=typeof n?.info?.id=="string"?n.info.id:null;if(!o){r.push(n);continue}const a=t.get(o);if(a===void 0){t.set(o,r.length),r.push(n);continue}r[a]=xy(r[a],n)}return r},by=(s,r)=>{let t=r,n=r?_o(r):null;for(const o of s){const a=o?.info?.id,i=_o(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},Us=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return t?o.set(r,t):o.delete(r),o},Xr=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return o.set(r,t),o},no=(s,r)=>{const t=new Map(s);let n=!1;for(const o of r)t.delete(o)&&(n=!0);return n?t:s},wy=(s,r)=>{const t=new Set,n=s.streamingMessageIds.get(r);return n&&t.add(n),s.messageStreamStates.forEach((o,a)=>{s.messageSessionIndex.get(a)===r&&t.add(a)}),t},Ql=(s,r,t)=>s.streamingMessageIds.get(r)===t?!0:s.messageSessionIndex.get(t)===r&&s.messageStreamStates.has(t),vy=async s=>{if(s)try{return rt.getState().getDirectoryForSession(s)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},Jl=s=>{if(!s)return null;try{return rt.getState().sessions.find(n=>n.id===s)?.revert?.messageID??null}catch{return null}},Zl=(s,r)=>{if(!r)return s;const t=s.findIndex(n=>n.info.id===r);return t===-1?s:s.slice(0,t)},Aa=async(s,r)=>{const t=await vy(s);return t?De.withDirectory(t,r):r()},yt=Bt()(Qt(Ms((s,r)=>({messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,messageSessionIndex:new Map,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,pendingAssistantParts:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,pendingAssistantHeaderSessions:new Set,pendingUserMessageMetaBySession:new Map,loadMessages:async(t,n=ls.VIEWPORT_MESSAGES)=>{const o=await Aa(t,()=>De.getSessionMessages(t)),a=Jl(t),i=Zl(o,a),l=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,u=(l?i.filter(m=>{const f=m?.info?.id;return f?ro(f,l):!0}):i).slice(-n);s(m=>{const f=new Map(m.messages),p=m.messages.get(t)||[],h=new Map(p.filter(C=>typeof C.info?.id=="string").map(C=>[C.info.id,C])),j=u.map(C=>{const k={...C.info,clientRole:C.info?.clientRole??C.info.role,userMessageMarker:C.info.role==="user"?!0:C.info?.userMessageMarker},A=(Array.isArray(C.parts)?C.parts:[]).map(L=>{if(L?.type==="text"){const U=L.text??L.content??"";if(ja(U))return{...L,synthetic:!0}}return L}),P=k?.id?h.get(k.id):void 0;if(P&&P.info.role==="assistant"){const L=Array.isArray(P.parts)?P.parts:[],U=tn(L),z=tn(A);if(Bo(P.info)&&U>z){const V=zo(L,A);return{...C,info:k,parts:V}}}return{...C,info:k,parts:A}}),g=Da(j),b=new Set(p.map(C=>C.info.id)),x=new Set(g.map(C=>C.info.id)),y=[];b.forEach(C=>{x.has(C)||y.push(C)}),f.set(t,g);const w=new Map(m.sessionMemoryState),S=m.sessionMemoryState.get(t);w.set(t,{...S,viewportAnchor:g.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>u.length,trimmedHeadMaxId:S?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const v={messages:f,sessionMemoryState:w};Mr(y);const N=Sn(m.messageStreamStates,y);if(N!==m.messageStreamStates&&(v.messageStreamStates=N),y.length>0){const C=m.streamingMessageIds.get(t);C&&y.includes(C)&&(v.streamingMessageIds=Us(v.streamingMessageIds??m.streamingMessageIds,t,null))}if(y.length>0){const C=no(v.messageSessionIndex??m.messageSessionIndex,y);C!==(v.messageSessionIndex??m.messageSessionIndex)&&(v.messageSessionIndex=C)}if(y.length>0){const C=new Map(m.pendingAssistantParts);let k=!1;y.forEach(A=>{C.delete(A)&&(k=!0)}),k&&(v.pendingAssistantParts=C)}const D=v.messageSessionIndex??m.messageSessionIndex;let M=D;return g.forEach(C=>{const k=C?.info?.id;typeof k=="string"&&k.length>0&&(M=Xr(M,k,t))}),M!==D&&(v.messageSessionIndex=M),v})},sendMessage:async(t,n,o,a,i,l,d,u)=>{if(!i)throw new Error("No session selected");const m=i;r().sessionAbortFlags.has(m)&&s(f=>{const p=new Map(f.sessionAbortFlags);return p.delete(m),{sessionAbortFlags:p}}),await Aa(m,async()=>{try{let f=t;if(t.startsWith("/")){const h=t.indexOf(" "),j=h===-1?t.substring(1):t.substring(1,h),g=h===-1?"":t.substring(h+1).trim(),b=De.getApiClient(),x=De.getDirectory();if(j==="init"){const y=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await b.session.init({sessionID:m,...x?{directory:x}:{},messageID:y,providerID:n,modelID:o});return}if(j==="summarize"){await b.session.summarize({sessionID:m,...x?{directory:x}:{},providerID:n,modelID:o});return}try{const y=await De.getCommandDetails(j);y?.template?f=y.template.replace(/\$ARGUMENTS/g,g):f=t}catch(y){console.error("Command template resolution failed:",y),f=t}}s({lastUsedProvider:{providerID:n,modelID:o}}),s(h=>{const j=h.sessionMemoryState.get(m)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},g=Yr.get(m);g&&(clearTimeout(g),Yr.delete(m));const b=new Map(h.sessionMemoryState);return b.set(m,{...j,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:b}});try{const h=new AbortController;s(b=>{const x=new Map(b.abortControllers);return x.set(m,h),{abortControllers:x}});const j=(l??[]).map(b=>({type:"file",mime:b.mimeType,filename:b.filename,url:b.dataUrl}));s(b=>{const x=new Set(b.pendingAssistantHeaderSessions);x.add(m);const y=new Map(b.pendingUserMessageMetaBySession);return y.set(m,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o}),{pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:y}});const g=u?.map(b=>({text:b.text,files:b.attachments?.map(x=>({type:"file",mime:x.mimeType,filename:x.filename,url:x.dataUrl}))}));if(await De.sendMessage({id:m,providerID:n,modelID:o,text:f,agent:a,files:j.length>0?j:void 0,additionalParts:g,agentMentions:d?[{name:d}]:void 0}),j.length>0)try{Ys.getState().clearAttachedFiles()}catch(b){console.error("Failed to clear attached files after send",b)}s(b=>{const x=new Map(b.abortControllers);return x.delete(m),{abortControllers:x}})}catch(h){let j="Network error while sending message. The message may still be processing.";if(h.name==="AbortError")j="Request timed out. The message may still be processing.";else if(h.message?.includes("504")||h.message?.includes("Gateway")){j="Gateway timeout - your message is being processed. Please wait for response.",s(g=>{const b=new Map(g.abortControllers);return b.delete(m),{abortControllers:b}});return}else h.message&&(j=h.message);throw s(g=>{const b=new Map(g.abortControllers);b.delete(m);const x=new Set(g.pendingAssistantHeaderSessions);x.delete(m);const y=new Map(g.pendingUserMessageMetaBySession);return y.delete(m),{abortControllers:b,pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:y}}),new Error(j)}}catch(f){let p="Network error while sending message. The message may still be processing.";throw f.name==="AbortError"?p="Request timed out. The message may still be processing.":f.response?.status===401?p="Session not found or unauthorized. Please refresh the page.":f.response?.status===502?p="OpenCode is restarting. Please wait a moment and try again.":f.message?.includes("504")||f.message?.includes("Gateway")?p="Gateway timeout - your message is being processed. Please wait for response.":f.message&&(p=f.message),s(h=>{const j=new Map(h.abortControllers);j.delete(m);const g=new Set(h.pendingAssistantHeaderSessions);g.delete(m);const b=new Map(h.pendingUserMessageMetaBySession);return b.delete(m),{abortControllers:j,pendingAssistantHeaderSessions:g,pendingUserMessageMetaBySession:b}}),new Error(p)}})},abortCurrentOperation:async t=>{if(!t)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const l=wy(n,t);if(l.size===0){const u=t?a.get(t)??[]:[];let m=null;for(let f=u.length-1;f>=0;f-=1){const p=u[f];if(!p||p.info.role!=="assistant")continue;if(m||(m=p.info.id),(p.parts??[]).some(j=>j.type==="reasoning"||j.type==="tool"||j.type==="step-start")){l.add(p.info.id);break}}l.size===0&&m&&l.add(m)}for(const u of l){const m=Dr.get(u);m&&(clearTimeout(m),Dr.delete(u),so.delete(u))}l.size>0&&Mr(l);const d=Date.now();s(u=>{const m=Sn(u.messageStreamStates,l),f=u.messages.get(t)??[];let p=!1,h=u.messages;if(f.length>0&&l.size>0){const x=f.map(y=>{if(!l.has(y.info.id)&&l.size>0)return y;const w=(y.parts??[]).map(S=>{if(S.type==="reasoning"){const v=S,N={...v.time??{}};return typeof N.end!="number"&&(N.end=d),{...v,time:N}}if(S.type==="tool"){const v=S,N={...v.state??{}};return(N.status==="running"||N.status==="pending")&&(N.status="aborted"),{...v,state:N}}return S.type==="step-start"?{...S,type:"step-finish",aborted:!0}:S});return p=!0,{...y,info:{...y.info,abortedAt:d,streaming:!1,status:"aborted"},parts:w}});p&&(h=new Map(u.messages),h.set(t,x))}const j=u.sessionMemoryState.get(t);let g=u.sessionMemoryState;if(j){const x=new Map(u.sessionMemoryState);x.set(t,{...j,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),g=x}const b=new Map(u.sessionAbortFlags);return b.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:g,sessionAbortFlags:b,abortControllers:(()=>{const x=new Map(u.abortControllers);return x.delete(t),x})(),streamingMessageIds:Us(u.streamingMessageIds,t,null),...p?{messages:h}:{}}}),De.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const l=r();if(Xl.has(n))return;const d=l.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!ro(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=l.messages.get(t)||[],m=u.find(h=>h.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",p=r().sessionMemoryState.get(t);if(p?.streamStartTime&&Date.now()-p.streamStartTime>ls.ZOMBIE_TIMEOUT){p.isZombie||s(j=>{const g=new Map(j.sessionMemoryState);return g.set(t,{...p,isZombie:!0}),{sessionMemoryState:g}}),setTimeout(()=>{r().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}s(h=>{const g=[...h.messages.get(t)||[]],b={},x=Xr(h.messageSessionIndex,n,t);x!==h.messageSessionIndex&&(b.messageSessionIndex=x);const y=C=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(t)))return C;const A=new Map(h.sessionAbortFlags);return A.delete(t),{...C,sessionAbortFlags:A}},w=C=>{const k=C||"",A=so.get(n);if(k&&A===k){const U=r();if(Ql(U,t,n)){const z=Dr.get(n);z&&(clearTimeout(z),Dr.delete(n)),setTimeout(()=>{const H=r();typeof H.forceCompleteMessage=="function"&&H.forceCompleteMessage(t,n,"timeout"),H.completeStreamingMessage(t,n)},100)}}so.set(n,k);const P=Dr.get(n);P&&clearTimeout(P);const L=setTimeout(()=>{const U=r();typeof U.forceCompleteMessage=="function"&&U.forceCompleteMessage(t,n,"timeout"),Ql(U,t,n)&&U.completeStreamingMessage(t,n),Dr.delete(n),so.delete(n)},8e3);Dr.set(n,L)},S=t!==i,v=h.sessionMemoryState.get(t);if(S&&v?.isStreaming){g.length>=ls.BACKGROUND_STREAMING_BUFFER&&g.shift();const C=new Map(h.sessionMemoryState);C.set(t,{...v,backgroundMessageCount:(v.backgroundMessageCount||0)+1}),h.sessionMemoryState=C}if(f==="assistant"){const C=h.sessionMemoryState.get(t);if(C){const k=Date.now(),A=new Map(h.sessionMemoryState);A.set(t,{...C,isStreaming:!0,streamStartTime:C.streamStartTime??k,lastAccessedAt:k,isZombie:!1}),h.sessionMemoryState=A}}const N=Tn(o);if(ja(N)&&(o.synthetic=!0),yy()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:N.length,snapshotParts:u.length})}catch{}const D=b.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const C=Us(D,t,n);C!==D&&(b.streamingMessageIds=C,window.__messageTracker?.(n,"streamingId_set_latest"))}const M=g.findIndex(C=>C.info.id===n);if(M!==-1&&f==="user"){const C=g[M],k=C.parts.findIndex(z=>z.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const A=kn(o,k!==-1?C.parts[k]:void 0);window.__messageTracker?.(n,`user_part_type:${A.type||"unknown"}`);const P={...C};k!==-1?P.parts=P.parts.map((z,H)=>H===k?A:z):P.parts=[...P.parts,A];const L=[...g];L[M]=P;const U=new Map(h.messages);return U.set(t,L),y({messages:U})}if(f==="assistant"&&M!==-1){const C=g[M],k=C.parts.findIndex(H=>H.id===o.id),A=kn(o,k!==-1?C.parts[k]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const P={...C};k!==-1?P.parts=P.parts.map((H,V)=>V===k?A:H):P.parts=[...P.parts,A];const L=[...g];L[M]=P;const U=new Map(h.messages);U.set(t,L),b.messageStreamStates=Sa(h.messageStreamStates,n);const z=Us(b.streamingMessageIds??h.streamingMessageIds,t,n);return z!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=z,window.__messageTracker?.(n,"streamingId_set")),A.type==="text"?w(A.text||""):w(""),y({messages:U,...b})}if(M===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const oe=kn(o);window.__messageTracker?.(n,`new_user_part_type:${oe.type||"unknown"}`);const ye=h.pendingUserMessageMetaBySession.get(t),I=vt.getState(),F=ye?.mode??I.getSessionAgentSelection(t)??I.getCurrentAgent(t),W=typeof F=="string"&&F.trim().length>0?F.trim():void 0,O=ye?.providerID??(h.lastUsedProvider?.providerID||void 0),_=ye?.modelID??(h.lastUsedProvider?.modelID||void 0);ye&&(b.pendingUserMessageMetaBySession=Kl(h.pendingUserMessageMetaBySession,t));const ee={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,...W?{mode:W}:{},...O?{providerID:O}:{},..._?{modelID:_}:{},time:{created:Date.now()}},parts:[oe]},ue=[...g,ee];ue.sort((pe,He)=>{const Y=pe.info?.time?.created||0,le=He.info?.time?.created||0;return Y-le});const me=new Map(h.messages);return me.set(t,ue),y({messages:me})}if(o?.type==="text"){const oe=Tn(o).trim();if(oe.length>0){const ye=[...g].reverse().find(I=>I.info.role==="user");if(ye){const I=ye.parts.map(F=>Tn(F)).join("").trim();if(I.length>0&&I===oe)return Xl.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const C=kn(o);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`),C.type==="text"?w(C.text||""):w("");const k=h.pendingAssistantParts.get(n),A=k?[...k.parts]:[],P=A.findIndex(oe=>oe.id===C.id);P!==-1?A[P]=C:A.push(C);const L=new Map(h.pendingAssistantParts);L.set(n,{sessionId:t,parts:A});const U=h.lastUsedProvider?.providerID||"",z=h.lastUsedProvider?.modelID||"",H=Date.now(),V=De.getDirectory()??"/",J=vt.getState(),T=J.getSessionAgentSelection(t)??J.getCurrentAgent(t),Z=typeof T=="string"&&T.trim().length>0?T.trim():void 0,E=h.pendingAssistantHeaderSessions.has(t);if(E){const oe=new Set(h.pendingAssistantHeaderSessions);oe.delete(t),b.pendingAssistantHeaderSessions=oe}const X={info:f==="user"?{id:n,sessionID:t,role:"user",time:{created:H},agent:Z||"default",model:{providerID:U,modelID:z},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:t,role:"assistant",time:{created:H},parentID:n,modelID:z,providerID:U,mode:Z||"default",...E?{openchamberHeaderAnchor:!0}:{},path:{cwd:V,root:V},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:A},re=[...g,X],q=new Map(h.messages);if(q.set(t,re),f==="assistant"){b.messageStreamStates=Sa(h.messageStreamStates,n);const oe=Us(b.streamingMessageIds??h.streamingMessageIds,t,n);oe!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=oe,window.__messageTracker?.(n,"streamingId_set"))}return y({messages:q,pendingAssistantParts:L,...b})}else{const C=g[M],k=C.parts.findIndex(z=>z.id===o.id),A=kn(o,k!==-1?C.parts[k]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const P={...C};k!==-1?P.parts=P.parts.map((z,H)=>H===k?A:z):P.parts=[...P.parts,A];const L=[...g];L[M]=P;const U=new Map(h.messages);if(U.set(t,L),P.info.role==="assistant"){b.messageStreamStates=Sa(h.messageStreamStates,n);const z=Us(b.streamingMessageIds??h.streamingMessageIds,t,n);z!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=z,window.__messageTracker?.(n,"streamingId_set"))}return A.type==="text"?w(A.text||""):w(""),y({messages:U,...b})}})},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){r()._addStreamingPartImmediate(t,n,o,a,i);return}Ca.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),Ma||(Ma=setTimeout(()=>{const l=[...Ca];Ca=[],Ma=null;const d=r();for(const u of l)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},py))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[l,d]of i.messages.entries())if(d.some(u=>u.info.id===n))return l;return null};s(i=>{const l=a(i);if(!l)return i;const d=i.messages.get(l)??[],u=d.findIndex(v=>v.info.id===n);if(u===-1)return i;const m=d[u];if(!m)return i;const f=Date.now(),p=m.info,h=typeof p?.time?.completed=="number"&&p.time.completed>0;let j=!1;const g={...p};h||(g.time={...p.time??{},completed:f},j=!0),g.status!=="completed"&&(g.status="completed",j=!0),g.streaming&&(g.streaming=!1,j=!0);let b=!1;const x=m.parts.map(v=>{if(!v)return v;if(v.type==="tool"){const N=v.state;if(!N)return v;const D=N.status,M=D==="running"||D==="pending"||D==="started",C=!N.time||typeof N.time?.end!="number";if(M||C){const k={...N};return M&&(k.status="completed"),C&&(k.time={...N.time??{},end:f}),b=!0,{...v,state:k}}return v}if(v.type==="reasoning"){const N=v.time;return!N||typeof N.end!="number"?(b=!0,{...v,time:{...N??{},end:f}}):v}if(v.type==="text"){const N=v.time;return N&&typeof N.end!="number"?(b=!0,{...v,time:{...N,end:f}}):v}return v});if(!j&&!b)return i;window.__messageTracker?.(n,`force_complete:${o}`);const y={...m,info:g,parts:b?x:m.parts},w=[...d];w[u]=y;const S=new Map(i.messages);return S.set(l,w),{messages:S}})},markMessageStreamSettled:t=>{s(n=>{Eu(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,i=!1;return n.messages.forEach((d,u)=>{if(i)return;const m=d.findIndex(g=>g.info.id===t);if(m===-1)return;const f=d[m];if(f.info?.animationSettled)return;const p={...f,info:{...f.info,animationSettled:!0}},h=[...d];h[m]=p;const j=new Map(n.messages);j.set(u,h),a=j,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),Mr([t])},updateMessageInfo:(t,n,o)=>{s(l=>{const d=l.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!ro(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),l;const m=[...l.messages.get(t)??[]],f=m.findIndex(M=>M.info.id===n),p=l.pendingAssistantParts.get(n),h=(M=[],C=[])=>{if(!C.length)return M;const k=[...M];return C.forEach(A=>{const P=k.findIndex(L=>L.id===A.id);P===-1?k.push(A):k[P]=A}),k},j=M=>{if(!M)return M;const C=M.clientRole??M.role,k=C==="user"?!0:M.userMessageMarker;return{...M,clientRole:C,...k?{userMessageMarker:!0}:{}}};if(f===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:t,messageId:n,messageInfo:o,existingCount:m.length}),m.length>0){const V=m[0]?.info,J=typeof V?.time?.created=="number"?V.time.created:null,T=typeof V?.id=="string"?V.id:null,Z=o,E=typeof Z?.time?.created=="number"?Z.time.created:null,B=typeof Z?.id=="string"?Z.id:n;let X=!1;if(E!==null&&J!==null&&(X=E<J),!X&&B&&T&&(X=B.localeCompare(T)<0),X)return window.__messageTracker?.(n,"skipped_evicted_message_update"),l}const M=j(o);if(M&&M.role==="user"){const H=p?.parts??[],V=l.pendingUserMessageMetaBySession.get(t),J={info:{...M,userMessageMarker:!0,clientRole:"user",...V?.mode?{mode:V.mode}:{},...V?.providerID?{providerID:V.providerID}:{},...V?.modelID?{modelID:V.modelID}:{}},parts:H.length>0?[...H]:[]},T=new Map(l.messages),Z=[...m,J];Z.sort((X,re)=>{const q=X.info?.time?.created||0,oe=re.info?.time?.created||0;return q-oe}),T.set(t,Z);const E={messages:T,...V?{pendingUserMessageMetaBySession:Kl(l.pendingUserMessageMetaBySession,t)}:{}},B=Xr(E.messageSessionIndex??l.messageSessionIndex,n,t);if(B!==(E.messageSessionIndex??l.messageSessionIndex)&&(E.messageSessionIndex=B),p){const X=new Map(l.pendingAssistantParts);X.delete(n),E.pendingAssistantParts=X}return E}if(!M||M.role!=="assistant")return l;const C=p?.parts??[],k=l.pendingAssistantHeaderSessions.has(t),A={info:{...M,animationSettled:M?.animationSettled??!1,...k?{openchamberHeaderAnchor:!0}:{}},parts:C.length>0?[...C]:[]},P=new Map(l.messages),L=[...m,A];P.set(t,L);const U={messages:P,...k?{pendingAssistantHeaderSessions:(()=>{const H=new Set(l.pendingAssistantHeaderSessions);return H.delete(t),H})()}:{}},z=Xr(U.messageSessionIndex??l.messageSessionIndex,n,t);if(z!==(U.messageSessionIndex??l.messageSessionIndex)&&(U.messageSessionIndex=z),p){const H=new Map(l.pendingAssistantParts);H.delete(n),U.pendingAssistantParts=H}return U}const g=m[f],b=g.info;if(b.userMessageMarker===!0||b.clientRole==="user"||b.role==="user"){const M={...g.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:b.providerID||void 0,modelID:b.modelID||void 0},C=l.pendingUserMessageMetaBySession.get(t);C&&!M.mode&&C.mode&&(M.mode=C.mode);const k={...g,info:M},A=new Map(l.messages),P=[...m];if(P[f]=k,A.set(t,P),C){const L=new Map(l.pendingUserMessageMetaBySession);return L.delete(t),{messages:A,pendingUserMessageMetaBySession:L}}return{messages:A}}const y={...g.info,...o};o.role&&o.role!==g.info.role&&(y.role=g.info.role),y.clientRole=y.clientRole??g.info.clientRole??g.info.role,y.clientRole==="user"&&(y.userMessageMarker=!0);const w=p?.parts?h(g.parts,p.parts):g.parts,S={...g,info:y,parts:w},v=new Map(l.messages),N=[...m];N[f]=S,v.set(t,N);const D={messages:v};if(p){const M=new Map(l.pendingAssistantParts);M.delete(n),D.pendingAssistantParts=M}return D});const a=o?.finish,i=o?.role;typeof a=="string"&&i!=="user"&&setTimeout(()=>{r().completeStreamingMessage(t,n)},0)},completeStreamingMessage:(t,n)=>{const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(t)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(t,n,"cooldown");const a=o.streamingMessageIds.get(t)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const i={};if(a&&(i.streamingMessageIds=Us(o.streamingMessageIds,t,null),i.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(t),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),i.messageStreamStates=d}Object.keys(i).length>0&&s(i),o.pendingAssistantParts.has(n)&&s(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),Mr([n]);let l=!1;if(s(d=>{const u=d.sessionMemoryState.get(t);if(!u||!u.isStreaming)return d;const m=new Map(d.sessionMemoryState),f=Date.now(),p={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:f,streamingCooldownUntil:f+2e3};return m.set(t,p),l=!0,{sessionMemoryState:m}}),l){const d=Yr.get(t);d&&(clearTimeout(d),Yr.delete(t));const u=setTimeout(()=>{s(m=>{const f=m.sessionMemoryState.get(t);if(!f||f.isStreaming)return m;const p=new Map(m.sessionMemoryState),{streamingCooldownUntil:h,...j}=f;return p.set(t,j),{sessionMemoryState:p}}),Yr.delete(t)},2e3);Yr.set(t,u)}},syncMessages:(t,n)=>{const o=Jl(t),a=Zl(n,o),i=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,l=i?a.filter(d=>{const u=d?.info?.id;return u?ro(u,i):!0}):a;s(d=>{const u=new Map(d.messages),m=d.messages.get(t)||[],f=new Map(m.filter(v=>typeof v.info?.id=="string").map(v=>[v.info.id,v])),p=l.map(v=>{const N={...v.info,clientRole:v.info?.clientRole??v.info.role,userMessageMarker:v.info.role==="user"?!0:v.info?.userMessageMarker,animationSettled:v.info.role==="assistant"?v.info?.animationSettled??!0:v.info?.animationSettled},D=(Array.isArray(v.parts)?v.parts:[]).map(k=>{if(k?.type==="text"){const A=k.text??k.content??"";if(ja(A))return{...k,synthetic:!0}}return k}),M=typeof N?.id=="string"?N.id:void 0,C=M?f.get(M):void 0;if(C&&C.info.role==="assistant"){const k=Array.isArray(C.parts)?C.parts:[],A=tn(k),P=tn(D);if(Bo(C.info)&&A>P){const U=zo(k,D);return{...v,info:N,parts:U}}}return{...v,info:N,parts:D}}),h=Da(p),j=new Set(m.map(v=>v.info.id)),g=new Set(h.map(v=>v.info.id)),b=[];j.forEach(v=>{g.has(v)||b.push(v)}),u.set(t,h);const x={messages:u,isSyncing:!0};Mr(b);const y=Sn(d.messageStreamStates,b);if(y!==d.messageStreamStates&&(x.messageStreamStates=y),b.length>0){const v=d.streamingMessageIds.get(t);v&&b.includes(v)&&(x.streamingMessageIds=Us(x.streamingMessageIds??d.streamingMessageIds,t,null))}if(b.length>0){const v=no(x.messageSessionIndex??d.messageSessionIndex,b);v!==(x.messageSessionIndex??d.messageSessionIndex)&&(x.messageSessionIndex=v)}if(b.length>0){const v=new Map(d.pendingAssistantParts);let N=!1;b.forEach(D=>{v.delete(D)&&(N=!0)}),N&&(x.pendingAssistantParts=v)}const w=x.messageSessionIndex??d.messageSessionIndex;let S=w;return h.forEach(v=>{const N=v?.info?.id;typeof N=="string"&&N.length>0&&(S=Xr(S,N,t))}),S!==w&&(x.messageSessionIndex=S),x}),setTimeout(()=>{s({isSyncing:!1})},100)},updateSessionCompaction:(t,n)=>{s(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(t)?(a.delete(t),{sessionCompactionUntil:a}):o;const i=n+hy;return a.get(t)===i?o:(a.set(t,i),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:t=>{t&&s(n=>{const o=n.sessionAbortFlags.get(t);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(t,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(t,n)=>{s(o=>{const a=o.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},i=new Map(o.sessionMemoryState);return i.set(t,{...a,viewportAnchor:n}),{sessionMemoryState:i}})},updateActiveTurnAnchor:(t,n,o)=>{s(a=>{const i=a.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},l=new Map(a.sessionMemoryState);return l.set(t,{...i,activeTurnAnchorId:n??void 0,activeTurnSpacerHeight:o}),{sessionMemoryState:l}})},getActiveTurnAnchor:t=>{const n=r().sessionMemoryState.get(t);return n?{anchorId:n.activeTurnAnchorId??null,spacerHeight:n.activeTurnSpacerHeight??0}:null},trimToViewportWindow:(t,n=ls.VIEWPORT_MESSAGES,o)=>{const a=r(),i=a.messages.get(t);if(!i||i.length<=n)return;const l=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(l.isStreaming&&t===o)return;const d=l.viewportAnchor||i.length-1;let u=Math.max(0,d-Math.floor(n/2));const m=Math.min(i.length,u+n);m===i.length&&m-u<n&&(u=Math.max(0,m-n));const f=i.slice(u,m),p=i.slice(0,u),h=new Set(f.map(g=>g.info.id)),j=i.filter(g=>!h.has(g.info.id)).map(g=>g.info.id);s(g=>{const b=new Map(g.messages);b.set(t,f);const x=new Map(g.sessionMemoryState),y={...l,viewportAnchor:d-u,trimmedHeadMaxId:by(p,l.trimmedHeadMaxId)};x.set(t,y);const w={messages:b,sessionMemoryState:x};Mr(j);const S=Sn(g.messageStreamStates,j);if(S!==g.messageStreamStates&&(w.messageStreamStates=S),j.length>0){const D=g.streamingMessageIds.get(t);D&&j.includes(D)&&(w.streamingMessageIds=Us(w.streamingMessageIds??g.streamingMessageIds,t,null))}if(j.length>0){const D=no(w.messageSessionIndex??g.messageSessionIndex,j);D!==(w.messageSessionIndex??g.messageSessionIndex)&&(w.messageSessionIndex=D)}const v=w.messageSessionIndex??g.messageSessionIndex;let N=v;return f.forEach(D=>{const M=D?.info?.id;typeof M=="string"&&M.length>0&&(N=Xr(N,M,t))}),N!==v&&(w.messageSessionIndex=N),w})},evictLeastRecentlyUsed:t=>{const n=r();if(n.messages.size<=ls.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const m=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,m])});const i=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(i.length===0)return;i.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const l=i[0][0];s(d=>{const m=(d.messages.get(l)||[]).map(S=>S.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(l),p.delete(l);const h={messages:f,sessionMemoryState:p},j=new Map(d.pendingAssistantParts);let g=!1;j.forEach((S,v)=>{S.sessionId===l&&(j.delete(v),g=!0)}),g&&(h.pendingAssistantParts=j);const b=new Map(d.sessionCompactionUntil);b.delete(l)&&(h.sessionCompactionUntil=b),Mr(m);const x=Sn(d.messageStreamStates,m);x!==d.messageStreamStates&&(h.messageStreamStates=x);const y=no(h.messageSessionIndex??d.messageSessionIndex,m);y!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=y);const w=Us(d.streamingMessageIds,l,null);if(w!==d.streamingMessageIds&&(h.streamingMessageIds=w),d.abortControllers.has(l)){const S=new Map(d.abortControllers);S.delete(l),h.abortControllers=S}return h})},loadMoreMessages:async(t,n="up")=>{const o=r(),a=o.messages.get(t),i=o.sessionMemoryState.get(t);if(!a||!i||i.totalAvailableMessages&&a.length>=i.totalAvailableMessages)return;const l=await Aa(t,()=>De.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=l.findIndex(m=>m.info.id===d.info.id);if(u>0){const m=Math.min(ls.VIEWPORT_MESSAGES,u),f=l.slice(u-m,u);s(p=>{const h=[...f,...a],j=Da(h),g=new Map(p.messages);g.set(t,j);const b=Math.max(0,j.length-a.length),x=new Map(p.sessionMemoryState);return x.set(t,{...i,viewportAnchor:i.viewportAnchor+b,hasMoreAbove:u-m>0,totalAvailableMessages:l.length}),{messages:g,sessionMemoryState:x}})}else u===0&&s(m=>{const f=new Map(m.sessionMemoryState);return f.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:f}})}},getLastMessageModel:t=>{const{messages:n}=r(),o=n.get(t);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const i=o[a];if(i.info.role==="assistant"&&"providerID"in i.info&&"modelID"in i.info)return{providerID:i.info.providerID,modelID:i.info.modelID}}return null}}),{name:"message-store",storage:Ds(()=>cs()),partialize:s=>({lastUsedProvider:s.lastUsedProvider,sessionMemoryState:Array.from(s.sessionMemoryState.entries()).map(([r,t])=>[r,{viewportAnchor:t.viewportAnchor,isStreaming:t.isStreaming,lastAccessedAt:t.lastAccessedAt,backgroundMessageCount:t.backgroundMessageCount,totalAvailableMessages:t.totalAvailableMessages,hasMoreAbove:t.hasMoreAbove,trimmedHeadMaxId:t.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(s.sessionAbortFlags.entries()).map(([r,t])=>[r,{timestamp:t.timestamp,acknowledged:t.acknowledged}])}),merge:(s,r)=>{if(!s)return r;let t=r.sessionMemoryState;Array.isArray(s.sessionMemoryState)&&(t=new Map(s.sessionMemoryState.map(o=>o)));let n=r.sessionAbortFlags;return Array.isArray(s.sessionAbortFlags)&&(n=new Map(s.sessionAbortFlags)),{...r,lastUsedProvider:s.lastUsedProvider??r.lastUsedProvider,sessionMemoryState:t,sessionAbortFlags:n}}}),{name:"message-store"})),jy=s=>typeof s=="object"&&s!==null,Sy=s=>{if(!Array.isArray(s))return[];const r=[];return s.forEach(t=>{if(!Array.isArray(t)||t.length!==2)return;const[n,o]=t;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},ky=async(s,r)=>{try{const n=rt.getState().getDirectoryForSession(s);if(n)return De.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return r()},Hn=Bt()(Qt(Ms((s,r)=>({permissions:new Map,addPermission:(t,n)=>{const o=t.sessionID;if(!o||r().permissions.get(o)?.some(f=>f.id===t.id))return;const i=t.permission?.toLowerCase?.()??null;let l=n?.currentAgentContext?.get(o);if(l||(l=n?.sessionAgentSelections?.get(o)??void 0),!l&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(l=f.getState().currentAgentName??void 0)}const d=Mo(l),u=n?.getSessionAgentEditMode?.(o,l)??d;if(u==="full"||u==="allow"&&dy(i)){r().respondToPermission(o,t.id,"once").catch(()=>{});return}s(f=>{const p=f.permissions.get(o)||[],h=new Map(f.permissions);return h.set(o,[...p,t]),{permissions:h}})},respondToPermission:async(t,n,o)=>{await ky(t,()=>De.replyToPermission(n,o)),o==="reject"&&await yt.getState().abortCurrentOperation(t),s(a=>{const l=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,l),{permissions:d}})}}),{name:"permission-store",storage:Ds(()=>cs()),partialize:s=>({permissions:Array.from(s.permissions.entries())}),merge:(s,r)=>{if(!jy(s))return r;const t=Sy(s.permissions);return{...r,permissions:new Map(t)}}}),{name:"permission-store"})),Vi=s=>s.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
|
|
9
|
+
`).replace(/\n\s*\n+/g,`
|
|
10
|
+
`),Fn=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},ec=(s,r,t)=>{if(!r)return null;const n=t(r)?.path;if(typeof n=="string"&&n.trim().length>0)return Fn(n);const o=s.find(a=>a.id===r);return o?Fn(o.directory??null):null},de=Bt()(Qt((s,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions:new Map,attachedFiles:[],isLoading:!1,error:null,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,abortPromptSessionId:null,abortPromptExpiresAt:null,sessionActivityPhase:new Map,userSummaryTitles:new Map,pendingInputText:null,newSessionDraft:{open:!0,directoryOverride:null,parentID:null},getSessionAgentEditMode:(t,n,o)=>vt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>vt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>vt.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>rt.getState().loadSessions(),openNewSessionDraft:t=>{let n=null;t?.directoryOverride!==void 0?n=t.directoryOverride:n=It.getState().getActiveProject()?.path??null,s({newSessionDraft:{open:!0,directoryOverride:n,parentID:t?.parentID??null,title:t?.title},currentSessionId:null,error:null});try{const o=at.getState(),a=o.getVisibleAgents();let i;if(o.settingsDefaultAgent){const l=a.find(d=>d.name===o.settingsDefaultAgent);l&&(i=l.name)}i||(i=a.find(l=>l.name==="build")?.name||a[0]?.name),i&&o.setAgent(i)}catch{}},closeNewSessionDraft:()=>{const t=rt.getState().currentSessionId;s({newSessionDraft:{open:!1,directoryOverride:null,parentID:null,title:void 0},currentSessionId:t})},createSession:async(t,n,o)=>{r().closeNewSessionDraft();const a=await rt.getState().createSession(t,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=yt.getState(),{messages:o,lastUsedProvider:a}=n;let i,l;if(o.forEach((x,y)=>{const w=x.find(S=>S.info?.id===t);w&&!i&&(i=w,l=y)}),!i||i.info.role!=="assistant")return;const d=Vi(i.parts);if(!d.trim())return;const u=rt.getState(),m=ec(u.sessions,l??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:j}=at.getState(),g=p||a?.providerID,b=h||a?.modelID;!g||!b||await De.sendMessage({id:f.id,providerID:g,modelID:b,text:d,prefaceText:Au,agent:j??void 0})},deleteSession:(t,n)=>rt.getState().deleteSession(t,n),deleteSessions:(t,n)=>rt.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>rt.getState().updateSessionTitle(t,n),shareSession:t=>rt.getState().shareSession(t),unshareSession:t=>rt.getState().unshareSession(t),setCurrentSession:async t=>{t&&r().closeNewSessionDraft();const n=rt.getState().currentSessionId,o=ec(rt.getState().sessions,t,rt.getState().getWorktreeMetadata),a=De.getDirectory()??ft.getState().currentDirectory??null,i=o??a;try{De.setDirectory(i??void 0)}catch(l){console.warn("Failed to set OpenCode directory for session switch:",l)}if(n&&n!==t&&!r().sessionMemoryState.get(n)?.isStreaming){const d=r().messages.get(n)||[];d.length>0&&r().updateViewportAnchor(n,d.length-1),r().trimToViewportWindow(n,ls.VIEWPORT_MESSAGES)}rt.getState().setCurrentSession(t),t&&(r().messages.get(t)||await r().loadMessages(t),r().trimToViewportWindow(t,Pg)),r().evictLeastRecentlyUsed()},loadMessages:t=>yt.getState().loadMessages(t),sendMessage:async(t,n,o,a,i,l,d)=>{const u=r().newSessionDraft,m=typeof a=="string"&&a.trim().length>0?a.trim():void 0,f=x=>{s(y=>{const w=new Map(y.sessionActivityPhase??new Map);return w.set(x,"busy"),{sessionActivityPhase:w}})},p=x=>{s(y=>{const w=new Map(y.sessionActivityPhase??new Map);return w.set(x,"idle"),{sessionActivityPhase:w}})};if(u?.open){const x=await rt.getState().createSession(u.title,u.directoryOverride??null,u.parentID??null);if(!x?.id)throw new Error("Failed to create session");const y=at.getState(),w=y.currentAgentName,S=m??w,v=y.currentProviderId,N=y.currentModelId;if(v&&N)try{vt.getState().saveSessionModelSelection(x.id,v,N)}catch{}if(S){try{vt.getState().saveSessionAgentSelection(x.id,S)}catch{}if(v&&N)try{vt.getState().saveAgentModelForSession(x.id,S,v,N)}catch{}}try{rt.getState().initializeNewOpenChamberSession(x.id,y.agents)}catch{}r().closeNewSessionDraft(),f(x.id);try{return await yt.getState().sendMessage(t,n,o,S,x.id,i,l,d)}catch(D){throw p(x.id),D}}const h=rt.getState().currentSessionId,j=h?vt.getState().getSessionAgentSelection(h):null,g=at.getState().currentAgentName,b=m||j||g||void 0;if(h&&b)try{vt.getState().saveSessionAgentSelection(h,b)}catch{}h&&f(h);try{return await yt.getState().sendMessage(t,n,o,b,h||void 0,i,l,d)}catch(x){throw h&&p(h),x}},abortCurrentOperation:()=>{const t=rt.getState().currentSessionId;return yt.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=rt.getState().currentSessionId;if(!n)return null;const o=Date.now()+t;return s({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{s({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:t=>{t&&yt.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const l=rt.getState().currentSessionId||t;return yt.getState().addStreamingPart(t,n,o,a,l)},completeStreamingMessage:(t,n)=>yt.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>yt.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>yt.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>yt.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:vt.getState().currentAgentContext,sessionAgentSelections:vt.getState().sessionAgentSelections,getSessionAgentEditMode:vt.getState().getSessionAgentEditMode};return Hn.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>Hn.getState().respondToPermission(t,n,o),clearError:()=>rt.getState().clearError(),getSessionsByDirectory:t=>rt.getState().getSessionsByDirectory(t),getDirectoryForSession:t=>rt.getState().getDirectoryForSession(t),getLastMessageModel:t=>yt.getState().getLastMessageModel(t),getCurrentAgent:t=>vt.getState().getCurrentAgent(t),syncMessages:(t,n)=>yt.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>rt.getState().applySessionMetadata(t,n),addAttachedFile:t=>Ys.getState().addAttachedFile(t),addServerFile:(t,n,o)=>Ys.getState().addServerFile(t,n,o),removeAttachedFile:t=>Ys.getState().removeAttachedFile(t),clearAttachedFiles:()=>Ys.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>yt.getState().updateViewportAnchor(t,n),updateActiveTurnAnchor:(t,n,o)=>yt.getState().updateActiveTurnAnchor(t,n,o),getActiveTurnAnchor:t=>yt.getState().getActiveTurnAnchor(t),trimToViewportWindow:(t,n)=>{const o=rt.getState().currentSessionId;return yt.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=rt.getState().currentSessionId;return yt.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>yt.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>vt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>vt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>vt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>vt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>vt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>vt.getState().getAgentModelForSession(t,n),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=yt.getState().messages;return vt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>rt.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>rt.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>rt.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>rt.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>rt.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>rt.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{if(r().newSessionDraft?.open)return null;const o=rt.getState().currentSessionId;if(!o)return null;const a=yt.getState().messages;return vt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=yt.getState().messages;return vt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=yt.getState().messages;return vt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=yt.getState().messages.get(t)||[],o=rt.getState().sessions.find(a=>a.id===t);console.log(`Debug session ${t}:`,{session:o,messageCount:n.length,messages:n.map(a=>({id:a.info.id,role:a.info.role,parts:a.parts.length,tokens:a.info.tokens}))})},pollForTokenUpdates:(t,n,o)=>{const a=yt.getState().messages;return vt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>rt.getState().updateSession(t),removeSessionFromStore:t=>rt.getState().removeSessionFromStore(t),revertToMessage:async(t,n)=>{const a=(yt.getState().messages.get(t)||[]).find(m=>m.info.id===n);let i="";a&&a.info.role==="user"&&(i=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
|
|
11
|
+
`).trim());const l=await De.revertSession(t,n);rt.getState().updateSession(l);const d=yt.getState().messages.get(t)||[],u=l.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);yt.getState().syncMessages(t,f)}}i&&s({pendingInputText:i})},handleSlashUndo:async t=>{const o=(r().messages.get(t)||[]).filter(p=>p.info.role==="user"),i=r().sessions.find(p=>p.id===t);if(o.length===0)return;const l=i?.revert?.messageID;let d;if(l){const p=o.findIndex(h=>h.info.id===l);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,d.info.id);const{toast:f}=await ns(async()=>{const{toast:p}=await import("./vendor-.bun-BEzqubWg.js").then(h=>h.cn);return{toast:p}},__vite__mapDeps([0,1]));f.success(`Undid to: ${m}`)},handleSlashRedo:async t=>{const a=r().sessions.find(m=>m.id===t)?.revert?.messageID;if(!a)return;const l=(r().messages.get(t)||[]).filter(m=>m.info.role==="user"),d=l.findIndex(m=>m.info.id===a),u=l[d-1];if(u){const m=u.parts.find(h=>h.type==="text"),f=typeof m=="object"&&m&&"text"in m?String(m.text).slice(0,50)+(String(m.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,u.info.id);const{toast:p}=await ns(async()=>{const{toast:h}=await import("./vendor-.bun-BEzqubWg.js").then(j=>j.cn);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await De.unrevertSession(t);await rt.getState().updateSession(m),await r().loadMessages(t);const{toast:f}=await ns(async()=>{const{toast:p}=await import("./vendor-.bun-BEzqubWg.js").then(h=>h.cn);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(t,n)=>{const a=r().sessions.find(i=>i.id===t);if(a)try{const i=await De.forkSession(t,n);if(!i||!i.id){const{toast:f}=await ns(async()=>{const{toast:p}=await import("./vendor-.bun-BEzqubWg.js").then(h=>h.cn);return{toast:p}},__vite__mapDeps([0,1]));f.error("Failed to fork session");return}const d=(r().messages.get(t)||[]).find(f=>f.info.id===n);if(!d){const{toast:f}=await ns(async()=>{const{toast:p}=await import("./vendor-.bun-BEzqubWg.js").then(h=>h.cn);return{toast:p}},__vite__mapDeps([0,1]));f.error("Message not found");return}let u="";for(const f of d.parts)f.type==="text"&&!f.synthetic&&!f.ignored&&(u+=f.text||"");r().setCurrentSession(i.id),u&&s({pendingInputText:u}),await r().loadMessages(i.id);const{toast:m}=await ns(async()=>{const{toast:f}=await import("./vendor-.bun-BEzqubWg.js").then(p=>p.cn);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(i){console.error("Failed to fork session:",i);const{toast:l}=await ns(async()=>{const{toast:d}=await import("./vendor-.bun-BEzqubWg.js").then(u=>u.cn);return{toast:d}},__vite__mapDeps([0,1]));l.error("Failed to fork session")}},setPendingInputText:t=>{s({pendingInputText:t})},consumePendingInputText:()=>{const t=r().pendingInputText;return t!==null&&s({pendingInputText:null}),t}}),{name:"composed-session-store"}));rt.subscribe((s,r)=>{if(s.sessions===r.sessions&&s.sessionsByDirectory===r.sessionsByDirectory&&s.currentSessionId===r.currentSessionId&&s.lastLoadedDirectory===r.lastLoadedDirectory&&s.isLoading===r.isLoading&&s.error===r.error&&s.webUICreatedSessions===r.webUICreatedSessions&&s.worktreeMetadata===r.worktreeMetadata&&s.availableWorktrees===r.availableWorktrees&&s.availableWorktreesByProject===r.availableWorktreesByProject)return;const t=de.getState().newSessionDraft?.open;de.setState({sessions:s.sessions,sessionsByDirectory:s.sessionsByDirectory,currentSessionId:t?null:s.currentSessionId,lastLoadedDirectory:s.lastLoadedDirectory,isLoading:s.isLoading,error:s.error,webUICreatedSessions:s.webUICreatedSessions,worktreeMetadata:s.worktreeMetadata,availableWorktrees:s.availableWorktrees,availableWorktreesByProject:s.availableWorktreesByProject})});yt.subscribe((s,r)=>{if(s.messages===r.messages&&s.sessionMemoryState===r.sessionMemoryState&&s.messageStreamStates===r.messageStreamStates&&s.sessionCompactionUntil===r.sessionCompactionUntil&&s.sessionAbortFlags===r.sessionAbortFlags&&s.streamingMessageIds===r.streamingMessageIds&&s.abortControllers===r.abortControllers&&s.lastUsedProvider===r.lastUsedProvider&&s.isSyncing===r.isSyncing)return;const t=new Map;s.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const i=n[a];if(!i||!i.info)continue;const l=i.info;if(l.role==="user"){const d=l.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=l.time&&typeof l.time.created=="number"?l.time.created:null;t.set(o,{title:u,createdAt:m});break}}}}}),de.setState({messages:s.messages,sessionMemoryState:s.sessionMemoryState,messageStreamStates:s.messageStreamStates,sessionCompactionUntil:s.sessionCompactionUntil,sessionAbortFlags:s.sessionAbortFlags,streamingMessageIds:s.streamingMessageIds,abortControllers:s.abortControllers,lastUsedProvider:s.lastUsedProvider,isSyncing:s.isSyncing,userSummaryTitles:t})});Ys.subscribe((s,r)=>{s.attachedFiles!==r.attachedFiles&&de.setState({attachedFiles:s.attachedFiles})});vt.subscribe((s,r)=>{s.sessionModelSelections===r.sessionModelSelections&&s.sessionAgentSelections===r.sessionAgentSelections&&s.sessionAgentModelSelections===r.sessionAgentModelSelections&&s.currentAgentContext===r.currentAgentContext&&s.sessionContextUsage===r.sessionContextUsage&&s.sessionAgentEditModes===r.sessionAgentEditModes||de.setState({sessionModelSelections:s.sessionModelSelections,sessionAgentSelections:s.sessionAgentSelections,sessionAgentModelSelections:s.sessionAgentModelSelections,currentAgentContext:s.currentAgentContext,sessionContextUsage:s.sessionContextUsage,sessionAgentEditModes:s.sessionAgentEditModes})});Hn.subscribe((s,r)=>{s.permissions!==r.permissions&&de.setState({permissions:s.permissions})});ft.subscribe((s,r)=>{const t=Fn(s.currentDirectory??null),n=Fn(r.currentDirectory??null);if(t===n)return;const o=de.getState().newSessionDraft;if(!o?.open)return;const a=Fn(o.directoryOverride);a&&a!==n||de.setState(i=>({newSessionDraft:{...i.newSessionDraft,directoryOverride:t,parentID:null}}))});const Ny=de.getState().newSessionDraft?.open;de.setState({sessions:rt.getState().sessions,currentSessionId:Ny?null:rt.getState().currentSessionId,lastLoadedDirectory:rt.getState().lastLoadedDirectory,isLoading:rt.getState().isLoading,error:rt.getState().error,webUICreatedSessions:rt.getState().webUICreatedSessions,worktreeMetadata:rt.getState().worktreeMetadata,availableWorktrees:rt.getState().availableWorktrees,availableWorktreesByProject:rt.getState().availableWorktreesByProject,messages:yt.getState().messages,sessionMemoryState:yt.getState().sessionMemoryState,messageStreamStates:yt.getState().messageStreamStates,sessionCompactionUntil:yt.getState().sessionCompactionUntil,sessionAbortFlags:yt.getState().sessionAbortFlags,streamingMessageIds:yt.getState().streamingMessageIds,abortControllers:yt.getState().abortControllers,lastUsedProvider:yt.getState().lastUsedProvider,isSyncing:yt.getState().isSyncing,permissions:Hn.getState().permissions,attachedFiles:Ys.getState().attachedFiles,sessionModelSelections:vt.getState().sessionModelSelections,sessionAgentSelections:vt.getState().sessionAgentSelections,sessionAgentModelSelections:vt.getState().sessionAgentModelSelections,currentAgentContext:vt.getState().currentAgentContext,sessionContextUsage:vt.getState().sessionContextUsage,sessionAgentEditModes:vt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=de);const Gi=({containerRef:s,minThumbSize:r=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=c.useState(!1),[l,d]=c.useState({length:0,offset:0}),[u,m]=c.useState({length:0,offset:0}),f=c.useRef(null),p=c.useRef(null),h=c.useRef(!1),j=c.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),g=c.useRef(null),b=c.useCallback(()=>{const C=s.current;if(!C)return;const{scrollHeight:k,clientHeight:A,scrollTop:P,scrollWidth:L,clientWidth:U,scrollLeft:z}=C,H=8;if(k>A){const V=Math.max(A-H*2,0),J=A/k*V,T=Math.max(r,Math.min(V,J)),Z=Math.max(V-T,0),E=Math.max(k-A,1),B=P/E*Z;d({length:T,offset:B})}else d({length:0,offset:0});if(!o&&L>U){const V=Math.max(U-H*2,0),J=U/L*V,T=Math.max(r,Math.min(V,J)),Z=Math.max(V-T,0),E=Math.max(L-U,1),B=z/E*Z;m({length:T,offset:B})}else m({length:0,offset:0})},[s,r,o]),x=c.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>i(!1),t)},[t]),y=c.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{b(),i(!0),x()})},[x,b]);c.useEffect(()=>{const C=s.current;if(!C)return;b(),i(!0),x(),C.addEventListener("scroll",y,{passive:!0});const k=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null;k?.observe(C);const A=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return A?.observe(C,{childList:!0,subtree:!0,characterData:!0}),()=>{C.removeEventListener("scroll",y),k?.disconnect(),A?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[s,y,x,b]);const w=(C,k)=>{const A=s.current;A&&(h.current=!0,j.current={pointerX:C.clientX,pointerY:C.clientY,scrollTop:A.scrollTop,scrollLeft:A.scrollLeft},g.current=k,i(!0),f.current&&clearTimeout(f.current),C.currentTarget.setPointerCapture(C.pointerId))},S=C=>{if(!h.current)return;const k=s.current;if(!k)return;const A=g.current;if(A==="vertical"){const{pointerY:P,scrollTop:L}=j.current,U=C.clientY-P,z=k.clientHeight,H=Math.max(z-l.length,1),V=Math.max(k.scrollHeight-k.clientHeight,1),J=U/H*V;k.scrollTop=L+J}else if(A==="horizontal"){const{pointerX:P,scrollLeft:L}=j.current,U=C.clientX-P,z=k.clientWidth,H=Math.max(z-u.length,1),V=Math.max(k.scrollWidth-k.clientWidth,1),J=U/H*V;k.scrollLeft=L+J}},v=C=>{h.current&&(h.current=!1,C.currentTarget.releasePointerCapture(C.pointerId),x())},N=l.length>0,D=u.length>0;if(!N&&!D)return null;const M=8;return e.jsxs("div",{className:R("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[N&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${l.length}px`,top:`${M+l.offset}px`,right:`${M/2}px`},onPointerDown:C=>w(C,"vertical"),onPointerMove:S,onPointerUp:v,onPointerCancel:v}),D&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${M+u.offset}px`,bottom:`${M/2}px`},onPointerDown:C=>w(C,"horizontal"),onPointerMove:S,onPointerUp:v,onPointerCancel:v})]})},ct=c.forwardRef(({className:s,outerClassName:r,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:l,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const h=c.useRef(null);return c.useImperativeHandle(p,()=>h.current,[]),e.jsxs("div",{className:R("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-none",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(i,{ref:h,className:R("overlay-scrollbar-target overlay-scrollbar-container overscroll-none",u?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",s),style:n,...f,children:t}),e.jsx(Gi,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:l,disableHorizontal:d})]})});ct.displayName="ScrollableOverlay";const tc="mobile-overlay-root",Cy=()=>{if(typeof document>"u")return null;let s=document.getElementById(tc);return s||(s=document.createElement("div"),s.id=tc,document.body.appendChild(s)),s},vs=({open:s,title:r,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:i,renderHeader:l})=>{const d=c.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=Cy()),c.useEffect(()=>{if(!s)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const p=h=>{h.key==="Escape"&&t()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",p)}},[s,t]),!s||!d.current)return null;const u=i??"max-h-[min(70vh,520px)]",m=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:R("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),"data-keyboard-avoid":"true",onClick:f=>f.stopPropagation(),children:[(()=>{const f=e.jsx("button",{type:"button",onClick:t,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(Lt,{className:"h-4 w-4"})});return l?l(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(ct,{outerClassName:u,className:"px-2 py-2 pwa-overlay-scroll",children:n}),o?e.jsx("div",{className:"border-t border-border/40 px-3 py-2",children:o}):null]})});return df.createPortal(m,d.current)},mi=({totalTokens:s,percentage:r,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[i,l]=c.useState(!1),d=c.useRef(void 0),u=b=>b>=1e6?`${(b/1e6).toFixed(1)}M`:b>=1e3?`${(b/1e3).toFixed(1)}K`:b.toFixed(1).replace(/\.0$/,""),m=b=>b>=90?"text-status-error":b>=75?"text-status-warning":"text-status-success",f=typeof n=="number"?Math.max(n,0):0,p=[`Used tokens: ${u(s)}`,`Context limit: ${u(t)}`,`Output limit: ${u(f)}`],h=c.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{l(!0)},500)},[]),j=c.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);c.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=e.jsxs("div",{className:R("app-region-no-drag flex items-center gap-1.5 text-muted-foreground/60 select-none",o==="compact"?"typography-micro":"typography-meta"),"aria-label":"Context usage",onTouchStart:a?h:void 0,onTouchEnd:a?j:void 0,children:[e.jsx(uf,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:R(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[g,e.jsx(vs,{open:i,onClose:()=>l(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(s)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(f)})]}),e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:R("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:g}),e.jsx(tt,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(b=>e.jsx("p",{className:"typography-micro leading-tight",children:b},b))})})]})},Cn={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Iu=(s,r,t)=>{if(typeof window>"u")return;const n=document.documentElement,o=r==="mobile",a=r==="tablet";n.classList.remove("device-mobile","device-tablet","device-desktop"),n.classList.add(r==="mobile"?"device-mobile":r==="tablet"?"device-tablet":"device-desktop"),s?(n.classList.add("desktop-runtime"),n.style.setProperty("--is-mobile","0"),n.style.setProperty("--device-type","desktop"),n.style.setProperty("--font-scale","1"),n.style.setProperty("--has-coarse-pointer","0"),n.style.setProperty("--has-touch-input","0"),n.classList.remove("mobile-pointer")):(n.classList.remove("desktop-runtime"),n.style.setProperty("--is-mobile",o?"1":"0"),n.style.setProperty("--device-type",r),n.style.setProperty("--font-scale",o?"0.9":a?"0.95":"1"),n.style.setProperty("--has-coarse-pointer",t?"1":"0"),n.style.setProperty("--has-touch-input",t?"1":"0"),t?n.classList.add("mobile-pointer"):n.classList.remove("mobile-pointer"))};function Ea(){const s=window.innerWidth,r=typeof window.matchMedia=="function",t=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,l=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,u=s>Cn.md&&s<=Cn.lg,m=s<=Cn.md;let f=d&&m,p=d&&!f&&u,h=!d||s>Cn.lg,j="desktop";l?(f=!1,p=!1,h=!0,j="desktop"):f?j="mobile":p?j="tablet":(h=!0,j="desktop"),Iu(l,j,d);let g="xs";for(const[b,x]of Object.entries(Cn))s>=x&&(g=b);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:j,screenWidth:s,breakpoint:g,hasTouchInput:d}}function $t(){const[s,r]=c.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Ea());return c.useEffect(()=>{if(typeof window>"u")return;const t=()=>{r(Ea())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(Ea())},a=[],i=l=>{l&&(typeof l.addEventListener=="function"?(l.addEventListener("change",o),a.push(()=>l.removeEventListener("change",o))):typeof l.addListener=="function"&&(l.addListener(o),a.push(()=>l.removeListener(o))))};return i(t),i(n),()=>{a.forEach(l=>l())}},[]),c.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,i=o?.matches??!1,l=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=i||l||d>0;Iu(t,s.deviceType,u)},[s.deviceType,s.hasTouchInput]),s}const oo=5e3,My=1e4,Dy=5e3,Ay=1e4,Ey=25,Iy=4,sc=15e3,Vs=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),Py=(s,r)=>{if(!s&&!r)return!1;if(!s||!r)return!0;const t=new Set([...Object.keys(s),...Object.keys(r)]);for(const n of t){const o=s[n],a=r[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},Ty=(s,r)=>{if(!s&&!r)return!1;if(!s||!r)return!0;const t=s.files??[],n=r.files??[];if(t.length!==n.length||s.ahead!==r.ahead||s.behind!==r.behind||s.current!==r.current||s.tracking!==r.tracking||s.isClean!==r.isClean)return!0;const o=new Set(t.map(a=>`${a.path}:${a.index}:${a.working_dir}`));for(const a of n)if(!o.has(`${a.path}:${a.index}:${a.working_dir}`))return!0;return!!Py(s.diffStats,r.diffStats)},Fy=(s,r)=>{const t=new Set;if(!r)return t;const n=s?.files??[],o=r.files??[],a=new Map(n.map(f=>[f.path,f])),i=new Map(o.map(f=>[f.path,f])),l=new Set([...a.keys(),...i.keys()]);for(const f of l){const p=a.get(f),h=i.get(f);if(!p||!h){t.add(f);continue}if(p.index!==h.index||p.working_dir!==h.working_dir){t.add(f);continue}}const d=s?.diffStats??{},u=r.diffStats??{},m=new Set([...Object.keys(d),...Object.keys(u)]);for(const f of m){const p=d[f],h=u[f];if(!p||!h){t.add(f);continue}(p.insertions!==h.insertions||p.deletions!==h.deletions)&&t.add(f)}return t},Ut=Bt()(Qt((s,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:oo,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=r();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,Vs()),s({activeDirectory:t,directories:a})}else s({activeDirectory:t})},getDirectoryState:t=>r().directories.get(t)??null,fetchStatus:async(t,n,o={})=>{const{silent:a=!1}=o,{directories:i}=r();let l=i.get(t);l||(l=Vs()),a||s({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const f=new Map(i);return f.set(t,{...l,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),s({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(t);if(Ty(l.status,m)){d=!0;const f=new Map(r().directories),p=f.get(t)??Vs(),h=Fy(p.status,m),j=new Set((p.status?.files??[]).map(y=>y.path)),g=new Set((m.files??[]).map(y=>y.path)),b=new Map(p.diffCache);for(const y of j)g.has(y)||b.delete(y);for(const y of h)b.delete(y);const x=h.size>0;f.set(t,{...p,isGitRepo:!0,status:m,diffCache:b,lastStatusFetch:Date.now(),lastStatusChange:x?Date.now():p.lastStatusChange}),s({directories:f})}else{const f=new Map(r().directories),p=f.get(t)??Vs();f.set(t,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),s({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||s({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{s({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(r().directories),i=a.get(t)??Vs();a.set(t,{...i,branches:o}),s({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{s({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=r(),i=a.get(t),l=o??i?.logMaxCount??25;s({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:l}),u=new Map(r().directories),m=u.get(t)??Vs();u.set(t,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:l}),s({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{s({isLoadingLog:!1})}},fetchIdentity:async(t,n)=>{s({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(t),a=new Map(r().directories),i=a.get(t)??Vs();a.set(t,{...i,identity:o}),s({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{s({isLoadingIdentity:!1})}},fetchAll:async(t,n,o={})=>{const{directories:a}=r();let i=a.get(t);if(!i){i=Vs();const f=new Map(a);f.set(t,i),s({directories:f})}const{force:l=!1}=o,d=Date.now();await r().fetchStatus(t,n);const u=r().directories.get(t);if(!u?.isGitRepo)return;await r().fetchBranches(t,n);const m=d-(u.lastLogFetch||0);(l||m>Ay||!u.log)&&await r().fetchLog(t,n),await r().fetchIdentity(t,n),r().fetchAllDiffs(t,n)},getDiff:(t,n)=>r().directories.get(t)?.diffCache.get(n)??null,setDiff:(t,n,o)=>{const a=new Map(r().directories),i=a.get(t)??Vs(),l=new Map(i.diffCache);l.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...i,diffCache:l}),s({directories:a})},clearDiffCache:t=>{const n=new Map(r().directories),o=n.get(t);o&&(n.set(t,{...o,diffCache:new Map}),s({directories:n}))},fetchAllDiffs:async(t,n)=>{const o=r().directories.get(t);if(!o?.status?.files||o.status.files.length===0)return;const l=o.status.files.filter(y=>!o.diffCache.has(y.path)).slice(0,Ey);if(l.length===0)return;let d=0;const u=[],m=()=>{const y=d;return d+=1,y<l.length?l[y]:null},f=async y=>{const w=n.getGitFileDiff(t,{path:y}),S=new Promise((N,D)=>{setTimeout(()=>D(new Error(`Timed out after ${sc}ms`)),sc)}),v=await Promise.race([w,S]);return{path:y,diff:{original:v.original??"",modified:v.modified??""}}},p=async()=>{for(;;){const y=m();if(!y)return;try{u.push(await f(y.path))}catch{}}},h=Math.min(Iy,l.length);await Promise.allSettled(Array.from({length:h},()=>p()));const j=new Map(r().directories),g=j.get(t);if(!g)return;const b=new Map(g.diffCache),x=Date.now();u.forEach(y=>{b.set(y.path,{...y.diff,fetchedAt:x})}),j.set(t,{...g,diffCache:b}),s({directories:j})},setLogMaxCount:(t,n)=>{const o=new Map(r().directories),a=o.get(t)??Vs();o.set(t,{...a,logMaxCount:n}),s({directories:o})},startPolling:t=>{const{pollIntervalId:n}=r();if(n)return;const o=()=>{const{currentPollInterval:a}=r();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){s({pollIntervalId:o()});return}const{activeDirectory:l}=r();if(!l){s({pollIntervalId:o()});return}if(await r().fetchStatus(l,t,{silent:!0}))await r().fetchLog(l,t),r().fetchAllDiffs(l,t),s({currentPollInterval:oo});else{const m=Math.min(a+Dy,My);s({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&s({pollIntervalId:o()})},a)};s({pollIntervalId:o(),currentPollInterval:oo})},stopPolling:()=>{const{pollIntervalId:t}=r();t&&(clearTimeout(t),s({pollIntervalId:null,currentPollInterval:oo}))},refresh:async(t,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,t,n)}}),{name:"git-store"})),Pu=s=>Ut(r=>s?r.directories.get(s)?.status??null:null),Tu=s=>Ut(r=>s?r.directories.get(s)?.branches??null:null),Ry=s=>Ut(r=>s?r.directories.get(s)?.log??null:null),Oy=s=>Ut(r=>s?r.directories.get(s)?.identity??null:null),qi=s=>Ut(r=>s?r.directories.get(s)?.isGitRepo??null:null),$y=s=>Ut(r=>s?r.directories.get(s)?.status?.files?.length??0:0);function Kt({...s}){return e.jsx(mf,{"data-slot":"dropdown-menu",...s})}function Yt({...s}){return e.jsx(ff,{"data-slot":"dropdown-menu-trigger",...s})}function Xt({className:s,sideOffset:r=4,...t}){return e.jsx(pf,{children:e.jsx(hf,{"data-slot":"dropdown-menu-content",sideOffset:r,className:R("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",s),...t})})}function jt({className:s,inset:r,variant:t="default",...n}){return e.jsx(bf,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":t,className:R("hover:bg-muted data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",s),...n})}function Fu({...s}){return e.jsx(gf,{"data-slot":"dropdown-menu-radio-group",...s})}function Ru({className:s,children:r,...t}){return e.jsxs(yf,{"data-slot":"dropdown-menu-radio-item",className:R("relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-muted [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",s),...t,children:[e.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:e.jsx(xf,{children:e.jsx(Ot,{className:"size-3"})})}),r]})}function on({className:s,inset:r,...t}){return e.jsx(vf,{"data-slot":"dropdown-menu-label","data-inset":r,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",s),...t})}function Xs({className:s,...r}){return e.jsx(wf,{"data-slot":"dropdown-menu-separator",className:R("bg-border -mx-1 my-0.5 h-px",s),...r})}const Ly={read:{displayName:"Read File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"offset",label:"Start Line",type:"text"},{key:"limit",label:"Lines to Read",type:"text"}]},write:{displayName:"Write File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"content",label:"Content",type:"code"}]},edit:{displayName:"Edit File",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"oldString",label:"Find",type:"code"},{key:"newString",label:"Replace",type:"code"},{key:"replaceAll",label:"Replace All",type:"text"}]},multiedit:{displayName:"Multi-Edit",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"edits",label:"Edits",type:"code",language:"json"}]},bash:{displayName:"Shell Command",category:"system",outputLanguage:"text",inputFields:[{key:"command",label:"Command",type:"command",language:"bash"},{key:"description",label:"Description",type:"text"},{key:"timeout",label:"Timeout (ms)",type:"text"}]},grep:{displayName:"Search Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"},{key:"include",label:"Include Pattern",type:"pattern"}]},glob:{displayName:"Find Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"}]},list:{displayName:"List Directory",category:"file",outputLanguage:"text",inputFields:[{key:"path",label:"Directory",type:"file"},{key:"ignore",label:"Ignore Patterns",type:"pattern"}]},task:{displayName:"Agent Task",category:"ai",outputLanguage:"markdown",inputFields:[{key:"description",label:"Task",type:"text"},{key:"prompt",label:"Instructions",type:"text"},{key:"subagent_type",label:"Agent Type",type:"text"}]},webfetch:{displayName:"Fetch URL",category:"web",outputLanguage:"auto",inputFields:[{key:"url",label:"URL",type:"text"},{key:"format",label:"Format",type:"text"},{key:"timeout",label:"Timeout",type:"text"}]},websearch:{displayName:"Web Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"numResults",label:"Results Count",type:"text"},{key:"type",label:"Search Type",type:"text"}]},codesearch:{displayName:"Code Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"tokensNum",label:"Tokens",type:"text"}]},todowrite:{displayName:"Update Todo List",category:"system",outputLanguage:"json",inputFields:[{key:"todos",label:"Todo Items",type:"code",language:"json"}]},todoread:{displayName:"Read Todo List",category:"system",outputLanguage:"json",inputFields:[]},skill:{displayName:"Load Skill",category:"ai",outputLanguage:"markdown",inputFields:[{key:"name",label:"Skill Name",type:"text"}]}};function Ki(s){return Ly[s]||{displayName:s.charAt(0).toUpperCase()+s.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function _y(s,r,t){const n=Ki(s);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=Hr(o);if(a)return a}if(s==="webfetch"){if(r.trim().startsWith("{")||r.trim().startsWith("["))try{return JSON.parse(r),"json"}catch{}if(r.trim().startsWith("<"))return"html";if(r.includes("```"))return"markdown"}return"text"}return n.outputLanguage||"text"}function Hr(s){const r=s.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",jsonc:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",cc:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",dart:"dart",r:"r",lua:"lua",vim:"vim",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",md:"markdown",mdx:"markdown",rst:"text",txt:"text",dockerfile:"dockerfile",makefile:"makefile",gitignore:"text",env:"text",conf:"text",cfg:"text",ini:"ini",sql:"sql",diff:"diff",patch:"diff"}[r||""]||null}const By=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function Ou(s){const r=s.split(".").pop()?.toLowerCase();return By.includes(r||"")}function zy(s){const r=s.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif"}[r||""]||"image/png"}function Wy(s,r){if(!s)return"";const t=n=>{const o=s[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(r==="bash"){const n=t("command");if(n)return n}if(r==="task"){const n=t("prompt");if(n)return n;const o=t("description");if(o)return o}if((r==="edit"||r==="multiedit")&&typeof s=="object"){const n=t("filePath")||t("file_path")||t("path");if(n)return`File path: ${n}`}if(r==="write"&&typeof s=="object"){const n=t("content");if(n)return n}return typeof s=="object"?Object.entries(s).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const i=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let l=a;return typeof a=="object"?l=JSON.stringify(a,null,2):typeof a=="boolean"&&(l=a?"Yes":"No"),`${i}: ${l}`}).join(`
|
|
12
|
+
`):String(s)}const Yi=c.createContext(null),vn=()=>{const s=c.useContext(Yi);if(!s)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return s},$u=s=>{const r=vn();return s(r)},Hy=()=>$u(s=>s.runtime.isDesktop),Lu=()=>$u(s=>s.runtime.isVSCode),Uy=jf("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg typography-ui-label font-medium transition-[background-color,border-color,color,box-shadow,opacity] duration-150 ease-in-out disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-none hover:bg-primary/90",destructive:"bg-destructive text-white shadow-none hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-none hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-none hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-lg gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-lg px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function ke({className:s,variant:r,size:t,asChild:n=!1,...o}){const a=n?Od:"button";return e.jsx(a,{"data-slot":"button",className:R(Uy({variant:r,size:t,className:s})),...o})}const Vy=({mode:s,onModeChange:r,className:t})=>{const n=c.useCallback(o=>{o.stopPropagation(),r(s==="side-by-side"?"unified":"side-by-side")},[s,r]);return e.jsx(ke,{size:"sm",variant:"ghost",className:R("h-5 w-5 p-0 opacity-60 hover:opacity-100",t),onClick:n,title:s==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:s==="side-by-side"?e.jsx(Sf,{className:"h-3 w-3"}):e.jsx(kf,{className:"h-3 w-3"})})},Xi=Me.createContext(void 0);function Ur(){const s=Me.useContext(Xi);if(!s)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return s}function na(){return Me.useContext(Xi)}const Gy="Flexoki",qy="dark",Ky={"editor.background":"#100F0F","editor.foreground":"#CECDC3","editor.hoverHighlightBackground":"#343331","editor.lineHighlightBackground":"#1C1B1A","editor.selectionBackground":"#CECDC333","editor.selectionHighlightBackground":"#CECDC333","editor.findMatchBackground":"#AD8301","editor.findMatchHighlightBackground":"#AD8301cc","editor.findRangeHighlightBackground":"#1C1B1A","editor.inactiveSelectionBackground":"#282726","editor.lineHighlightBorder":"#282726","editor.rangeHighlightBackground":"#403E3C","notifications.background":"#282726","editorInlayHint.typeBackground":"#343331","editorInlayHint.typeForeground":"#CECDC3","editorWhitespace.foreground":"#403E3C","editorIndentGuide.background1":"#343331","editorHoverWidget.background":"#282726","editorLineNumber.activeForeground":"#CECDC3","editorLineNumber.foreground":"#403E3C","editorGutter.background":"#100F0F","editorGutter.modifiedBackground":"#3AA99F","editorGutter.addedBackground":"#879A39","editorGutter.deletedBackground":"#D14D41","editorBracketMatch.background":"#282726","editorBracketMatch.border":"#343331","editorError.foreground":"#D14D41","editorWarning.foreground":"#DA702C","editorInfo.foreground":"#4385BE","diffEditor.insertedTextBackground":"#66800B99","diffEditor.removedTextBackground":"#AF302999","editorGroupHeader.tabsBackground":"#100F0F","editorGroup.border":"#343331","tab.activeBackground":"#100F0F","tab.inactiveBackground":"#1C1B1A","tab.inactiveForeground":"#878580","tab.activeForeground":"#CECDC3","tab.hoverBackground":"#343331","tab.unfocusedHoverBackground":"#343331","tab.border":"#343331","tab.activeModifiedBorder":"#D0A215","tab.inactiveModifiedBorder":"#4385BE","tab.unfocusedActiveModifiedBorder":"#AD8301","tab.unfocusedInactiveModifiedBorder":"#205EA6","editorWidget.background":"#1C1B1A","editorWidget.border":"#343331","editorSuggestWidget.background":"#100F0F","editorSuggestWidget.border":"#343331","editorSuggestWidget.foreground":"#CECDC3","editorSuggestWidget.highlightForeground":"#878580","editorSuggestWidget.selectedBackground":"#343331","peekView.border":"#343331","peekViewEditor.background":"#100F0F","peekViewEditor.matchHighlightBackground":"#403E3C","peekViewResult.background":"#1C1B1A","peekViewResult.fileForeground":"#CECDC3","peekViewResult.lineForeground":"#878580","peekViewResult.matchHighlightBackground":"#403E3C","peekViewResult.selectionBackground":"#282726","peekViewResult.selectionForeground":"#575653","peekViewTitle.background":"#343331","peekViewTitleDescription.foreground":"#878580","peekViewTitleLabel.foreground":"#CECDC3","merge.currentHeaderBackground":"#879A39","merge.currentContentBackground":"#66800B","merge.incomingHeaderBackground":"#3AA99F","merge.incomingContentBackground":"#24837B","merge.border":"#343331","merge.commonContentBackground":"#403E3C","merge.commonHeaderBackground":"#343331","panel.background":"#100F0F","panel.border":"#343331","panelTitle.activeBorder":"#403E3C","panelTitle.activeForeground":"#CECDC3","panelTitle.inactiveForeground":"#878580","statusBar.background":"#100F0F","statusBar.foreground":"#CECDC3","statusBar.border":"#343331","statusBar.debuggingBackground":"#D14D41","statusBar.debuggingForeground":"#CECDC3","statusBar.noFolderBackground":"#403E3C","statusBar.noFolderForeground":"#575653","titleBar.activeBackground":"#100F0F","titleBar.activeForeground":"#CECDC3","titleBar.inactiveBackground":"#1C1B1A","titleBar.inactiveForeground":"#878580","titleBar.border":"#343331","menu.foreground":"#CECDC3","menu.background":"#100F0F","menu.selectionForeground":"#CECDC3","menu.selectionBackground":"#343331","menu.border":"#343331","editorInlayHint.foreground":"#878580","editorInlayHint.background":"#343331","terminal.foreground":"#CECDC3","terminal.background":"#100F0F","terminalCursor.foreground":"#CECDC3","terminalCursor.background":"#100F0F","terminal.ansiRed":"#D14D41","terminal.ansiGreen":"#879A39","terminal.ansiYellow":"#D0A215","terminal.ansiBlue":"#4385BE","terminal.ansiMagenta":"#3AA99F","terminal.ansiCyan":"#3AA99F","activityBar.background":"#100F0F","activityBar.foreground":"#CECDC3","activityBar.inactiveForeground":"#878580","activityBar.activeBorder":"#CECDC3","activityBar.border":"#343331","sideBar.background":"#100F0F","sideBar.foreground":"#CECDC3","sideBar.border":"#343331","sideBarTitle.foreground":"#CECDC3","sideBarSectionHeader.background":"#1C1B1A","sideBarSectionHeader.foreground":"#CECDC3","sideBarSectionHeader.border":"#343331","sideBar.activeBackground":"#403E3C","sideBar.activeForeground":"#CECDC3","sideBar.hoverBackground":"#343331","sideBar.hoverForeground":"#878580","sideBar.folderIcon.foreground":"#879A39","sideBar.fileIcon.foreground":"#4385BE","list.warningForeground":"#DA702C","list.errorForeground":"#D14D41","list.inactiveSelectionBackground":"#343331","list.activeSelectionBackground":"#403E3C","list.inactiveSelectionForeground":"#CECDC3","list.activeSelectionForeground":"#CECDC3","list.hoverForeground":"#CECDC3","list.hoverBackground":"#343331","input.background":"#1C1B1A","input.foreground":"#CECDC3","input.border":"#343331","input.placeholderForeground":"#878580","inputOption.activeBorder":"#343331","inputOption.activeBackground":"#282726","inputOption.activeForeground":"#CECDC3","inputValidation.infoBackground":"#3AA99F","inputValidation.infoBorder":"#24837B","inputValidation.warningBackground":"#DA702C","inputValidation.warningBorder":"#BC5215","inputValidation.errorBackground":"#D14D41","inputValidation.errorBorder":"#AF3029","dropdown.background":"#1C1B1A","dropdown.foreground":"#CECDC3","dropdown.border":"#343331","dropdown.listBackground":"#100F0F","badge.background":"#3AA99F","activityBarBadge.background":"#3AA99F","button.background":"#3AA99F","button.foreground":"#100F0F","badge.foreground":"#100F0F","activityBarBadge.foreground":"#100F0F"},Yy=[{name:"plain",scope:["source","support.type.property-name.css"],settings:{foreground:"#CECDC3"}},{name:"classes",scope:["entity.name.type.class"],settings:{foreground:"#DA702C"}},{name:"interfaces",scope:["entity.name.type.interface","entity.name.type"],settings:{foreground:"#D0A215"}},{name:"structs",scope:["entity.name.type.struct"],settings:{foreground:"#DA702C"}},{name:"enums",scope:["entity.name.type.enum"],settings:{foreground:"#DA702C"}},{name:"keys",scope:["meta.object-literal.key","support.type.property-name"],settings:{foreground:"#DA702C"}},{name:"methods",scope:["entity.name.function.method","meta.function.method"],settings:{foreground:"#879A39"}},{name:"functions",scope:["entity.name.function","support.function","meta.function-call.generic"],settings:{foreground:"#DA702C",fontStyle:"bold"}},{name:"variables",scope:["variable","meta.variable","variable.other.object.property"],settings:{foreground:"#CECDC3"}},{name:"variablesOther",scope:["variable.other.object","variable.other.readwrite.alias"],settings:{foreground:"#879A39"}},{name:"globalVariables",scope:["variable.other.global","variable.language.this"],settings:{foreground:"#CE5D97"}},{name:"localVariables",scope:["variable.other.local"],settings:{foreground:"#282726"}},{name:"parameters",scope:["variable.parameter","meta.parameter"],settings:{foreground:"#CECDC3"}},{name:"properties",scope:["variable.other.property","meta.property"],settings:{foreground:"#4385BE"}},{name:"strings",scope:["string","string.other.link","markup.inline.raw.string.markdown"],settings:{foreground:"#3AA99F"}},{name:"stringEscapeSequences",scope:["constant.character.escape","constant.other.placeholder"],settings:{foreground:"#CECDC3"}},{name:"keywords",scope:["keyword"],settings:{foreground:"#879A39"}},{name:"keywordsControl",scope:["keyword.control.import","keyword.control.from","keyword.import"],settings:{foreground:"#D14D41"}},{name:"storageModifiers",scope:["storage.modifier","keyword.modifier","storage.type"],settings:{foreground:"#4385BE"}},{name:"comments",scope:["comment","punctuation.definition.comment"],settings:{foreground:"#878580"}},{name:"docComments",scope:["comment.documentation","comment.line.documentation"],settings:{foreground:"#575653"}},{name:"numbers",scope:["constant.numeric"],settings:{foreground:"#8B7EC8"}},{name:"booleans",scope:["constant.language.boolean","constant.language.json"],settings:{foreground:"#D0A215"}},{name:"operators",scope:["keyword.operator"],settings:{foreground:"#D14D41"}},{name:"macros",scope:["entity.name.function.preprocessor","meta.preprocessor"],settings:{foreground:"#4385BE"}},{name:"preprocessor",scope:["meta.preprocessor"],settings:{foreground:"#CE5D97"}},{name:"urls",scope:["markup.underline.link"],settings:{foreground:"#4385BE"}},{name:"tags",scope:["entity.name.tag"],settings:{foreground:"#4385BE"}},{name:"jsxTags",scope:["support.class.component"],settings:{foreground:"#CE5D97"}},{name:"attributes",scope:["entity.other.attribute-name","meta.attribute"],settings:{foreground:"#D0A215"}},{name:"types",scope:["support.type"],settings:{foreground:"#D0A215"}},{name:"constants",scope:["variable.other.constant","variable.readonly"],settings:{foreground:"#CECDC3"}},{name:"labels",scope:["entity.name.label","punctuation.definition.label"],settings:{foreground:"#CE5D97"}},{name:"namespaces",scope:["entity.name.namespace","storage.modifier.namespace","markup.bold.markdown"],settings:{foreground:"#D0A215"}},{name:"modules",scope:["entity.name.module","storage.modifier.module"],settings:{foreground:"#D14D41"}},{name:"typeParameters",scope:["variable.type.parameter","variable.parameter.type"],settings:{foreground:"#DA702C"}},{name:"exceptions",scope:["keyword.control.exception","keyword.control.trycatch"],settings:{foreground:"#CE5D97"}},{name:"decorators",scope:["meta.decorator","punctuation.decorator","entity.name.function.decorator"],settings:{foreground:"#D0A215"}},{name:"calls",scope:["variable.function"],settings:{foreground:"#CECDC3"}},{name:"punctuation",scope:["punctuation","punctuation.terminator","punctuation.definition.tag","punctuation.separator","punctuation.definition.string","punctuation.section.block"],settings:{foreground:"#878580"}},{name:"yellow",scope:["storage.type.numeric.go","storage.type.byte.go","storage.type.boolean.go","storage.type.string.go","storage.type.uintptr.go","storage.type.error.go","storage.type.rune.go","constant.language.go","support.class.dart","keyword.other.documentation","storage.modifier.import.java","punctuation.definition.list.begin.markdown","punctuation.definition.quote.begin.markdown","meta.separator.markdown","entity.name.section.markdown"],settings:{foreground:"#D0A215"}},{name:"green",scope:[],settings:{foreground:"#879A39"}},{name:"cyan",scope:["markup.italic.markdown","support.type.python","variable.legacy.builtin.python","support.constant.property-value.css","storage.modifier.attribute.swift"],settings:{foreground:"#3AA99F"}},{name:"blue",scope:[],settings:{foreground:"#4385BE"}},{name:"purple",scope:["keyword.channel.go","keyword.other.platform.os.swift"],settings:{foreground:"#8B7EC8"}},{name:"magenta",scope:["punctuation.definition.heading.markdown"],settings:{foreground:"#CE5D97"}},{name:"red",scope:[],settings:{foreground:"#D14D41"}},{name:"orange",scope:[],settings:{foreground:"#DA702C"}}],Xy={name:Gy,type:qy,colors:Ky,tokenColors:Yy},Qy="Flexoki",Jy="light",Zy={"editor.background":"#FFFCF0","editor.foreground":"#100F0F","editor.hoverHighlightBackground":"#DAD8CE","editor.lineHighlightBackground":"#F2F0E5","editor.selectionBackground":"#100F0F44","editor.selectionHighlightBackground":"#100F0F44","editor.findMatchBackground":"#D0A215","editor.findMatchHighlightBackground":"#D0A215cc","editor.findRangeHighlightBackground":"#F2F0E5","editor.inactiveSelectionBackground":"#E6E4D9","editor.lineHighlightBorder":"#E6E4D9","editor.rangeHighlightBackground":"#CECDC3","notifications.background":"#E6E4D9","editorInlayHint.typeBackground":"#DAD8CE","editorInlayHint.typeForeground":"#100F0F","editorWhitespace.foreground":"#CECDC3","editorIndentGuide.background1":"#DAD8CE","editorHoverWidget.background":"#E6E4D9","editorLineNumber.activeForeground":"#100F0F","editorLineNumber.foreground":"#CECDC3","editorGutter.background":"#FFFCF0","editorGutter.modifiedBackground":"#24837B","editorGutter.addedBackground":"#66800B","editorGutter.deletedBackground":"#AF3029","editorBracketMatch.background":"#E6E4D9","editorBracketMatch.border":"#DAD8CE","editorError.foreground":"#AF3029","editorWarning.foreground":"#BC5215","editorInfo.foreground":"#205EA6","diffEditor.insertedTextBackground":"#879A3999","diffEditor.removedTextBackground":"#D14D4199","editorGroupHeader.tabsBackground":"#FFFCF0","editorGroup.border":"#DAD8CE","tab.activeBackground":"#FFFCF0","tab.inactiveBackground":"#F2F0E5","tab.inactiveForeground":"#6F6E69","tab.activeForeground":"#100F0F","tab.hoverBackground":"#DAD8CE","tab.unfocusedHoverBackground":"#DAD8CE","tab.border":"#DAD8CE","tab.activeModifiedBorder":"#AD8301","tab.inactiveModifiedBorder":"#205EA6","tab.unfocusedActiveModifiedBorder":"#D0A215","tab.unfocusedInactiveModifiedBorder":"#4385BE","editorWidget.background":"#F2F0E5","editorWidget.border":"#DAD8CE","editorSuggestWidget.background":"#FFFCF0","editorSuggestWidget.border":"#DAD8CE","editorSuggestWidget.foreground":"#100F0F","editorSuggestWidget.highlightForeground":"#6F6E69","editorSuggestWidget.selectedBackground":"#DAD8CE","peekView.border":"#DAD8CE","peekViewEditor.background":"#FFFCF0","peekViewEditor.matchHighlightBackground":"#CECDC3","peekViewResult.background":"#F2F0E5","peekViewResult.fileForeground":"#100F0F","peekViewResult.lineForeground":"#6F6E69","peekViewResult.matchHighlightBackground":"#CECDC3","peekViewResult.selectionBackground":"#E6E4D9","peekViewResult.selectionForeground":"#B7B5AC","peekViewTitle.background":"#DAD8CE","peekViewTitleDescription.foreground":"#6F6E69","peekViewTitleLabel.foreground":"#100F0F","merge.currentHeaderBackground":"#66800B","merge.currentContentBackground":"#879A39","merge.incomingHeaderBackground":"#24837B","merge.incomingContentBackground":"#3AA99F","merge.border":"#DAD8CE","merge.commonContentBackground":"#CECDC3","merge.commonHeaderBackground":"#DAD8CE","panel.background":"#FFFCF0","panel.border":"#DAD8CE","panelTitle.activeBorder":"#CECDC3","panelTitle.activeForeground":"#100F0F","panelTitle.inactiveForeground":"#6F6E69","statusBar.background":"#FFFCF0","statusBar.foreground":"#100F0F","statusBar.border":"#DAD8CE","statusBar.debuggingBackground":"#AF3029","statusBar.debuggingForeground":"#100F0F","statusBar.noFolderBackground":"#CECDC3","statusBar.noFolderForeground":"#B7B5AC","titleBar.activeBackground":"#FFFCF0","titleBar.activeForeground":"#100F0F","titleBar.inactiveBackground":"#F2F0E5","titleBar.inactiveForeground":"#6F6E69","titleBar.border":"#DAD8CE","menu.foreground":"#100F0F","menu.background":"#FFFCF0","menu.selectionForeground":"#100F0F","menu.selectionBackground":"#DAD8CE","menu.border":"#DAD8CE","editorInlayHint.foreground":"#6F6E69","editorInlayHint.background":"#DAD8CE","terminal.foreground":"#100F0F","terminal.background":"#FFFCF0","terminalCursor.foreground":"#100F0F","terminalCursor.background":"#FFFCF0","terminal.ansiRed":"#AF3029","terminal.ansiGreen":"#66800B","terminal.ansiYellow":"#AD8301","terminal.ansiBlue":"#205EA6","terminal.ansiMagenta":"#24837B","terminal.ansiCyan":"#24837B","activityBar.background":"#FFFCF0","activityBar.foreground":"#100F0F","activityBar.inactiveForeground":"#6F6E69","activityBar.activeBorder":"#100F0F","activityBar.border":"#DAD8CE","sideBar.background":"#FFFCF0","sideBar.foreground":"#100F0F","sideBar.border":"#DAD8CE","sideBarTitle.foreground":"#100F0F","sideBarSectionHeader.background":"#F2F0E5","sideBarSectionHeader.foreground":"#100F0F","sideBarSectionHeader.border":"#DAD8CE","sideBar.activeBackground":"#CECDC3","sideBar.activeForeground":"#100F0F","sideBar.hoverBackground":"#DAD8CE","sideBar.hoverForeground":"#6F6E69","sideBar.folderIcon.foreground":"#66800B","sideBar.fileIcon.foreground":"#205EA6","list.warningForeground":"#BC5215","list.errorForeground":"#AF3029","list.inactiveSelectionBackground":"#DAD8CE","list.activeSelectionBackground":"#CECDC3","list.inactiveSelectionForeground":"#100F0F","list.activeSelectionForeground":"#100F0F","list.hoverForeground":"#100F0F","list.hoverBackground":"#DAD8CE","input.background":"#F2F0E5","input.foreground":"#100F0F","input.border":"#DAD8CE","input.placeholderForeground":"#6F6E69","inputOption.activeBorder":"#DAD8CE","inputOption.activeBackground":"#E6E4D9","inputOption.activeForeground":"#100F0F","inputValidation.infoBackground":"#24837B","inputValidation.infoBorder":"#3AA99F","inputValidation.warningBackground":"#BC5215","inputValidation.warningBorder":"#DA702C","inputValidation.errorBackground":"#AF3029","inputValidation.errorBorder":"#D14D41","dropdown.background":"#F2F0E5","dropdown.foreground":"#100F0F","dropdown.border":"#DAD8CE","dropdown.listBackground":"#FFFCF0","badge.background":"#24837B","activityBarBadge.background":"#24837B","button.background":"#24837B","button.foreground":"#FFFCF0","badge.foreground":"#FFFCF0","activityBarBadge.foreground":"#FFFCF0"},ex=[{name:"plain",scope:["source","support.type.property-name.css"],settings:{foreground:"#100F0F"}},{name:"classes",scope:["entity.name.type.class"],settings:{foreground:"#BC5215"}},{name:"interfaces",scope:["entity.name.type.interface","entity.name.type"],settings:{foreground:"#AD8301"}},{name:"structs",scope:["entity.name.type.struct"],settings:{foreground:"#BC5215"}},{name:"enums",scope:["entity.name.type.enum"],settings:{foreground:"#BC5215"}},{name:"keys",scope:["meta.object-literal.key","support.type.property-name"],settings:{foreground:"#BC5215"}},{name:"methods",scope:["entity.name.function.method","meta.function.method"],settings:{foreground:"#66800B"}},{name:"functions",scope:["entity.name.function","support.function","meta.function-call.generic"],settings:{foreground:"#BC5215",fontStyle:"bold"}},{name:"variables",scope:["variable","meta.variable","variable.other.object.property"],settings:{foreground:"#100F0F"}},{name:"variablesOther",scope:["variable.other.object","variable.other.readwrite.alias"],settings:{foreground:"#66800B"}},{name:"globalVariables",scope:["variable.other.global","variable.language.this"],settings:{foreground:"#A02F6F"}},{name:"localVariables",scope:["variable.other.local"],settings:{foreground:"#E6E4D9"}},{name:"parameters",scope:["variable.parameter","meta.parameter"],settings:{foreground:"#100F0F"}},{name:"properties",scope:["variable.other.property","meta.property"],settings:{foreground:"#205EA6"}},{name:"strings",scope:["string","string.other.link","markup.inline.raw.string.markdown"],settings:{foreground:"#24837B"}},{name:"stringEscapeSequences",scope:["constant.character.escape","constant.other.placeholder"],settings:{foreground:"#100F0F"}},{name:"keywords",scope:["keyword"],settings:{foreground:"#66800B"}},{name:"keywordsControl",scope:["keyword.control.import","keyword.control.from","keyword.import"],settings:{foreground:"#AF3029"}},{name:"storageModifiers",scope:["storage.modifier","keyword.modifier","storage.type"],settings:{foreground:"#205EA6"}},{name:"comments",scope:["comment","punctuation.definition.comment"],settings:{foreground:"#6F6E69"}},{name:"docComments",scope:["comment.documentation","comment.line.documentation"],settings:{foreground:"#B7B5AC"}},{name:"numbers",scope:["constant.numeric"],settings:{foreground:"#5E409D"}},{name:"booleans",scope:["constant.language.boolean","constant.language.json"],settings:{foreground:"#AD8301"}},{name:"operators",scope:["keyword.operator"],settings:{foreground:"#AF3029"}},{name:"macros",scope:["entity.name.function.preprocessor","meta.preprocessor"],settings:{foreground:"#205EA6"}},{name:"preprocessor",scope:["meta.preprocessor"],settings:{foreground:"#A02F6F"}},{name:"urls",scope:["markup.underline.link"],settings:{foreground:"#205EA6"}},{name:"tags",scope:["entity.name.tag"],settings:{foreground:"#205EA6"}},{name:"jsxTags",scope:["support.class.component"],settings:{foreground:"#A02F6F"}},{name:"attributes",scope:["entity.other.attribute-name","meta.attribute"],settings:{foreground:"#AD8301"}},{name:"types",scope:["support.type"],settings:{foreground:"#AD8301"}},{name:"constants",scope:["variable.other.constant","variable.readonly"],settings:{foreground:"#100F0F"}},{name:"labels",scope:["entity.name.label","punctuation.definition.label"],settings:{foreground:"#A02F6F"}},{name:"namespaces",scope:["entity.name.namespace","storage.modifier.namespace","markup.bold.markdown"],settings:{foreground:"#AD8301"}},{name:"modules",scope:["entity.name.module","storage.modifier.module"],settings:{foreground:"#AF3029"}},{name:"typeParameters",scope:["variable.type.parameter","variable.parameter.type"],settings:{foreground:"#BC5215"}},{name:"exceptions",scope:["keyword.control.exception","keyword.control.trycatch"],settings:{foreground:"#A02F6F"}},{name:"decorators",scope:["meta.decorator","punctuation.decorator","entity.name.function.decorator"],settings:{foreground:"#AD8301"}},{name:"calls",scope:["variable.function"],settings:{foreground:"#100F0F"}},{name:"punctuation",scope:["punctuation","punctuation.terminator","punctuation.definition.tag","punctuation.separator","punctuation.definition.string","punctuation.section.block"],settings:{foreground:"#6F6E69"}},{name:"yellow",scope:["storage.type.numeric.go","storage.type.byte.go","storage.type.boolean.go","storage.type.string.go","storage.type.uintptr.go","storage.type.error.go","storage.type.rune.go","constant.language.go","support.class.dart","keyword.other.documentation","storage.modifier.import.java","punctuation.definition.list.begin.markdown","punctuation.definition.quote.begin.markdown","meta.separator.markdown","entity.name.section.markdown"],settings:{foreground:"#AD8301"}},{name:"green",scope:[],settings:{foreground:"#66800B"}},{name:"cyan",scope:["markup.italic.markdown","support.type.python","variable.legacy.builtin.python","support.constant.property-value.css","storage.modifier.attribute.swift"],settings:{foreground:"#24837B"}},{name:"blue",scope:[],settings:{foreground:"#205EA6"}},{name:"purple",scope:["keyword.channel.go","keyword.other.platform.os.swift"],settings:{foreground:"#5E409D"}},{name:"magenta",scope:["punctuation.definition.heading.markdown"],settings:{foreground:"#A02F6F"}},{name:"red",scope:[],settings:{foreground:"#AF3029"}},{name:"orange",scope:[],settings:{foreground:"#BC5215"}}],tx={name:Qy,type:Jy,colors:Zy,tokenColors:ex},Qi="flexoki-dark",Ji="flexoki-light",sx=Xy,rx=tx;function _u(s,r){return Object.defineProperty(s,"toString",{value:()=>r,enumerable:!1,configurable:!0}),Object.defineProperty(s,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0}),s}function Bu(s,r,t){const n=s.colors?.["editor.background"],o=s.colors?.["editor.foreground"];if(!n||!o)throw new Error(`Flexoki Shiki theme "${r}" is missing editor.background/editor.foreground`);const a=s.tokenColors??[];return{...s,name:r,type:t,fg:o,bg:n,settings:a}}const Zi=Bu(sx,Qi,"dark"),el=Bu(rx,Ji,"light");_u(Zi,Qi);_u(el,Ji);const pn={dark:Qi,light:Ji},rc=[el,Zi];let nc=!1;function zu(){nc||(yl(pn.dark,async()=>Zi),yl(pn.light,async()=>el),nc=!0)}const nx=`
|
|
13
|
+
:host {
|
|
14
|
+
font-family: var(--font-mono);
|
|
15
|
+
font-size: var(--text-code);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
:host, pre, [data-diffs], [data-code] {
|
|
19
|
+
transform: translateZ(0);
|
|
20
|
+
-webkit-transform: translateZ(0);
|
|
21
|
+
-webkit-backface-visibility: hidden;
|
|
22
|
+
backface-visibility: hidden;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
pre, [data-code] {
|
|
26
|
+
font-family: var(--font-mono);
|
|
27
|
+
font-size: var(--text-code);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
[data-code] {
|
|
31
|
+
-webkit-overflow-scrolling: touch;
|
|
32
|
+
}
|
|
33
|
+
/* Reduce hunk separator height */
|
|
34
|
+
[data-separator-content] {
|
|
35
|
+
height: 24px !important;
|
|
36
|
+
}
|
|
37
|
+
[data-expand-button] {
|
|
38
|
+
height: 24px !important;
|
|
39
|
+
width: 24px !important;
|
|
40
|
+
}
|
|
41
|
+
[data-separator-multi-button] {
|
|
42
|
+
row-gap: 0 !important;
|
|
43
|
+
}
|
|
44
|
+
[data-expand-up] {
|
|
45
|
+
height: 12px !important;
|
|
46
|
+
min-height: 12px !important;
|
|
47
|
+
max-height: 12px !important;
|
|
48
|
+
margin: 0 !important;
|
|
49
|
+
margin-top: 3px !important;
|
|
50
|
+
padding: 0 !important;
|
|
51
|
+
border-radius: 4px 4px 0 0 !important;
|
|
52
|
+
}
|
|
53
|
+
[data-expand-down] {
|
|
54
|
+
height: 12px !important;
|
|
55
|
+
min-height: 12px !important;
|
|
56
|
+
max-height: 12px !important;
|
|
57
|
+
margin: 0 !important;
|
|
58
|
+
margin-top: -3px !important;
|
|
59
|
+
padding: 0 !important;
|
|
60
|
+
border-radius: 0 0 4px 4px !important;
|
|
61
|
+
}
|
|
62
|
+
`;function ox(s,r,t){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${s}:${r.length}:${t.length}:${n.length}:${o.length}`}const oc=({original:s,modified:r,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const l=na()?.currentTheme?.metadata?.variant==="dark";zu();const d=Me.useRef(null),u=Me.useMemo(()=>{const f=ox(n,s,r);if(d.current?.key===f)return d.current.fileDiff;const p={name:n,contents:s,cacheKey:`old-${f}`},h={name:n,contents:r,cacheKey:`new-${f}`},j=ti(p,h);return d.current={key:f,fileDiff:j},j},[n,s,r,t]),m=Me.useMemo(()=>({theme:{dark:pn.dark,light:pn.light},themeType:l?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!1,enableHoverUtility:!1,unsafeCSS:nx}),[l,o,a]);return typeof window>"u"?null:e.jsx(ct,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(Nf,{fileDiff:u,options:m})})},ax=1100,ix=s=>{const{index:r,working_dir:t}=s;return r==="A"||t==="A"||r==="?"||t==="?"},ac=(s,r)=>{const t=s??0,n=r??0;return!t&&!n?null:e.jsxs("span",{className:"typography-meta flex flex-shrink-0 items-center gap-1 text-xs whitespace-nowrap",children:[t?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",t]}):null,n?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",n]}):null]})},lx=c.memo(({changedFiles:s,selectedFile:r,selectedFileEntry:t,onSelectFile:n,isMobile:o})=>{const a=c.useCallback(i=>{if(!o)return i;const l=i.lastIndexOf("/");return l>=0?i.slice(l+1):i},[o]);return s.length===0?null:e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[t?e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:a(t.path)}),ac(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Ct,{className:"size-4 opacity-50"})]})}),e.jsx(Xt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(Fu,{value:r??"",onValueChange:n,children:s.map(i=>e.jsx(Ru,{value:i.path,children:e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:a(i.path)}),e.jsx("span",{className:"ml-auto",children:ac(i.insertions,i.deletions)})]})},i.path))})})]})}),cx=c.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n})=>{const o=r.original.length>0,a=r.modified.length>0;if(!t)return e.jsx("div",{className:"absolute inset-0 hidden"});const i=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",l=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:i,children:[o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),dx=c.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=c.useMemo(()=>Hr(s)||"text",[s]);return Ou(s)?e.jsx(cx,{filePath:s,diff:r,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(oc,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})}):e.jsx("div",{className:"absolute inset-0 hidden",children:e.jsx(oc,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})})}),ux=c.memo(({directory:s,filePath:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=Ut(c.useCallback(l=>l.directories.get(s)?.diffCache.get(r)??null,[s,r])),i=c.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return i?e.jsx(dx,{filePath:r,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),mx=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=de(),{currentDirectory:n}=ft(),o=s?t.get(s)??void 0:void 0,i=r.find(l=>l.id===s)?.directory;return o?.path??i??n??void 0},fx=()=>{const{git:s}=vn(),r=mx(),{screenWidth:t,isMobile:n}=$t(),o=qi(r??null),a=Pu(r??null),i=Ut(T=>T.isLoadingStatus),{setActiveDirectory:l,fetchStatus:d,setDiff:u}=Ut(),[m,f]=c.useState(null),[p,h]=c.useState(0),[j,g]=c.useState(null),b=c.useRef(null),x=Re(T=>T.pendingDiffFile),y=Re(T=>T.setPendingDiffFile),w=Re(T=>T.diffLayoutPreference),S=Re(T=>T.diffFileLayout),v=Re(T=>T.setDiffFileLayout),N=Re(T=>T.diffWrapLines),D=Re(T=>T.setDiffWrapLines),M=n||N,C=c.useMemo(()=>{if(!a?.files)return[];const T=a.diffStats??{};return a.files.map(Z=>({...Z,insertions:T[Z.path]?.insertions??0,deletions:T[Z.path]?.deletions??0,isNew:ix(Z)})).sort((Z,E)=>Z.path.localeCompare(E.path))},[a]),k=c.useMemo(()=>m?C.find(T=>T.path===m)??null:null,[C,m]),A=c.useMemo(()=>{if(!k)return null;const T=S[k.path];if(T)return T;if(w==="inline")return"inline";if(w==="side-by-side")return"side-by-side";const Z=t<ax;return k.isNew||Z?"inline":"side-by-side"},[k,S,w,t]);c.useEffect(()=>{r&&(l(r),Ut.getState().directories.get(r)?.status||d(r,s))},[r,l,d,s]),c.useEffect(()=>{x&&(f(x),y(null))},[x,y]),c.useEffect(()=>{!m&&!x&&C.length>0&&f(C[0].path)},[C,m,x]),c.useEffect(()=>{m&&C.length>0&&(C.some(Z=>Z.path===m)||f(C[0]?.path??null))},[C,m]);const P=c.useCallback(T=>{f(T)},[]),L=(A??"side-by-side")==="side-by-side",U=Ut(c.useCallback(T=>!r||!m?null:T.directories.get(r)?.diffCache.get(m)??null,[r,m])),z=!!U,H=!!m&&!z;c.useEffect(()=>{if(g(null),!r||!m){b.current=null;return}if(U){b.current=null;return}const T=`${r}::${m}::${p}`;if(b.current===T)return;b.current=T;let Z=!1;return(async()=>{try{const E=s.getGitFileDiff(r,{path:m}),B=15e3,X=new Promise((q,oe)=>{setTimeout(()=>oe(new Error(`Timed out after ${B}ms`)),B)}),re=await Promise.race([E,X]);if(Z)return;u(r,m,{original:re.original??"",modified:re.modified??""})}catch(E){if(Z)return;const B=E instanceof Error?E.message:String(E);g(B)}})(),()=>{Z=!0,b.current===T&&(b.current=null)}},[r,m,U,s,u,p]);const V=()=>!r||C.length===0?null:C.map(T=>e.jsx(ux,{directory:r,filePath:T.path,isVisible:T.path===m,renderSideBySide:L,wrapLines:M},T.path)),J=()=>r?i&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(is,{size:16,className:"animate-spin"}),"Loading repository status…"]}):o===!1?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Not a git repository. Use the Git tab to initialize or change directories."}):C.length===0?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Working tree clean — no changes to display"}):e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[V(),H&&!z&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:j?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:j}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{g(null),h(T=>T+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(is,{size:16,className:"animate-spin"}),"Loading diff…"]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 bg-background",children:[!n&&e.jsxs("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:[e.jsx(Mi,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:i&&!a?"Loading changes…":`${C.length} ${C.length===1?"file":"files"} changed`})]}),e.jsx(lx,{changedFiles:C,selectedFile:m,selectedFileEntry:k,onSelectFile:P,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),k&&e.jsx("button",{type:"button",onClick:()=>D(!N),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${M?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:M?"Disable line wrap":"Enable line wrap",children:e.jsx(Cf,{className:"size-4"})}),k&&A&&e.jsx(Vy,{mode:A==="side-by-side"?"side-by-side":"unified",onModeChange:T=>{if(!k)return;const Z=T==="side-by-side"?"side-by-side":"inline";v(k.path,Z)}})]}),J()]})},px=()=>{const{git:s}=vn(),{currentSessionId:r,sessions:t,worktreeMetadata:n}=de(),{currentDirectory:o}=ft(),a=r?n.get(r)??void 0:void 0,l=t.find(p=>p.id===r)?.directory,d=a?.path??l??o??void 0,{setActiveDirectory:u,fetchStatus:m}=Ut(),f=$y(d??null);return c.useEffect(()=>{d&&(u(d),Ut.getState().directories.get(d)?.status||m(d,s))},[d,u,m,s]),f},hx=()=>{const s=Re(d=>d.setSessionSwitcherOpen),r=Re(d=>d.toggleSidebar),{isMobile:t}=$t(),[n,o]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const i=c.useCallback(()=>{t?s(!0):r()},[t,s,r]),l="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground";return t||!n||!a?null:e.jsx("div",{className:"fixed top-[0.375rem] left-[5.25rem] z-[9999]",style:{pointerEvents:"auto","--padding-scale":"1"},children:e.jsx("button",{type:"button",onClick:i,"aria-label":"Open sessions",className:l,children:e.jsx(Yo,{className:"h-5 w-5"})})})},ic=()=>{const s=Re(E=>E.setSessionSwitcherOpen),r=Re(E=>E.toggleSidebar),t=Re(E=>E.setSettingsDialogOpen),n=Re(E=>E.toggleCommandPalette),o=Re(E=>E.toggleHelpDialog),a=Re(E=>E.isSidebarOpen),i=Re(E=>E.sidebarWidth),l=Re(E=>E.activeMainTab),d=Re(E=>E.setActiveMainTab),{getCurrentModel:u}=at(),m=de(E=>E.getContextUsage),{isMobile:f}=$t(),p=px(),h=ta(E=>E.available),j=c.useRef(null),[g,b]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Me.useEffect(()=>{if(typeof window>"u")return;const E=typeof window.opencodeDesktop<"u";b(E)},[]);const y=u(),w=y&&typeof y.limit=="object"&&y.limit!==null?y.limit:null,S=w&&typeof w.context=="number"?w.context:0,v=w&&typeof w.output=="number"?w.output:0,N=m(S,v),D=Re(E=>E.isSessionSwitcherOpen),M=c.useCallback(()=>{if(typeof document>"u")return;const E=document.activeElement;if(!E)return;const B=E.tagName;(B==="INPUT"||B==="TEXTAREA"||B==="SELECT"||E.isContentEditable)&&E.blur()},[]),C=c.useCallback(()=>{if(f){M(),s(!D);return}r()},[M,f,D,s,r]),k=c.useCallback(()=>{f&&M(),s(!1),t(!0)},[M,f,s,t]),A="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground",P=c.useMemo(()=>g&&x?a?"pl-0":"pl-[8.0rem]":"pl-3",[g,x,a]),L=c.useCallback(()=>{if(typeof document>"u")return;const E=j.current?.getBoundingClientRect().height;E&&document.documentElement.style.setProperty("--oc-header-height",`${E}px`)},[]);Me.useEffect(()=>{if(typeof window>"u")return;L();const E=j.current;if(!E||typeof ResizeObserver>"u")return()=>{};const B=new ResizeObserver(()=>{L()});return B.observe(E),window.addEventListener("resize",L),window.addEventListener("orientationchange",L),()=>{B.disconnect(),window.removeEventListener("resize",L),window.removeEventListener("orientationchange",L)}},[L]),Me.useEffect(()=>{L()},[L,f]);const U=c.useCallback(async E=>{if(!E.target.closest("button, a, input, select, textarea")&&E.button===0&&g)try{const{getCurrentWindow:B}=await ns(async()=>{const{getCurrentWindow:re}=await import("./vendor-.bun-BEzqubWg.js").then(q=>q.co);return{getCurrentWindow:re}},__vite__mapDeps([0,1]));await B().startDragging()}catch(B){console.error("Failed to start window dragging:",B)}},[g]),z=c.useCallback(async E=>{if(E.button===0&&g)try{const{getCurrentWindow:B}=await ns(async()=>{const{getCurrentWindow:re}=await import("./vendor-.bun-BEzqubWg.js").then(q=>q.co);return{getCurrentWindow:re}},__vite__mapDeps([0,1]));await B().startDragging()}catch(B){console.error("Failed to start window dragging:",B)}},[g]),H=c.useMemo(()=>[{id:"chat",label:"Chat",icon:Mf},{id:"diff",label:"Diff",icon:er,badge:!f&&p>0?p:void 0},{id:"terminal",label:"Terminal",icon:Sr},{id:"git",label:"Git",icon:Ft,showDot:f&&p>0}],[p,f]);Me.useEffect(()=>{const E=B=>{if(bs(B)&&!B.shiftKey&&!B.altKey){const X=parseInt(B.key,10);X>=1&&X<=H.length&&(B.preventDefault(),d(H[X-1].id))}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[H,d]);const V=(E,B)=>{const X=l===E.id,re=E.icon,q=E.id==="chat",oe=E.id==="git";return e.jsxs(c.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(E.id),onMouseDown:X?z:void 0,className:R("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",X?"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",X?"text-foreground":"text-muted-foreground",X&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",X&&q&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",q&&!(g&&x&&a)&&"border-l",oe&&"border-r",q&&!f&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...X&&q&&a?{"--sidebar-w":g&&x?`${i}px`:"64px"}:{},...q&&!(g&&x&&a)||oe?{borderColor:"var(--interactive-border)"}:{}},"aria-label":E.label,"aria-selected":X,role:"tab",children:[f?e.jsx(re,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(re,{size:16}),e.jsx("span",{className:"header-tab-label",children:E.label})]}),q&&!f&&N&&N.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(mi,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact"})}),E.badge!==void 0&&E.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:E.badge})]}),!B&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},E.id)},J=()=>e.jsxs("div",{onMouseDown:U,className:R("app-region-drag relative flex h-12 select-none items-center",P),role:"tablist","aria-label":"Main navigation",children:[!(g&&x)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:C,"aria-label":"Open sessions",className:`${A} mr-2.5`,children:e.jsx(Yo,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:H.map((E,B)=>V(E,B===H.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:A,children:e.jsx($r,{className:"h-5 w-5"})})}),e.jsx(tt,{children:e.jsxs("p",{children:["Command Palette (",Gt(),"+K)"]})})]}),e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:A,children:e.jsx(cn,{className:"h-5 w-5"})})}),e.jsx(tt,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Gt(),"+.)"]})})]})]})]}),T=()=>e.jsxs("div",{className:"app-region-drag relative flex items-center justify-between gap-2 px-3 py-2 select-none",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:C,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open sessions",children:e.jsx(Df,{className:"h-5 w-5"})}),N&&N.totalTokens>0&&l==="chat"&&e.jsx(mi,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact",isMobile:!0})]}),e.jsxs("div",{className:"app-region-no-drag flex items-center gap-1.5",children:[e.jsx("div",{className:"flex items-center",role:"tablist","aria-label":"Main navigation",children:H.map(E=>{const B=l===E.id,X=E.icon;return e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{f&&M(),d(E.id)},"aria-label":E.label,"aria-selected":B,role:"tab",className:R(A,"relative",B&&"text-foreground"),children:[e.jsx(X,{className:"h-5 w-5"}),E.badge!==void 0&&E.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:E.badge}),E.showDot&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),e.jsx(tt,{children:e.jsx("p",{children:E.label})})]},E.id)})}),e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:k,"aria-label":"Open settings",className:R(A,"relative"),children:[e.jsx(Rr,{className:"h-5 w-5"}),h&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Update available"})]})}),e.jsx(tt,{children:e.jsx("p",{children:h?"Settings (Update available)":"Settings"})})]})]})]}),Z=R("header-safe-area border-b relative z-10",g?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:j,className:Z,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:f?T():J()})};function tl({className:s,...r}){return e.jsx("div",{"data-slot":"card",className:R("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",s),...r})}function Wu({className:s,...r}){return e.jsx("div",{"data-slot":"card-header",className:R("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",s),...r})}function Hu({className:s,...r}){return e.jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",s),...r})}function Uu({className:s,...r}){return e.jsx("div",{"data-slot":"card-content",className:R("px-6",s),...r})}class rs extends c.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:e.jsxs(tl,{className:"w-full max-w-md",children:[e.jsx(Wu,{className:"text-center",children:e.jsxs(Hu,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(si,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(Uu,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The application encountered an unexpected error. This has been logged for debugging."}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(ke,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(ws,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let ao=0;function ds({...s}){return e.jsx(Af,{"data-slot":"dialog",...s})}function gx({...s}){return e.jsx(Pf,{"data-slot":"dialog-portal",...s})}const Vu=Me.forwardRef(({className:s,...r},t)=>(Me.useEffect(()=>(ao+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{ao=Math.max(0,ao-1),ao===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx($d,{ref:t,"data-slot":"dialog-overlay",className:R("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",s),...r})));Vu.displayName=$d.displayName;function us({className:s,children:r,showCloseButton:t=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(gx,{"data-slot":"dialog-portal",children:[e.jsx(Vu,{className:"rounded-none"}),e.jsxs(Ef,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:R("bg-background text-foreground fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border p-6 shadow-none overflow-hidden pwa-dialog-content",s),...o,children:[r,t&&e.jsxs(If,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(Lt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function fs({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:R("flex flex-col gap-2 text-center sm:text-left",s),...r})}function Ws({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:R("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",s),...r})}function ps({className:s,...r}){return e.jsx(Tf,{"data-slot":"dialog-title",className:R("typography-markdown leading-none font-semibold text-foreground",s),...r})}function ys({className:s,...r}){return e.jsx(Ff,{"data-slot":"dialog-description",className:R("text-muted-foreground typography-ui-label",s),...r})}const lc="https://github.com/btriapitsyn/openchamber/releases";async function yx(){try{const s=await fetch("/api/openchamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return s.ok?{success:!0}:{success:!1,error:(await s.json().catch(()=>({}))).error||`Server error: ${s.status}`}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Failed to install update"}}}async function xx(s=30,r=2e3){for(let t=0;t<s;t++){try{if((await fetch("/health",{method:"GET"})).ok)return!0}catch{}await new Promise(n=>setTimeout(n,r))}return!1}const fi=({open:s,onOpenChange:r,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:l,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Me.useState(!1),[p,h]=Me.useState("idle"),[j,g]=Me.useState(null),b=t?.version?`${lc}/tag/v${t.version}`:lc,x=a?.total?Math.round(a.downloaded/a.total*100):0,y=u==="web",w=t?.updateCommand||"openchamber update";Me.useEffect(()=>{s||(h("idle"),g(null))},[s]);const S=async()=>{try{await navigator.clipboard.writeText(w),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},v=Me.useCallback(async()=>{h("updating"),g(null);const D=await yx();if(!D.success){h("error"),g(D.error||"Update failed");return}h("restarting"),await new Promise(C=>setTimeout(C,2e3)),h("reconnecting"),await xx()?window.location.reload():(h("error"),g("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),N=p!=="idle"&&p!=="error";return e.jsx(ds,{open:s,onOpenChange:N?void 0:r,children:e.jsxs(us,{className:"max-w-md",children:[e.jsx(fs,{children:e.jsxs(ps,{className:"flex items-center gap-2",children:[e.jsx(Rf,{className:"h-5 w-5 text-primary"}),p==="restarting"||p==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(t?.currentVersion||t?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[t?.currentVersion&&e.jsx("span",{className:"font-mono",children:t.currentVersion}),t?.currentVersion&&t?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),t?.version&&e.jsx("span",{className:"font-mono text-primary",children:t.version})]}),y&&N&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xo,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"text-sm",children:[p==="updating"&&"Installing update...",p==="restarting"&&"Server restarting...",p==="reconnecting"&&"Waiting for server..."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),t?.body&&!N&&e.jsx(ct,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:t.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((D,M)=>/^\d+\.\d+\.\d+$/.test(D.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",D.trim(),`
|
|
63
|
+
`]},M):D.replace(/^- /gm,"• ").trim()+`
|
|
64
|
+
|
|
65
|
+
`)})}),y&&p==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Of,{className:"h-4 w-4"}),e.jsx("span",{children:"Or update via terminal:"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 px-3 py-2 bg-muted rounded-md font-mono text-sm text-foreground overflow-x-auto",children:w}),e.jsx("button",{onClick:S,className:R("flex items-center justify-center p-2 rounded-md","text-muted-foreground hover:text-foreground hover:bg-accent","transition-colors",m&&"text-primary"),title:m?"Copied!":"Copy command",children:m?e.jsx(Ot,{className:"h-4 w-4"}):e.jsx($f,{className:"h-4 w-4"})})]})]}),!y&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[x,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${x}%`}})})]}),(i||j)&&e.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-sm text-destructive",children:i||j})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:b,target:"_blank",rel:"noopener noreferrer",className:R("flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md","text-sm text-muted-foreground","hover:text-foreground hover:bg-accent","transition-colors"),children:[e.jsx(Po,{className:"h-4 w-4"}),"GitHub"]}),!y&&!o&&!n&&e.jsxs("button",{onClick:l,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(dn,{className:"h-4 w-4"}),"Download Update"]}),!y&&n&&e.jsxs("button",{disabled:!0,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(xo,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!y&&o&&e.jsxs("button",{onClick:d,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(ws,{className:"h-4 w-4"}),"Restart to Update"]}),y&&!N&&e.jsxs("button",{onClick:v,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(dn,{className:"h-4 w-4"}),"Update Now"]}),y&&N&&e.jsxs("button",{disabled:!0,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(xo,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},cc=264,dc=200,uc=500,bx=40,mc="openchamber:check-for-updates",wx=({isOpen:s,isMobile:r,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:i}=Re(),[l,d]=c.useState(!1),u=c.useRef(0),m=c.useRef(n||cc),[f,p]=c.useState(!1),h=ta(),j=c.useRef(!1),g=h.checkForUpdates,{available:b,downloaded:x,checking:y}=h,[w,S]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),v=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const k=typeof window.opencodeDesktop<"u";S(k)},[]),c.useEffect(()=>{if(typeof window>"u")return;const k=()=>{typeof window.opencodeDesktop<"u"&&(j.current=!0,g())};return window.addEventListener(mc,k),()=>{window.removeEventListener(mc,k)}},[g]),c.useEffect(()=>{j.current&&(y||(b||x?p(!0):se.success("No updates available",{description:"You are running the latest version."}),j.current=!1))},[b,x,y]),c.useEffect(()=>{if(r||!l)return;const k=P=>{const L=P.clientX-u.current,U=Math.min(uc,Math.max(dc,m.current+L));o(U)},A=()=>{d(!1)};return window.addEventListener("pointermove",k),window.addEventListener("pointerup",A,{once:!0}),()=>{window.removeEventListener("pointermove",k),window.removeEventListener("pointerup",A)}},[r,l,o]),c.useEffect(()=>{r&&l&&d(!1)},[r,l]);const N=c.useCallback(async k=>{if(k.button===0&&w)try{const{getCurrentWindow:A}=await ns(async()=>{const{getCurrentWindow:L}=await import("./vendor-.bun-BEzqubWg.js").then(U=>U.co);return{getCurrentWindow:L}},__vite__mapDeps([0,1]));await A().startDragging()}catch(A){console.error("Failed to start window dragging from sidebar:",A)}},[w]);if(r)return null;const D=s?Math.min(uc,Math.max(dc,n||cc)):0,M=w&&v,C=k=>{s&&(d(!0),u.current=k.clientX,m.current=D,k.preventDefault())};return e.jsxs("aside",{className:R("relative flex h-full overflow-hidden border-r",w?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",l?"transition-none":"",!s&&"border-r-0"),style:{width:`${D}px`,minWidth:`${D}px`,maxWidth:`${D}px`,pointerEvents:s?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!s||D===0,children:[s&&e.jsx("div",{className:R("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",l?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:C,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:R("relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out",!s&&"pointer-events-none select-none opacity-0"),style:{width:`${D}px`,overflowX:"hidden"},"aria-hidden":!s,children:[M&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${bx}px`},onMouseDown:N,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(rs,{children:t})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:R("flex items-center gap-2 rounded-md px-3 py-2","text-sm font-semibold text-muted-foreground","hover:text-foreground","transition-colors"),children:[e.jsx(Rr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),b||x?e.jsxs("button",{onClick:()=>p(!0),className:R("flex items-center gap-1.5 rounded-md px-2.5 py-1.5","text-xs font-medium","bg-primary/10 text-primary","hover:bg-primary/20","transition-colors"),children:[e.jsx(dn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!w&&e.jsxs(nt,{children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{onClick:()=>i(!0),className:R("flex items-center justify-center rounded-md p-1.5","text-muted-foreground","hover:text-foreground hover:bg-muted/50","transition-colors"),children:e.jsx(as,{className:"h-4 w-4"})})}),e.jsx(tt,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(fi,{open:f,onOpenChange:p,info:h.info,downloading:h.downloading,downloaded:h.downloaded,progress:h.progress,error:h.error,onDownload:h.downloadUpdate,onRestart:h.restartToUpdate,runtimeType:h.runtimeType})]})]})};function Gu({className:s,...r}){return e.jsx(Lr,{"data-slot":"command",className:R("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",s),...r})}function vx({title:s="Command Palette",description:r="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(ds,{...a,children:[e.jsxs(fs,{className:"sr-only",children:[e.jsx(ps,{children:s}),e.jsx(ys,{children:r})]}),e.jsx(us,{className:R("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Gu,{className:"[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-input]]:h-8 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-item]]:typography-meta",children:t})})]})}function qu({className:s,...r}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(ur,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Lr.Input,{"data-slot":"command-input",className:R("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",s),...r})]})}function Ku({className:s,children:r,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(ct,{as:Lr.List,"data-slot":"command-list",outerClassName:"max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0",className:R("scroll-py-1 overflow-x-hidden h-full min-h-0",s),scrollbarClassName:t??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:n??!0,...o,children:r})}function Yu({...s}){return e.jsx(Lr.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...s})}function an({className:s,...r}){return e.jsx(Lr.Group,{"data-slot":"command-group",className:R("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium",s),...r})}function Wo({className:s,...r}){return e.jsx(Lr.Separator,{"data-slot":"command-separator",className:R("bg-border -mx-1 h-px",s),...r})}function es({className:s,...r}){return e.jsx(Lr.Item,{"data-slot":"command-item",className:R("data-[selected=true]:bg-muted hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",s),...r})}function rr({className:s,...r}){const t=a=>{const i=a.trim().toLowerCase();return i==="ctrl"||i==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?e.jsx($r,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(Gn,{className:"size-3.5"}):e.jsx("span",{className:"text-xs font-medium",children:a})},n=typeof r.children=="string"?r.children:"",o=n?n.split("+").map(a=>a.trim()).filter(Boolean):[];return e.jsx("span",{"data-slot":"command-shortcut",className:R("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",s),...r,children:o.length>0?o.map((a,i)=>e.jsxs(Me.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):r.children})}const fc=["artful","bionic","cosmic","disco","focal","groovy","jammy","kinetic","lunar","noble","bold","brave","calm","eager","gentle","happy","keen","lively","merry","swift","warm","wise","bright","clever","daring","agile","crisp","fresh","lucid","quick","sharp","vivid","zealous"],pc=["aardvark","beaver","chipmunk","dolphin","falcon","gopher","hedgehog","jackal","koala","lemur","mongoose","narwhal","otter","pangolin","quokka","raccoon","salamander","toucan","walrus","yak","zebra","badger","condor","dingo","egret","ferret","gecko","heron","iguana"];function jx(){const s=fc[Math.floor(Math.random()*fc.length)],r=pc[Math.floor(Math.random()*pc.length)];return`${s}-${r}`}function hc(s){const r=jx();return s&&s.trim()?`${s.trim().replace(/\/+$/,"")}/${r}`:r}async function Sx(s,r,t=10){let n;try{const o=await Wi(s);n=new Set(o?.all??[])}catch{return hc(r)}for(let o=0;o<t;o++){const a=hc(r);if(!n.has(a))return a}return null}const kx=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let Ia=!1;async function oa(){if(Ia)return null;const s=It.getState().getActiveProject();if(!s?.path)return se.error("No active project",{description:"Please select a project first."}),null;const r=s.path;let t=!1;try{t=await Wr(r)}catch{}if(!t)return se.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Ia=!0,_s("Creating new worktree session...");try{const n=s.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,i=await Sx(r,o);if(!i)return se.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const l=kx(i),u=await ju({projectDirectory:r,worktreeSlug:l,branch:i,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await Hi(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=de.getState(),h=await p.createSession(void 0,u.path);if(!h)return await Zg({projectDirectory:r,path:u.path,force:!0}).catch(()=>{}),se.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const j=at.getState(),g=j.agents;p.initializeNewOpenChamberSession(h.id,g),p.setSessionDirectory(h.id,u.path),p.setWorktreeMetadata(h.id,f);try{const y=j.getVisibleAgents();let w;if(j.settingsDefaultAgent){const S=y.find(v=>v.name===j.settingsDefaultAgent);S&&(w=S.name)}if(w||(w=y.find(S=>S.name==="build")?.name||y[0]?.name),w){j.setAgent(w),vt.getState().saveSessionAgentSelection(h.id,w);const S=j.settingsDefaultModel;if(S){const v=S.split("/");if(v.length===2){const[N,D]=v;j.getModelMetadata(N,D)&&(vt.getState().saveSessionModelSelection(h.id,N,D),vt.getState().saveAgentModelForSession(h.id,w,N,D))}}}}catch{}ft.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const x=(await Yn(r)).filter(y=>y.trim().length>0);return x.length>0?(se.success("Worktree created",{description:`Branch: ${i}. Running ${x.length} setup command${x.length===1?"":"s"}...`}),ku(u.path,r,x).then(y=>{if(y.success)se.success("Setup commands completed",{description:`All ${y.results.length} command${y.results.length===1?"":"s"} succeeded.`});else{const w=y.results.filter(v=>!v.success),S=y.results.filter(v=>v.success);se.error("Setup commands failed",{description:`${w.length} of ${y.results.length} command${y.results.length===1?"":"s"} failed.`+(S.length>0?` ${S.length} succeeded.`:"")})}}).catch(()=>{se.error("Setup commands failed",{description:"Could not execute setup commands."})})):se.success("Worktree created",{description:`Branch: ${i}`}),h}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return se.error("Failed to create worktree",{description:o}),null}finally{xs(),Ia=!1}}const Nx=()=>{const{isCommandPaletteOpen:s,setCommandPaletteOpen:r,setHelpDialogOpen:t,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:i,toggleSidebar:l}=Re(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=de(),f=at(z=>z.settingsAutoCreateWorktree),{currentDirectory:p}=ft(),{themeMode:h,setThemeMode:j}=Ur(),g=()=>{r(!1)},b=async()=>{n("chat"),a(!1),d(),g()},x=z=>{u(z),g()},y=z=>{j(z),g()},w=()=>{t(!0),g()},S=()=>{g(),oa()},{isMobile:v}=$t(),N=()=>{if(v){const{isSessionSwitcherOpen:z}=Re.getState();a(!z)}else l();g()},D=()=>{n("diff"),g()},M=()=>{n("git"),g()},C=()=>{n("terminal"),g()},k=()=>{o(!0),g()},A=()=>{Pn(),g()},P=()=>{i(!0),g()},L=m(p??""),U=c.useMemo(()=>L.slice(0,5),[L]);return e.jsxs(vx,{open:s,onOpenChange:r,children:[e.jsx(qu,{placeholder:"Type a command or search..."}),e.jsxs(Ku,{children:[e.jsx(Yu,{children:"No results found."}),e.jsxs(an,{heading:"Actions",children:[e.jsxs(es,{onSelect:N,children:[e.jsx(Yo,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(rr,{children:[Gt()," + L"]})]}),e.jsxs(es,{onSelect:b,children:[e.jsx(_t,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(rr,{children:f?`Shift + ${Gt()} + N`:`${Gt()} + N`})]}),e.jsxs(es,{onSelect:S,children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(rr,{children:f?`${Gt()} + N`:`Shift + ${Gt()} + N`})]}),e.jsxs(es,{onSelect:w,children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(rr,{children:[Gt()," + ."]})]}),e.jsxs(es,{onSelect:D,children:[e.jsx(er,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(rr,{children:[Gt()," + 2"]})]}),e.jsxs(es,{onSelect:C,children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(rr,{children:[Gt()," + 3"]})]}),e.jsxs(es,{onSelect:M,children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(rr,{children:[Gt()," + 4"]})]}),e.jsxs(es,{onSelect:P,children:[e.jsx(tr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(rr,{children:[Gt()," + T"]})]}),e.jsxs(es,{onSelect:k,children:[e.jsx(Rr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(rr,{children:[Gt()," + ,"]})]}),e.jsxs(es,{onSelect:A,children:[e.jsx(ws,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Wo,{}),e.jsxs(an,{heading:"Theme",children:[e.jsxs(es,{onSelect:()=>y("light"),children:[e.jsx(Lf,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx(Ot,{className:"ml-auto h-4 w-4"})]}),e.jsxs(es,{onSelect:()=>y("dark"),children:[e.jsx(_f,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx(Ot,{className:"ml-auto h-4 w-4"})]}),e.jsxs(es,{onSelect:()=>y("system"),children:[e.jsx(Ld,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx(Ot,{className:"ml-auto h-4 w-4"})]})]}),U.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Wo,{}),e.jsx(an,{heading:"Recent Sessions",children:U.map(z=>e.jsxs(es,{onSelect:()=>x(z.id),children:[e.jsx(Di,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:z.title||"Untitled Session"})]},z.id))})]})]})]})},Cx=(s,r)=>{const t=s.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(Xo,{className:"h-3.5 w-3.5"},`ctrl-${r}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx($r,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:s.trim()},`key-${r}`)},Mx=s=>{const r=s.split("+").map(t=>t.trim()).filter(Boolean);return r.length===0?s.trim():r.map((t,n)=>e.jsxs(c.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),Cx(t,n)]},`${t}-${n}`))},Dx=()=>{const{isHelpDialogOpen:s,setHelpDialogOpen:r}=Re(),t=at(a=>a.settingsAutoCreateWorktree),n=Gt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:$r},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:cn},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:Yo},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:xn}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:t?"Create new session in worktree":"Create New Session",icon:t?Ft:_t},{keys:[`Shift + ${n} + N`],description:t?"Create New Session":"Create new session in worktree",icon:t?_t:Ft},{keys:[`${n} + I`],description:"Focus Chat Input",icon:_d},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:un}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:Bf},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:er},{keys:[`${n} + 3`],description:"Open Terminal",icon:Sr},{keys:[`${n} + 4`],description:"Open Git Panel",icon:Ft},{keys:[`${n} + T`],description:"Open Timeline",icon:tr},{keys:[`${n} + ,`],description:"Open Settings",icon:Rr}]}];return e.jsx(ds,{open:s,onOpenChange:r,children:e.jsxs(us,{className:"max-w-2xl",children:[e.jsxs(fs,{children:[e.jsxs(ps,{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(ys,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsx("div",{className:"space-y-4 mt-3",children:o.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:a.category}),e.jsx("div",{className:"space-y-1",children:a.items.map((i,l)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.icon&&e.jsx(i.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:i.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(i.keys)?i.keys:i.keys.split(" / ")).map((d,u)=>e.jsxs(c.Fragment,{children:[u>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:Mx(d)})]},`${d}-${u}`))})]},l))})]},a.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(cn,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("p",{className:"font-medium mb-1",children:"Pro Tips:"}),e.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[e.jsxs("li",{children:["• Use Command Palette (",n," + K) to quickly access all actions"]}),e.jsx("li",{children:"• The 5 most recent sessions appear in the Command Palette"}),e.jsx("li",{children:"• Theme cycling remembers your preference across sessions"})]})]})]})})]})})},Pa=new Set,Ta=new Set,Fa=new Set,hn={onDeleteRequest(s){return Pa.add(s),()=>{Pa.delete(s)}},requestDelete(s){!s.sessions.length&&s.mode!=="worktree"||Pa.forEach(r=>r(s))},onCreateRequest(s){return Ta.add(s),()=>{Ta.delete(s)}},requestCreate(s){const r=s??{};Ta.forEach(t=>t(r))},onDirectoryRequest(s){return Fa.add(s),()=>{Fa.delete(s)}},requestDirectoryDialog(){Fa.forEach(s=>s())}};function Xu(s){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...s,children:e.jsx("path",{d:"M232.49,192.49l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,0,1,17-17L180,187V141L128,89,76,141V187l11.51-11.52a12,12,0,0,1,17,17l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,1,1,17-17L52,187V136a12,12,0,0,1,3.51-8.49L116,67V24a12,12,0,0,1,24,0V67l60.49,60.48A12,12,0,0,1,204,136v51l11.51-11.52a12,12,0,0,1,17,17Z",transform:"rotate(180 128 128)"})})}const gc="oc.sessions.projectCollapse",yc="oc.sessions.expandedParents",xc=s=>{const r=new Date(s),t=new Date,n=(i,l)=>i.getFullYear()===l.getFullYear()&&i.getMonth()===l.getMonth()&&i.getDate()===l.getDate(),o=new Date(t);return o.setDate(t.getDate()-1),n(r,t)?"Today":n(r,o)?"Yesterday":r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},Gs=s=>{if(!s)return null;const r=s.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},bc=s=>s.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),Ax=({id:s,projectLabel:r,projectDescription:t,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:i,isDesktopRuntime:l,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:h,onOpenMultiRunLauncher:j,onClose:g,sentinelRef:b,children:x})=>{const{attributes:y,listeners:w,setNodeRef:S,isDragging:v}=Zf({id:s});return e.jsxs("div",{ref:S,className:R("relative",v&&"opacity-40"),children:[l&&e.jsx("div",{ref:b,"data-project-id":s,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("div",{className:R("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b",!l&&"bg-sidebar"),style:{backgroundColor:l?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:i?"var(--color-border)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...y,children:[e.jsxs(nt,{delayDuration:1500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...w,className:"flex-1 min-w-0 flex items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-sm cursor-grab active:cursor-grabbing",children:e.jsx("span",{className:R("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(tt,{side:"right",sideOffset:8,children:t})]}),e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",m?"opacity-70":"opacity-0 group-hover/project:opacity-100"),"aria-label":"Project menu",onClick:N=>N.stopPropagation(),children:e.jsx(kr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Xt,{align:"end",className:"min-w-[180px]",children:[a&&!u&&e.jsxs(jt,{onClick:j,children:[e.jsx(Xu,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(jt,{onClick:g,className:"text-destructive focus:text-destructive",children:[e.jsx(Lt,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),e.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),h()},className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground flex-shrink-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"New session",children:e.jsx(_t,{className:"h-4 w-4"})})]})}),x]})},Ex=({projectLabel:s,isActiveProject:r})=>e.jsx("div",{className:"bg-sidebar border border-border rounded-md shadow-lg px-2 py-1.5",style:{width:"max-content",maxWidth:"280px"},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:R("typography-ui font-semibold truncate",r?"text-primary":"text-foreground"),children:s}),e.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground ml-auto",children:e.jsx(_t,{className:"h-4 w-4"})})]})}),pi=({mobileVariant:s=!1,onSessionSelected:r,allowReselect:t=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,i]=c.useState(null),[l,d]=c.useState(""),[u,m]=c.useState(null),f=c.useRef(null),[p,h]=c.useState(new Set),[j,g]=c.useState(()=>new Map),b=c.useRef(new Set),x=c.useMemo(()=>cs(),[]),[y,w]=c.useState(new Set),[S,v]=c.useState(new Map),[N,D]=c.useState(new Set),[M,C]=c.useState(null),[k,A]=c.useState(null),[P,L]=c.useState(new Set),U=c.useRef(new Map),z=c.useRef(0),H=ft(Q=>Q.homeDirectory),V=ft(Q=>Q.currentDirectory),J=ft(Q=>Q.setDirectory),T=It(Q=>Q.projects),Z=It(Q=>Q.activeProjectId),E=It(Q=>Q.addProject),B=It(Q=>Q.removeProject),X=It(Q=>Q.setActiveProject),re=It(Q=>Q.setActiveProjectIdOnly),q=It(Q=>Q.reorderProjects),oe=Re(Q=>Q.setActiveMainTab),ye=Re(Q=>Q.setSessionSwitcherOpen),I=Re(Q=>Q.openMultiRunLauncher),F=at(Q=>Q.settingsAutoCreateWorktree),W=de(Q=>Q.sessions),O=de(Q=>Q.sessionsByDirectory),_=de(Q=>Q.currentSessionId),ee=de(Q=>Q.setCurrentSession),ue=de(Q=>Q.updateSessionTitle),me=de(Q=>Q.shareSession),pe=de(Q=>Q.unshareSession),He=de(Q=>Q.sessionMemoryState),Y=de(Q=>Q.sessionActivityPhase),le=de(Q=>Q.permissions),te=de(Q=>Q.worktreeMetadata),ne=de(Q=>Q.availableWorktreesByProject),K=de(Q=>Q.getSessionsByDirectory),ie=de(Q=>Q.openNewSessionDraft),[ce,ae]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");c.useEffect(()=>{try{const Q=x.getItem(yc);if(Q){const xe=JSON.parse(Q);Array.isArray(xe)&&h(new Set(xe.filter(Ie=>typeof Ie=="string")))}const be=x.getItem(gc);if(be){const xe=JSON.parse(be);Array.isArray(xe)&&w(new Set(xe.filter(Ie=>typeof Ie=="string")))}}catch{}},[x]),c.useEffect(()=>{typeof window>"u"||ae(typeof window.opencodeDesktop<"u")},[]);const $=c.useMemo(()=>[...W].sort((Q,be)=>(be.time?.created||0)-(Q.time?.created||0)),[W]);c.useEffect(()=>{let Q=!1;const be=T.map(xe=>({id:xe.id,path:Gs(xe.path)})).filter(xe=>!!xe.path);return v(new Map),be.length===0?()=>{Q=!0}:(be.forEach(xe=>{Wr(xe.path).then(Ie=>{Q||v($e=>{const Ue=new Map($e);return Ue.set(xe.id,Ie),Ue})}).catch(()=>{Q||v(Ie=>{const $e=new Map(Ie);return $e.set(xe.id,null),$e})})}),()=>{Q=!0})},[T]);const we=c.useMemo(()=>{const Q=new Map;return $.forEach(be=>{const xe=be.parentID;xe&&Q.set(be.id,xe)}),Q},[$]),fe=c.useMemo(()=>{const Q=new Map;return $.forEach(be=>{const xe=be.parentID;if(!xe)return;const Ie=Q.get(xe)??[];Ie.push(be),Q.set(xe,Ie)}),Q.forEach(be=>be.sort((xe,Ie)=>(Ie.time?.created||0)-(xe.time?.created||0))),Q},[$]);c.useEffect(()=>{_&&h(Q=>{const be=new Set(Q);let xe=we.get(_)||null,Ie=!1;for(;xe;)be.has(xe)||(be.add(xe),Ie=!0),xe=we.get(xe)||null;return Ie?be:Q})},[_,we]),c.useEffect(()=>{const Q=new Set;$.forEach(be=>{const xe=Gs(be.directory??null);xe&&Q.add(xe)}),T.forEach(be=>{const xe=Gs(be.path);xe&&Q.add(xe)}),Q.forEach(be=>{const xe=j.get(be);xe&&xe!=="unknown"||b.current.has(be)||(b.current.add(be),De.listLocalDirectory(be).then(()=>{g(Ie=>{const $e=new Map(Ie);return $e.get(be)==="exists"?Ie:($e.set(be,"exists"),$e)})}).catch(()=>{g(Ie=>{const $e=new Map(Ie);return $e.get(be)==="missing"?Ie:($e.set(be,"missing"),$e)})}).finally(()=>{b.current.delete(be)}))})},[$,T,j]),c.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const ve=e.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-ui-label font-semibold",children:"No sessions yet"}),e.jsx("p",{className:"typography-meta mt-1",children:"Create your first session to start coding."})]}),Le=c.useCallback((Q,be,xe,Ie)=>{if(!xe){if(Ie&&Ie!==Z&&re(Ie),be&&be!==V&&J(be,{showOverlay:!1}),s&&(oe("chat"),ye(!1)),!t&&Q===_){r?.(Q);return}ee(Q),r?.(Q)}},[Z,t,V,_,s,r,oe,re,ee,J,ye]),Ge=c.useCallback(async()=>{a&&l.trim()&&(await ue(a,l.trim()),i(null),d(""))},[a,l,ue]),Te=c.useCallback(()=>{i(null),d("")},[]),Pe=c.useCallback(async Q=>{const be=await me(Q.id);be&&be.share?.url?se.success("Session shared",{description:"You can copy the link from the menu."}):se.error("Unable to share session")},[me]),Ve=c.useCallback((Q,be)=>{navigator.clipboard.writeText(Q).then(()=>{m(be),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{se.error("Failed to copy URL")})},[]),pt=c.useCallback(async Q=>{await pe(Q)?se.success("Session unshared"):se.error("Unable to unshare session")},[pe]),et=c.useCallback(Q=>{const be=[],xe=Ie=>{(fe.get(Ie)??[]).forEach(Ue=>{be.push(Ue),xe(Ue.id)})};return xe(Q),be},[fe]),wt=de(Q=>Q.deleteSession),Nt=de(Q=>Q.deleteSessions),Pt=c.useCallback(async Q=>{const be=et(Q.id),xe=te.get(Q.id);if(xe){const Ie=xe.path,$e=[],Ue=new Set;W.forEach(xt=>{const je=te.get(xt.id);je&&je.path===Ie&&!Ue.has(xt.id)&&($e.push(xt),Ue.add(xt.id),et(xt.id).forEach(qe=>{Ue.has(qe.id)||($e.push(qe),Ue.add(qe.id))}))}),hn.requestDelete({sessions:$e,mode:"worktree",worktree:xe});return}if(be.length===0)await wt(Q.id)?se.success("Session deleted"):se.error("Failed to delete session");else{const Ie=[Q.id,...be.map(xt=>xt.id)],{deletedIds:$e,failedIds:Ue}=await Nt(Ie);$e.length>0&&se.success(`Deleted ${$e.length} session${$e.length===1?"":"s"}`),Ue.length>0&&se.error(`Failed to delete ${Ue.length} session${Ue.length===1?"":"s"}`)}},[et,wt,Nt,te,W]),St=c.useCallback(()=>{ce&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(Q=>{Q.success&&Q.path?E(Q.path,{id:Q.projectId})||se.error("Failed to add project",{description:"Please select a valid directory."}):Q.error&&Q.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:Q.error})}).catch(Q=>{console.error("Desktop: Error selecting directory:",Q),se.error("Failed to select directory")}):hn.requestDirectoryDialog()},[E,ce]),At=c.useCallback(Q=>{h(be=>{const xe=new Set(be);xe.has(Q)?xe.delete(Q):xe.add(Q);try{x.setItem(yc,JSON.stringify(Array.from(xe)))}catch{}return xe})},[x]),Jt=c.useCallback(Q=>{const be=fe.get(Q.id)??[];return{session:Q,children:be.map(xe=>Jt(xe)),worktree:te.get(Q.id)??null}},[fe,te]),Ee=c.useCallback((Q,be,xe)=>{const Ie=Gs(be??null),$e=[...Q].sort((lt,gt)=>(gt.time?.created||0)-(lt.time?.created||0)),Ue=new Map($e.map(lt=>[lt.id,lt])),xt=new Map;$e.forEach(lt=>{const gt=lt.parentID;if(!gt)return;const Rt=xt.get(gt)??[];Rt.push(lt),xt.set(gt,Rt)}),xt.forEach(lt=>lt.sort((gt,Rt)=>(Rt.time?.created||0)-(gt.time?.created||0)));const je=new Map;xe.forEach(lt=>{if(lt.path){const gt=Gs(lt.path)??lt.path;je.set(gt,lt)}});const Xe=lt=>{const gt=Gs(lt.directory??null),Rt=te.get(lt.id)??null;if(Rt)return Rt;if(gt){const hs=je.get(gt)??null;if(hs&>!==Ie)return hs}return null},qe=lt=>{const gt=xt.get(lt.id)??[];return{session:lt,children:gt.map(Rt=>qe(Rt)),worktree:Xe(lt)}},Dt=$e.filter(lt=>{const gt=lt.parentID;return gt?!Ue.has(gt):!0}).map(lt=>qe(lt));return[{id:"all",label:"All sessions",description:Ie?Ir(Ie,H):null,isMain:!0,worktree:null,directory:Ie,sessions:Dt}]},[H,te]),Oe=c.useCallback(Q=>{D(be=>{const xe=new Set(be);return xe.has(Q)?xe.delete(Q):xe.add(Q),xe})},[]),We=c.useCallback(Q=>{z.current=Date.now()+150,w(be=>{const xe=new Set(be);xe.has(Q)?xe.delete(Q):xe.add(Q);try{x.setItem(gc,JSON.stringify(Array.from(xe)))}catch{}return xe})},[x]),Ze=c.useMemo(()=>T.map(Q=>({...Q,normalizedPath:Gs(Q.path)})).filter(Q=>!!Q.normalizedPath),[T]),Zt=c.useCallback(Q=>{const be=ne.get(Q.normalizedPath)??[],xe=[Q.normalizedPath,...be.map(Ue=>Gs(Ue.path)??Ue.path).filter(Ue=>!!Ue)],Ie=new Set,$e=[];return xe.forEach(Ue=>{(O.get(Ue)??K(Ue)).forEach(je=>{Ie.has(je.id)||(Ie.add(je.id),$e.push(je))})}),$e},[ne,K,O]),zt=c.useMemo(()=>Ze.map(Q=>{const be=Zt(Q),xe=ne.get(Q.normalizedPath)??[],Ie=Ee(be,Q.normalizedPath,xe);return{project:Q,groups:Ie}}),[Ze,Zt,Ee,ne]);c.useEffect(()=>{if(!ce)return;const Q=new IntersectionObserver(be=>{be.forEach(xe=>{const Ie=xe.target.dataset.projectId;Ie&&L($e=>{const Ue=new Set($e);return xe.isIntersecting?Ue.delete(Ie):Ue.add(Ie),Ue})})},{threshold:0});return U.current.forEach(be=>{be&&Q.observe(be)}),()=>Q.disconnect()},[ce,zt]);const dt=c.useCallback((Q,be=0,xe,Ie)=>{const $e=Q.session,Ue=Gs($e.directory??null)??Gs(xe??null),je=(Ue?j.get(Ue):null)==="missing",Xe=He.get($e.id),qe=_===$e.id,ut=$e.title||"Untitled Session",Dt=Q.children.length>0,lt=p.has($e.id),gt=$e.summary?.additions,Rt=$e.summary?.deletions,hs=typeof gt=="number"||typeof Rt=="number";if(a===$e.id)return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",be>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[e.jsxs("form",{className:"flex w-full items-center gap-2","data-keyboard-avoid":"true",onSubmit:Et=>{Et.preventDefault(),Ge()},children:[e.jsx("input",{value:l,onChange:Et=>d(Et.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename session",onKeyDown:Et=>{Et.key==="Escape"&&Te()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Ot,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:Te,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Lt,{className:"size-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Dt?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:lt?e.jsx(Ct,{className:"h-3 w-3"}):e.jsx(Ls,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:xc($e.time?.created||Date.now())}),$e.share?e.jsx(fa,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,hs&&((gt??0)!==0||(Rt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,gt??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Rt??0)]})]}):null,Dt?e.jsxs("span",{className:"truncate",children:[Q.children.length," ",Q.children.length===1?"task":"tasks"]}):null]})]})},$e.id);const hr=Y?.get($e.id)??"idle",jn=hr==="busy"||hr==="cooldown",Vr=le.get($e.id)?.length??0,As=Xe&&Xe.isZombie?e.jsx(si,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(c.Fragment,{children:[e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1",qe?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",je?"opacity-75":"",be>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:je,onClick:()=>Le($e.id,Ue,je,Ie),className:R("flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("span",{className:R("truncate typography-ui-label font-normal text-foreground",jn&&"animate-pulse [animation-duration:1.8s]"),children:ut}),Vr>0?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:"Permission required","aria-label":"Permission required",children:[e.jsx(zf,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:Vr})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Dt?e.jsx("span",{role:"button",tabIndex:0,onClick:Et=>{Et.stopPropagation(),At($e.id)},onKeyDown:Et=>{(Et.key==="Enter"||Et.key===" ")&&(Et.preventDefault(),Et.stopPropagation(),At($e.id))},className:"inline-flex items-center justify-center text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 flex-shrink-0 rounded-sm","aria-label":lt?"Collapse subsessions":"Expand subsessions",children:lt?e.jsx(Ct,{className:"h-3 w-3"}):e.jsx(Ls,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:xc($e.time?.created||Date.now())}),$e.share?e.jsx(fa,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Q.worktree?e.jsxs(nt,{delayDuration:700,children:[e.jsx(ot,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(Ft,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(tt,{side:"top",className:"text-xs",children:Q.worktree.branch||Q.worktree.label||"Worktree"})]}):null,hs&&((gt??0)!==0||(Rt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,gt??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Rt??0)]})]}):null,Dt?e.jsxs("span",{className:"truncate",children:[Q.children.length," ",Q.children.length===1?"task":"tasks"]}):null,je?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(si,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[As,e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:Et=>Et.stopPropagation(),onKeyDown:Et=>Et.stopPropagation(),children:e.jsx(kr,{className:s?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Xt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(jt,{onClick:()=>{i($e.id),d(ut)},className:"[&>svg]:mr-1",children:[e.jsx(or,{className:"mr-1 h-4 w-4"}),"Rename"]}),$e.share?e.jsxs(e.Fragment,{children:[e.jsx(jt,{onClick:()=>{$e.share?.url&&Ve($e.share.url,$e.id)},className:"[&>svg]:mr-1",children:u===$e.id?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Bs,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(jt,{onClick:()=>pt($e.id),className:"[&>svg]:mr-1",children:[e.jsx(Wf,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(jt,{onClick:()=>Pe($e),className:"[&>svg]:mr-1",children:[e.jsx(fa,{className:"mr-1 h-4 w-4"}),"Share"]}),Q.worktree?e.jsxs(jt,{onClick:()=>{Ie&&Ie!==Z&&X(Ie),oe("chat"),s&&ye(!1),ie({directoryOverride:Q.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(Ft,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(jt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Pt($e),children:[e.jsx(zs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),Dt&<?Q.children.map(Et=>dt(Et,be+1,Ue??xe,Ie)):null]},$e.id)},[j,He,Y,le,_,p,a,l,Ge,Te,At,Le,Pe,Ve,pt,Pt,u,s,Z,X,oe,ye,ie]),Be=c.useCallback((Q,be,xe)=>{const Ie=N.has(be),$e=n?10:5,Ue=Q.sessions.length,xt=Ie?Q.sessions:Q.sessions.slice(0,$e),je=Ue-xt.length;return e.jsxs(e.Fragment,{children:[xt.map(Xe=>dt(Xe,0,Q.directory,xe)),Ue===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,je>0&&!Ie?e.jsxs("button",{type:"button",onClick:()=>Oe(be),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:["Show ",je," more ",je===1?"session":"sessions"]}):null,Ie&&Ue>$e?e.jsx("button",{type:"button",onClick:()=>Oe(be),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})},[N,n,dt,Oe]),Ye=Hf(xl(Jf,{activationConstraint:{distance:8}}),xl(Qf,{coordinateGetter:Xf})),Je=c.useCallback(Q=>{A(Q.active.id)},[]),Qe=c.useCallback(Q=>{const{active:be,over:xe}=Q;if(A(null),!xe||be.id===xe.id)return;const Ie=Ze.findIndex(Ue=>Ue.id===be.id),$e=Ze.findIndex(Ue=>Ue.id===xe.id);Ie!==-1&&$e!==-1&&q(Ie,$e)},[Ze,q]),it=c.useCallback(()=>{A(null)},[]),ht=c.useMemo(()=>{if(!k)return null;const Q=zt.find(xe=>xe.project.id===k);if(!Q)return null;const be=Q.project;return{id:be.id,label:bc(be.label?.trim()||vl(be.normalizedPath,H)||be.normalizedPath),isActive:be.id===Z}},[k,zt,H,Z]);return e.jsxs("div",{className:R("flex h-full flex-col text-foreground overflow-x-hidden",s?"":ce?"bg-transparent":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-8 select-none pl-3.5 pr-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("p",{className:"typography-ui-label font-medium text-muted-foreground",children:"Projects"}),e.jsx("span",{className:"typography-micro text-muted-foreground/50",children:T.length})]}),e.jsx("button",{type:"button",onClick:St,className:R("inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!ce&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(Uf,{className:"h-4.5 w-4.5"})})]})}),e.jsx(ct,{outerClassName:"flex-1 min-h-0",className:R("space-y-1 pb-1 pl-2.5 pr-1",""),children:zt.length===0?ve:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const Q=zt.find(Ie=>Ie.project.id===Z)??zt[0];if(!Q)return ve;const be=Q.groups.find(Ie=>Ie.isMain&&Ie.sessions.length>0)??Q.groups.find(Ie=>Ie.sessions.length>0)??Q.groups.find(Ie=>Ie.isMain)??Q.groups[0];if(!be)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const xe=`${Q.project.id}:${be.id}`;return Be(be,xe,Q.project.id)})()}):e.jsxs(Vf,{sensors:Ye,collisionDetection:Gf,onDragStart:Je,onDragEnd:Qe,onDragCancel:it,children:[e.jsx(qf,{items:Ze.map(Q=>Q.id),strategy:Kf,children:zt.map(Q=>{const be=Q.project,xe=be.id,Ie=bc(be.label?.trim()||vl(be.normalizedPath,H)||be.normalizedPath),$e=Ir(be.normalizedPath,H),Ue=y.has(xe),xt=xe===Z,je=S.get(xe),Xe=M===xe;return e.jsx(Ax,{id:xe,projectLabel:Ie,projectDescription:$e,isCollapsed:Ue,isActiveProject:xt,isRepo:!!je,isHovered:Xe,isDesktopRuntime:ce,isStuck:P.has(xe),hideDirectoryControls:n,mobileVariant:s,onToggle:()=>We(xe),onHoverChange:qe=>C(qe?xe:null),onNewSession:()=>{xe!==Z&&X(xe),oe("chat"),s&&ye(!1),F&&je?oa():ie({directoryOverride:be.normalizedPath})},onOpenMultiRunLauncher:()=>{xe!==Z&&X(xe),I()},onClose:()=>B(xe),sentinelRef:qe=>{U.current.set(xe,qe)},children:Ue?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:Q.groups[0]?Be(Q.groups[0],`${xe}:all`,xe):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},xe)})}),e.jsx(Yf,{children:ht?e.jsx(Ex,{projectLabel:ht.label,isActiveProject:ht.isActive}):null})]})})]})};function mt({className:s,type:r,...t}){return e.jsx("input",{type:r,"data-slot":"input",className:R("text-foreground border-input file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none hover:border-input focus:border-ring flex h-9 w-full min-w-0 rounded-lg border bg-transparent px-3 py-1 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",s),...t})}const aa=()=>{const[s,r]=Me.useState(!1);Me.useEffect(()=>{r(ss())},[]);const t=Me.useCallback(async a=>s?await bh(a):{success:!0,path:a},[s]),n=Me.useCallback(async a=>s?await wh(a):{success:!0},[s]),o=Me.useCallback(async a=>s?await vh(a):{success:!0},[s]);return{isDesktop:s,requestAccess:t,startAccessing:n,stopAccessing:o}},wc=({currentPath:s,onSelectPath:r,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:l=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=c.useMemo(()=>ss(),[]),[p,h]=c.useState([]),[j,g]=c.useState(new Set),[b,x]=c.useState(!0),[y,w]=c.useState(!1),[S,v]=c.useState(""),[N,D]=c.useState(new Set),[M,C]=c.useState(null),[k,A]=c.useState(""),[P,L]=c.useState(!0),U=c.useRef(null),{requestAccess:z,startAccessing:H,isDesktop:V}=aa(),J=c.useRef(l),T=c.useCallback(Y=>{if(!Y)return Y;if(Y==="/"||Y.length===0)return"/";let le=Y;for(;le.length>1&&le.endsWith("/");)le=le.slice(0,-1);return le.length===0?"/":le},[]),Z=c.useMemo(()=>{if(!S)return null;const Y=S.replace(/\\/g,"/");return T(Y)},[S,T]),E=c.useMemo(()=>{if(typeof d=="string"&&d.length>0){const Y=d.replace(/\\/g,"/"),le=T(Y);if(le&&le!=="/")return le}return Z&&Z!=="/"?Z:null},[d,Z,T]),B=c.useMemo(()=>typeof u=="boolean"?!!(u&&E):!!E,[u,E]);c.useEffect(()=>{B||(x(!0),h([]))},[B]);const X=c.useCallback(Y=>{if(!Y||!B||!E)return!1;const le=Y.replace(/\\/g,"/"),te=T(le)??le;if(te===E)return!0;const ne=`${E}/`;return te.startsWith(ne)},[B,E,T]),re=async Y=>{if(B){if(a==="deferred"){r(Y);return}if(V){const le=await z(Y);le.success&&le.path?(await H(le.path),r(le.path)):(console.error("Failed to get directory access:",le.error),r(Y))}else r(Y)}};c.useEffect(()=>{let Y=!1;const le=K=>{if(!K)return!1;const ie=T(K.replace(/\\/g,"/"));return!ie||ie==="/"?!1:(v(typeof ie=="string"?ie:K.replace(/\\/g,"/")),!0)};return d&&le(d)||(async()=>{try{const K=await De.getFilesystemHome();if(!Y&&le(K))return}catch(K){console.warn("Failed to resolve filesystem home directory:",K)}try{const K=await De.getSystemInfo();if(!Y&&le(K?.homeDirectory))return}catch(K){console.warn("Failed to resolve home directory from system info:",K)}})(),()=>{Y=!0}},[d,T]),c.useEffect(()=>{let Y=!1;const le=ie=>{if(Y)return;const ce=ie.filter(ae=>typeof ae=="string"&&ae.length>0).map(ae=>{const $=ae.replace(/\\/g,"/");return T($)??$});D(new Set(ce))},te=()=>{try{const ie=localStorage.getItem("pinnedDirectories");if(!ie)return;const ce=JSON.parse(ie);Array.isArray(ce)&&le(ce)}catch(ie){console.warn("Failed to load pinned directories from local storage:",ie)}},ne=async()=>{try{let ie=[];if(f){const ce=await wn();ie=Array.isArray(ce?.pinnedDirectories)?ce.pinnedDirectories:[]}else{const ce=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(ce.ok){const ae=await ce.json();ie=Array.isArray(ae?.pinnedDirectories)?ae.pinnedDirectories:[]}}if(Y)return;le(ie)}catch(ie){console.warn("Failed to load pinned directories:",ie)}};te();const K=ie=>{const ce=ie.detail;ce&&Array.isArray(ce.pinnedDirectories)&&le(ce.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",K),ne(),()=>{Y=!0,window.removeEventListener("openchamber:settings-synced",K)}},[f,T]);const q=c.useRef(!0);c.useEffect(()=>{if(q.current){q.current=!1;return}const Y={pinnedDirectories:Array.from(N)};os(Y)},[N]),c.useEffect(()=>{E&&D(Y=>{const le=Array.from(Y).map(te=>T(te.replace(/\\/g,"/"))??te).filter(te=>X(te));return new Set(le)})},[E,X,T]),c.useEffect(()=>{J.current!==l&&(J.current=l,g(new Set))},[l]);const oe=Y=>{D(le=>{if(!X(Y))return le;const te=T(Y.replace(/\\/g,"/"))??Y.replace(/\\/g,"/"),ne=new Set(le);return ne.has(te)?ne.delete(te):ne.add(te),ne})},ye=c.useMemo(()=>Array.from(N).map(Y=>T(Y.replace(/\\/g,"/"))??Y).filter(Y=>X(Y)).map(Y=>({path:Y,name:Y.split("/").pop()||Y})).sort((Y,le)=>Y.name.localeCompare(le.name)),[N,X,T]),I=c.useCallback(async Y=>{const le=ce=>l||!ce.startsWith("."),te=E;if(!B||!te)return[];const ne=Y&&Y.length>0?Y:te,K=ne?ne.replace(/\\/g,"/"):null,ie=K?T(K)??K:null;if(ie){const ce=`${te}/`;if(!(ie===te||ie.startsWith(ce)))return[]}try{return(await De.listLocalDirectory(Y)).filter(ae=>{if(!ae.isDirectory||!le(ae.name))return!1;const $=ae.path.replace(/\\/g,"/"),we=T($)??$,fe=we===te?te:`${te}/`;return we===te||we.startsWith(fe)}).map(ae=>({name:ae.name,path:ae.path.replace(/\\/g,"/"),isDirectory:!0})).sort((ae,$)=>ae.name.localeCompare($.name))}catch{try{const ae=await De.getApiClient().file.list({path:".",directory:Y});return ae.data?ae.data.filter($=>{if($.type!=="directory"||!$.name||!le($.name))return!1;const we=String($.absolute||$.path||$.name).replace(/\\/g,"/"),fe=T(we)??we,ve=fe===te?te:`${te}/`;return fe===te||fe.startsWith(ve)}).map($=>({name:$.name||"",path:String($.absolute||$.path||$.name).replace(/\\/g,"/"),isDirectory:!0})).filter($=>$.name!=="").sort(($,we)=>$.name.localeCompare(we.name)):[]}catch{return[]}}},[l,E,T,B]),F=c.useCallback(async()=>{if(!B||!E){x(!0),h([]);return}x(!0);try{const Y=await I(E);h(Y)}catch{}finally{x(!1)}},[B,E,I]);c.useEffect(()=>{B&&(n==="inline"||y)&&F()},[n,y,B,F]);const W=async Y=>{if(!B)return;const le=j.has(Y.path),te=new Set(j);if(le){te.delete(Y.path),g(te);return}te.add(Y.path),g(te);const ne=await I(Y.path),K=ie=>ie.map(ce=>ce.path===Y.path?{...ce,children:ne}:ce.children?{...ce,children:K(ce.children)}:ce);h(ie=>K(ie))};c.useEffect(()=>{M&&U.current&&(U.current.focus(),U.current.select())},[M]);const O=(Y,le=[])=>{const te="new_directory",ne=le.map(ae=>ae.name);if(!ne.includes(te))return te;let K=1;const ie=new RegExp(`^${te}(\\d+)$`);for(const ae of ne){const $=ae.match(ie);if($){const we=parseInt($[1],10);we>K&&(K=we)}}let ce=2;for(;ne.includes(`${te}${ce}`);)ce++;return`${te}${Math.max(ce,K+1)}`},_=async Y=>{if(B){if(j.has(Y.path)){const le=O(Y.path,Y.children);A(le)}else{const le=new Set(j);if(le.add(Y.path),g(le),Y.children){const te=O(Y.path,Y.children);A(te)}else{const te=await I(Y.path),ne=ie=>ie.map(ce=>ce.path===Y.path?{...ce,children:te}:ce.children?{...ce,children:ne(ce.children)}:ce);h(ie=>ne(ie));const K=O(Y.path,te);A(K)}}C(Y.path)}},ee=async()=>{if(!M||!B)return;const Y=k.trim()||"new_directory",le=`${M}/${Y}`;try{await De.createDirectory(le);const te=await I(M),ne=K=>K.map(ie=>ie.path===M?{...ie,children:te}:ie.children?{...ie,children:ne(ie.children)}:ie);h(K=>ne(K)),C(null),A("")}catch(te){console.error("Failed to create directory:",te)}},ue=()=>{C(null),A("")},me=(Y,le=0)=>{const te=j.has(Y.path),ne=Y.isDirectory,K=N.has(Y.path),ie=s===Y.path,ce=n==="inline",ae=e.jsxs(e.Fragment,{children:[ne&&e.jsx("button",{onClick:$=>{$.stopPropagation(),W(Y)},className:"p-0.5 hover:bg-accent rounded",children:te?e.jsx(Ct,{className:"h-3 w-3"}):e.jsx(Ls,{className:"h-3 w-3"})}),!ne&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:$=>{$.stopPropagation(),re(Y.path),n==="dropdown"&&a==="immediate"&&w(!1)},onDoubleClick:$=>{$.stopPropagation(),i&&i(Y.path)},className:R("flex items-center gap-1.5 flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",ce&&ie?"text-primary":"text-foreground"),children:[te?e.jsx(Ts,{className:R("h-3.5 w-3.5 text-muted-foreground",ce&&ie&&"text-primary")}):e.jsx(Ts,{className:R("h-3.5 w-3.5 text-muted-foreground",ce&&ie&&"text-primary")}),e.jsx("span",{className:R("typography-ui-label font-medium truncate",ce&&ie?"text-primary":"text-foreground"),children:Y.name})]}),e.jsx("button",{onClick:$=>{$.stopPropagation(),_(Y)},className:R("p-1 hover:bg-accent rounded transition-opacity",m?"opacity-70":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(_t,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("button",{onClick:$=>{$.stopPropagation(),oe(Y.path)},className:R("p-1 hover:bg-accent rounded transition-opacity",m?"opacity-70":"opacity-0 group-hover:opacity-100"),title:K?"Unpin directory":"Pin directory",children:K?e.jsx(pa,{className:"h-3 w-3 text-primary"}):e.jsx(ep,{className:"h-3 w-3 text-muted-foreground"})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:R("group flex items-center gap-1 rounded px-2 py-1.5 text-left hover:bg-accent/40",ie?"text-primary":"text-foreground"),style:{paddingLeft:`${le*12+8}px`},children:ae}),te&&e.jsxs(e.Fragment,{children:[M===Y.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(le+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Ts,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(mt,{ref:U,value:k,onChange:$=>A($.target.value),onKeyDown:$=>{$.key==="Enter"?($.preventDefault(),$.stopPropagation(),ee()):$.key==="Escape"&&($.preventDefault(),$.stopPropagation(),ue())},onBlur:ee,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:$=>{$.preventDefault(),$.stopPropagation(),ee()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Ot,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:$=>{$.preventDefault(),$.stopPropagation(),ue()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Lt,{className:"h-3 w-3 text-muted-foreground"})})]}),Y.children&&Y.children.map($=>me($,le+1))]})]},Y.path):e.jsxs("div",{children:[e.jsxs(jt,{className:R("flex items-center gap-1 cursor-pointer group",s===Y.path&&"bg-accent"),style:{paddingLeft:`${le*12+8}px`},onSelect:$=>{$.preventDefault()},children:[ne&&e.jsx("button",{onClick:$=>{$.stopPropagation(),W(Y)},className:"p-0.5 hover:bg-accent rounded",children:te?e.jsx(Ct,{className:"h-3 w-3"}):e.jsx(Ls,{className:"h-3 w-3"})}),!ne&&e.jsx("div",{className:"w-4"}),ae]}),te&&e.jsxs("div",{children:[M===Y.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(le+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Ts,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(mt,{ref:U,value:k,onChange:$=>A($.target.value),onKeyDown:$=>{$.key==="Enter"?($.preventDefault(),$.stopPropagation(),ee()):$.key==="Escape"&&($.preventDefault(),$.stopPropagation(),ue())},onBlur:ee,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:$=>{$.preventDefault(),$.stopPropagation(),ee()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Ot,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:$=>{$.preventDefault(),$.stopPropagation(),ue()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Lt,{className:"h-3 w-3 text-muted-foreground"})})]}),Y.children&&Y.children.map($=>me($,le+1))]})]},Y.path)},pe=(Y,le)=>{if(n==="inline"){const te=s===le;return e.jsxs("div",{className:R("group flex items-center gap-2 px-2 py-1.5 hover:bg-accent/40"),children:[e.jsxs("button",{onClick:()=>re(le),onDoubleClick:ne=>{ne.stopPropagation(),i&&i(le)},className:R("flex flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",te?"text-primary":"text-foreground"),children:[e.jsx(Ts,{className:R("h-3.5 w-3.5 text-muted-foreground",te&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:R("typography-ui-label font-medium truncate",te?"text-primary":"text-foreground"),children:Y}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:Ir(le,S)})]})]}),e.jsx("button",{onClick:()=>oe(le),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(pa,{className:"h-3 w-3 text-primary"})})]},le)}return e.jsxs(jt,{onSelect:te=>{te.preventDefault(),re(le),a==="immediate"&&w(!1)},className:R("flex items-start gap-2 cursor-pointer group py-2",s===le&&"bg-accent"),children:[e.jsx(Ts,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium",children:Y}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Ir(le,S)})]}),e.jsx("button",{onClick:te=>{te.stopPropagation(),te.preventDefault(),oe(le)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(pa,{className:"h-3 w-3 text-primary"})})]},le)},He=e.jsx(e.Fragment,{children:B?e.jsxs(e.Fragment,{children:[ye.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>L(Y=>!Y),className:"flex w-full items-center gap-1.5 px-2 py-1.5 typography-meta font-semibold text-muted-foreground hover:bg-accent/30 rounded transition-colors",children:[P?e.jsx(Ct,{className:"h-3.5 w-3.5"}):e.jsx(Ls,{className:"h-3.5 w-3.5"}),e.jsx(sn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Pinned"}),e.jsx("span",{className:"ml-auto typography-micro text-muted-foreground/70",children:ye.length})]}),P&&ye.map(({name:Y,path:le})=>pe(Y,le)),n==="dropdown"&&e.jsx(Xs,{}),n==="inline"&&P&&e.jsx("div",{className:"mx-2 my-1.5 border-t border-border/30"})]}),e.jsxs("div",{className:"px-2 py-1.5 typography-meta font-semibold text-muted-foreground flex items-center gap-1.5",children:[e.jsx(Ts,{className:"h-3.5 w-3.5"}),"Browse"]}),b?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):p.map(Y=>me(Y)),!b&&p.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No directories found"})]}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Locating home directory..."})});return n==="inline"?e.jsx("div",{className:R("overflow-hidden rounded-xl border border-border/40 bg-sidebar/70",o),children:e.jsx(ct,{outerClassName:"max-h-full",className:"w-full",children:He})}):e.jsxs(Kt,{open:y,onOpenChange:w,children:[e.jsx(Yt,{asChild:!0,children:e.jsxs(ke,{variant:"ghost",className:R("w-full h-8 px-2.5 justify-between items-center rounded-lg border border-transparent bg-sidebar-accent/40 text-foreground/90 hover:bg-sidebar-accent/60 typography-meta",t),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(Ts,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:s,children:Ir(s,S)})]}),e.jsx(Ct,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Xt,{align:"start",className:"w-[350px]",children:e.jsx(ct,{outerClassName:"h-full",className:"w-full",children:He})})]})},vc="directoryTreeShowHidden",Ix=({open:s,onOpenChange:r})=>{const{currentDirectory:t,homeDirectory:n,isHomeReady:o}=ft(),{addProject:a,getActiveProject:i}=It(),[l,d]=c.useState(null),[u,m]=c.useState(""),[f,p]=c.useState(!1),[h,j]=c.useState(!1),[g,b]=c.useState(()=>{if(typeof window>"u")return!1;try{const E=window.localStorage.getItem(vc);if(E==="true")return!0;if(E==="false")return!1}catch{}return!1}),{isDesktop:x,requestAccess:y,startAccessing:w}=aa(),{isMobile:S}=$t(),v=c.useCallback(E=>E?Ir(E,n):"",[n]);c.useEffect(()=>{if(s){p(!1),j(!1);const B=i()?.path||t||n||"";d(B),m(v(B))}},[s,t,n,v,i]),c.useEffect(()=>{!s||f||l||n&&o&&(d(n),p(!0),m("~"))},[s,f,l,n,o]),c.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(vc,g?"true":"false")}catch{}},[g]);const N=c.useCallback(()=>{r(!1)},[r]),D=c.useCallback(async E=>{if(!(!E||h)){j(!0);try{let B=E,X;if(x){const q=await y(E);if(!q.success){se.error("Unable to access directory",{description:q.error||"Desktop denied directory access."});return}B=q.path??E,X=q.projectId;const oe=await w(B);if(!oe.success){se.error("Failed to open directory",{description:oe.error||"Desktop could not grant file access."});return}}if(!a(B,{id:X})){se.error("Failed to add project",{description:"Please select a valid directory path."});return}N()}catch(B){se.error("Failed to select directory",{description:B instanceof Error?B.message:"Unknown error occurred."})}finally{j(!1)}}},[a,N,x,y,w,h]),M=c.useCallback(async()=>{const E=u.trim()||l;E&&await D(E)},[D,u,l]),C=c.useCallback(E=>{d(E),p(!0),m(v(E))},[v]),k=c.useCallback(async E=>{d(E),p(!0),m(v(E)),await D(E)},[D,v]),A=c.useCallback(E=>{const B=E.target.value;if(m(B),p(!0),B.startsWith("/")||B.startsWith("~")){const X=B.startsWith("~")&&n?B.replace(/^~/,n):B;d(X)}},[n]),P=c.useCallback(E=>{E.key==="Enter"&&(E.preventDefault(),M())},[M]),L=c.useCallback(()=>{b(E=>!E)},[]),U=e.jsxs(fs,{className:"flex-shrink-0 px-4 pb-2 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)] sm:px-0 sm:pb-3 sm:pt-0",children:[e.jsx(ps,{children:"Add project directory"}),e.jsx(ys,{className:"hidden sm:block",children:"Choose a folder to add as a project."})]}),z=e.jsx(mt,{value:u,onChange:A,onKeyDown:P,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),H=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 p-1.5 sm:p-2 sm:flex-none",children:e.jsx(wc,{variant:"inline",currentPath:l??t,onSelectPath:C,onDoubleClickPath:k,className:"h-full sm:min-h-[280px] sm:h-[380px]",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o})}),V=e.jsxs("button",{type:"button",onClick:L,className:"flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-accent/40 transition-colors typography-meta text-muted-foreground",children:[g?e.jsx(Ai,{className:"h-4 w-4 text-primary"}):e.jsx(Ei,{className:"h-4 w-4"}),"Show hidden"]}),J=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:z}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:V}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 p-1.5 overflow-hidden",children:e.jsx(wc,{variant:"inline",currentPath:l??t,onSelectPath:C,onDoubleClickPath:k,className:"h-full",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),T=e.jsxs(ct,{outerClassName:"flex-1 min-h-0 overflow-hidden",className:"directory-dialog-body sm:px-0 sm:pb-0 flex flex-col gap-3",children:[z,e.jsx("div",{className:"flex items-center justify-end",children:V}),H]}),Z=()=>e.jsxs(e.Fragment,{children:[e.jsx(ke,{variant:"ghost",onClick:N,disabled:h,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(ke,{onClick:M,disabled:h||!f||!l&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:h?"Adding...":"Add Project"})]});return S?e.jsx(vs,{open:s,onClose:()=>r(!1),title:"Add project directory",className:"max-w-full",contentMaxHeightClassName:"max-h-[min(70vh,520px)] h-[min(70vh,520px)]",footer:e.jsx("div",{className:"flex flex-row gap-2",children:Z()}),children:J}):e.jsx(ds,{open:s,onOpenChange:r,children:e.jsxs(us,{className:R("flex w-full max-w-[min(560px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-xl sm:p-6"),onOpenAutoFocus:E=>{E.preventDefault()},children:[U,T,e.jsx(Ws,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-row gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:justify-end sm:border-0 sm:bg-transparent sm:px-0 sm:pt-3",children:Z()})]})})},io=s=>s?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:s}):void 0,Px=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Tx=()=>{const[s,r]=c.useState(!1),[t,n]=c.useState(!1),o=c.useRef(new Set),[a,i]=c.useState(null),[l,d]=c.useState([]),[u,m]=c.useState(!1),[f,p]=c.useState(!1),{deleteSession:h,deleteSessions:j,loadSessions:g,getWorktreeMetadata:b}=de(),{currentDirectory:x,homeDirectory:y,isHomeReady:w}=ft(),{projects:S,addProject:v,activeProjectId:N}=It(),{requestAccess:D,startAccessing:M}=aa(),{isMobile:C,isTablet:k,hasTouchInput:A}=$t(),P=C||k||A,L=c.useMemo(()=>{const W=(N?S.find(O=>O.id===N)??null:null)?.path??x;return Px(W)},[N,x,S]),U=c.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||l.some(F=>F.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,l]),z=c.useMemo(()=>{const F=a?.worktree;return F&&typeof F.branch=="string"&&F.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:W})=>typeof W.branch=="string"&&W.branch.trim().length>0)},[a?.worktree,l]),H=a?.mode==="worktree",V=H,J=f||!H||!z;c.useEffect(()=>{L&&(o.current.has(L)||Lg(L).then(()=>o.current.add(L)).catch(F=>{console.warn("Failed to ensure .openchamber directory is ignored:",F),o.current.delete(L)}))},[L]),c.useEffect(()=>{g()},[g,x]);const T=c.useMemo(()=>S.map(F=>`${F.id}:${F.path}`).join("|"),[S]),Z=c.useRef(T);c.useEffect(()=>{T!==Z.current&&(Z.current=T,g())},[g,T]),c.useEffect(()=>{if(!(t||!w||S.length>0)){if(n(!0),ss()){D("").then(async F=>{if(!F.success||!F.path){F.error&&F.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:F.error});return}const W=await M(F.path);if(!W.success){se.error("Failed to open directory",{description:W.error||"Desktop could not grant file access."});return}v(F.path,{id:F.projectId})||se.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(F=>{console.error("Desktop: Error selecting directory:",F),se.error("Failed to select directory")});return}r(!0)}},[v,t,w,S.length,D,M]);const E=c.useCallback(F=>{i({sessions:F.sessions,dateLabel:F.dateLabel,mode:F.mode??"session",worktree:F.worktree??null})},[]),B=c.useCallback(()=>{i(null),d([]),m(!1),p(!1)},[]);c.useEffect(()=>hn.onDeleteRequest(F=>{E(F)}),[E]),c.useEffect(()=>hn.onDirectoryRequest(()=>{r(!0)}),[]),c.useEffect(()=>{if(!a){d([]),m(!1);return}const F=a.sessions.map(O=>{const _=b(O.id);return _?{session:O,metadata:_}:null}).filter(O=>!!O);if(d(F),m(!1),F.length===0)return;let W=!1;return(async()=>{const O=await Promise.all(F.map(async({metadata:_})=>{if(_.status&&typeof _.status.isDirty=="boolean")return _.status;try{return await Hi(_.path)}catch{return _.status}})).catch(_=>(console.warn("Failed to inspect worktree status before deletion:",_),F.map(({metadata:ee})=>ee.status)));W||!Array.isArray(O)||d(_=>_.map((ee,ue)=>({session:ee.session,metadata:{...ee.metadata,status:O[ue]??ee.metadata.status}})))})(),()=>{W=!0}},[a,b]),c.useEffect(()=>{z||m(!1)},[z]);const X=c.useCallback(async()=>{if(a){p(!0);try{const F=V,W=F&&u;if(a.sessions.length===0&&H&&a.worktree){const O=u&&z;await Su({projectDirectory:L,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:O});const _=O?"Worktree and remote branch removed.":"Worktree removed.";se.success("Worktree removed",{description:io(_)}),B(),g();return}if(a.sessions.length===1){const O=a.sessions[0];if(!await h(O.id,{archiveWorktree:F,deleteRemoteBranch:W})){se.error("Failed to delete session"),p(!1);return}const ee=F?W?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;se.success("Session deleted",{description:io(ee)})}else{const O=a.sessions.map(ue=>ue.id),{deletedIds:_,failedIds:ee}=await j(O,{archiveWorktree:F,deleteRemoteBranch:W});if(_.length>0){const ue=F?W?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,pe=[ee.length>0?`${ee.length} session${ee.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,ue].filter(Boolean).join(" ");se.success(`Deleted ${_.length} session${_.length===1?"":"s"}`,{description:io(pe||void 0)})}if(ee.length>0&&(se.error(`Failed to delete ${ee.length} session${ee.length===1?"":"s"}`,{description:io("Please try again in a moment.")}),_.length===0)){p(!1);return}}B()}finally{p(!1)}}},[a,u,h,j,B,V,H,z,L,g]),re=a?.worktree??l[0]?.metadata??null,q=a?a.mode==="worktree"?a.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and ${a.sessions.length===1?"1 linked session":`${a.sessions.length} linked sessions`}.`:`This action permanently removes ${a.sessions.length===1?"1 session":`${a.sessions.length} sessions`}${a.dateLabel?` from ${a.dateLabel}`:""}.`:"",oe=a?e.jsxs("div",{className:"space-y-2",children:[a.sessions.length>0&&e.jsxs("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[H&&e.jsx("span",{className:"typography-meta font-medium text-foreground",children:a.sessions.length===1?"Linked session":"Linked sessions"}),e.jsxs("ul",{className:"space-y-0.5",children:[a.sessions.slice(0,5).map(F=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:F.title||"Untitled Session"},F.id)),a.sessions.length>5&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",a.sessions.length-5," more"]})]})]}),H?e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),re?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:re.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:re?Ir(re.path,y):"Worktree path unavailable."}),U&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),z?e.jsxs("button",{type:"button",onClick:()=>{J||m(F=>!F)},disabled:J,className:R("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",J?"cursor-not-allowed opacity-60":"hover:bg-sidebar/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[e.jsx("span",{className:"mt-0.5 flex size-5 items-center justify-center text-muted-foreground",children:u?e.jsx(Ai,{className:"size-4 text-primary"}):e.jsx(Ei,{className:"size-4"})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Delete remote branch"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:u?"Remote branch on origin will also be removed.":"Keep the remote branch intact."})]})]}):e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Remote branch information unavailable for this worktree."})]}):e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,ye=e.jsxs(e.Fragment,{children:[e.jsx(ke,{variant:"ghost",onClick:B,disabled:f,children:"Cancel"}),e.jsx(ke,{variant:"destructive",onClick:X,disabled:f,children:f?"Deleting…":H?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),I=H?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[P?e.jsx(vs,{open:!!a,onClose:()=>{f||B()},title:I,footer:e.jsx("div",{className:"flex justify-end gap-2",children:ye}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[q&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:q}),oe]})}):e.jsx(ds,{open:!!a,onOpenChange:F=>{if(!F){if(f)return;B()}},children:e.jsxs(us,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(fs,{children:[e.jsx(ps,{children:I}),q&&e.jsx(ys,{children:q})]}),oe,e.jsx(Ws,{className:"mt-2 gap-2 pt-1 pb-1",children:ye})]})}),e.jsx(Ix,{open:s,onOpenChange:r})]})};function Fx(){return new Worker(tp,{type:"module"})}const Rx=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function Ox(s,r,t){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${s}:${r.length}:${t.length}:${n.length}:${o.length}`}function jc(s){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>s(void 0),0);return()=>window.clearTimeout(r)}const $x=({children:s})=>{const r=rp(),t=Ut(l=>l.activeDirectory),n=Ut(l=>t?l.directories.get(t)?.lastStatusChange??0:0),o=Ut(l=>t?l.directories.get(t)?.diffCache.size??0:0),a=Me.useRef(!1),i=Me.useRef(new Map);return Me.useEffect(()=>{if(!r||a.current)return;a.current=!0;const l={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=ti(l,{...l,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Me.useEffect(()=>{if(!r||!t||!n||o===0)return;const l=Ut.getState().directories.get(t);if(!l||l.diffCache.size===0||(i.current.get(t)??0)>=l.lastStatusChange)return;i.current.set(t,l.lastStatusChange);let u=!1,m=null;const f=Array.from(l.diffCache.entries());let p=0;const h=j=>{if(u)return;const g=Date.now();for(;p<f.length&&!(j&&j.timeRemaining()<8||!j&&Date.now()-g>8);){const[b,x]=f[p];p+=1,Hr(b);const y=Ox(b,x.original,x.modified),w={name:b,contents:x.original,cacheKey:`old-${y}`},S={name:b,contents:x.modified,cacheKey:`new-${y}`},v=ti(w,S),N={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(N,v)}p<f.length&&(m=jc(h))};return h(void 0),p<f.length&&(m=jc(h)),()=>{u=!0,m?.()}},[r,t,n,o]),e.jsx(e.Fragment,{children:s})},Lx=({children:s})=>{const t=na()?.currentTheme?.metadata?.variant==="dark";zu();const n=Me.useMemo(()=>({theme:{dark:pn.dark,light:pn.light},themeType:t?"dark":"light",langs:Rx}),[t]);return e.jsx(sp,{poolOptions:{workerFactory:Fx,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx($x,{children:s})})},js=Me.forwardRef(({className:s,...r},t)=>e.jsx(ct,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:R("text-foreground border-input placeholder:text-muted-foreground appearance-none hover:border-input focus:border-ring focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-3 py-2 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label",s),...r}));js.displayName="Textarea";const ia=np,sl=({className:s,...r})=>e.jsx(op,{className:R("flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left text-foreground hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",s),...r}),la=({className:s,...r})=>e.jsx(ap,{className:R("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",s),...r}),hi=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),_x=(s,r)=>{const t=hi(s),n=hi(r);return`${t}-${n}`.substring(0,60)},Sc=(s,r)=>`${s}/${r}`,Bx=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),zx=()=>{const s=It.getState(),r=s.activeProjectId,t=r?s.projects.find(l=>l.id===r)?.path:void 0;if(typeof t=="string"&&t.trim().length>0)return t;const n=ft.getState().currentDirectory??null;if(!n)return null;const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n,i=o.indexOf("/.openchamber/");return i>0?o.slice(0,i):o.endsWith("/.openchamber")?o.slice(0,o.length-13):o},Rn=Bt()(Qt(s=>({isLoading:!1,error:null,createMultiRun:async r=>{const t=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:i,setupCommands:l}=r;if(!t)return s({error:"Group name is required"}),null;if(!n)return s({error:"Prompt is required"}),null;if(o.length<1)return s({error:"Select at least 1 model"}),null;if(o.length>5)return s({error:"Maximum 5 models allowed"}),null;s({isLoading:!0,error:null});try{const d=zx();if(!d)return s({error:"No directory selected",isLoading:!1}),null;if(!await Wr(d))return s({error:"Not in a git repository",isLoading:!1}),null;const m=hi(t),f=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",p=f!=="HEAD"?f:void 0,h=[],j=l?.filter(v=>v.trim().length>0)??[],g=new Map;for(const v of o){const N=`${v.providerID}:${v.modelID}`;g.set(N,(g.get(N)||0)+1)}const b=new Map;for(const v of o){const N=`${v.providerID}:${v.modelID}`,D=g.get(N)||1,M=(b.get(N)||0)+1;b.set(N,M);const C=_x(v.providerID,v.modelID),k=D>1?Sc(m,`${C}/${M}`):Sc(m,C);if(!k)return s({error:"Branch name is required for worktree creation",isLoading:!1}),null;const A=Bx(k);if(!A)return s({error:`Invalid branch name: ${k}`,isLoading:!1}),null;try{const P=await ju({projectDirectory:d,worktreeSlug:A,branch:k,createBranch:!0,startPoint:p}),L=D>1?`${m}/${v.providerID}/${v.modelID}/${M}`:`${m}/${v.providerID}/${v.modelID}`,U=await De.withDirectory(P.path,()=>De.createSession({title:L}));rt.getState().setWorktreeMetadata(U.id,P),h.push({sessionId:U.id,worktreePath:P.path,providerID:v.providerID,modelID:v.modelID})}catch(P){console.warn("[MultiRun] Failed to create session:",P)}}const x=l?.filter(v=>v.trim().length>0)??[];x.length>0&&bu(d,x).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const y=h.map(v=>v.sessionId),w=h[0]?.sessionId??null;if(y.length===0)return s({error:"Failed to create any sessions",isLoading:!1}),null;const S=i?.map(v=>({type:"file",mime:v.mime,filename:v.filename,url:v.url}));try{await rt.getState().loadSessions()}catch{}if(j.length>0)for(const v of h)ku(v.worktreePath,d,j).then(N=>{if(!N.success){const D=N.results.filter(M=>!M.success);console.warn(`[MultiRun] Setup commands failed for ${v.worktreePath}:`,D)}}).catch(N=>{console.warn(`[MultiRun] Setup commands error for ${v.worktreePath}:`,N)});return(async()=>{try{await Promise.allSettled(h.map(async v=>{try{await De.withDirectory(v.worktreePath,()=>De.sendMessage({id:v.sessionId,providerID:v.providerID,modelID:v.modelID,text:n,agent:a,files:S}))}catch(N){console.warn("[MultiRun] Failed to start run:",N)}}))}catch(v){console.warn("[MultiRun] Failed to start runs:",v)}})(),s({isLoading:!1}),{groupSlug:m,sessionIds:y,firstSessionId:w}}catch(d){return s({error:d instanceof Error?d.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{s({error:null})}}),{name:"multirun-store"})),Wx="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!--%20Uploaded%20to:%20SVG%20Repo,%20www.svgrepo.com,%20Generator:%20SVG%20Repo%20Mixer%20Tools%20--%3e%3csvg%20fill='%23000000'%20width='800px'%20height='800px'%20viewBox='0%200%2024%2024'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.702%202.29c-2.494-1.554-5.778-1.187-8.706.654C9.076%201.104%205.79.736%203.3%202.29c-3.941%202.463-4.42%208.806-1.07%2014.167%202.47%203.954%206.333%206.269%209.77%206.226%203.439.043%207.301-2.273%209.771-6.226%203.347-5.361%202.872-11.704-1.069-14.167zM4.042%2015.328a12.838%2012.838%200%200%201-1.546-3.541%2010.12%2010.12%200%200%201-.336-3.338c.15-1.98.956-3.524%202.27-4.345%201.315-.822%203.052-.87%204.903-.137.281.113.556.24.825.382A15.11%2015.11%200%200%200%207.5%207.54c-2.035%203.255-2.655%206.878-1.945%209.765a13.247%2013.247%200%200%201-1.514-1.98zm17.465-3.541a12.866%2012.866%200%200%201-1.547%203.54%2013.25%2013.25%200%200%201-1.513%201.984c.635-2.589.203-5.76-1.353-8.734a.39.39%200%200%200-.563-.153l-4.852%203.032a.397.397%200%200%200-.126.546l.712%201.139a.395.395%200%200%200%20.547.126l3.145-1.965c.101.306.203.606.28.916.296%201.086.41%202.214.335%203.337-.15%201.982-.956%203.525-2.27%204.347a4.437%204.437%200%200%201-2.25.65h-.101a4.432%204.432%200%200%201-2.25-.65c-1.314-.822-2.121-2.365-2.27-4.347a10.153%2010.153%200%200%201%20.335-3.337%2013.212%2013.212%200%200%201%204.05-6.482%2010.148%2010.148%200%200%201%202.849-1.765c1.845-.733%203.586-.685%204.9.137%201.316.822%202.122%202.365%202.271%204.345a10.146%2010.146%200%200%201-.33%203.334z'/%3e%3c/svg%3e",Hx=Object.assign({"../assets/provider-logos/gocode.svg":Wx}),gi=new Map;for(const[s,r]of Object.entries(Hx)){const t=s.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&r&&gi.set(t[1].toLowerCase(),r)}function Qu(s){const r=s?.toLowerCase()??null,t=r?gi.has(r):!1,n=r?gi.get(r)??null:null,[o,a]=Me.useState(t?"local":"remote");Me.useEffect(()=>{a(t?"local":"remote")},[t,r]);const i=Me.useCallback(()=>{a(l=>l==="local"&&t?"remote":"none")},[t]);return r?o==="local"&&n?{src:n,onError:i,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:i,hasLogo:!0}:{src:null,onError:i,hasLogo:!1}:{src:null,onError:i,hasLogo:!1}}const ts=({providerId:s,alt:r,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=Qu(s),l=c.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:r||`${s} logo`,className:R("dark:invert",t),onError:l})},rl=s=>s.nativeEvent.isComposing||s.nativeEvent.keyCode===229,nl=()=>{const{providers:s}=at(),{favoriteModels:r,recentModels:t}=Re(),n=c.useMemo(()=>r.map(({providerID:a,modelID:i})=>{const l=s.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===i);return u?{provider:l,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null),[r,s]),o=c.useMemo(()=>t.map(({providerID:a,modelID:i})=>{const l=s.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===i);return u?{provider:l,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:i})=>!r.some(l=>l.providerID===a&&l.modelID===i)),[t,s,r]);return{favoriteModelsList:n,recentModelsList:o}},Ju="h-7",Ho=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Ux=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Vx=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=Ux.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Gx=({model:s,instanceIndex:r,totalSameModel:t,onRemove:n})=>{const o=s.displayName||`${s.providerID}/${s.modelID}`,a=t>1?`${o} (${r})`:o;return e.jsxs("div",{className:R("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",Ju),children:[e.jsx(ts,{providerId:s.providerID,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:a}),e.jsx("button",{type:"button",onClick:n,className:"text-muted-foreground hover:text-foreground ml-0.5",children:e.jsx(Lt,{className:"h-3.5 w-3.5"})})]})},Zu=({selectedModels:s,onAdd:r,onRemove:t,minModels:n,addButtonLabel:o="Add model",showChips:a=!0,maxModels:i})=>{const{providers:l,modelsMetadata:d}=at(),{favoriteModelsList:u,recentModelsList:m}=nl(),[f,p]=c.useState(!1),[h,j]=c.useState(""),[g,b]=c.useState(0),[x,y]=c.useState(null),w=c.useRef(null),S=c.useRef(null),v=c.useRef(null),N=c.useRef([]),D=c.useMemo(()=>{const V=new Map;for(const J of s){const T=`${J.providerID}:${J.modelID}`;V.set(T,(V.get(T)||0)+1)}return V},[s]),M=c.useCallback(V=>s.filter(T=>T.providerID===V.providerID&&T.modelID===V.modelID).findIndex(T=>T.instanceId===V.instanceId)+1,[s]),C=(V,J)=>{const T=`${V}/${J}`;return d.get(T)},k=V=>{const J=V?.name||V?.id||"",T=String(J);return T.length>40?T.substring(0,37)+"...":T},A=c.useCallback((V,J)=>{if(!h.trim())return!0;const T=h.toLowerCase();return V.toLowerCase().includes(T)||J.toLowerCase().includes(T)},[h]),P=c.useMemo(()=>u.filter(({model:V,providerID:J})=>{const Z=l.find(B=>B.id===J)?.name||J,E=k(V);return A(E,Z)}),[u,l,A]),L=c.useMemo(()=>m.filter(({model:V,providerID:J})=>{const Z=l.find(B=>B.id===J)?.name||J,E=k(V);return A(E,Z)}),[m,l,A]),U=c.useMemo(()=>l.map(V=>{const T=(Array.isArray(V.models)?V.models:[]).filter(Z=>{const E=k(Z);return A(E,V.name||V.id||"")});return{...V,models:T}}).filter(V=>V.models.length>0),[l,A]),z=P.length>0||L.length>0||U.length>0;c.useEffect(()=>{if(f&&v.current){const J=v.current.getBoundingClientRect().top-100;y(Math.max(150,Math.min(400,J)))}},[f]),c.useEffect(()=>{f&&w.current&&w.current.focus()},[f]),c.useEffect(()=>{if(!f)return;const V=J=>{S.current&&!S.current.contains(J.target)&&(p(!1),j(""),b(0))};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[f]),c.useEffect(()=>{b(0)},[h]);const H=(V,J,T,Z,E,B)=>{const X=`${J}:${T}`,re=D.get(X)||0,q=C(J,T),oe=Vx(q?.limit?.context);return e.jsxs("button",{ref:ye=>{N.current[E]=ye},type:"button",onClick:()=>{r({providerID:J,modelID:T,displayName:V.name||T,instanceId:Ho()})},onMouseEnter:()=>b(E),className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",B?"bg-accent":"hover:bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:k(V)}),oe&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:oe})]}),re>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",re]})]},`${Z}-${X}`)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsxs("div",{className:"relative",ref:S,children:[e.jsxs(ke,{ref:v,type:"button",variant:"outline",size:"sm",className:Ju,onClick:()=>p(!f),children:[e.jsx(_t,{className:"h-3.5 w-3.5 mr-1"}),o]}),f&&(()=>{const V=[];P.forEach(({model:E,providerID:B,modelID:X})=>{V.push({model:E,providerID:B,modelID:X,section:"fav"})}),L.forEach(({model:E,providerID:B,modelID:X})=>{V.push({model:E,providerID:B,modelID:X,section:"recent"})}),U.forEach(E=>{E.models.forEach(B=>{V.push({model:B,providerID:E.id,modelID:B.id,section:"provider"})})});const J=V.length,T=E=>{if(!rl(E))if(E.key==="ArrowDown"){E.preventDefault(),E.stopPropagation();const B=(g+1)%Math.max(1,J);b(B),setTimeout(()=>{N.current[B]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(E.key==="ArrowUp"){E.preventDefault(),E.stopPropagation();const B=(g-1+Math.max(1,J))%Math.max(1,J);b(B),setTimeout(()=>{N.current[B]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(E.key==="Enter"){E.preventDefault(),E.stopPropagation();const B=V[g];B&&r({providerID:B.providerID,modelID:B.modelID,displayName:B.model.name||B.modelID,instanceId:Ho()})}else E.key==="Escape"&&(E.preventDefault(),E.stopPropagation(),p(!1),j(""),b(0))};let Z=0;return e.jsxs("div",{className:"absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden bg-background shadow-lg w-[min(380px,calc(100vw-2rem))] flex flex-col",children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(ur,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(mt,{ref:w,type:"text",placeholder:"Search models",value:h,onChange:E=>j(E.target.value),onKeyDown:T,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(ct,{outerClassName:"flex-1",style:{maxHeight:x?`${x}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!z&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),P.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ar,{className:"h-4 w-4 text-primary"}),"Favorites"]}),P.map(({model:E,providerID:B,modelID:X})=>{const re=Z++;return H(E,B,X,"fav",re,g===re)})]}),L.length>0&&e.jsxs(e.Fragment,{children:[P.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(tr,{className:"h-4 w-4"}),"Recent"]}),L.map(({model:E,providerID:B,modelID:X})=>{const re=Z++;return H(E,B,X,"recent",re,g===re)})]}),(P.length>0||L.length>0)&&U.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),U.map((E,B)=>e.jsxs(c.Fragment,{children:[B>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ts,{providerId:E.id,className:"h-4 w-4 flex-shrink-0"}),E.name]}),E.models.map(X=>{const re=Z++;return H(X,E.id,X.id,"provider",re,g===re)})]},E.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),a&&s.map((V,J)=>{const T=`${V.providerID}:${V.modelID}`,Z=D.get(T)||1,E=M(V);return e.jsx(Gx,{model:V,instanceIndex:E,totalSameModel:Z,onRemove:()=>t(J)},V.instanceId)})]}),n!==void 0&&s.length<n&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",n," ",i!==void 0?`to ${i} models`:"","."]})]})};function ks({...s}){return e.jsx(ip,{"data-slot":"select",...s})}function Tr({...s}){return e.jsx(pp,{"data-slot":"select-group",...s})}function Un({...s}){return e.jsx(dp,{"data-slot":"select-value",...s})}function Ns({className:s,size:r="default",children:t,...n}){return e.jsxs(lp,{"data-slot":"select-trigger","data-size":r,className:R("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-muted data-[state=open]:bg-muted focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 data-[size=lg]:h-8 data-[size=lg]:py-1.5 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",s),...n,children:[t,e.jsx(cp,{asChild:!0,children:e.jsx(Ct,{className:"size-4 opacity-50"})})]})}function Cs({className:s,children:r,position:t="popper",fitContent:n=!1,...o}){return e.jsx(up,{children:e.jsx(mp,{"data-slot":"select-content",className:R("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden rounded-xl border shadow-none transform-gpu will-change-transform",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",n&&"w-max min-w-0",s),position:t,...o,children:e.jsx(ct,{as:fp,outerClassName:R("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:R("p-1",t==="popper"&&(n?"h-[var(--radix-select-trigger-height)] w-max min-w-0 scroll-my-1":"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1")),children:r})})})}function ln({className:s,...r}){return e.jsx(hp,{"data-slot":"select-label",className:R("text-muted-foreground px-2 py-1.5 typography-meta",s),...r})}function qt({className:s,children:r,...t}){return e.jsxs(gp,{"data-slot":"select-item",className:R("hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",s),...t,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(yp,{children:e.jsx(Ot,{className:"size-4"})})}),e.jsx(xp,{children:r})]})}function Uo({className:s,...r}){return e.jsx(bp,{"data-slot":"select-separator",className:R("bg-border pointer-events-none -mx-1 my-1 h-px",s),...r})}function ol(s){const[r,t]=c.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=c.useState(!1),[a,i]=c.useState(null);return c.useEffect(()=>{let l=!1;if(!s){i(null),o(!1),t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),i(null),(async()=>{try{const d=await Wr(s);if(l)return;if(i(d),!d){t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await Wi(s).catch(()=>null);if(l)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(j=>!j.startsWith("remotes/")).sort((j,g)=>j.localeCompare(g)).forEach(j=>{m.push({value:j,label:j,group:"local"})}),u.all.filter(j=>j.startsWith("remotes/")).map(j=>j.replace(/^remotes\//,"")).sort((j,g)=>j.localeCompare(g)).forEach(j=>{m.push({value:j,label:j,group:"remote"})})),t(m)}finally{l||o(!1)}})(),()=>{l=!0}},[s]),{branches:r,isLoading:n,isGitRepository:a}}const em=({directory:s,value:r,onChange:t,className:n,disabled:o,id:a})=>{const{branches:i,isLoading:l,isGitRepository:d}=ol(s),u=c.useMemo(()=>i.find(f=>f.value===r)?.label??null,[i,r]);c.useEffect(()=>{!i.some(p=>p.value===r)&&i.length>0&&t("HEAD")},[i,r,t]);const m=o||!d||l;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ks,{value:r,onValueChange:t,disabled:m,children:[e.jsx(Ns,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(Un,{children:u}):e.jsx(Un,{placeholder:l?"Loading branches…":"Select a branch"})}),e.jsxs(Cs,{fitContent:!0,children:[e.jsxs(Tr,{children:[e.jsx(ln,{children:"Default"}),i.filter(f=>f.group==="special").map(f=>e.jsx(qt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),i.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(Uo,{}),e.jsxs(Tr,{children:[e.jsx(ln,{children:"Local branches"}),i.filter(f=>f.group==="local").map(f=>e.jsx(qt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,i.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(Uo,{}),e.jsxs(Tr,{children:[e.jsx(ln,{children:"Remote branches"}),i.filter(f=>f.group==="remote").map(f=>e.jsx(qt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null]})]}),d===!1&&e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."})]})},tm=({value:s,onChange:r,className:t,disabled:n,id:o})=>{const a=at(f=>f.getVisibleAgents),i=at(f=>f.loadAgents),l=at(f=>f.currentAgentName),d=a(),u=c.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);c.useEffect(()=>{i()},[i]),c.useEffect(()=>{if(n)return;const f=s.trim();if(f.length>0&&u.some(j=>j.name===f))return;const p=typeof l=="string"&&l.trim().length>0?l.trim():null;if(p&&u.some(j=>j.name===p)){r(p);return}const h=u[0]?.name;h&&r(h)},[l,n,r,u,s]);const m=s.trim().length>0?s:void 0;return e.jsxs(ks,{value:m,onValueChange:r,disabled:n,children:[e.jsx(Ns,{id:o,size:"lg",className:t??"max-w-full typography-meta text-foreground",children:e.jsx(Un,{placeholder:"Select an agent"})}),e.jsx(Cs,{fitContent:!0,children:u.length>0&&e.jsx(Tr,{children:u.map(f=>e.jsx(qt,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},qx=10*1024*1024,kc=5,Nc=({initialPrompt:s,onCreated:r,onCancel:t})=>{const[n,o]=c.useState(""),[a,i]=c.useState(()=>s??""),[l,d]=c.useState([]),[u,m]=c.useState(""),[f,p]=c.useState([]),[h,j]=c.useState(!1),[g,b]=c.useState([]),[x,y]=c.useState(!1),[w,S]=c.useState(!1),v=c.useRef(null),N=ft(F=>F.currentDirectory??null),D=c.useMemo(()=>{if(typeof window>"u")return null;const F=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof F=="string"&&F.trim().length>0?F.trim():null},[]),M=It(F=>F.activeProjectId),C=It(F=>F.projects),k=c.useMemo(()=>{if(M){const ee=C.find(ue=>ue.id===M);if(ee?.path)return ee.path}const F=N??D;if(!F)return null;const W=F.replace(/\\/g,"/").replace(/\/+$/,"")||F,_=W.indexOf("/.openchamber/");return _>0?W.slice(0,_):W.endsWith("/.openchamber")?W.slice(0,W.length-13):W},[M,C,N,D]),A=Re(F=>F.isSidebarOpen),[P,L]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),U=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const F=typeof window.opencodeDesktop<"u";L(F)},[]);const z=c.useMemo(()=>P&&U?A?"pl-0":"pl-[8.0rem]":"pl-3",[P,U,A]),[H,V]=c.useState("HEAD"),{isLoading:J,isGitRepository:T}=ol(N),Z=Rn(F=>F.createMultiRun),E=Rn(F=>F.error),B=Rn(F=>F.clearError);c.useEffect(()=>{typeof s=="string"&&s.trim().length>0&&i(F=>F.trim().length>0?F:s)},[s]),c.useEffect(()=>{if(!k)return;let F=!1;return S(!0),(async()=>{try{const W=await Yn(k);F||b(W)}catch{}finally{F||S(!1)}})(),()=>{F=!0}},[k]);const X=F=>{l.length>=kc||(d(W=>[...W,F]),B())},re=F=>{d(W=>W.filter((O,_)=>_!==F)),B()},q=async F=>{const W=F.target.files;if(!W)return;let O=0;for(let _=0;_<W.length;_++){const ee=W[_];if(ee.size>qx){se.error(`File "${ee.name}" is too large (max 10MB)`);continue}try{const ue=await new Promise((pe,He)=>{const Y=new FileReader;Y.onload=()=>pe(Y.result),Y.onerror=He,Y.readAsDataURL(ee)}),me={id:Ho(),filename:ee.name,mimeType:ee.type||"application/octet-stream",size:ee.size,dataUrl:ue};p(pe=>[...pe,me]),O++}catch(ue){console.error("File attach failed",ue),se.error(`Failed to attach "${ee.name}"`)}}O>0&&se.success(`Attached ${O} file${O>1?"s":""}`),v.current&&(v.current.value="")},oe=F=>{p(W=>W.filter(O=>O.id!==F))},ye=async F=>{if(F.preventDefault(),!!a.trim()&&!(l.length<2)){j(!0),B();try{const W=l.map(({instanceId:me,...pe})=>pe),O=f.map(me=>({mime:me.mimeType,filename:me.filename,url:me.dataUrl})),_=g.filter(me=>me.trim().length>0),ee={name:n.trim(),prompt:a.trim(),models:W,agent:u||void 0,worktreeBaseBranch:H,files:O.length>0?O:void 0,setupCommands:_.length>0?_:void 0},ue=await Z(ee);ue&&(ue.firstSessionId&&de.getState().setCurrentSession(ue.firstSessionId),r?.())}finally{j(!1)}}},I=!!(n.trim()&&a.trim()&&l.length>=2&&T&&!J);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:R("flex h-12 items-center justify-between border-b app-region-drag",z),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:R("flex items-center gap-3",P&&U&&A&&"pl-4"),children:e.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"})}),t&&e.jsx("div",{className:"flex items-center pr-3",children:e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,"aria-label":"Close",className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:e.jsx(Lt,{className:"h-5 w-5"})})}),e.jsx(tt,{children:e.jsx("p",{children:"Close"})})]})})]}),e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"chat-column py-6",children:e.jsxs("form",{onSubmit:ye,className:"space-y-6","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:["Group name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(mt,{id:"group-name",value:n,onChange:F=>o(F.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body max-w-full sm:max-w-xs",required:!0}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch names"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Worktrees"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Create one worktree per model by creating a new branch from a base branch."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"multirun-worktree-base-branch",children:"Base branch"}),e.jsx(em,{directory:N,value:H,onChange:V,id:"multirun-worktree-base-branch"}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:H||"HEAD"}),"."]})]}),e.jsxs(ia,{open:x,onOpenChange:y,children:[e.jsxs(sl,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",g.filter(F=>F.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",g.filter(F=>F.trim()).length," configured)"]})]}),e.jsx(Ct,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",x&&"rotate-180")})]}),e.jsx(la,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_WORKTREE_PATH"})," for project root."]}),w?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[g.map((F,W)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(mt,{value:F,onChange:O=>{const _=[...g];_[W]=O.target.value,b(_)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const O=g.filter((_,ee)=>ee!==W);b(O)},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(Lt,{className:"h-4 w-4"})})]},W)),e.jsxs("button",{type:"button",onClick:()=>b([...g,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(_t,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",htmlFor:"multirun-agent",children:"Agent"}),e.jsx(tm,{value:u,onChange:m,id:"multirun-agent"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:["Prompt ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(js,{id:"prompt",value:a,onChange:F=>i(F.target.value),placeholder:"Enter the prompt to send to all models...",className:"typography-body min-h-[120px] max-h-[400px] resize-none overflow-y-auto field-sizing-content",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Attachments"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"(optional, same files for all runs)"})]}),e.jsx("input",{ref:v,type:"file",multiple:!0,className:"hidden",onChange:q,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(ke,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>v.current?.click(),children:[e.jsx(To,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(F=>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:[F.mimeType.startsWith("image/")?e.jsx(mr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Qs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:F.filename,children:F.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",F.size<1024?`${F.size}B`:F.size<1024*1024?`${(F.size/1024).toFixed(1)}KB`:`${(F.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>oe(F.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Lt,{className:"h-3.5 w-3.5"})})]},F.id))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Models ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Zu,{selectedModels:l,onAdd:X,onRemove:re,minModels:2,maxModels:kc})]}),E&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:E}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(ke,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(ke,{type:"submit",disabled:!I||h,children:h?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(wp,{className:"h-4 w-4 mr-2"}),"Start (",l.length," models)"]})})]})]})})})]})},Kx=(s={})=>{const{edgeThreshold:r=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=s,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:l}=Re(),d=Me.useRef(null),u=Me.useRef(null);return Me.useEffect(()=>{if(!o||!a)return;const m=j=>{const g=j.touches[0];if(!g){d.current=null;return}g.clientX<=r?d.current={x:g.clientX,y:g.clientY,time:Date.now()}:d.current=null},f=j=>{if(!d.current)return;const g=j.touches[0];if(!g)return;g.clientX-d.current.x>10&&j.preventDefault()},p=j=>{if(!d.current)return;const g=j.changedTouches[0];if(!g){d.current=null,u.current=null;return}u.current={x:g.clientX,y:g.clientY,time:Date.now()};const{x:b,y:x,time:y}=d.current,{x:w,y:S,time:v}=u.current,N=w-b,D=S-x,M=v-y,C=Math.abs(D)<Math.abs(N),k=M<=n,A=Math.abs(D)<t;N>=t&&C&&k&&A&&!l&&i(!0),d.current=null,u.current=null},h=()=>{d.current=null,u.current=null};return document.addEventListener("touchstart",m,{passive:!0,capture:!0}),document.addEventListener("touchmove",f,{passive:!1,capture:!0}),document.addEventListener("touchend",p,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",m,{capture:!0}),document.removeEventListener("touchmove",f,{capture:!0}),document.removeEventListener("touchend",p,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0})}},[o,a,r,t,n,i,l]),null},An=s=>s==="full"?{text:"var(--status-info)",border:"var(--status-info-border)",background:"var(--status-info-background)",borderWidth:1.5}:s==="allow"?{text:"var(--status-success)",border:"var(--status-success-border)",background:"var(--status-success-background)",borderWidth:1.5}:null;Me.memo(()=>{const s=Me.useRef(null),{addAttachedFile:r}=de(),{isMobile:t}=Re(),n=Lu(),o=t?"h-9 w-9":"h-7 w-7",a=t?"h-5 w-5":"h-[18px] w-[18px]",i=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],h=de.getState().attachedFiles.length;try{await r(p),de.getState().attachedFiles.length>h&&m++}catch(j){console.error("File attach failed",j),se.error(j instanceof Error?j.message:"Failed to attach file")}}m>0&&se.success(`Attached ${m} file${m>1?"s":""}`)},l=async u=>{const m=u.target.files;m&&(await i(m),s.current&&(s.current.value=""))},d=async()=>{try{const m=await(await fetch("/api/vscode/pick-files")).json(),f=Array.isArray(m?.files)?m.files:[],p=Array.isArray(m?.skipped)?m.skipped:[];if(p.length>0){const j=p.map(g=>`${g?.name||"file"}: ${g?.reason||"skipped"}`).join(`
|
|
66
|
+
`);se.error(`Some files were skipped:
|
|
67
|
+
${j}`)}const h=f.map(j=>{if(!j?.dataUrl)return null;try{const[g,b]=j.dataUrl.split(","),x=j.mimeType||g?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!b)return null;const y=atob(b),w=new Uint8Array(y.length);for(let v=0;v<y.length;v++)w[v]=y.charCodeAt(v);const S=new Blob([w],{type:x});return new File([S],j.name||"file",{type:x})}catch(g){return console.error("Failed to decode VS Code picked file",g),null}}).filter(Boolean);h.length>0&&await i(h)}catch(u){console.error("VS Code file pick failed",u),se.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:s,type:"file",multiple:!0,className:"hidden",onChange:l,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():s.current?.click()},className:R(o,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),title:"Attach files",children:e.jsx(To,{className:R(a,"text-current")})})]})});const Yx=Me.memo(({file:s,onRemove:r})=>{const t=()=>s.mimeType.startsWith("image/")?e.jsx(mr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("text")||s.mimeType.includes("code")?e.jsx(Qs,{className:"h-3.5 w-3.5"}):s.mimeType.includes("json")||s.mimeType.includes("xml")?e.jsx(Qo,{className:"h-3.5 w-3.5"}):e.jsx(Qs,{className:"h-3.5 w-3.5"}),n=i=>i<1024?i+" B":i<1048576?(i/1024).toFixed(1)+" KB":(i/1048576).toFixed(1)+" MB",a=(i=>{const d=i.replace(/\\/g,"/").split("/");return d[d.length-1]||i})(s.filename);return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[e.jsx("div",{title:s.source==="server"?"Server file":"Local file",children:s.source==="server"?e.jsx(vp,{className:"h-3 w-3 text-primary"}):e.jsx(Ld,{className:"h-3 w-3 text-muted-foreground"})}),t(),e.jsx("span",{title:s.serverPath||a,children:a}),e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["(",n(s.size),")"]}),e.jsx("button",{onClick:r,className:"ml-1 hover:text-destructive p-0.5",title:"Remove file",children:e.jsx(Lt,{className:"h-3 w-3"})})]})}),Xx=Me.memo(()=>{const{attachedFiles:s,removeAttachedFile:r}=de();return s.length===0?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Attached:"}),s.map(t=>e.jsx(Yx,{file:t,onRemove:()=>r(t.id)},t.id))]})})}),sm=Me.memo(({files:s,onShowPopup:r})=>{const t=s.filter(d=>d.type==="file"&&(d.mime||d.url)),n=d=>{if(!d)return"Unnamed file";const m=d.replace(/\\/g,"/").split("/");return m[m.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(mr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(Qs,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Qo,{className:"h-3.5 w-3.5"}):e.jsx(Qs,{className:"h-3.5 w-3.5"}):e.jsx(Qs,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),i=t.filter(d=>!d.mime?.startsWith("image/")),l=c.useCallback(d=>{if(!r||!d?.url)return;const u=n(d.filename)||"Image",m={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};r(m)},[r]);return t.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("span",{children:n(d.filename)})]},`file-${u}`))}),a.length>0&&e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-1 scrollbar-thin",children:e.jsx("div",{className:"flex gap-3 snap-x snap-mandatory",children:a.map((d,u)=>{const m=n(d.filename)||"Image";return e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>l(d),className:"relative flex-none w-16 sm:w-20 md:w-24 aspect-square rounded-xl border border-border/40 bg-muted/10 overflow-hidden snap-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[d.url?e.jsx("img",{src:d.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:f=>{const p=f.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(mr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(tt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),rm=Me.memo(({message:s,sessionId:r,onEdit:t})=>{const n=qs(i=>i.removeFromQueue),o=c.useMemo(()=>{const i=s.content.split(`
|
|
68
|
+
`),l=i[0]||"",d=50;return l.length>d?l.substring(0,d)+"...":l+(i.length>1?"...":"")},[s.content]),a=s.attachments?.length??0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta group",children:[e.jsx(jp,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>t(s),className:"flex items-center gap-1.5 hover:text-foreground transition-colors text-left",title:"Click to edit",children:[e.jsx("span",{className:"truncate max-w-[200px]",children:o||"(empty)"}),a>0&&e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["+",a," file",a>1?"s":""]})]}),e.jsx("button",{type:"button",onClick:()=>n(r,s.id),className:"ml-1 hover:text-destructive p-0.5 opacity-60 group-hover:opacity-100 transition-opacity",title:"Remove from queue",children:e.jsx(Lt,{className:"h-3 w-3"})})]})});rm.displayName="QueuedMessageChip";const Cc=[],nm=Me.memo(({onEditMessage:s})=>{const r=de(a=>a.currentSessionId),t=qs(c.useCallback(a=>r?a.queuedMessages[r]??Cc:Cc,[r])),n=qs(a=>a.popToInput),o=c.useCallback(a=>{if(!r)return;const i=n(r,a.id);if(i){if(i.attachments&&i.attachments.length>0){const l=Ys.getState().attachedFiles;Ys.setState({attachedFiles:[...l,...i.attachments]})}s(i.content,i.attachments)}},[r,n,s]);return t.length===0||!r?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Queued:"}),t.map(a=>e.jsx(rm,{message:a,sessionId:r,onEdit:o},a.id))]})})});nm.displayName="QueuedMessageChips";const om=(s,r=200)=>{const[t,n]=Me.useState(s);return Me.useEffect(()=>{const o=window.setTimeout(()=>{n(s)},r);return()=>{window.clearTimeout(o)}},[s,r]),t},Qx=c.forwardRef(({searchQuery:s,onFileSelect:r,onClose:t},n)=>{const{currentDirectory:o}=ft(),{addServerFile:a}=de(),i=Li(A=>A.searchFiles),l=om(s,180),[d,u]=c.useState([]),[m,f]=c.useState(!1),[p,h]=c.useState(0),[j,g]=c.useState(360),[b,x]=c.useState({}),[y,w]=c.useState({}),S=c.useRef([]),v=c.useRef([]),N=c.useRef([]),D=c.useRef(null),M=c.useCallback((A,P)=>{const L=A.trim().toLowerCase();if(!L)return 0;const U=P.toLowerCase();let z=0,H=-1,V=0;for(let J=0;J<L.length;J+=1){const T=L[J];if(!T||T===" ")continue;const Z=U.indexOf(T,H+1);if(Z===-1)return null;const E=Z-H-1;if(E===0?V+=1:V=0,z+=10,z+=Math.max(0,18-Z),z-=Math.max(0,E),Z===0)z+=12;else{const B=U[Z-1];(B==="/"||B==="_"||B==="-"||B==="."||B===" ")&&(z+=10)}z+=V>0?12:0,H=Z}return z+=Math.max(0,24-Math.round(U.length/3)),z},[]);c.useEffect(()=>{const A=P=>{const L=P.target;!L||!D.current||D.current.contains(L)||t()};return document.addEventListener("pointerdown",A,!0),()=>{document.removeEventListener("pointerdown",A,!0)}},[t]),c.useEffect(()=>{if(!o){u([]);return}const P=(l??"").trim().toLowerCase();let L=!1;return f(!0),i(o,P,80).then(U=>{if(L)return;const z=P?U.map(H=>{const V=H.relativePath||H.name||H.path,J=M(P,V);return J===null?null:{file:H,score:J,labelLength:V.length}}).filter(Boolean):U.map(H=>({file:H,score:0,labelLength:(H.relativePath||H.name||H.path).length}));z.sort((H,V)=>V.score-H.score||H.labelLength-V.labelLength||H.file.path.localeCompare(V.file.path)),u(z.slice(0,15).map(H=>H.file))}).catch(()=>{L||u([])}).finally(()=>{L||f(!1)}),()=>{L=!0}},[o,l,M,i]),c.useEffect(()=>{h(0),x({}),w({})},[d]),c.useEffect(()=>{S.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]),c.useEffect(()=>{let A=null;const P=()=>{A!==null&&cancelAnimationFrame(A),A=requestAnimationFrame(()=>{const L={},U={};v.current.forEach((z,H)=>{if(!z)return;const J=N.current[H]?.offsetWidth??z.scrollWidth,T=Math.max(0,J-z.clientWidth),Z=T>8;if(L[H]=Z,Z){const E=Math.max(.6,T/110);U[H]=E}}),x(L),w(U)})};return P(),window.addEventListener("resize",P),()=>{A!==null&&cancelAnimationFrame(A),window.removeEventListener("resize",P)}},[d]),c.useEffect(()=>{const A=v.current[p];if(!A)return;const P=()=>{const U=A.clientWidth;U>0&&g(U)};if(P(),typeof ResizeObserver>"u")return;const L=new ResizeObserver(P);return L.observe(A),()=>{L.disconnect()}},[p]);const C=c.useCallback(async A=>{await a(A.path,A.name),r(A)},[a,r]);c.useImperativeHandle(n,()=>({handleKeyDown:A=>{if(A==="Escape"){t();return}const P=d.length;if(P!==0){if(A==="ArrowDown"){h(L=>(L+1)%P);return}if(A==="ArrowUp"){h(L=>(L-1+P)%P);return}if(A==="Enter"||A==="Tab"){const L=(p%P+P)%P,U=d[L];U&&C(U)}}}}),[d,p,t,C]);const k=A=>{switch(A.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(er,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(er,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(mr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Qo,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:D,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(ct,{outerClassName:"flex-1 min-h-0",className:"px-0",children:m?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(qn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((A,P)=>{const L=A.relativePath||A.name,U=eu(L,{maxLength:45}),z=p===P,H=b[P]??!1,V=y[P]??2.6,J=e.jsxs("div",{ref:T=>{S.current[P]=T},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",z&&"bg-muted"),onClick:()=>C(A),onMouseEnter:()=>h(P),children:[k(A),e.jsxs("span",{ref:T=>{v.current[P]=T},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:z?{"--file-mention-marquee-width":`${j}px`,"--file-mention-marquee-duration":`${V}s`}:void 0,"aria-label":L,children:[e.jsx("span",{ref:T=>{N.current[P]=T},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:L}),H&&z?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:L}):e.jsx("span",{className:"block truncate",children:U})]})]});return e.jsx(c.Fragment,{children:J},A.path)}),d.length>0&&e.jsx("div",{className:"h-2"}),d.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No files found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})}),am=c.forwardRef(({searchQuery:s,onCommandSelect:r,onClose:t},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=de(Ii(b=>{const x=b.currentSessionId;return{hasMessagesInCurrentSession:(x?b.messages.get(x)?.length??0:0)>0,currentSessionId:x}})),i=!!a,[l,d]=c.useState([]),[u,m]=c.useState(!1),[f,p]=c.useState(0),h=c.useRef([]),j=c.useRef(null);c.useEffect(()=>{const b=x=>{const y=x.target;!y||!j.current||j.current.contains(y)||t()};return document.addEventListener("pointerdown",b,!0),()=>{document.removeEventListener("pointerdown",b,!0)}},[t]),c.useEffect(()=>{(async()=>{m(!0);try{const y=(await De.listCommands()).map(M=>({name:M.name,description:M.description,agent:M.agent,model:M.model,isBuiltIn:!1})),w=[...i&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...i?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],S=new Map;w.forEach(M=>S.set(M.name,M)),y.forEach(M=>S.set(M.name,M));const v=Array.from(S.values()),N=!o,D=(s?v.filter(M=>M.name.toLowerCase().includes(s.toLowerCase())||M.description&&M.description.toLowerCase().includes(s.toLowerCase())):v).filter(M=>N||M.name!=="init");D.sort((M,C)=>{const k=M.name.toLowerCase().startsWith(s.toLowerCase()),A=C.name.toLowerCase().startsWith(s.toLowerCase());return k&&!A?-1:!k&&A?1:M.name.localeCompare(C.name)}),d(D)}catch{const x=!o,y=[...i&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...i?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],w=(s?y.filter(S=>S.name.toLowerCase().includes(s.toLowerCase())||S.description&&S.description.toLowerCase().includes(s.toLowerCase())):y).filter(S=>x||S.name!=="init");d(w)}finally{m(!1)}})()},[s,o,i]),c.useEffect(()=>{p(0)},[l]),c.useEffect(()=>{h.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),c.useImperativeHandle(n,()=>({handleKeyDown:b=>{const x=l.length;if(b==="Escape"){t();return}if(x!==0){if(b==="ArrowDown"){p(y=>(y+1)%x);return}if(b==="ArrowUp"){p(y=>(y-1+x)%x);return}if(b==="Enter"||b==="Tab"){const y=(f%x+x)%x,w=l[y];w&&r(w)}}}}),[l,f,t,r]);const g=b=>{switch(b.name){case"init":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(On,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(Np,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(tr,{className:"h-3.5 w-3.5 text-blue-500"});case"summarize":return e.jsx(kp,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Sr,{className:"h-3.5 w-3.5 text-cyan-500"});default:return b.isBuiltIn?e.jsx(Sp,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx($r,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:j,className:"absolute z-[100] min-w-0 w-full max-w-[450px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(ct,{outerClassName:"flex-1 min-h-0",className:"px-0",children:u?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(qn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[l.map((b,x)=>e.jsxs("div",{ref:y=>{h.current[x]=y},className:R("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",x===f&&"bg-muted"),onClick:()=>r(b),onMouseEnter:()=>p(x),children:[e.jsx("div",{className:"mt-0.5",children:g(b)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-medium",children:["/",b.name]}),b.agent&&e.jsx("span",{className:"typography-meta text-muted-foreground bg-muted px-1.5 py-0.5 rounded",children:b.agent})]}),b.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:b.description})]})]},b.name)),l.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});am.displayName="CommandAutocomplete";const Jx=s=>s?s!=="primary":!1,im=c.forwardRef(({searchQuery:s,onAgentSelect:r,onClose:t},n)=>{const o=c.useRef(null),[a,i]=c.useState(0),[l,d]=c.useState([]),{getVisibleAgents:u}=at();c.useEffect(()=>{const p=u().filter(g=>Jx(g.mode)).map(g=>({name:g.name,description:g.description,mode:g.mode??void 0})),h=s.trim().toLowerCase(),j=h.length?p.filter(g=>g.name.toLowerCase().includes(h)):p;j.sort((g,b)=>g.name.localeCompare(b.name)),d(j),i(0)},[u,s]),c.useEffect(()=>{const f=p=>{const h=p.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",f,!0),()=>{document.removeEventListener("pointerdown",f,!0)}},[t]),c.useImperativeHandle(n,()=>({handleKeyDown:f=>{if(f==="Escape"){t();return}if(l.length){if(f==="ArrowDown"){i(p=>(p+1)%l.length);return}if(f==="ArrowUp"){i(p=>(p-1+l.length)%l.length);return}if(f==="Enter"||f==="Tab"){const p=l[(a+l.length)%l.length];p&&r(p.name)}}}}),[l,r,t,a]);const m=(f,p)=>e.jsx("div",{className:R("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",p===a&&"bg-muted"),onClick:()=>r(f.name),onMouseEnter:()=>i(p),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-semibold",children:["#",f.name]})}),f.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:f.description})]})},f.name);return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(ct,{outerClassName:"flex-1 min-h-0",className:"px-0",children:l.length?e.jsx("div",{children:l.map((f,p)=>m(f,p))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No agents found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});im.displayName="AgentMentionAutocomplete";function Zx({className:s,children:r,...t}){return e.jsxs(Cp,{"data-slot":"scroll-area",className:R("relative",s),...t,children:[e.jsx(Mp,{"data-slot":"scroll-area-viewport",className:"focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:outline-none focus-visible:ring-[3px] will-change-scroll",children:r}),e.jsx(eb,{}),e.jsx(Dp,{})]})}function eb({className:s,orientation:r="vertical",...t}){return e.jsx(Ap,{"data-slot":"scroll-area-scrollbar",orientation:r,className:R("flex touch-none p-px select-none",r==="vertical"&&"h-full w-2.5 border-l border-l-transparent",r==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",s),...t,children:e.jsx(Ep,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const tb=({onFilesSelected:s,multiSelect:r=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=$t(),l=i,{currentDirectory:d}=ft(),u=Li(te=>te.searchFiles),[m,f]=c.useState(!1),[p,h]=c.useState(!1),[j,g]=c.useState(""),b=om(j,200),[x,y]=c.useState(new Set),[w,S]=c.useState(new Set),[v,N]=c.useState({}),D=c.useRef(new Set),M=c.useRef(new Set),[C,k]=c.useState([]),[A,P]=c.useState(!1),[L,U]=c.useState(!1),[z,H]=c.useState(!1),[V,J]=c.useState(null),T=n??m,Z=o??f,E=c.useCallback(te=>te.slice().sort((ne,K)=>ne.type!==K.type?ne.type==="directory"?-1:1:ne.name.localeCompare(K.name)),[]),B=c.useCallback((te,ne)=>E(ne.filter(K=>!K.name.startsWith(".")).map(K=>{const ie=K.name,ce=!K.isDirectory&&ie.includes(".")?ie.split(".").pop()?.toLowerCase():void 0;return{name:ie,path:K.path||`${te}/${ie}`,type:K.isDirectory?"directory":"file",size:0,extension:ce}})),[E]),X=c.useCallback(async te=>{U(!0),J(null);try{const ne=await De.listLocalDirectory(te),K=B(te,ne.map(ie=>({name:ie.name,path:ie.path,isDirectory:ie.isDirectory})));D.current=new Set([te]),M.current=new Set,N({[te]:K}),S(new Set)}catch{J("Failed to load directory contents"),D.current=new Set([te]),M.current=new Set,N({[te]:[]}),S(new Set)}finally{U(!1)}},[B]),re=c.useCallback(async te=>{const ne=te.trim();if(ne&&!D.current.has(ne)&&!M.current.has(ne)){M.current=new Set(M.current),M.current.add(ne);try{const K=await De.listLocalDirectory(ne),ie=B(ne,K.map(ce=>({name:ce.name,path:ce.path,isDirectory:ce.isDirectory})));D.current=new Set(D.current),D.current.add(ne),N(ce=>({...ce,[ne]:ie}))}catch{N(K=>K[ne]?K:{...K,[ne]:[]})}finally{M.current=new Set(M.current),M.current.delete(ne)}}},[B]);c.useEffect(()=>{(T||p)&&d&&X(d)},[T,p,d,X]),c.useEffect(()=>{if(!(T||p)||!d){k([]),P(!1);return}const te=b.trim();if(!te){k([]),P(!1);return}let ne=!1;return P(!0),u(d,te,150).then(K=>{if(ne)return;const ie=K.map(ce=>({name:ce.name,path:ce.path,type:"file",extension:ce.extension,relativePath:ce.relativePath,size:0}));k(ie)}).catch(()=>{ne||k([])}).finally(()=>{ne||P(!1)}),()=>{ne=!0}},[T,p,d,b,u]),c.useEffect(()=>{!T&&!p&&(y(new Set),g(""),k([]),P(!1))},[T,p]);const q=te=>{if(te.type==="directory")return w.has(te.path)?e.jsx(Ts,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(Ts,{className:"h-3.5 w-3.5 text-primary/60"});switch(te.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(er,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(er,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(ri,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(mr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(ri,{className:"h-3.5 w-3.5 text-muted-foreground"})}},oe=async te=>{w.has(te)?S(K=>{const ie=new Set(K);return ie.delete(te),ie}):(S(K=>{const ie=new Set(K);return ie.add(te),ie}),await re(te))},ye=te=>{y(r?ne=>{const K=new Set(ne);return K.has(te)?K.delete(te):K.add(te),K}:new Set([te]))},I=async()=>{const te=new Map;Object.values(v).forEach(ie=>{ie.forEach(ce=>{ce.type==="file"&&te.set(ce.path,ce)})});const ne=new Map(C.map(ie=>[ie.path,ie])),K=Array.from(x).map(ie=>te.get(ie)??ne.get(ie)).filter(ie=>!!ie);H(!0);try{await s(K),y(new Set),Z(!1),h(!1)}finally{H(!1)}},F=c.useMemo(()=>d?v[d]??[]:[],[v,d]),W=j.trim().length>0,O=te=>v[te]??[],_=te=>{if(d&&te.startsWith(d)){const ne=te.substring(d.length);return ne.startsWith("/")?ne.substring(1):ne}return te.split("/").pop()||te},ee=(te,ne)=>{const K=W?te.relativePath||_(te.path):te.name,ie=W&&K.includes("/")&&K.length>45,ce=ie?eu(K,{maxLength:l?42:48}):K,ae=e.jsxs("div",{className:R("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded hover:bg-muted cursor-pointer typography-ui-label text-foreground text-left",te.type==="file"&&x.has(te.path)&&"bg-primary/10"),style:{paddingLeft:`${ne*12}px`},onClick:$=>{$.preventDefault(),$.stopPropagation(),te.type==="file"&&ye(te.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:q(te)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":K,children:ce})]}),te.type==="file"&&x.has(te.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return ie?e.jsxs(nt,{delayDuration:120,children:[e.jsx(ot,{asChild:!0,children:ae}),e.jsx(tt,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:K})})]},te.path):c.cloneElement(ae,{key:te.path})},ue=(te,ne)=>{const K=te.type==="directory",ie=K?O(te.path):[],ce=w.has(te.path),ae=K&&ce&&M.current.has(te.path)&&ie.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!K&&x.has(te.path)&&"bg-primary/10"),style:{paddingLeft:`${ne*12}px`},onClick:$=>{$.preventDefault(),$.stopPropagation(),K?oe(te.path):ye(te.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:q(te)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:te.name}),!K&&x.has(te.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),K&&ce&&ie.length>0&&e.jsx("div",{children:ie.map($=>ue($,ne+1))}),K&&ce&&ae&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(ne+1)*12}px`},children:"Loading…"})]},te.path)},me=x.size>0?`${x.size} file${x.size!==1?"s":""} selected`:"No files selected",pe=e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 shrink-0",children:[e.jsx("div",{className:"typography-meta text-muted-foreground",children:me}),e.jsx(ke,{size:"sm",onClick:I,disabled:x.size===0||z,className:"h-6 typography-meta",children:z?"Attaching...":"Attach Files"})]}),He=l?"flex-1 min-h-[240px]":"h-[300px]",Y=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsx("div",{className:"font-medium typography-ui-label text-foreground",children:"Select Project Files"})}),e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(ur,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(mt,{value:j,onChange:te=>g(te.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:te=>te.stopPropagation()}),j&&e.jsx("button",{onClick:te=>{te.stopPropagation(),g("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(Lt,{className:"h-3 w-3"})})]})}),e.jsxs(Zx,{className:He,children:[L&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Loading files..."})}),V&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:V})}),!L&&!V&&e.jsxs("div",{className:"py-1 px-2",children:[W?A?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):C.map(te=>ee(te,0)):F.map(te=>ue(te,0)),!W&&F.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),W&&!A&&C.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),le=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:te=>{te.preventDefault(),te.stopPropagation(),h(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:te=>{te.preventDefault(),te.stopPropagation(),Z(!0)},children:t}):null,e.jsx(vs,{open:T,onClose:()=>Z(!1),title:"Select Project Files",footer:pe,children:e.jsx("div",{className:"flex flex-col gap-0",children:Y})})]}):l?e.jsxs(e.Fragment,{children:[le,e.jsx(vs,{open:p,onClose:()=>h(!1),title:"Select Project Files",footer:pe,children:e.jsx("div",{className:"flex flex-col gap-0",children:Y})})]}):e.jsxs(Kt,{open:T,onOpenChange:Z,children:[e.jsx(Yt,{asChild:!0,children:t}),e.jsxs(Xt,{className:R("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[Y,e.jsx(Xs,{}),pe]})]})},lo=[{var:"--status-success",class:"agent-success"},{var:"--syntax-keyword",class:"agent-keyword"},{var:"--syntax-type",class:"agent-type"},{var:"--syntax-function",class:"agent-function"},{var:"--syntax-number",class:"agent-number"},{var:"--status-info",class:"agent-info"},{var:"--status-warning",class:"agent-warning"},{var:"--syntax-variable",class:"agent-variable"}];function xr(s){if(!s||s==="build")return lo[0];let r=0;for(let n=0;n<s.length;n++){const o=s.charCodeAt(n);r=(r<<5)-r+o,r=r&r}const t=1+Math.abs(r)%(lo.length-1);return lo[t]}const sb=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),lm=s=>sb(s),rb=s=>s?typeof s=="string"?s==="ask":lm(s)?Object.values(s).some(r=>r==="ask"):!1:!1,nb=s=>s?typeof s=="string"?s==="deny":lm(s)?Object.values(s).some(r=>r==="deny"):!1:!1,cm=({agentDefaultEditMode:s,webfetchPermission:r,bashPermission:t})=>{const n=rb(t),o=nb(t),a=!n&&!o,i=r==="allow",l=r!=="deny",d=s==="allow"||s==="full",u=s==="ask";let m=s;d&&i&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:s!=="deny"&&l&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:l}},co=s=>s==="primary"||s==="all"||s===void 0||s===null,Vo=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},uo=(s,r)=>{const t=Vo(s);if(!(!t||t.length===0)){for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},ob=(s,r)=>{const t=Vo(s);if(!t||t.length===0)return;const n={};for(const o of t)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},ab=[{key:"tool_call",icon:Jo,label:"Tool calling",isActive:s=>s?.tool_call===!0},{key:"reasoning",icon:xn,label:"Reasoning",isActive:s=>s?.reasoning===!0}],ib={text:{icon:_d,label:"Text"},image:{icon:mr,label:"Image"},video:{icon:Pp,label:"Video"},audio:{icon:Ip,label:"Audio"},pdf:{icon:Qo,label:"PDF"}},lb=s=>s.trim().toLowerCase(),Mn=(s,r)=>{const t=r==="input"?s?.modalities?.input:s?.modalities?.output;return!Array.isArray(t)||t.length===0?[]:Array.from(new Set(t.map(o=>lb(o)))).map(o=>{const a=ib[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},cb=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),db=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Is=s=>{if(typeof s!="number"||Number.isNaN(s))return"—";if(s===0)return"0";const r=cb.format(s);return r.endsWith(".0")?r.slice(0,-2):r},mo=s=>typeof s!="number"||!Number.isFinite(s)?"—":db.format(s),Ra=s=>ab.filter(r=>r.isActive(s)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Mc=s=>{if(!s)return"—";const r=s.match(/^(\d{4})-(\d{2})$/);if(r){const t=Number.parseInt(r[1],10),n=Number.parseInt(r[2],10)-1,o=new Date(Date.UTC(t,n,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return s},Dc=s=>{if(!s)return"—";const r=new Date(s);return Number.isNaN(r.getTime())?s:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(r)},Ac=({className:s})=>{const{providers:r,currentProviderId:t,currentModelId:n,currentAgentName:o,setProvider:a,setModel:i,setAgent:l,getCurrentProvider:d,getModelMetadata:u,getCurrentAgent:m,getVisibleAgents:f}=at(),p=f(),{currentSessionId:h,messages:j,saveSessionAgentSelection:g,getSessionAgentSelection:b,saveAgentModelForSession:x,getAgentModelForSession:y,analyzeAndSaveExternalSessionChoices:w,getSessionAgentEditMode:S,setSessionAgentEditMode:v}=de(),N=vt(he=>he.hasHydrated),{toggleFavoriteModel:D,isFavoriteModel:M,addRecentModel:C,isModelSelectorOpen:k,setModelSelectorOpen:A}=Re(),{favoriteModelsList:P,recentModelsList:L}=nl(),{isMobile:U}=$t(),z=Hy(),H=Lu(),V=U,[J,T]=c.useState(null),[Z,E]=c.useState(null),[B,X]=c.useState(""),re=c.useCallback(()=>T(null),[]),q=c.useCallback(()=>E(null),[]),oe=c.useRef(void 0),[ye,I]=c.useState(()=>{const he=new Set;return t&&he.add(t),he}),[F,W]=c.useState(!1),O=k,_=A,[ee,ue]=c.useState(!1),me=c.useId(),[pe,He]=c.useState(""),[Y,le]=c.useState(0),te=c.useRef([]);c.useEffect(()=>{J==="model"&&I(()=>{const he=new Set;return t&&he.add(t),he})},[J,t]),c.useEffect(()=>{J!=="agent"&&W(!1),J!=="model"&&X("")},[J]);const ne=c.useRef(O);c.useEffect(()=>{const he=ne.current;ne.current=O,O||(ue(!1),He(""),le(0),he&&!V&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[O,V]),c.useEffect(()=>{le(0)},[pe]);const K=m?.(),ie=c.useMemo(()=>K?uo(K.permission,"edit")??"ask":"deny",[K]),ce=c.useMemo(()=>{if(K)return uo(K.permission,"webfetch")},[K]),ae=c.useMemo(()=>{if(!K)return;const he=ob(K.permission,"bash");return he||void 0},[K]),$=c.useMemo(()=>cm({agentDefaultEditMode:ie,webfetchPermission:ce,bashPermission:ae}),[ie,ce,ae]),{cascadeDefaultMode:we,modeAvailability:fe,autoApproveAvailable:ve}=$,Le=!!(h&&o),Ge=Le&&h&&o?S(h,o,we):we,Te={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},Pe=c.useCallback(he=>!fe[he],[fe]),Ve=c.useMemo(()=>!Le||Pe(Ge)&&Ge!==we?we:Ge,[we,Pe,Le,Ge]),pt=[{mode:"ask",label:Te.ask,disabled:Pe("ask")},{mode:"allow",label:Te.allow,disabled:Pe("allow")},{mode:"full",label:Te.full,disabled:Pe("full")}],et=c.useMemo(()=>An(Ve),[Ve]),wt=!Le||!ve;c.useEffect(()=>{wt&&(W(!1),ue(!1))},[wt]);const Nt=U?"mobile":H?"vscode":"default",Pt=Nt==="mobile"?"h-9":Nt==="vscode"?"h-6":"h-8",St=Nt==="mobile"?"h-5 w-5":"h-4 w-4",At=Nt==="mobile"?"h-5 w-5":"h-4 w-4",Jt=V?"typography-micro":"typography-meta",Ee=Nt==="mobile"?"gap-x-2":Nt==="vscode"?"gap-x-1":"gap-x-3",Oe=Te[Ve],We=c.useCallback((he,Ne=St)=>{const Se=R(Ne,"flex-shrink-0"),G=An(he),_e={color:G?G.text:"var(--foreground)"};return he==="full"?e.jsx(or,{className:Se,style:_e}):he==="allow"?e.jsx(bo,{className:Se,style:_e}):he==="deny"?e.jsx(un,{className:Se,style:_e}):e.jsx(cn,{className:Se,style:_e})},[St]),Ze=c.useCallback(he=>{wt||!h||!o||Pe(he)||(v(h,o,he,we),_(!1),W(!1),ue(!1))},[we,wt,h,o,v,_,ue,Pe]),Zt=d(),zt=Array.isArray(Zt?.models)?Zt.models:[],dt=t&&n?u(t,n):void 0,Be=Ra(dt),Ye=Mn(dt,"input"),Je=Mn(dt,"output"),Qe=[{label:"Input",value:mo(dt?.cost?.input)},{label:"Output",value:mo(dt?.cost?.output)},{label:"Cache read",value:mo(dt?.cost?.cache_read)},{label:"Cache write",value:mo(dt?.cost?.cache_write)}],it=[{label:"Context",value:Is(dt?.limit?.context)},{label:"Output",value:Is(dt?.limit?.output)}],ht=c.useRef(void 0),Q=h?j.get(h)?.length??-1:-1,be=c.useRef(null),xe=c.useCallback((he,Ne,Se)=>{if(!he||!Ne)return"model-missing";const G=r.find(Ce=>Ce.id===he);return G?(Array.isArray(G.models)?G.models:[]).find(Ce=>Ce.id===Ne)?(a(he),i(Ne),h&&Se&&x(h,Se,he,Ne),"applied"):"model-missing":"provider-missing"},[r,a,i,h,x]);c.useEffect(()=>{if(!h){be.current=null;return}if(!N||r.length===0||p.length===0)return;(!be.current||be.current.sessionId!==h)&&(be.current={sessionId:h,resolved:!1,inFlight:!1});const he=be.current;if(!he||he.resolved||he.inFlight)return;let Ne=!1;const Se=()=>{if(Ne)return;const Ce=be.current;Ce&&Ce.sessionId===h&&(Ce.resolved=!0,Ce.inFlight=!1)},G=()=>{const Ce=b(h);if(Ce){o!==Ce&&l(Ce);const Fe=y(h,Ce);if(Fe){const ge=xe(Fe.providerId,Fe.modelId,Ce);if(ge==="applied")return"resolved";if(ge==="provider-missing")return"waiting"}else return"resolved"}for(const Fe of p){const ge=y(h,Fe.name);if(!ge)continue;o!==Fe.name&&l(Fe.name),g(h,Fe.name);const ze=xe(ge.providerId,ge.modelId,Fe.name);if(ze==="applied")return"resolved";if(ze==="provider-missing")return"waiting"}return"continue"},Ae=()=>{if(p.length===0)return;const Ce=p.filter(ge=>co(ge.mode)),Fe=p.find(ge=>ge.name==="build")||Ce[0]||p[0];Fe&&(g(h,Fe.name),o!==Fe.name&&l(Fe.name),Fe.model?.providerID&&Fe.model?.modelID&&xe(Fe.model.providerID,Fe.model.modelID,Fe.name))};return(async()=>{try{const Ce=G();if(Ce==="resolved"){Se();return}if(Ce==="waiting"||Q===-1)return;if(Q>0){he.inFlight=!0;try{const Fe=await w(h,p);if(Ne)return;if(Fe.size>0){let ge=null,ze=-1/0;for(const[Ke,st]of Fe)st.timestamp>ze&&(ze=st.timestamp,ge=Ke);if(ge){g(h,ge),o!==ge&&l(ge);const Ke=Fe.get(ge);if(Ke){const st=xe(Ke.providerId,Ke.modelId,ge);if(st==="applied"){Se();return}if(st==="provider-missing")return}else{Se();return}}}}catch(Fe){Ne||console.error("[ModelControls] Error resolving session from messages:",Fe)}finally{const Fe=be.current;!Ne&&Fe&&Fe.sessionId===h&&(Fe.inFlight=!1)}}Ae(),Se()}catch(Ce){Ne||console.error("[ModelControls] Error in session switch:",Ce)}})(),()=>{Ne=!0}},[h,Q,p,o,b,y,l,xe,w,g,N,r]),c.useEffect(()=>{if(!N||!h||r.length===0||p.length===0)return;const Ne=b(h)||o;if(!Ne)return;const Se=y(h,Ne);if(!Se)return;const G=r.find(Fe=>Fe.id===Se.providerId);if(!G||!(Array.isArray(G.models)?G.models.some(Fe=>Fe.id===Se.modelId):!1))return;const _e=t===Se.providerId,Ce=n===Se.modelId;_e&&Ce||(Ne!==o&&l(Ne),xe(Se.providerId,Se.modelId,Ne))},[N,h,o,t,n,r,p,b,y,xe,l]),c.useEffect(()=>{if(!N)return;(async()=>{try{if(o!==ht.current&&(ht.current=o,o&&h)){await new Promise(G=>setTimeout(G,50));const Ne=y(h,o);if(Ne){const G=xe(Ne.providerId,Ne.modelId,o);if(G==="applied"||G==="provider-missing")return}const Se=p.find(G=>G.name===o);if(Se?.model?.providerID&&Se?.model?.modelID&&xe(Se.model.providerID,Se.model.modelID,o)==="provider-missing")return}}catch(Ne){console.error("[ModelControls] Agent change error:",Ne)}})()},[o,h,y,xe,p,N]);const Ie=he=>{try{l(he),_(!1),h&&g(h,he),V&&re()}catch(Ne){console.error("[ModelControls] Handle agent change error:",Ne)}},$e=(he,Ne)=>{try{const Se=xe(he,Ne,o||void 0);if(Se!=="applied"){Se==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",he):Se==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:he,modelId:Ne});return}C(he,Ne),_(!1),V&&re(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(Se){console.error("[ModelControls] Handle model change error:",Se)}},Ue=he=>{const Ne=typeof he?.name=="string"?he.name:typeof he?.id=="string"?he.id:"";return Ne.length>40?Ne.substring(0,37)+"...":Ne},xt=()=>r.find(Ne=>Ne.id===t)?.name||t,je=()=>{if(!t||!n||zt.length===0)return"Not selected";const he=zt.find(Ne=>Ne.id===n);return Ue(he)},Xe=()=>{if(!o){const Ne=p.filter(Ae=>co(Ae.mode)),G=Ne.find(Ae=>Ae.name==="build")||Ne[0];return G?qe(G.name):"Select Agent"}const he=p.find(Ne=>Ne.name===o);return qe(he?he.name:o)},qe=he=>he.charAt(0).toUpperCase()+he.slice(1),ut=(he,Ne,Se)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:Ne,"aria-label":Ne,role:"img",children:e.jsx(he,{className:"h-3.5 w-3.5"})},Se),Dt=c.useCallback(he=>{I(Ne=>{const Se=new Set(Ne);return Se.has(he)?Se.delete(he):Se.add(he),Se})},[]),lt=c.useCallback(he=>{oe.current&&clearTimeout(oe.current),oe.current=setTimeout(()=>{E(he)},500)},[]),gt=c.useCallback(()=>{oe.current&&clearTimeout(oe.current)},[]);c.useEffect(()=>()=>{oe.current&&clearTimeout(oe.current)},[]);const Rt=()=>!V||Z!=="model"?null:e.jsx(vs,{open:!0,onClose:q,title:dt?.name||je(),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:xt()})]}),Be.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Capabilities"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Be.map(({key:he,icon:Ne,label:Se})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[ut(Ne,Se,`cap-${he}`),e.jsx("span",{className:"typography-meta text-foreground",children:Se})]},he))})]}),(Ye.length>0||Je.length>0)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[Ye.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Input"}),e.jsx("div",{className:"flex gap-1",children:Ye.map(({key:he,icon:Ne,label:Se})=>ut(Ne,`${Se} input`,`input-${he}`))})]}),Je.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Output"}),e.jsx("div",{className:"flex gap-1",children:Je.map(({key:he,icon:Ne,label:Se})=>ut(Ne,`${Se} output`,`output-${he}`))})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Is(dt?.limit?.context)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Output"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Is(dt?.limit?.output)})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Metadata"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Knowledge"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Mc(dt?.knowledge)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Release"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Dc(dt?.release_date)})]})]})]})]})}),hs=()=>{if(!V||Z!=="agent"||!K)return null;const he=!!(K.prompt&&K.prompt.trim().length>0),Ne=K.model?.providerID&&K.model?.modelID,Se=K.temperature!==void 0||K.topP!==void 0,G=Fe=>{const ge=Vo(K.permission)??[],ze=ge.some(st=>st.permission===Fe&&st.pattern!=="*"),Ke=uo(ge,Fe)??"ask";return ze?{mode:"ask",label:"Custom"}:Ke==="allow"?{mode:"allow",label:"Allow"}:Ke==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Ae=G("edit"),_e=G("bash"),Ce=G("webfetch");return e.jsx(vs,{open:!0,onClose:q,title:qe(K.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[K.description&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsx("div",{className:"typography-meta text-foreground",children:K.description})}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Mode"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:K.mode==="primary"?"Primary":K.mode==="subagent"?"Subagent":K.mode==="all"?"All":"—"})]}),(Ne||Se)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Model"}),Ne&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[K.model.providerID," / ",K.model.modelID]}),Se&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[K.temperature!==void 0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Temperature"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:K.temperature})]}),K.topP!==void 0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Top P"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:K.topP})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Permissions"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[We(Ae.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ae.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[We(_e.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:_e.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[We(Ce.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ce.label})]})]})]})]}),he&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(bo,{className:"h-4 w-4 text-foreground"})]})})]})})},hr=()=>{if(!V)return null;const he=B.trim().toLowerCase(),Ne=r.map(Se=>{const G=Array.isArray(Se.models)?Se.models:[],Ae=he.length===0?!0:Se.name.toLowerCase().includes(he)||Se.id.toLowerCase().includes(he),_e=he.length===0?G:G.filter(Ce=>{const Fe=Ue(Ce).toLowerCase(),ge=typeof Ce.id=="string"?Ce.id.toLowerCase():"";return Fe.includes(he)||ge.includes(he)});return{provider:Se,providerModels:_e,matchesProvider:Ae}}).filter(({matchesProvider:Se,providerModels:G})=>Se||G.length>0);return e.jsx(vs,{open:J==="model",onClose:re,title:"Select model",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"relative",children:[e.jsx(ur,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(mt,{value:B,onChange:Se=>X(Se.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),B&&e.jsx("button",{type:"button",onClick:()=>X(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(un,{className:"h-4 w-4"})})]})}),Ne.length===0&&e.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),!B&&P.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(ar,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:P.map(({model:Se,providerID:G,modelID:Ae})=>{const _e=G===t&&Ae===n,Ce=u(G,Ae);return e.jsxs("button",{type:"button",onClick:()=>$e(G,Ae),className:R("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",_e?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ts,{providerId:G,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ue(Se)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Ce?.limit?.context||Ce?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Ce?.limit?.context?`${Is(Ce?.limit?.context)} ctx`:"",Ce?.limit?.context&&Ce?.limit?.output?" • ":"",Ce?.limit?.output?`${Is(Ce?.limit?.output)} out`:""]})})]},`fav-mobile-${G}-${Ae}`)})})]}),!B&&L.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(tr,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:L.map(({model:Se,providerID:G,modelID:Ae})=>{const _e=G===t&&Ae===n,Ce=u(G,Ae);return e.jsxs("button",{type:"button",onClick:()=>$e(G,Ae),className:R("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",_e?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ts,{providerId:G,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ue(Se)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Ce?.limit?.context||Ce?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Ce?.limit?.context?`${Is(Ce?.limit?.context)} ctx`:"",Ce?.limit?.context&&Ce?.limit?.output?" • ":"",Ce?.limit?.output?`${Is(Ce?.limit?.output)} out`:""]})})]},`recent-mobile-${G}-${Ae}`)})})]}),Ne.map(({provider:Se,providerModels:G})=>{if(G.length===0&&!he.length)return null;const Ae=Se.id===t,_e=ye.has(Se.id)||he.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>Dt(Se.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":_e,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{providerId:Se.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Se.name}),Ae&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),_e?e.jsx(Ct,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Ls,{className:"h-3 w-3 text-muted-foreground"})]}),_e&&G.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:G.map(Ce=>{const Fe=Ae&&Ce.id===n,ge=u(Se.id,Ce.id),ze=Ra(ge).slice(0,3),Ke=Mn(ge,"input");return e.jsxs("div",{className:R("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 last:border-b-0","rounded-lg transition-colors",!Fe&&"hover:bg-muted",Fe?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>$e(Se.id,Ce.id),className:R("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary"),children:[e.jsx("div",{className:"flex min-w-0 flex-col",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ue(Ce)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(ge?.limit?.context||ge?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[ge?.limit?.context?e.jsxs("span",{children:[Is(ge?.limit?.context)," ctx"]}):null,ge?.limit?.context&&ge?.limit?.output?e.jsx("span",{children:"•"}):null,ge?.limit?.output?e.jsxs("span",{children:[Is(ge?.limit?.output)," out"]}):null]}),(ze.length>0||Ke.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...ze,...Ke].map(({key:st,icon:Mt,label:Tt})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Tt,"aria-label":Tt,children:e.jsx(Mt,{className:"h-3 w-3"})},`meta-${Se.id}-${Ce.id}-${st}`))})]})]}),e.jsx("button",{type:"button",onClick:st=>{st.preventDefault(),st.stopPropagation(),D(Se.id,Ce.id)},className:R("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",M(Se.id,Ce.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":M(Se.id,Ce.id)?"Unfavorite":"Favorite",title:M(Se.id,Ce.id)?"Remove from favorites":"Add to favorites",children:M(Se.id,Ce.id)?e.jsx(ar,{className:"h-4 w-4"}):e.jsx(sn,{className:"h-4 w-4"})})]},Ce.id)})})]},Se.id)})]})})},jn=()=>{if(!V)return null;const he=p.filter(Ne=>co(Ne.mode));return e.jsx(vs,{open:J==="agent",onClose:re,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[he.map(Ne=>{const Se=Ne.name===o,G=xr(Ne.name);return e.jsxs("button",{type:"button",className:R("flex w-full flex-col gap-1 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary agent-list-item",G.class,Se?"active":"border-border/40"),onClick:()=>Ie(Ne.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:R("h-2 w-2 rounded-full",G.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:Se?{color:`var(${G.var})`}:void 0,children:qe(Ne.name)})]}),Ne.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:Ne.description})]},Ne.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:wt,onClick:()=>{wt||W(Ne=>!Ne)},className:R("flex w-full items-center justify-between gap-2 px-2 py-1.5 text-left bg-transparent","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-t-xl",wt?"cursor-not-allowed opacity-60":void 0),children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:et?et.text:"var(--foreground)",mixBlendMode:"normal"},children:Oe})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:R("flex items-center justify-center p-1",!et&&"text-muted-foreground"),style:et?{color:et.text}:void 0,children:We(Ve,St)}),e.jsx(Ct,{className:R("h-4 w-4 text-muted-foreground transition-transform",F?"rotate-180":"")})]})]}),F&&!wt&&e.jsx("div",{className:"border-t border-border/40 bg-transparent px-2 py-1.5",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:pt.map(Ne=>{const Se=Ne.mode===Ve,G=An(Ne.mode);return e.jsxs("button",{type:"button",disabled:Ne.disabled,onClick:()=>Ze(Ne.mode),className:R("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",Ne.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",Se?"bg-primary/10":void 0),style:Se&&G?{backgroundColor:G.background??void 0}:void 0,children:[We(Ne.mode,St),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:G?G.text:"var(--foreground)"},children:Ne.label})})]},Ne.mode)})})})]})]})})},Vr=()=>e.jsx(tt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:dt?e.jsxs("div",{className:"flex min-w-[240px] flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-micro font-semibold text-foreground",children:dt.name||je()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:xt()})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Capabilities"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:Be.length>0?Be.map(({key:he,icon:Ne,label:Se})=>ut(Ne,Se,`cap-${he}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Input"}),e.jsx("div",{className:"flex items-center gap-1.5",children:Ye.length>0?Ye.map(({key:he,icon:Ne,label:Se})=>ut(Ne,`${Se} input`,`input-${he}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),e.jsx("div",{className:"flex items-center gap-1.5",children:Je.length>0?Je.map(({key:he,icon:Ne,label:Se})=>ut(Ne,`${Se} output`,`output-${he}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Cost ($/1M tokens)"}),Qe.map(he=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:he.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:he.value})]},he.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),it.map(he=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:he.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:he.value})]},he.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Metadata"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Knowledge"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Mc(dt.knowledge)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Release"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Dc(dt.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),As=(he,Ne,Se,G,Ae,_e)=>{const Ce=u(Ne,Se),Fe=Ra(Ce).map(Vt=>({...Vt,id:`cap-${Vt.key}`})),ge=[...Mn(Ce,"input"),...Mn(Ce,"output")],ze=Array.from(new Map(ge.map(Vt=>[Vt.key,Vt])).values()).map(Vt=>({...Vt,id:`mod-${Vt.key}`})),Ke=[...Fe,...ze],st=Is(Ce?.limit?.context),Mt=t===Ne&&n===Se,Tt=M(Ne,Se);return e.jsxs("div",{ref:Vt=>{te.current[Ae]=Vt},className:R("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",_e?"bg-accent":"hover:bg-accent/50"),onClick:()=>$e(Ne,Se),onMouseEnter:()=>le(Ae),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:Ue(he)}),Ce?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:st}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Ke.length>0&&e.jsx("div",{className:R("items-center gap-0.5",_e?"flex":"hidden group-hover:flex"),children:Ke.map(({id:Vt,icon:Hs,label:Cr})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":Cr,role:"img",title:Cr,children:e.jsx(Hs,{className:"h-2.5 w-2.5"})},Vt))}),Mt&&e.jsx(Ot,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:Vt=>{Vt.preventDefault(),Vt.stopPropagation(),D(Ne,Se)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Tt?"text-yellow-500":"text-muted-foreground"),"aria-label":Tt?"Unfavorite":"Favorite",title:Tt?"Remove from favorites":"Add to favorites",children:Tt?e.jsx(ar,{className:"h-3.5 w-3.5"}):e.jsx(sn,{className:"h-3.5 w-3.5"})})]})]},`${G}-${Ne}-${Se}`)},Et=(he,Ne,Se)=>{if(!Se.trim())return!0;const G=Se.toLowerCase();return he.toLowerCase().includes(G)||Ne.toLowerCase().includes(G)},gl=()=>{const he=P.filter(({model:ge,providerID:ze})=>{const st=r.find(Tt=>Tt.id===ze)?.name||ze,Mt=Ue(ge);return Et(Mt,st,pe)}),Ne=L.filter(({model:ge,providerID:ze})=>{const st=r.find(Tt=>Tt.id===ze)?.name||ze,Mt=Ue(ge);return Et(Mt,st,pe)}),Se=r.map(ge=>{const Ke=(Array.isArray(ge.models)?ge.models:[]).filter(st=>{const Mt=Ue(st);return Et(Mt,ge.name||ge.id||"",pe)});return{...ge,models:Ke}}).filter(ge=>ge.models.length>0),G=he.length>0||Ne.length>0||Se.length>0,Ae=[];he.forEach(({model:ge,providerID:ze,modelID:Ke})=>{Ae.push({model:ge,providerID:ze,modelID:Ke,section:"fav"})}),Ne.forEach(({model:ge,providerID:ze,modelID:Ke})=>{Ae.push({model:ge,providerID:ze,modelID:Ke,section:"recent"})}),Se.forEach(ge=>{ge.models.forEach(ze=>{Ae.push({model:ze,providerID:ge.id,modelID:ze.id,section:"provider"})})});const _e=Ae.length,Ce=ge=>{if(ge.key==="ArrowDown")ge.preventDefault(),ge.stopPropagation(),le(ze=>(ze+1)%Math.max(1,_e)),setTimeout(()=>{const ze=(Y+1)%Math.max(1,_e);te.current[ze]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(ge.key==="ArrowUp")ge.preventDefault(),ge.stopPropagation(),le(ze=>(ze-1+Math.max(1,_e))%Math.max(1,_e)),setTimeout(()=>{const ze=(Y-1+Math.max(1,_e))%Math.max(1,_e);te.current[ze]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(ge.key==="Enter"){ge.preventDefault(),ge.stopPropagation();const ze=Ae[Y];ze&&$e(ze.providerID,ze.modelID)}else ge.key==="Escape"&&(ge.preventDefault(),ge.stopPropagation(),_(!1))};let Fe=0;return e.jsxs(nt,{delayDuration:1e3,children:[V?e.jsxs("button",{type:"button",onClick:()=>T("model"),onTouchStart:()=>lt("model"),onTouchEnd:gt,onTouchCancel:gt,className:R("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",Pt),children:[t?e.jsx(ts,{providerId:t,className:R(At,"flex-shrink-0")}):e.jsx(or,{className:R(At,"text-muted-foreground")}),e.jsx("span",{className:R("model-controls__model-label typography-micro font-medium truncate min-w-0",!U&&"max-w-[220px]"),children:je()})]}):e.jsxs(Kt,{open:O,onOpenChange:_,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Yt,{asChild:!0,children:e.jsxs("div",{className:R("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",Pt),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(ts,{providerId:t,className:R(At,"flex-shrink-0")}),e.jsx(or,{className:R(At,"text-primary/60 hidden")})]}):e.jsx(or,{className:R(At,"text-muted-foreground")}),e.jsx("span",{className:R("model-controls__model-label",Jt,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:je()},`${t}-${n}`)]})})}),e.jsxs(Xt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(ur,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(mt,{type:"text",placeholder:"Search models",value:pe,onChange:ge=>He(ge.target.value),onKeyDown:Ce,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(ct,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!G&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),he.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(on,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ar,{className:"h-4 w-4 text-primary"}),"Favorites"]}),he.map(({model:ge,providerID:ze,modelID:Ke})=>{const st=Fe++;return As(ge,ze,Ke,"fav",st,Y===st)})]}),Ne.length>0&&e.jsxs(e.Fragment,{children:[he.length>0&&e.jsx(Xs,{}),e.jsxs(on,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(tr,{className:"h-4 w-4"}),"Recent"]}),Ne.map(({model:ge,providerID:ze,modelID:Ke})=>{const st=Fe++;return As(ge,ze,Ke,"recent",st,Y===st)})]}),(he.length>0||Ne.length>0)&&Se.length>0&&e.jsx(Xs,{}),Se.map((ge,ze)=>e.jsxs(c.Fragment,{children:[ze>0&&e.jsx(Xs,{}),e.jsxs(on,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ts,{providerId:ge.id,className:"h-4 w-4 flex-shrink-0"}),ge.name]}),ge.models.map(Ke=>{const st=Fe++;return As(Ke,ge.id,Ke.id,"provider",st,Y===st)})]},ge.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})]}),Vr()]})},Xn=()=>{if(!K)return e.jsx(tt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"No agent selected."})});const he=!!(K.prompt&&K.prompt.trim().length>0),Ne=K.model?.providerID&&K.model?.modelID,Se=K.temperature!==void 0||K.topP!==void 0,G=Fe=>{const ge=Vo(K.permission)??[],ze=ge.some(st=>st.permission===Fe&&st.pattern!=="*"),Ke=uo(ge,Fe)??"ask";return ze?{mode:"ask",label:"Custom"}:Ke==="allow"?{mode:"allow",label:"Allow"}:Ke==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Ae=G("edit"),_e=G("bash"),Ce=G("webfetch");return e.jsx(tt,{align:"start",sideOffset:8,className:"max-w-[280px]",children:e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-2.5",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-micro font-semibold text-foreground",children:qe(K.name)}),K.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:K.description})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Mode"}),e.jsx("span",{className:"typography-meta text-foreground",children:K.mode==="primary"?"Primary":K.mode==="subagent"?"Subagent":K.mode==="all"?"All":"—"})]}),(Ne||Se)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Model"}),Ne?e.jsxs("span",{className:"typography-meta text-foreground",children:[K.model.providerID," / ",K.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),Se&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[K.temperature!==void 0&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Temperature"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:K.temperature})]}),K.topP!==void 0&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Top P"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:K.topP})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Permissions"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[We(Ae.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ae.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[We(_e.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:_e.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[We(Ce.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ce.label})]})]})]}),he&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(bo,{className:"h-4 w-4 text-foreground"})]})]})})},ua=()=>V?e.jsxs("button",{type:"button",onClick:()=>T("agent"),onTouchStart:()=>lt("agent"),onTouchEnd:gt,onTouchCancel:gt,className:R("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Pt,"cursor-pointer hover:opacity-70",V&&"ml-1"),children:[e.jsx($n,{className:R(At,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${xr(o).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",Jt,"font-medium truncate min-w-0"),style:o?{color:`var(${xr(o).var})`}:void 0,children:Xe()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(nt,{delayDuration:1e3,children:[e.jsxs(Kt,{children:[e.jsx(ot,{asChild:!0,children:e.jsx(Yt,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Pt),children:[e.jsx($n,{className:R(At,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${xr(o).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",Jt,"font-medium min-w-0 truncate",z?"max-w-[220px]":void 0),style:o?{color:`var(${xr(o).var})`}:void 0,children:Xe()})]})})}),e.jsxs(Xt,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[p.filter(he=>co(he.mode)).map(he=>e.jsx(jt,{className:"typography-meta",onSelect:()=>Ie(he.name),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:R("h-1 w-1 rounded-full agent-dot",xr(he.name).class)}),e.jsx("span",{className:"font-medium",children:qe(he.name)})]}),he.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:he.description})]})},he.name)),e.jsx(Xs,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:wt,onClick:()=>{wt||ue(he=>!he)},className:R("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",wt?"cursor-not-allowed opacity-60":void 0),"aria-expanded":ee,"aria-controls":me,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:et?et.text:"var(--foreground)"},children:Oe})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:R("flex items-center justify-center p-1",!et&&"text-muted-foreground"),style:et?{color:et.text}:void 0,children:We(Ve)}),e.jsx(Ct,{className:R("h-3.5 w-3.5 transition-transform text-muted-foreground",ee?"rotate-180":"")})]})]}),ee&&!wt&&e.jsx("div",{id:me,className:"flex flex-col gap-1 rounded-xl border border-border/40 px-2 py-2 bg-transparent",role:"group","aria-label":"Edit permission options",children:pt.map(he=>{const Ne=he.mode===Ve,Se=An(he.mode);return e.jsxs("button",{type:"button",disabled:he.disabled,onClick:()=>Ze(he.mode),className:R("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",he.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",Ne?"bg-primary/10":void 0),style:Ne&&Se?{backgroundColor:Se.background??void 0}:void 0,children:[We(he.mode,St),e.jsx("span",{className:"typography-meta font-medium",style:{color:Se?Se.text:"var(--foreground)"},children:he.label})]},he.mode)})})]})]})]}),Xn()]})}),ma=R("@container/model-controls flex items-center min-w-0",Ee,U&&"w-full",s);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:ma,children:[e.jsx("div",{className:R("flex items-center min-w-0 flex-1 justify-end",U&&"overflow-hidden"),children:gl()}),e.jsx("div",{className:R("flex items-center min-w-0",Ee,U&&"flex-shrink-0"),children:ua()})]}),hr(),jn(),Rt(),hs()]})},ub=s=>s?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(s):!0,Ec=(s,r)=>{if(typeof s!="string"||s.length===0)return{sanitizedText:s,mention:null};const t=r.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!s.includes("#"))return{sanitizedText:s,mention:null};let n=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let i;for(;(i=a.exec(s))!==null;){const l=i.index,d=l+i[0].length,u=l>0?s[l-1]:null;if(!ub(u))continue;const m={name:o.name,source:{value:i[0],start:l,end:d}};n||(n=m)}}return n?{sanitizedText:s,mention:n}:{sanitizedText:s,mention:null}},dm=s=>({id:s.id,content:s.content,status:s.status||"pending",priority:s.priority||"medium"}),yi=Bt()(Qt((s,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){s({isLoading:!0});try{const n=de.getState().getDirectoryForSession(t),a=(n?await De.withDirectory(n,()=>De.getSessionTodos(t)):await De.getSessionTodos(t)).map(dm);s(i=>{const l=new Map(i.sessionTodos);return l.set(t,a),{sessionTodos:l,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),s({isLoading:!1})}}},updateTodos:(t,n)=>{s(o=>{const a=new Map(o.sessionTodos);return a.set(t,n),{sessionTodos:a}})},getTodosForSession:t=>r().sessionTodos.get(t)||[],clearTodos:t=>{s(n=>{const o=new Map(n.sessionTodos);return o.delete(t),{sessionTodos:o}})}}),{name:"todo-store"})),mb=(s,r)=>{const t=r.map(dm);yi.getState().updateTodos(s,t)},Ic=[{variant:"shine",component:({children:s,className:r,...t})=>e.jsx(Jr.span,{...t,className:R("bg-[linear-gradient(110deg,#bfbfbf,35%,#000,50%,#bfbfbf,75%,#bfbfbf)] dark:bg-[linear-gradient(110deg,#404040,35%,#fff,50%,#404040,75%,#404040)]","bg-[length:200%_100%] bg-clip-text text-transparent",r),initial:{backgroundPosition:"200% 0"},animate:{backgroundPosition:"-200% 0"},transition:{repeat:Number.POSITIVE_INFINITY,duration:2,ease:"linear"},children:s})},{variant:"generate-effect",component:({children:s,className:r,...t})=>typeof s!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:s.split("").map((n,o)=>Me.createElement(Jr.span,{...t,key:n+String(o),className:R("inline-block whitespace-pre text-primary-foreground",r),initial:{opacity:0,filter:"blur(4px)",rotateX:90,y:5},whileInView:{opacity:1,filter:"blur(0px)",rotateX:0,y:0},transition:{ease:"easeOut",duration:.3,delay:o*.015},viewport:{once:!0}},n))})},{variant:"glitch",component:({children:s,className:r,...t})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...t,className:R("invisible",r),children:s}),e.jsx("span",{...t,className:R("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",r),children:s}),e.jsx("span",{...t,className:R("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",r),children:s})]})},{variant:"hover-enter",component:({children:s,className:r,...t})=>{if(typeof s!="string")return null;const n=.25,o=.025,a=s.split("").map(i=>i===" "?" ":i);return e.jsxs(Jr.span,{...t,className:R("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",r),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((i,l)=>e.jsx(Jr.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:i},String(l)))}),e.jsx("div",{className:R("absolute inset-0"),children:a.map((i,l)=>e.jsx(Jr.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:i},String(l)))})]})}},{variant:"shake",component:({children:s,className:r,...t})=>e.jsx("span",{...t,className:R("text-primary-muted hover:animate-text-shake",r),children:s})},{variant:"hover-decoration",component:({children:s,className:r,...t})=>e.jsx("div",{className:R("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:e.jsx("span",{...t,className:R("text-primary-muted",r),children:s})})}];function Oa({variant:s="shine",className:r,...t}){const a=Ic.find(i=>i.variant===s)?.component||Ic[0].component;return e.jsx(Od,{children:e.jsx(a,{...t,className:r})})}const Pc=1500,fb=2e3;function pb({statusText:s,isGenericStatus:r,isWaitingForPermission:t,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:i}){const[l,d]=Me.useState("idle"),[u,m]=Me.useState(null),[f,p]=Me.useState(!1),h=Me.useRef(0),j=Me.useRef(null),g=Me.useRef(null),b=Me.useRef(null),x=Me.useRef(null),y=Me.useRef(!1),w=Me.useRef(!1),S=Me.useRef(!1),v=Me.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),b.current&&(clearTimeout(b.current),b.current=null)},[]),N=Me.useCallback((L,U)=>{v(),j.current=null,m(L),p(U),d("showing"),h.current=Date.now(),y.current=!0},[v]),D=Me.useCallback(()=>{if(g.current)return;const L=Date.now()-h.current,U=Math.max(0,Pc-L);g.current=setTimeout(()=>{g.current=null;const z=j.current;z&&N(z.text,z.permission)},U)},[N]),M=Me.useCallback(L=>{if(v(),j.current=null,!y.current){d("idle"),m(null),i?.(!1);return}if(L==="done"&&o&&x.current===o){d("idle"),m(null),y.current=!1,i?.(!1);return}L==="done"&&o&&(x.current=o),d(L),m(null),i?.(!0),b.current=setTimeout(()=>{b.current=null,d("idle"),y.current=!1,i?.(!1)},fb)},[v,o,i]);if(Me.useEffect(()=>{if(n&&!S.current){S.current=!0,M("aborted");return}if(S.current=!!n,a&&!w.current){w.current=!0,M("done");return}if(!a&&w.current&&(w.current=!1),!(l==="done"||l==="aborted")&&s){const U=Date.now()-h.current;if(l==="idle"||!u)N(s,!!t);else if(s!==u||!!t!==f){if(r)return;U>=Pc?N(s,!!t):(j.current={text:s,permission:!!t},D())}}},[s,t,n,a,l,u,f,N,M,D,r]),Me.useEffect(()=>()=>v(),[v]),Me.useEffect(()=>{const L=()=>{typeof document>"u"||document.visibilityState==="visible"&&(l==="done"||l==="aborted")&&(v(),d("idle"),m(null),y.current=!1)};return document.addEventListener("visibilitychange",L),()=>document.removeEventListener("visibilitychange",L)},[l,v]),l==="idle"&&!u)return null;let C,k=!0;l==="done"?(C="Done",k=!1):l==="aborted"?(C="Aborted",k=!1):u?C=u.charAt(0).toUpperCase()+u.slice(1):C="Working";const A=k?`${C}...`:C,P=l!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${P?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":C,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:l==="done"?e.jsx(Oa,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):l==="aborted"?e.jsx(Oa,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(Oa,{variant:"shine",className:"typography-ui-header",children:A})})})}const Tc={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},hb=({todo:s})=>{const r=Tc[s.status]||Tc.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:R("flex-1 typography-ui-label",r.textClassName),children:s.content})})},Fc=[],gb=({isWorking:s,statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:i,isComplete:l,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=c.useState(!1),h=de(U=>U.currentSessionId),j=yi(U=>h?U.sessionTodos.get(h)??Fc:Fc),g=yi(U=>U.loadTodos),{isMobile:b}=Re(),x=b||Ht();c.useEffect(()=>{h&&g(h)},[h,g]);const y=c.useMemo(()=>{const U={in_progress:0,pending:1,completed:2,cancelled:3};return[...j].filter(z=>z.status!=="cancelled").sort((z,H)=>U[z.status]-U[H.status])},[j]),w=c.useMemo(()=>y.find(U=>U.status==="in_progress")||y.find(U=>U.status==="pending")||null,[y]),S=c.useMemo(()=>{const U=j.filter(H=>H.status!=="cancelled").length;return{completed:j.filter(H=>H.status==="completed").length,total:U}},[j]),v=y.length>0,N=!m&&(o||!a),[D,M]=c.useState(!1),C=s||l||o||D||v||m,k=c.useRef(null);if(c.useEffect(()=>{if(!f)return;const U=z=>{k.current&&!k.current.contains(z.target)&&p(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[f]),!C)return null;const A=()=>p(U=>!U),P=d&&u?e.jsx("button",{type:"button",onClick:u,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:e.jsx(un,{size:18,"aria-hidden":"true"})}):null,L=v?e.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!x&&w?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:w.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[S.completed,"/",S.total]}),f?e.jsx(Xo,{className:"h-3.5 w-3.5"}):e.jsx(Ct,{className:"h-3.5 w-3.5"})]}):null;return e.jsx("div",{className:"chat-column mb-1",style:{containerType:"inline-size"},children:e.jsxs("div",{className:"flex items-center justify-between pr-[2ch] py-0.5 gap-2 h-[1.2rem]",children:[e.jsx("div",{className:"flex-1 flex items-center overflow-hidden min-w-0",children:m?e.jsx("div",{className:"flex h-full items-center text-[var(--status-error)] pl-[2ch]",children:e.jsxs("span",{className:"flex items-center gap-1.5 typography-ui-label",children:[e.jsx(un,{size:16,"aria-hidden":"true"}),"Aborted"]})}):N?e.jsx(pb,{statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,completionId:i??null,isComplete:l,onResultVisibilityChange:M},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:k,children:[P,L,f&&v&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:R("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px]","rounded-xl border border-border bg-background shadow-md","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"Tasks"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[S.completed,"/",S.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:y.map(U=>e.jsx(hb,{todo:U},U.id))})]})]})]})})},xi=s=>!s||typeof s!="object"?!1:!!s.synthetic,Rc=s=>!Array.isArray(s)||s.length===0?!1:s.every(r=>xi(r)),yb=s=>!Array.isArray(s)||s.length===0?[]:s.some(t=>!xi(t))?s.filter(t=>!xi(t)):s,xb={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function bb(s){const r=de(t=>!s||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(s)??"idle");return c.useMemo(()=>{if(r==="idle")return xb;const t=r==="busy",n=r==="cooldown";return{phase:r,isWorking:t||n,isBusy:t,isCooldown:n}},[r])}function al(){const s=de(r=>r.currentSessionId);return bb(s)}const wb={activity:"idle",hasWorkingContext:!1,hasActiveTools:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,lifecyclePhase:null,statusText:null,isGenericStatus:!0,isWaitingForPermission:!1,canAbort:!1,compactionDeadline:null,activePartType:void 0,activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1},Oc=s=>s.role==="assistant",vb=s=>s.type==="reasoning",um=s=>s.type==="text",$c=s=>{if(um(s))return s.text;const r=s;if(typeof r.text=="string")return r.text;if(typeof r.content=="string")return r.content;if(typeof r.value=="string")return r.value},Lc=s=>(um(s)||vb(s),s.time),jb=s=>{if(s.tool)return s.tool;const r=s;return typeof r.name=="string"?r.name:"tool"};function mm(){const{currentSessionId:s,messages:r,permissions:t,sessionAbortFlags:n}=de(Ii(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=al(),l=c.useMemo(()=>s?r.get(s)??[]:[],[s,r]),d=c.useMemo(()=>{if(l.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=l.filter(C=>Oc(C.info)&&!Rc(C.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const j=[...h].sort((C,k)=>{const A=typeof C.info.time?.created=="number"?C.info.time.created:null,P=typeof k.info.time?.created=="number"?k.info.time.created:null;return A!==null&&P!==null&&A!==P?A-P:C.info.id.localeCompare(k.info.id)}),g=j[j.length-1];let b,x;const y=new Set(["edit","write"]);for(let C=(g.parts??[]).length-1;C>=0;C-=1){const k=g.parts?.[C];if(k)switch(k.type){case"reasoning":{const A=k.time??Lc(k);(!A||typeof A.end>"u")&&!b&&(b="reasoning");break}case"tool":{const A=k.state?.status;if((A==="running"||A==="pending")&&!b){const P=jb(k);y.has(P)?b="editing":(b="tool",x=P)}break}case"text":{const A=$c(k)??"";if(typeof A=="string"&&A.trim().length>0){const P=Lc(k);(!P||typeof P.end>"u")&&!b&&(b="text")}break}}}const w={read:"reading file",write:"writing file",edit:"editing file",multiedit:"editing files",bash:"running command",grep:"searching content",glob:"finding files",list:"listing directory",task:"delegating task",webfetch:"fetching URL",websearch:"searching web",codesearch:"web code search",todowrite:"updating todos",todoread:"reading todos",skill:"learning skill"},S=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],v=C=>w[C]??`using ${C}`,N=()=>S[Math.floor(Math.random()*S.length)],D=b===void 0,M=b==="editing"?"editing file":b==="tool"&&x?v(x):b==="reasoning"?"thinking":b==="text"?"composing":N();return{activePartType:b,activeToolName:x,statusText:M,isGenericStatus:D}},[l]),u=c.useMemo(()=>{const h=s,j=h?n?.get(h)??null:null,g=!!(j&&!j.acknowledged);return{wasAborted:g,abortActive:g}},[s,n]),m=c.useMemo(()=>{if(u.wasAborted)return{...wb,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,j=o==="busy",g=i;let b="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?b="tooling":b=g?"cooldown":"streaming"),{activity:b,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:j,isCooldown:g,lifecyclePhase:j?"streaming":g?"cooldown":null,statusText:h?d.statusText:null,isGenericStatus:h?d.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:h,compactionDeadline:null,activePartType:h?d.activePartType:void 0,activeToolName:h?d.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:g}},[o,a,i,d,u]),f=c.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||l.length===0)return{isActive:h,characterCount:0};const j=l.filter(x=>Oc(x.info)&&!Rc(x.parts));if(j.length===0)return{isActive:h,characterCount:0};const g=j[j.length-1];let b=0;return(g.parts??[]).forEach(x=>{if(x.type!=="text")return;const y=$c(x)??"";typeof y=="string"&&y.trim().length>0&&(b+=y.length)}),{isActive:h,characterCount:b}},[l,a,d.activePartType]),p=c.useMemo(()=>{if(m.wasAborted||m.abortActive)return m;const h=s;return(h?t?.get(h)??[]:[]).length>0?{...m,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:m},[s,t,m]);return{forming:f,working:p}}const Sb=8,_c=[],kb=s=>s==="primary"||s==="all"||s===void 0||s===null,fm=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},Bc=(s,r)=>{const t=fm(s);if(!(!t||t.length===0)){for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},Nb=(s,r)=>{const t=fm(s);if(!t||t.length===0)return;const n={};for(const o of t)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},fo=({onOpenSettings:s,scrollToBottom:r})=>{const[t,n]=c.useState(""),[o,a]=c.useState(!1),[i,l]=c.useState(!1),[d,u]=c.useState(""),[m,f]=c.useState(!1),[p,h]=c.useState(""),[j,g]=c.useState(!1),[b,x]=c.useState(""),[y,w]=c.useState(null),S=c.useRef(null),v=c.useRef(null),N=c.useRef(null),D=c.useRef(null),M=c.useRef(null),C=de(G=>G.sendMessage),k=de(G=>G.currentSessionId),A=de(G=>G.newSessionDraft?.open),P=de(G=>G.abortCurrentOperation),L=de(G=>G.acknowledgeSessionAbort),U=de(G=>G.abortPromptSessionId),z=de(G=>G.abortPromptExpiresAt),H=de(G=>G.clearAbortPrompt),V=de(G=>G.sessionAbortFlags),J=de(G=>G.attachedFiles),T=de(G=>G.addAttachedFile),Z=de(G=>G.addServerFile),E=de(G=>G.clearAttachedFiles),B=de(G=>G.saveSessionAgentSelection),X=de(G=>G.consumePendingInputText),re=de(G=>G.pendingInputText),{currentProviderId:q,currentModelId:oe,currentAgentName:ye,setAgent:I,getVisibleAgents:F}=at(),W=F(),{isMobile:O,inputBarOffset:_,isKeyboardOpen:ee,setTimelineDialogOpen:ue}=Re(),{working:me}=mm(),[pe,He]=c.useState(!1),Y=c.useRef(null),le=c.useRef(!1),te=c.useRef(!1),ne=qs(G=>G.queueModeEnabled),K=qs(c.useCallback(G=>k?G.queuedMessages[k]??_c:_c,[k])),ie=qs(G=>G.addToQueue),ce=qs(G=>G.clearQueue),{phase:ae}=al(),$=c.useRef(ae),we=c.useRef(!1),fe=c.useCallback(G=>{if(!O||G.pointerType!=="touch")return;const Ae=S.current;if(!Ae||document.activeElement===Ae)return;G.preventDefault(),G.stopPropagation();const _e=document.scrollingElement;_e&&_e.scrollTop!==0&&(_e.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{Ae.focus({preventScroll:!0})}catch{Ae.focus()}const Ce=Ae.value.length;try{Ae.setSelectionRange(Ce,Ce)}catch{}},[O]);c.useEffect(()=>{if(re!==null){const G=X();G&&(n(G),setTimeout(()=>{S.current?.focus()},0))}},[re,X]);const ve=c.useMemo(()=>{if(ye)return W.find(G=>G.name===ye)},[W,ye]),Le=c.useMemo(()=>ve?Bc(ve.permission,"edit")??"ask":"deny",[ve]),Ge=de(c.useCallback(G=>!k||!ye?void 0:G.sessionAgentEditModes.get(k)?.get(ye),[k,ye])),Te=c.useMemo(()=>{if(ve)return Bc(ve.permission,"webfetch")},[ve]),Pe=c.useMemo(()=>{if(!ve)return;const G=Nb(ve.permission,"bash");return G||void 0},[ve]),Ve=c.useMemo(()=>cm({agentDefaultEditMode:Le,webfetchPermission:Te,bashPermission:Pe}),[Le,Te,Pe]),pt=!!(k&&ye),et=c.useMemo(()=>pt&&Ge&&Ve.modeAvailability[Ge]?Ge:Ve.cascadeDefaultMode,[Ve,pt,Ge]),wt=c.useMemo(()=>An(et),[et]),Nt=c.useCallback(G=>Ht()?`color-mix(in srgb, ${G} 55%, transparent)`:G,[]),Pt=c.useMemo(()=>{const G=Ht()?1:2;if(!wt)return{borderWidth:G};const Ae=wt.border??wt.text;return{borderColor:Nt(Ae),borderWidth:G}},[wt,Nt]),St=t.trim()||J.length>0,At=K.length>0,Jt=St||At,Ee=me.isWorking,Oe=c.useMemo(()=>k?U===k&&!!z:!1,[U,z,k]),We=c.useCallback(()=>{if(!St||!k)return;const G=t.replace(/^\n+|\n+$/g,""),Ae=J.map(_e=>({..._e}));ie(k,{content:G,attachments:Ae.length>0?Ae:void 0}),n(""),Ae.length>0&&E(),O||S.current?.focus()},[St,k,t,J,ie,E,O]),Ze=async G=>{if(G?.preventDefault(),!Jt||!k&&!A)return;if(r?.({instant:!0,force:!0}),!q||!oe){console.warn("Cannot send message: provider or model not selected");return}let Ae="",_e=[],Ce;const Fe=[];for(let Ke=0;Ke<K.length;Ke++){const st=K[Ke],{sanitizedText:Mt,mention:Tt}=Ec(st.content,W);!Ce&&Tt?.name&&(Ce=Tt.name),Ke===0?(Ae=Mt,_e=st.attachments??[]):Fe.push({text:Mt,attachments:st.attachments})}if(St){const Ke=t.replace(/^\n+|\n+$/g,""),{sanitizedText:st,mention:Mt}=Ec(Ke,W),Tt=J.map(Vt=>({...Vt}));!Ce&&Mt?.name&&(Ce=Mt.name),K.length===0?(Ae=st,_e=Tt):Fe.push({text:st,attachments:Tt.length>0?Tt:void 0})}if(!Ae&&Fe.length===0)return;k&&At&&ce(k),n(""),J.length>0&&E(),O&&S.current?.blur();const ge=Ae.trimStart();if(ge.startsWith("/")){const Ke=ge.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(Ke==="undo"&&k){await de.getState().handleSlashUndo(k),r?.({instant:!0,force:!0});return}else if(Ke==="redo"&&k){await de.getState().handleSlashRedo(k),r?.({instant:!0,force:!0});return}else if(Ke==="timeline"&&k){ue(!0),n("");return}else Ke==="summarize"&&r?.({instant:!0,force:!0})}const ze=[..._e,...Fe.flatMap(Ke=>Ke.attachments??[])];await C(Ae,q,oe,ye,_e,Ce,Fe.length>0?Fe:void 0).catch(Ke=>{const st=Ke instanceof Error?Ke.message:typeof Ke=="string"?Ke:String(Ke??""),Mt=st.toLowerCase();console.error("Message send failed:",st||Ke),!(Mt.includes("timeout")||Mt.includes("timed out")||Mt.includes("may still be processing")||Mt.includes("being processed")||Mt.includes("failed to fetch")||Mt.includes("networkerror")||Mt.includes("network error")||Mt.includes("gateway timeout")||Mt==="failed to send message")&&(ze.length>0&&Ys.setState({attachedFiles:ze}),se.error(st||"Message failed to send. Attachments restored."))}),O||S.current?.focus()},Zt=c.useRef(Ze);Zt.current=Ze,c.useEffect(()=>{const G=$.current==="busy"||$.current==="cooldown",Ae=ae==="idle",_e=k&&V.has(k)&&(()=>{const Ce=V.get(k);return Ce?Date.now()-Ce.timestamp<2e3:!1})();G&&Ae&&K.length>0&&!we.current&&!_e&&(we.current=!0,setTimeout(()=>{k&&q&&oe&&Zt.current(),we.current=!1},100)),$.current=ae},[ae,K.length,k,q,oe,V]);const zt=G=>{if(!rl(G)){if(m&&D.current&&(G.key==="Enter"||G.key==="ArrowUp"||G.key==="ArrowDown"||G.key==="Escape"||G.key==="Tab")){G.preventDefault(),D.current.handleKeyDown(G.key);return}if(j&&M.current&&(G.key==="Enter"||G.key==="ArrowUp"||G.key==="ArrowDown"||G.key==="Escape"||G.key==="Tab")){G.preventDefault(),M.current.handleKeyDown(G.key);return}if(i&&N.current&&(G.key==="Enter"||G.key==="ArrowUp"||G.key==="ArrowDown"||G.key==="Escape"||G.key==="Tab")){G.preventDefault(),N.current.handleKeyDown(G.key);return}if(G.key==="Tab"&&!m&&!i){G.preventDefault(),Ye();return}if(G.key==="Enter"&&!G.shiftKey&&!O){G.preventDefault();const Ae=G.ctrlKey||G.metaKey,_e=St&&k&&ae!=="idle";ne?Ae||!_e?Ze():We():Ae&&_e?We():Ze()}}},dt=c.useCallback(()=>{Y.current&&(clearTimeout(Y.current),Y.current=null),He(!0),Y.current=setTimeout(()=>{He(!1),Y.current=null},1800)},[]),Be=c.useCallback(()=>{H(),dt(),P()},[P,H,dt]),Ye=()=>{const G=W.filter(Fe=>kb(Fe.mode));if(G.length<=1)return;const _e=(G.findIndex(Fe=>Fe.name===ye)+1)%G.length,Ce=G[_e];I(Ce.name),k&&B(k,Ce.name)},Je=c.useCallback(()=>{const G=S.current;if(!G)return;G.style.height="auto";const Ae=G.ownerDocument?.defaultView,_e=Ae?Ae.getComputedStyle(G):null,Ce=_e?parseFloat(_e.lineHeight):NaN,Fe=_e?parseFloat(_e.paddingTop):NaN,ge=_e?parseFloat(_e.paddingBottom):NaN,ze=22,st=Number.isNaN(Fe)||Number.isNaN(ge)?16:Fe+ge,Tt=(Number.isNaN(Ce)?ze:Ce)*Sb+st,Vt=G.scrollHeight||G.offsetHeight,Hs=Math.min(Vt,Tt);G.style.height=`${Hs}px`,G.style.maxHeight=`${Tt}px`,w(Cr=>Cr&&Cr.height===Hs&&Cr.maxHeight===Tt?Cr:{height:Hs,maxHeight:Tt})},[]);c.useLayoutEffect(()=>{Je()},[Je,t,O]);const Qe=c.useCallback((G,Ae)=>{if(G.startsWith("/")){const ge=G.indexOf(" "),ze=G.indexOf(`
|
|
69
|
+
`),Ke=Math.min(ge===-1?G.length:ge,ze===-1?G.length:ze);if(Ae<=Ke&&ge===-1){const st=G.substring(1,Ke);h(st),f(!0),l(!1),g(!1)}else f(!1);return}f(!1);const _e=G.substring(0,Ae),Ce=_e.lastIndexOf("#");if(Ce!==-1){const ge=Ce>0?_e[Ce-1]:null,ze=_e.substring(Ce+1),Ke=ze.includes(" ")||ze.includes(`
|
|
70
|
+
`);if((!ge||/\s/.test(ge))&&!Ke){x(ze),g(!0),l(!1);return}}g(!1),x("");const Fe=_e.lastIndexOf("@");if(Fe!==-1){const ge=_e.substring(Fe+1);!ge.includes(" ")&&!ge.includes(`
|
|
71
|
+
`)?(u(ge),l(!0)):l(!1)}else l(!1)},[x,h,u,g,f,l]),it=c.useCallback(G=>{if(!G)return;const Ae=S.current;if(!Ae){const ze=t+G;n(ze),Qe(ze,ze.length),requestAnimationFrame(()=>Je());return}const _e=Ae.selectionStart??t.length,Ce=Ae.selectionEnd??t.length,Fe=`${t.substring(0,_e)}${G}${t.substring(Ce)}`;n(Fe);const ge=_e+G.length;requestAnimationFrame(()=>{const ze=S.current;ze&&(ze.selectionStart=ge,ze.selectionEnd=ge),Je()}),Qe(Fe,ge)},[Je,t,Qe]),ht=G=>{const Ae=G.target.value,_e=G.target.selectionStart??Ae.length;n(Ae),Je(),Qe(Ae,_e)},Q=c.useCallback(async G=>{const Ae=new Map;Array.from(G.clipboardData.files||[]).forEach(ge=>{ge.type.startsWith("image/")&&Ae.set(`${ge.name}-${ge.size}`,ge)}),Array.from(G.clipboardData.items||[]).forEach(ge=>{if(ge.kind==="file"&&ge.type.startsWith("image/")){const ze=ge.getAsFile();ze&&Ae.set(`${ze.name}-${ze.size}`,ze)}});const _e=Array.from(Ae.values());if(_e.length===0||!k&&!A)return;G.preventDefault();const Ce=G.clipboardData.getData("text");Ce&&it(Ce);let Fe=0;for(const ge of _e){const ze=de.getState().attachedFiles.length;try{await T(ge),de.getState().attachedFiles.length>ze&&(Fe+=1)}catch(Ke){console.error("Clipboard image attach failed",Ke),se.error(Ke instanceof Error?Ke.message:"Failed to attach image from clipboard")}}Fe>0&&se.success(`Attached ${Fe} image${Fe>1?"s":""} from clipboard`)},[T,k,A,it]),be=G=>{const Ae=S.current?.selectionStart||0,Ce=t.substring(0,Ae).lastIndexOf("@");if(Ce!==-1){const Fe=t.substring(0,Ce)+G.name+t.substring(Ae);n(Fe)}l(!1),u(""),S.current?.focus()},xe=G=>{const _e=S.current?.selectionStart??t.length,Fe=t.substring(0,_e).lastIndexOf("#");if(Fe!==-1){const ge=t.substring(0,Fe)+`#${G} `+t.substring(_e);n(ge);const ze=Fe+G.length+2;requestAnimationFrame(()=>{S.current&&(S.current.selectionStart=ze,S.current.selectionEnd=ze),Je(),Qe(ge,ze)})}g(!1),x(""),S.current?.focus()},Ie=G=>{n(`/${G.name} `);const Ae=S.current;Ae&&(Ae._commandMetadata=G),f(!1),h(""),setTimeout(()=>{S.current&&(S.current.focus(),S.current.setSelectionRange(S.current.value.length,S.current.value.length))},0)};c.useEffect(()=>{k&&S.current&&!O&&S.current.focus()},[k,O]),c.useEffect(()=>{U&&U!==k&&H()},[U,k,H]);const $e=G=>{G.preventDefault(),G.stopPropagation(),(k||A)&&!o&&a(!0)},Ue=G=>{G.preventDefault(),G.stopPropagation(),G.currentTarget===G.target&&a(!1)},xt=async G=>{if(G.preventDefault(),G.stopPropagation(),a(!1),!k&&!A)return;const Ae=Array.from(G.dataTransfer.files);let _e=0;for(const Ce of Ae){const Fe=de.getState().attachedFiles.length;try{await T(Ce),de.getState().attachedFiles.length>Fe&&(_e+=1)}catch(ge){console.error("File attach failed",ge),se.error(ge instanceof Error?ge.message:"Failed to attach file")}}_e>0&&se.success(`Attached ${_e} file${_e>1?"s":""}`)},je=c.useCallback(async G=>{let Ae=0;for(const _e of G){const Ce=de.getState().attachedFiles.length;try{await Z(_e.path,_e.name),de.getState().attachedFiles.length>Ce&&(Ae+=1)}catch(Fe){console.error("Server file attach failed",Fe),se.error(Fe instanceof Error?Fe.message:"Failed to attach file")}}Ae>0&&se.success(`Attached ${Ae} file${Ae>1?"s":""}`)},[Z]),Xe=c.useRef(null),[qe,ut]=c.useState(!1),Dt=c.useCallback(async G=>{let Ae=0;const _e=Array.isArray(G)?G:Array.from(G);for(const Ce of _e){const Fe=de.getState().attachedFiles.length;try{await T(Ce),de.getState().attachedFiles.length>Fe&&(Ae+=1)}catch(ge){console.error("File attach failed",ge),se.error(ge instanceof Error?ge.message:"Failed to attach file")}}Ae>0&&se.success(`Attached ${Ae} file${Ae>1?"s":""}`)},[T]),lt=c.useCallback(async()=>{try{const Ae=await(await fetch("/api/vscode/pick-files")).json(),_e=Array.isArray(Ae?.files)?Ae.files:[],Ce=Array.isArray(Ae?.skipped)?Ae.skipped:[];if(Ce.length>0){const ge=Ce.map(ze=>`${ze?.name||"file"}: ${ze?.reason||"skipped"}`).join(`
|
|
72
|
+
`);se.error(`Some files were skipped:
|
|
73
|
+
${ge}`)}const Fe=_e.map(ge=>{if(!ge?.dataUrl)return null;try{const[ze,Ke]=ge.dataUrl.split(","),st=ge.mimeType||ze?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Ke)return null;const Mt=atob(Ke),Tt=new Uint8Array(Mt.length);for(let Hs=0;Hs<Mt.length;Hs++)Tt[Hs]=Mt.charCodeAt(Hs);const Vt=new Blob([Tt],{type:st});return new File([Vt],ge.name||"file",{type:st})}catch(ze){return console.error("Failed to decode VS Code picked file",ze),null}}).filter(Boolean);Fe.length>0&&await Dt(Fe)}catch(G){console.error("VS Code file pick failed",G),se.error(G instanceof Error?G.message:"Failed to pick files in VS Code")}},[Dt]),gt=c.useCallback(()=>{if(Ht()){lt();return}Xe.current?.click()},[lt]),Rt=c.useCallback(async G=>{const Ae=G.target.files;Ae&&(await Dt(Ae),G.target.value="")},[Dt]),hs="gap-x-1.5 gap-y-0",hr=Ht(),jn=O?"px-1.5 py-1.5":hr?"px-1.5 py-1":"px-2.5 py-1.5",Vr=O?"h-9 w-9":hr?"h-[22px] w-[22px]":"h-7 w-7",As=O?"h-5 w-5":hr?"h-4 w-4":"h-[18px] w-[18px]",Et=R(Vr,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),Xn=!O&&Oe&&Ee?e.jsx("button",{type:"button",onClick:Be,className:R(Et,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(un,{className:R(As)})}):e.jsx("button",{type:O?"button":"submit",disabled:!Jt||!k&&!A,onPointerDownCapture:G=>{!O||G.pointerType!=="touch"||!Jt||!k&&!A||(te.current=!0,G.preventDefault(),G.stopPropagation(),Ze())},onClick:G=>{if(O){if(te.current){te.current=!1;return}G.preventDefault(),Ze()}},className:R(Et,Jt&&(k||A)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Bd,{className:R(As)})}),ua=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Xe,type:"file",multiple:!0,className:"hidden",onChange:Rt,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(tb,{onFilesSelected:je,multiSelect:!0,presentation:O?"modal":"dropdown",open:qe,onOpenChange:ut,children:O?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx("button",{type:"button",className:Et,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(zd,{className:R(As,"text-current")})})}),e.jsxs(Xt,{align:"start",children:[e.jsxs(jt,{onSelect:()=>{requestAnimationFrame(()=>gt())},children:[e.jsx(To,{}),"Attach files"]}),e.jsxs(jt,{onSelect:()=>{requestAnimationFrame(()=>{ut(!0)})},children:[e.jsx(Tp,{}),"Attach from project"]})]})]})]})]}),ma=s?e.jsx("button",{type:"button",onClick:s,className:Et,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx($n,{className:R(As,"text-current")})}):null,he=e.jsxs(e.Fragment,{children:[ua,ma]}),Ne=me.statusText;c.useEffect(()=>{const G=!!me.wasAborted;!le.current&&G&&!pe&&(dt(),k&&L(k)),le.current=G},[L,k,pe,dt,me.wasAborted]),c.useEffect(()=>()=>{Y.current&&(clearTimeout(Y.current),Y.current=null)},[]);const Se=O&&Ee;return e.jsxs("form",{onSubmit:Ze,className:"pt-0 pb-2 md:pb-4 bottom-safe-area","data-keyboard-avoid":"true",style:O&&_>0&&!ee?{marginBottom:`${_}px`}:void 0,children:[e.jsx(gb,{isWorking:me.isWorking,statusText:Ne,isGenericStatus:me.isGenericStatus,isWaitingForPermission:me.isWaitingForPermission,wasAborted:me.wasAborted,abortActive:me.abortActive,completionId:me.lastCompletionId,isComplete:me.isComplete,showAbort:Se,onAbort:Be,showAbortStatus:pe}),e.jsxs("div",{ref:v,className:R("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:$e,onDragLeave:Ue,onDrop:xt,children:[o&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-xl",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-flex justify-center",children:e.jsx("button",{type:"button",className:Et,onClick:()=>gt(),title:"Attach files","aria-label":"Attach files",children:e.jsx(To,{className:R(As,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(Xx,{}),e.jsx(nm,{onEditMessage:G=>{n(G),setTimeout(()=>{S.current?.focus()},0)}}),e.jsxs("div",{className:R("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:Pt,children:[m&&e.jsx(am,{ref:D,searchQuery:p,onCommandSelect:Ie,onClose:()=>f(!1)}),j&&e.jsx(im,{ref:M,searchQuery:b,onAgentSelect:xe,onClose:()=>g(!1)}),i&&e.jsx(Qx,{ref:N,searchQuery:d,onFileSelect:be,onClose:()=>l(!1)}),e.jsx(js,{ref:S,"data-chat-input":"true",value:t,onChange:ht,onKeyDown:zt,onPaste:Q,onPointerDownCapture:fe,placeholder:k||A?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!k&&!A,className:R("min-h-[52px] resize-none border-0 px-3 shadow-none rounded-t-xl rounded-b-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent",O?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:y?`${y.height}px`:void 0,maxHeight:y?`${y.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:R("rounded-b-xl bg-transparent",jn,O?"flex items-center gap-x-1.5":R("flex items-center justify-between",hs)),"data-chat-input-footer":"true",children:O?e.jsxs("div",{className:"flex w-full items-center gap-x-1.5",children:[e.jsx("div",{className:"flex items-center flex-shrink-0 gap-x-1",children:he}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-x-1 min-w-0",children:[e.jsx("div",{className:"flex flex-1 min-w-0 justify-end overflow-hidden",children:e.jsx(Ac,{className:R("w-full flex items-center justify-end min-w-0")})}),Xn]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("flex items-center flex-shrink-0",hs),children:he}),e.jsxs("div",{className:R("flex items-center flex-1 justify-end",hs,"md:gap-x-3"),children:[e.jsx(Ac,{className:R("flex-1 min-w-0 justify-end")}),Xn]})]})})]})]})]})};function $a({className:s,...r}){return e.jsx("div",{"data-slot":"skeleton",className:R("bg-accent animate-pulse rounded-xl",s),...r})}const zc=(s,r,t,n,o=4)=>{const a=[];for(let i=0;i<o;i++)for(let l=0;l<o;l++){const d=l/o,u=(l+1)/o,m=i/o,f=(i+1)/o,p=(y,w,S)=>y+(w-y)*S,h=(y,w,S,v,N,D)=>{const M=p(y,w,N),C=p(v,S,N);return p(M,C,D)},j={x:h(s.x,r.x,t.x,n.x,d,m),y:h(s.y,r.y,t.y,n.y,d,m)},g={x:h(s.x,r.x,t.x,n.x,u,m),y:h(s.y,r.y,t.y,n.y,u,m)},b={x:h(s.x,r.x,t.x,n.x,u,f),y:h(s.y,r.y,t.y,n.y,u,f)},x={x:h(s.x,r.x,t.x,n.x,d,f),y:h(s.y,r.y,t.y,n.y,d,f)};a.push({path:`M${j.x} ${j.y} L${g.x} ${g.y} L${b.x} ${b.y} L${x.x} ${x.y} Z`,row:i,col:l})}return a},il=({className:s="",width:r=70,height:t=70,isAnimated:n=!1})=>{const o=na();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const i=a?"white":"black",l=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,h=50,j={x:50,y:h-m},g={x:50-m*f,y:h-m*p},b={x:50+m*f,y:h-m*p},x={x:50,y:h},y={x:50-m*f,y:h+m*p},w={x:50+m*f,y:h+m*p},S={x:50,y:h+m},N=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(j.y+g.y+x.y+b.y)/4})`,D=zc(g,x,S,y),M=zc(x,b,w,S),C=Me.useMemo(()=>{const k=[];for(let A=0;A<32;A++)k.push(.1+Math.random()*.5);return k},[]);return e.jsxs("svg",{width:r,height:t,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:s,role:"img","aria-label":"OpenChamber logo",children:[e.jsx("path",{d:`M${x.x} ${x.y} L${g.x} ${g.y} L${y.x} ${y.y} L${S.x} ${S.y} Z`,fill:l,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),D.map((k,A)=>e.jsx("path",{d:k.path,fill:u,opacity:C[A]},`left-${A}`)),e.jsx("path",{d:`M${x.x} ${x.y} L${b.x} ${b.y} L${w.x} ${w.y} L${S.x} ${S.y} Z`,fill:l,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),M.map((k,A)=>e.jsx("path",{d:k.path,fill:u,opacity:C[A+16]},`right-${A}`)),e.jsx("path",{d:`M${j.x} ${j.y} L${g.x} ${g.y} L${x.x} ${x.y} L${b.x} ${b.y} Z`,fill:"none",stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${N} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function Cb({children:s,className:r,interval:t=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:i=!0,mode:l="popLayout"}){const[d,u]=Me.useState(0),m=Me.Children.toArray(s);Me.useEffect(()=>{if(!i)return;const p=t*1e3,h=setInterval(()=>{u(j=>{const g=(j+1)%m.length;return a?.(g),g})},p);return()=>clearInterval(h)},[m.length,t,a,i]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:R("relative",r),children:[e.jsx("div",{className:"invisible whitespace-nowrap",children:m.map((p,h)=>e.jsx("div",{className:h===0?"":"absolute",children:p},h))}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(Fp,{mode:l,initial:!1,children:e.jsx(Jr.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const Mb=["Fix the failing tests","Refactor this to be more readable","Add form validation","Optimize this function","Write tests for this","Explain how this works","Add a new feature","Help me debug this","Review my code","Simplify this logic","Add error handling","Create a new component","Update the documentation","Find the bug here","Improve performance","Add type definitions"],Db=()=>{const s=na();let r=!0;s?r=s.currentTheme.metadata.variant!=="light":typeof window<"u"&&(r=window.matchMedia("(prefers-color-scheme: dark)").matches);const t=r?"rgba(255,255,255,0.4)":"rgba(0,0,0,0.4)";return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[e.jsx(il,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(Cb,{className:"text-body-md",interval:4,transition:{duration:.5},children:Mb.map(n=>e.jsxs("span",{style:{color:t},children:['"',n,'…"']},n))})]})},La=c.memo(Db),Ab={'code[class*="language-"]':{color:"#cdccc3",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:"#cdccc3",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0",overflow:"auto"},comment:{color:"#6b6964",fontStyle:"italic"},prolog:{color:"#6b6964"},doctype:{color:"#6b6964"},cdata:{color:"#6b6964"},punctuation:{color:"#6b6963"},property:{color:"#d29470"},tag:{color:"#d8886d"},boolean:{color:"#d39373"},number:{color:"#d39373"},constant:{color:"#6cacd6"},symbol:{color:"#6cacd6"},deleted:{color:"#d98678"},selector:{color:"#81af6c"},"attr-name":{color:"#c2974d"},string:{color:"#81af6c"},char:{color:"#81af6c"},builtin:{color:"#5aa9d9"},inserted:{color:"#81af6c"},operator:{color:"#d29470"},entity:{color:"#edb449",cursor:"help"},url:{color:"#5aa9d9"},".language-css .token.string":{color:"#81af6c"},".style .token.string":{color:"#81af6c"},variable:{color:"#d29470"},atrule:{color:"#c2974d"},"attr-value":{color:"#81af6c"},function:{color:"#5aa9d9"},"class-name":{color:"#c2974d"},keyword:{color:"#d8886d"},regex:{color:"#81af6c"},important:{color:"#d8886d",fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{opacity:.7},title:{color:"#edb449",fontWeight:"bold"},"code-block":{color:"#81af6c"},"code-snippet":{color:"#81af6c"},list:{color:"#d29470"},hr:{color:"#6b6963"},table:{color:"#5aa9d9"},blockquote:{color:"#6b6964",fontStyle:"italic"},strike:{textDecoration:"line-through"}},Eb={'code[class*="language-"]':{color:"#403e3c",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:"#403e3c",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0",overflow:"auto"},comment:{color:"#7a756a",fontStyle:"italic"},prolog:{color:"#7a756a"},doctype:{color:"#7a756a"},cdata:{color:"#7a756a"},punctuation:{color:"#6b6963"},property:{color:"#c07845"},tag:{color:"#b96f55"},boolean:{color:"#b97659"},number:{color:"#b97659"},constant:{color:"#4791ba"},symbol:{color:"#4791ba"},deleted:{color:"#c15748"},selector:{color:"#6a9354"},"attr-name":{color:"#9f7d3e"},string:{color:"#6a9354"},char:{color:"#6a9354"},builtin:{color:"#4791ba"},inserted:{color:"#6a9354"},operator:{color:"#c07845"},entity:{color:"#d09930",cursor:"help"},url:{color:"#4791ba"},".language-css .token.string":{color:"#6a9354"},".style .token.string":{color:"#6a9354"},variable:{color:"#c07845"},atrule:{color:"#9f7d3e"},"attr-value":{color:"#6a9354"},function:{color:"#4791ba"},"class-name":{color:"#9f7d3e"},keyword:{color:"#b96f55"},regex:{color:"#6a9354"},important:{color:"#b96f55",fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{opacity:.7},title:{color:"#d09930",fontWeight:"bold"},"code-block":{color:"#6a9354"},"code-snippet":{color:"#6a9354"},list:{color:"#c07845"},hr:{color:"#6b6963"},table:{color:"#4791ba"},blockquote:{color:"#7a756a",fontStyle:"italic"},strike:{textDecoration:"line-through"}};class wr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return wr.instance||(wr.instance=new wr),wr.instance}recordSessionStart(r){this.sessionStartTimes.set(r,Date.now())}getSessionStartTime(r){return this.sessionStartTimes.get(r)}shouldAnimateMessage(r,t){if(r.role!=="assistant"||this.seenMessageIds.has(r.id))return!1;const n=this.sessionStartTimes.get(t);if(!n)return this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created),!1;const o=r.time.created>n-5e3;return o||(this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created)),o}clearSession(r){this.sessionStartTimes.delete(r)}hasSessionTiming(r){return this.sessionStartTimes.has(r)}hasBeenAnimated(r){return this.seenMessageIds.has(r)}markMessageAsAnimated(r,t){this.seenMessageIds.add(r),this.messageCreationTimes.set(r,t)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function pm(s){const r=s.colors.syntax,t=s.colors.surface;return{'code[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"0",margin:"0",overflow:"auto"},comment:{color:r.base.comment,fontStyle:"italic"},prolog:{color:r.base.comment},doctype:{color:r.base.comment},cdata:{color:r.base.comment},punctuation:{color:r.tokens?.punctuation||t.mutedForeground},property:{color:r.tokens?.variableProperty||r.base.variable},tag:{color:r.tokens?.tag||r.base.keyword},"attr-name":{color:r.tokens?.tagAttribute||r.base.variable},"attr-value":{color:r.tokens?.tagAttributeValue||r.base.string},boolean:{color:r.tokens?.boolean||r.base.number},number:{color:r.base.number},constant:{color:r.tokens?.constant||r.base.number},symbol:{color:r.tokens?.constant||r.base.number},string:{color:r.base.string},char:{color:r.base.string},function:{color:r.base.function},builtin:{color:r.tokens?.functionBuiltin||r.base.function},"class-name":{color:r.tokens?.className||r.base.type},namespace:{color:r.tokens?.namespace||r.base.type,opacity:.8},keyword:{color:r.base.keyword},atrule:{color:r.base.keyword},selector:{color:r.base.function},operator:{color:r.base.operator},variable:{color:r.base.variable},regex:{color:r.tokens?.regex||r.base.string},url:{color:r.base.function,textDecoration:"underline"},entity:{color:r.base.function,cursor:"help"},".language-css .token.string":{color:r.base.string},".style .token.string":{color:r.base.string},deleted:{color:s.colors.status.error,backgroundColor:s.colors.status.errorBackground},inserted:{color:s.colors.status.success,backgroundColor:s.colors.status.successBackground},title:{color:s.colors.primary.base,fontWeight:"bold"},"code-block":{color:r.base.string},"code-snippet":{color:r.base.string},list:{color:r.base.variable},hr:{color:t.mutedForeground},table:{color:r.base.function},blockquote:{color:t.mutedForeground,fontStyle:"italic"},important:{color:r.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:r.tokens?.decorator||r.base.function},annotation:{color:r.tokens?.decorator||r.base.function}}}const ms=({children:s,className:r})=>{const[t,n]=c.useState(!1);return c.useEffect(()=>{let o=null;const a=()=>n(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o=window.requestAnimationFrame(a):a(),()=>{o!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(o)}},[]),e.jsx("div",{className:R("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:s})},Ib=({isUser:s,providerID:r,agentName:t,modelName:n,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:l}=Qu(r);return e.jsx(ms,{children:e.jsx("div",{className:R("pl-3","mb-2"),children:e.jsx("div",{className:R("flex items-center justify-between gap-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0",children:s?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(Ss,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:l&&a?e.jsx("img",{src:a,alt:`${r} logo`,className:"h-4 w-4",style:{filter:o?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:i}):e.jsx(xn,{className:"h-4 w-4",style:{color:`var(${xr(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:R("font-bold typography-ui-header tracking-tight leading-none",s?"text-primary":"text-foreground"),children:s?"You":n||"Assistant"}),!s&&t&&e.jsx("div",{className:R("flex items-center gap-1 px-1.5 py-0 rounded","agent-badge typography-meta",xr(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},Pb=c.memo(Ib),Wc=(s,r)=>{const t=s[Symbol.toPrimitive];if(typeof t=="function")try{if(t()===r)return s}catch{}try{Object.defineProperty(s,"toString",{value:()=>r,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(s,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0})}catch{}return s},Hc=()=>{if(!Ht()||typeof window>"u")return rc;const s=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(s?.light&&s?.dark){const r=Wc({...s.light},`vscode-shiki-light:${String(s.light?.name??"theme")}`),t=Wc({...s.dark},`vscode-shiki-dark:${String(s.dark?.name??"theme")}`);return[r,t]}return rc},hm=()=>{const[s,r]=c.useState(Hc);return c.useEffect(()=>{if(!Ht()||typeof window>"u")return;const t=n=>{r(Hc())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),s},gm=s=>{const r=[],t=[],n=s.querySelector("thead");n&&n.querySelectorAll("th").forEach(i=>r.push(i.innerText.trim()));const o=s.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(i=>{const l=i.querySelectorAll("td"),d=[];l.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:r,rows:t}},ym=({headers:s,rows:r})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
|
|
74
|
+
`)?`"${o.replace(/"/g,'""')}"`:o,n=[];return s.length>0&&n.push(s.map(t).join(",")),r.forEach(o=>n.push(o.map(t).join(","))),n.join(`
|
|
75
|
+
`)},Tb=({headers:s,rows:r})=>{const t=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return s.length>0&&n.push(s.map(t).join(" ")),r.forEach(o=>n.push(o.map(t).join(" "))),n.join(`
|
|
76
|
+
`)},Fb=({headers:s,rows:r})=>{if(s.length===0)return"";const t=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${s.map(t).join(" | ")} |`),n.push(`| ${s.map(()=>"---").join(" | ")} |`),r.forEach(o=>{const a=s.map((i,l)=>t(o[l]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
|
|
77
|
+
`)},Rb=(s,r,t)=>{const n=new Blob([r],{type:t}),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=s,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)},Ob=({tableRef:s})=>{const[r,t]=c.useState(!1),[n,o]=c.useState(!1),a=c.useRef(null);c.useEffect(()=>{const l=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[]);const i=async l=>{const d=s.current?.querySelector("table");if(d)try{const u=gm(d),m=l==="csv"?ym(u):Tb(u);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([m],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),t(!0),o(!1),setTimeout(()=>t(!1),2e3)}catch(u){console.error("Failed to copy table:",u)}};return e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>o(!n),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:r?e.jsx(Ot,{className:"size-3.5"}):e.jsx(Bs,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("tsv"),children:"TSV"})]})]})},$b=({tableRef:s})=>{const[r,t]=c.useState(!1),n=c.useRef(null);c.useEffect(()=>{const a=i=>{n.current&&!n.current.contains(i.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const i=s.current?.querySelector("table");if(i)try{const l=gm(i),d=a==="csv"?ym(l):Fb(l);Rb(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),t(!1)}catch(l){console.error("Failed to download table:",l)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>t(!r),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(dn,{className:"size-3.5"})}),r&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("markdown"),children:"Markdown"})]})]})},Lb=({children:s,className:r})=>{const t=c.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:t,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(Ob,{tableRef:t}),e.jsx($b,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:R("w-full border-collapse border border-border",r),"data-streamdown":"table",children:s})})]})},_b=({children:s,className:r,style:t,...n})=>{const[o,a]=c.useState(!1),i=c.useRef(null),l=c.useMemo(()=>{if(!t)return t;const m={...t},f=j=>{if(typeof j!="string")return{value:void 0,vars:{}};const[g,...b]=j.split(";").map(y=>y.trim()).filter(Boolean),x={};for(const y of b){const w=y.indexOf(":");if(w===-1)continue;const S=y.slice(0,w).trim(),v=y.slice(w+1).trim();!S.startsWith("--")||v.length===0||(x[S]=v)}return{value:g,vars:x}},p=f(t.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[j,g]of Object.entries(p.vars))m[j]=g;const h=f(t.color);h.value&&(m.color=h.value,m["--shiki-light"]=h.value);for(const[j,g]of Object.entries(h.vars))m[j]=g;return m},[t]),d=()=>i.current&&i.current.querySelector("code")?.innerText||"",u=async()=>{const m=d();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:i,children:[e.jsx("pre",{...n,className:R(r),style:l,children:s}),e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:u,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(Ot,{className:"size-3.5"}):e.jsx(Bs,{className:"size-3.5"})})})]})},xm={pre:_b,table:Lb},Bb=({content:s,part:r,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const l=hm(),d=c.useMemo(()=>`markdown-${r?.id?`part-${r.id}`:`message-${t}`}`,[t,r?.id]),u=i==="tool"?"streamdown-content streamdown-tool":"streamdown-content",m=e.jsx("div",{className:R("break-words",o),children:e.jsx(Wd,{mode:a?"streaming":"static",shikiTheme:l,className:u,controls:{code:!1,table:!1},components:xm,children:s})});return n?e.jsx(ms,{children:m},d):m},Fr=({content:s,className:r,variant:t="assistant"})=>{const n=hm(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:R("break-words",r),children:e.jsx(Wd,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:xm,children:s})})},zb={thinking:{label:"Thinking",Icon:xn},justification:{label:"Justification",Icon:Di}},bm=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
|
|
78
|
+
`).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
|
|
79
|
+
`).trim(),Wb=s=>{if(!s)return"";const r=s.trim(),t=r.indexOf(`
|
|
80
|
+
`),n=r.indexOf("."),o=[t>=0?t:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?r.substring(0,a).trim():r},ll=({text:s,variant:r,onContentChange:t,blockId:n})=>{const[o,a]=c.useState(!1),i=c.useMemo(()=>Wb(s),[s]),{label:l,Icon:d}=zb[r];return c.useEffect(()=>{s.trim().length!==0&&t?.("structural")},[t,o,s]),!s||s.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>a(u=>!u),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:R("absolute inset-0 transition-opacity",o&&"opacity-0",!o&&"group-hover/tool:opacity-0"),children:e.jsx(d,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",o&&"opacity-100",!o&&"opacity-0 group-hover/tool:opacity-100"),children:o?e.jsx(Ct,{className:"h-3.5 w-3.5"}):e.jsx(Ls,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:l})]}),i&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:i})})]}),o&&e.jsx("div",{className:R("relative pr-2 pb-2 pt-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:e.jsx(ct,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:s})})]})},wm=({part:s,onContentChange:r,messageId:t})=>{const n=s,o=n.text||n.content||"",a=c.useMemo(()=>bm(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(ll,{text:a,variant:"thinking",onContentChange:r,blockId:s.id||`${t}-reasoning`}):null},Hb=s=>bm(s),Ub=({part:s,messageId:r,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=s,l=i.text,d=typeof l=="string"?l:i.content||i.value||"",u=c.useMemo(()=>a?Hb(d):d,[d,a]),m=t==="streaming",f=t==="cooldown",p=c.useRef(m);if(m||f)return p.current=!0,null;const h=i.time;return!(h&&typeof h.end<"u")&&(!u||u.trim().length===0)||!u||u.trim().length===0?null:a?e.jsx(ll,{text:u,variant:"justification",onContentChange:o,blockId:s.id||`${r}-reasoning-text`},s.id||`${r}-text`):e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Bb,{content:u,part:s,messageId:r,isAnimated:n,isStreaming:!1})},s.id||`${r}-text`)},Vb=s=>`https://opencode.ai/docs/agents/#${encodeURIComponent(s)}`,Gb=({part:s,messageId:r,agentMention:t})=>{const n=s,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,l]=c.useState(!1),[d,u]=c.useState(!1),m=c.useRef(null);c.useEffect(()=>{const h=m.current;if(!h||i)return;const j=()=>{u(h.scrollHeight>h.clientHeight)};j();const g=new ResizeObserver(j);return g.observe(h),()=>g.disconnect()},[a,i]);const f=c.useCallback(()=>{(d||i)&&l(h=>!h)},[d,i]);if(!a||a.trim().length===0)return null;const p=()=>{if(!t?.token||!a.includes(t.token))return a;const h=a.indexOf(t.token),j=a.slice(0,h),g=a.slice(h+t.token.length);return e.jsxs(e.Fragment,{children:[j,e.jsx("a",{href:Vb(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:b=>b.stopPropagation(),children:t.token}),g]})};return e.jsx("div",{className:R("break-words whitespace-pre-wrap font-sans typography-markdown",!i&&"line-clamp-3",(d||i)&&"cursor-pointer"),ref:m,onClick:f,children:p()},s.id||`${r}-user-text`)},qb=c.memo(Gb),Kb=s=>{let r=s.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},vm=s=>s?s.includes("<file_diagnostics>")||s.includes("This file has errors")||s.includes("please fix"):!1,Yb=s=>s?s.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Uc=(s,r)=>!s||typeof s!="object"?String(s):Wy(s,r||""),_a=(s,r,t)=>{let n=Kb(s);if((r==="edit"||r==="multiedit")&&vm(n)&&(n=Yb(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},Xb=(s,r)=>{try{const t=s.trim().split(`
|
|
81
|
+
`).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,l]=a,d=Math.floor(i.length/2),u=!l.endsWith("/");n.push({name:l.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:R("w-full min-w-0 font-mono space-y-0.5",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:ir.tool.popup,children:n.map((o,a)=>e.jsx("div",{className:"min-w-0",style:{paddingLeft:`${o.depth*20}px`},children:o.isFile?e.jsx("span",{className:"text-foreground/90 block truncate",children:o.name}):e.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[o.name,"/"]})},a))})}catch{return null}},Qb=(s,r,t)=>{try{const n=s.trim().split(`
|
|
82
|
+
`).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,l,d,u]=i,m=u!==void 0?d:"",f=u!==void 0?u:d;o[l]||(o[l]=[]),o[l].push({lineNum:m,content:f})}}),e.jsxs("div",{className:R("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:ir.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,i])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:R("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((l,d)=>!l.lineNum&&!l.content?null:e.jsxs("div",{className:R("flex items-start gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[l.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",l.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:l.content||" "})]})]},d))})]},a))]})}catch{return null}},Jb=(s,r,t)=>{try{const n=s.trim().split(`
|
|
83
|
+
`).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const l=i.lastIndexOf("/"),d=l>0?i.substring(0,l):"/",u=l>=0?i.substring(l+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:R("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:ir.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(i=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:R("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:R("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(l=>e.jsxs("div",{className:R("flex items-center gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:l})]},l))})]},i))]})}catch{return null}},Zb=(s,r)=>{try{const t=JSON.parse(s);if(!Array.isArray(t))return null;const n={in_progress:t.filter(a=>a.status==="in_progress"),pending:t.filter(a=>a.status==="pending"),completed:t.filter(a=>a.status==="completed"),cancelled:t.filter(a=>a.status==="cancelled")},o=a=>{const i="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:i,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:i,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:R("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:ir.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",t.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"w-3 h-3",style:{color:"var(--status-success)"}}),e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:"Completed"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.completed.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ot,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||i))})]})]})}catch{return null}},ew=(s,r,t)=>{try{return e.jsx("div",{className:R("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:ir.tool.popup,children:e.jsx(Fr,{content:s,variant:"tool"})})}catch{return null}},jm=s=>{const r=s.split(`
|
|
84
|
+
`);let t="";const n=[];let o=0;for(;o<r.length;){const a=r[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(t=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const i=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),l=i?parseInt(i[1]):0,d=i?parseInt(i[2]):0,u=[];let m=d,f=o+1;for(;f<r.length&&!r[f].startsWith("@@")&&!r[f].startsWith("Index:");){const p=r[f];p.startsWith("+")?(u.push({type:"added",lineNumber:m,content:p.substring(1)}),m++):p.startsWith("-")?u.push({type:"removed",lineNumber:null,content:p.substring(1)}):p.startsWith(" ")&&(u.push({type:"context",lineNumber:m,content:p.substring(1)}),m++),f++}n.push({file:t,oldStart:l,newStart:d,lines:u}),o=f;continue}o++}return n},bi=(s,r,t)=>_y(r,s,t),Sm=s=>{const r="h-3.5 w-3.5 flex-shrink-0",t=s.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(Rp,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(Hd,{className:r}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(ri,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(Sr,{className:r}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(Ts,{className:r}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(Op,{className:r}):t==="glob"?e.jsx($p,{className:r}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(ni,{className:r}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(ni,{className:r}):t==="todowrite"||t==="todoread"?e.jsx(Lp,{className:r}):t==="skill"?e.jsx(Ud,{className:r}):t.startsWith("git")?e.jsx(Ft,{className:r}):e.jsx(Jo,{className:r})},tw=(s,r,t=Date.now())=>{const o=(r?r-s:t-s)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},sw=({start:s,end:r,active:t})=>{const[n,o]=c.useState(()=>Date.now());return c.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:tw(s,r,n)})},rw=s=>{if(!s?.diff||typeof s.diff!="string")return null;const r=s.diff.split(`
|
|
85
|
+
`);let t=0,n=0;for(const o of r)o.startsWith("+")&&!o.startsWith("+++")&&t++,o.startsWith("-")&&!o.startsWith("---")&&n++;return t===0&&n===0?null:{added:t,removed:n}},wi=(s,r,t)=>{if(t)return s.split("/").pop()||s;if(s.startsWith(r)){const n=s.substring(r.length);return n.startsWith("/")?n.substring(1):n}return s},nw=(s,r,t,n)=>{const o=r,a=o.metadata,i=o.input;if((s.tool==="edit"||s.tool==="multiedit")&&i){const d=i?.filePath||i?.file_path||i?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return wi(d,n,t)}if((s.tool==="read"||s.tool==="write")&&i){const d=i?.filePath||i?.file_path||i?.path;if(typeof d=="string")return wi(d,n,t)}if(s.tool==="bash"&&i?.command&&typeof i.command=="string"){const d=i.command.split(`
|
|
86
|
+
`)[0];return t?d.substring(0,50):d.substring(0,100)}if(s.tool==="task"&&i?.description&&typeof i.description=="string")return t?i.description.substring(0,40):i.description.substring(0,80);if(s.tool==="skill"&&i?.name&&typeof i.name=="string")return i.name;const l=i?.description||a?.description||"title"in r&&r.title||"";return typeof l=="string"?l:""},vi=({children:s,maxHeightClass:r="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(ct,{outerClassName:R("w-full min-w-0 flex-none overflow-hidden",r,n),className:R("tool-output-surface p-2 rounded-xl w-full min-w-0 border border-border/20 bg-transparent",t),disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:s})}),ow=s=>{const r=s.state?.title;return typeof r=="string"&&r.trim().length>0?r:typeof s.tool=="string"&&s.tool.trim().length>0?s.tool:"tool"},aw=s=>s.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),iw=({entries:s,isExpanded:r,hasPrevTool:t,hasNextTool:n,output:o,sessionId:a})=>{const i=de(g=>g.setCurrentSession),l=c.useMemo(()=>s.filter(g=>g.state?.status==="completed"),[s]),d=typeof o=="string"?aw(o):"",u=d.length>0,[m,f]=c.useState(!1),p=g=>{g.stopPropagation(),a&&i(a)};if(l.length===0&&!u&&!a)return null;const h=r?l:l.slice(-6),j=Math.max(0,l.length-h.length);return e.jsxs("div",{className:R("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',t?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[l.length>0?e.jsx(vi,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[j>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",j," more…"]}):null,h.map((g,b)=>{const x=typeof g.tool=="string"&&g.tool.trim().length>0?g.tool:"tool",y=ow(g),w=Ki(x).displayName;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:Sm(x)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:w}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:y})]},g.id??`${x}-${b}`)})]})}):null,a&&e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:g=>g.stopPropagation(),onClick:p,children:[e.jsx(Po,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-primary font-medium",children:"Open subAgent session"})]}),u?e.jsxs("div",{className:R("space-y-1",(l.length>0||a)&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:g=>g.stopPropagation(),onClick:g=>{g.stopPropagation(),f(b=>!b)},children:[m?e.jsx(Ct,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Ls,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?e.jsx(vi,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Fr,{content:d,variant:"tool"})})}):null]}):null]})},lw=({diff:s,syntaxTheme:r,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:jm(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} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,i)=>e.jsxs("div",{className:R("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(lr,{style:r,language:Hr(typeof t?.file_path=="string"?t.file_path:typeof t?.filePath=="string"?t.filePath:n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},i))})]},o))}),cw=({content:s,syntaxTheme:r,filePath:t,displayPath:n})=>{const o=s.split(`
|
|
87
|
+
`),a=Hr(t??"")||bi(s,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),l=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${l})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(lr,{style:r,language:a||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},dw=({content:s,filePath:r,displayPath:t})=>{const n=zy(r),o=r.toLowerCase().endsWith(".svg"),a=c.useMemo(()=>o&&!s.startsWith("data:")?`data:image/svg+xml;base64,${btoa(s)}`:s.startsWith("data:")?s:`data:${n};base64,${s}`,[s,n,o]);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-2",children:t}),e.jsx("div",{className:"flex justify-center p-4 bg-muted/10 rounded-lg border border-border/10",children:e.jsx("img",{src:a,alt:t,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})},uw=({part:s,state:r,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const l=r,d=l.metadata,u=l.input,m=l.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",h=typeof d?.diff=="string"?d.diff:null,j=s.tool==="write"?typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0:void 0,g=s.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,b=s.tool==="write"&&!!g,x=j?Ou(j):!1,y=b?j?wi(j,o,n):"New file":null,w=c.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&s.tool==="bash"?Uc(u,s.tool):typeof u.content=="string"?u.content??"":Uc(u,s.tool),[u,s.tool]),S=w.trim().length>0,v=(D,M)=>e.jsx(vi,{maxHeightClass:M?.maxHeightClass,className:M?.className,disableHorizontal:M?.disableHorizontal,outerClassName:M?.outerClassName,children:D}),N=()=>{if(s.tool==="todowrite"||s.tool==="todoread"){if(r.status==="completed"&&f){const D=Zb(p,{unstyled:!0});return v(D??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(s.tool==="list"&&f){const D=Xb(p,{unstyled:!0});return v(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="grep"&&f){const D=Qb(p,n,{unstyled:!0});return v(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="glob"&&f){const D=Jb(p,n,{unstyled:!0});return v(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="task"&&f)return v(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Fr,{content:p,variant:"tool"})}));if((s.tool==="web-search"||s.tool==="websearch"||s.tool==="search_web")&&f){const D=ew(p,t,{unstyled:!0});return v(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="codesearch"&&f)return v(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Fr,{content:p,variant:"tool"})}));if(s.tool==="skill"&&f)return v(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Fr,{content:p,variant:"tool"})}));if((s.tool==="edit"||s.tool==="multiedit")&&(!f&&h||p.trim().length===0||vm(p))&&h)return v(e.jsx(lw,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&p.trim()){if(s.tool==="read"){const D=_a(p,s.tool,d),M=D.split(`
|
|
88
|
+
`),C=typeof u?.offset=="number"?u.offset:0,k=typeof u?.limit=="number"?u.limit:void 0,A=P=>P.trim().startsWith("(");return v(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:M.map((P,L)=>{const U=A(P),z=C+L+1,H=!U&&(k===void 0||L<k);return e.jsxs("div",{className:R("typography-code font-mono flex w-full min-w-0",U&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-3 self-start select-none",children:H?z:""}),e.jsx("div",{className:"flex-1 min-w-0",children:U?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:P}):e.jsx(lr,{style:t,language:bi(D,s.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:P})})]},L)})}),{className:"p-1"})}return v(e.jsx(lr,{style:t,language:bi(_a(p,s.tool,d),s.tool,u),PreTag:"div",customStyle:{...wo.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:_a(p,s.tool,d)}),{className:"p-1"})}return v(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:R("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",i?"before:bottom-[-0.6rem]":"before:bottom-0"),children:s.tool==="todowrite"||s.tool==="todoread"?N():e.jsxs(e.Fragment,{children:[b&&x?e.jsx("div",{className:"my-1",children:v(e.jsx(dw,{content:g,filePath:j,displayPath:y??"New file"}))}):b?e.jsx("div",{className:"my-1",children:v(e.jsx(cw,{content:g,syntaxTheme:t,filePath:j,displayPath:y??"New file"}))}):S?e.jsx("div",{className:"my-1",children:v(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:w}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,s.tool!=="write"&&r.status==="completed"&&"output"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),N()]}),r.status==="error"&&"error"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]})]})})},Do=({part:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:l=!1})=>{const d=s.state,u=ft(z=>z.currentDirectory),m=s.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",p=d.status==="running"||d.status==="pending",h=d.status==="error",j=c.useRef(r);c.useEffect(()=>{!f&&!m||j.current!==r&&(j.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const g=d,b=g.metadata,x=g.input,y=g.time,w=c.useRef({}),S=c.useRef(s.id);if(S.current!==s.id&&(S.current=s.id,w.current={}),m){if(typeof y?.start=="number"){const z=w.current.start;(typeof z!="number"||y.start<z)&&(w.current.start=y.start)}typeof y?.end=="number"&&(w.current.end=y.end)}const v=m?w.current.start??y?.start:y?.start,N=m?w.current.end??y?.end:y?.end,D=c.useMemo(()=>{if(!m)return;const z=b;return typeof z?.sessionId=="string"?z.sessionId:void 0},[m,b]),M=c.useMemo(()=>{if(!m)return[];const z=b?.summary;return Array.isArray(z)?z.filter(H=>typeof H=="object"&&H!==null):[]},[m,b]),C=c.useRef(M.length);c.useEffect(()=>{m&&C.current!==M.length&&(C.current=M.length,a?.("structural"))},[m,a,M.length]);const k=s.tool==="edit"||s.tool==="multiedit"?rw(b):null,A=nw(s,d,o,u),P=Ki(s.tool).displayName,L=c.useContext(Yi),U=z=>{if(m||!L?.editor){t(s.id);return}let H;if((s.tool==="edit"||s.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(s.tool))&&(H=x?.filePath||x?.file_path||x?.path||b?.filePath||b?.file_path||b?.path),typeof H=="string"){z.stopPropagation();let V=H;H.startsWith("/")||(V=u.endsWith("/")?u+H:u+"/"+H),L.editor.openFile(V)}else t(s.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:U,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:z=>{z.stopPropagation(),t(s.id)},children:[e.jsx("div",{className:R("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&h?{color:"var(--status-error)"}:{},children:Sm(s.tool)}),e.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",r&&"opacity-100",!r&&o&&"opacity-0",!r&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:r?e.jsx(Ct,{className:"h-3.5 w-3.5"}):e.jsx(Ls,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:P})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[A&&e.jsx("span",{className:R("truncate",o&&"max-w-[120px]"),children:A}),k&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",k.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",k.removed]})]}),typeof v=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(sw,{start:v,end:typeof N=="number"?N:void 0,active:!!(m&&p&&typeof N!="number")})})]})]}),m&&(M.length>0||p||f||D)?e.jsx(iw,{entries:M,isExpanded:r,hasPrevTool:i,hasNextTool:l,output:typeof g.output=="string"?g.output:void 0,sessionId:D}):null,!m&&r?e.jsx(uw,{part:s,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:l}):null]})},mw=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
|
|
89
|
+
`).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
|
|
90
|
+
`).trim(),fw=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=c.useMemo(()=>mw(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(ll,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},pw=c.memo(fw),hw=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(", ")},Vc=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}),gw=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},yw=({parts:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:l,isWorking:d,previewedPartIds:u,diffStats:m})=>{const f=c.useRef(r),[p,h]=c.useState(0);c.useEffect(()=>{if(f.current===r)return;const x=f.current===!1;f.current=r,l?.("structural"),r&&x&&h(y=>y+1)},[r,l]);const j=c.useMemo(()=>Vc(d?s.filter(x=>x.part.id&&u.has(x.id)):s),[s,d,u]),g=hw(j),b=gw(j);return j.length===0?null:e.jsx(ms,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl 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:R("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(Ln,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",r&&"opacity-100",!r&&o&&"opacity-0",!r&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:r?e.jsx(Ct,{className:"h-3.5 w-3.5"}):e.jsx(Ls,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(g||m)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[g&&e.jsx("span",{className:"truncate block",children:g}),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:R("relative pr-2 pb-1 pt-1 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:j.map((x,y)=>{const w=x.part.id||`group-part-${y}`,S=b[w],v=`${w}-exp${p}`;switch(x.kind){case"tool":return e.jsx(ms,{children:e.jsx(Do,{part:x.part,isExpanded:a.has(w),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:l,hasPrevTool:S?.hasPrev??!1,hasNextTool:S?.hasNext??!1})},v);case"reasoning":return e.jsx(ms,{children:e.jsx(wm,{part:x.part,messageId:x.messageId,onContentChange:l})},v);case"justification":return e.jsx(ms,{children:e.jsx(pw,{part:x.part,messageId:x.messageId,onContentChange:l})},v);default:return null}})})]})})},xw=c.memo(yw),bw=({isMigrating:s,children:r,className:t})=>e.jsx("div",{className:R("w-full overflow-hidden",s&&"pointer-events-none",t),style:s?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:r}),Ba=c.memo(bw),km=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},Nm=s=>{if(s.type!=="text")return!1;const r=km(s);return!r||r.trim().length===0},ww=(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"))},vw=(s,r)=>{const t=c.useRef(null),n=c.useRef(null),[o,a]=c.useState(!1),i=c.useRef(s);i.current=s;const l=c.useRef(r);l.current=r;const d=c.useRef(!1),u=r.size>0;return c.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=i.current;if(!m)return;const f=Array.from(l.current);f.length>0&&m.markPartsPreviewed(f)},300)},1e3)))},[u,s]),c.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]),c.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},jw=new Set(["task"]),Qr=s=>typeof s=="string"&&jw.has(s.toLowerCase()),Sw=({messageId:s,parts:r,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:l,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=c.useState(!1),h=c.useRef(null),j=c.useMemo(()=>r.filter(M=>M.type!=="text"?!1:!Nm(M)),[r]),g=d?.token;let b=!1;const x=!!a,y=!!i,w=!!(n??t),S=!!o,v=c.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),N=c.useCallback(()=>{!w||!x||!S||typeof window>"u"||(v(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[x,v,S,w]);c.useEffect(()=>{S||(p(!1),v())},[v,S]);const D=c.useCallback(M=>{!a||!S||(M.stopPropagation(),M.preventDefault(),a(),w&&N())},[S,w,a,N]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:w&&x&&S?N:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:j.map((M,C)=>{let k;return d&&g&&!b&&km(M).includes(g)&&(k=d,b=!0),e.jsx(ms,{children:e.jsx(qb,{part:M,messageId:s,isMobile:t,agentMention:k})},`user-text-${C}`)})}),e.jsx(sm,{files:r,onShowPopup:l}),x&&S||u||m?e.jsxs("div",{className:R("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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{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:M=>M.stopPropagation(),onClick:M=>{M.stopPropagation(),u()},children:e.jsx(On,{className:"h-3.5 w-3.5"})})}),e.jsx(tt,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{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:M=>M.stopPropagation(),onClick:M=>{M.stopPropagation(),m()},children:e.jsx(Ft,{className:"h-3.5 w-3.5"})})}),e.jsx(tt,{sideOffset:6,children:"Fork from here"})]}),x&&S&&e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{type:"button",variant:"ghost",size:"icon","data-visible":f||y?"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:M=>M.stopPropagation(),onClick:D,onFocus:()=>p(!0),onBlur:()=>{y||p(!1)},children:y?e.jsx(Ot,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Bs,{className:"h-3.5 w-3.5"})})}),e.jsx(tt,{sideOffset:6,children:"Copy message"})]})]}):null]})},kw=({messageId:s,parts:r,isMessageCompleted:t,messageFinish:n,syntaxTheme:o,isMobile:a,hasTouchInput:i,expandedTools:l,onToggleTool:d,onShowPopup:u,streamPhase:m,allowAnimation:f,onContentChange:p,hasTextContent:h=!1,onCopyMessage:j,copiedMessage:g=!1,onAuxiliaryContentComplete:b,showReasoningTraces:x=!1,turnGroupingContext:y,errorMessage:w})=>{const[S,v]=c.useState(!1),N=c.useRef(null),D=!!j,M=!!g,C=!!(i??a),k=!t,A=c.useMemo(()=>r.filter(Be=>!Nm(Be)).filter(Be=>Be.type!=="compaction"),[r]),P=c.useMemo(()=>A.filter(Be=>Be.type==="tool"),[A]),L=c.useMemo(()=>A.filter(Be=>Be.type==="text"),[A]),U=de(Be=>Be.createSessionFromAssistantMessage),z=Re(Be=>Be.openMultiRunLauncherWithPrompt),H=y?.isLastAssistantInTurn??!1,V=n==="stop",J=P.length>0,T=c.useMemo(()=>P.some(Be=>{const Je=(Be.state??{})?.status;return Je==="pending"||Je==="running"||Je==="started"}),[P]),Z=c.useCallback(Be=>{const Ye=Be.state??{},Je=Ye?.status;if(Je==="pending"||Je==="running"||Je==="started")return!1;const Qe=Ye?.time??{},it=typeof Qe?.end=="number"?Qe.end:void 0,ht=typeof Qe?.start=="number"?Qe.start:void 0;return!(typeof it!="number"||typeof ht=="number"&&it<ht)},[]),E=c.useMemo(()=>P.length===0?!0:T?!1:P.every(Be=>Z(Be)),[P,T,Z]),B=c.useMemo(()=>L.length===0?!0:L.every(Be=>typeof Be.time?.end=="number"),[L]),X=c.useMemo(()=>A.filter(Be=>Be.type==="reasoning"),[A]),re=c.useMemo(()=>X.length===0?!0:X.every(Be=>typeof Be.time?.end=="number"),[X]),q=typeof n!="string",oe=X.length>0&&J&&(T||q||!E),ye=c.useMemo(()=>J?L.length===0?q||T||!E:!0:L.length>0?oe:!1,[L.length,q,T,J,oe,E]),I=k||ye&&(!B||!E||T||q)||oe,F=k||J&&(T||q||!E),W=k||oe,O=J||X.length>0,_=L.length===0,ee=O&&_&&!F&&!W&&E&&re,ue=c.useRef(!1),me=c.useRef(!1);c.useEffect(()=>{me.current=!1},[s]),c.useEffect(()=>{if(!ee){ue.current=!1;return}ue.current||(ue.current=!0,b?.())},[ee,b]),c.useEffect(()=>{if(k){me.current=!1;return}if(J){me.current=!1;return}X.length!==0&&(W||!re||me.current||(me.current=!0,p?.("structural")))},[k,J,p,re,X.length,W]);const pe=!!h&&!k,He=c.useCallback(()=>{N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null)},[]),Y=c.useCallback(()=>{!C||!D||!pe||typeof window>"u"||(He(),v(!0),N.current=window.setTimeout(()=>{v(!1),N.current=null},1800))},[D,He,pe,C]);c.useEffect(()=>{pe||(v(!1),He())},[He,pe]);const le=c.useCallback(Be=>{!j||!pe||(Be.stopPropagation(),Be.preventDefault(),j(),C&&Y())},[pe,C,j,Y]),te=c.useCallback(Be=>{Be.stopPropagation(),Be.preventDefault(),U&&U(s)},[U,s]),ne=c.useCallback(Be=>{Be.stopPropagation(),Be.preventDefault();const Ye=Vi(L);if(!Ye.trim())return;const Je=`${ny}
|
|
91
|
+
|
|
92
|
+
${Ye}`;z(Je)},[L,z]);c.useEffect(()=>()=>{He()},[He]);const K=c.useMemo(()=>{const Be={},Ye=P.filter(Je=>Qr(Je.tool)||F?!1:Z(Je));return Ye.forEach((Je,Qe)=>{Be[Je.id]={hasPrev:Qe>0,hasNext:Qe<Ye.length-1}}),Be},[P,F,Z]),ie=c.useMemo(()=>y?.activityParts??[],[y]),ce=c.useMemo(()=>y?ie.filter(Be=>Be.messageId===s):[],[ie,s,y]),ae=c.useMemo(()=>y?y.activityGroupSegments.filter(Be=>Be.anchorMessageId===s):[],[s,y]),$=c.useMemo(()=>{const Be=new Map;return ce.forEach(Ye=>{Be.set(Ye.part,Ye)}),Be},[ce]),we=c.useMemo(()=>y?(x?ie:ie.filter(Ye=>Ye.kind==="tool")).filter(Ye=>{if(Ye.kind!=="tool")return!0;const Je=Ye.part.tool;return!Qr(Je)}):[],[ie,x,y]),[fe,ve]=c.useState(!1);c.useEffect(()=>{if(!y)return;const Be=y.activityGroupSegments.some(Ye=>Ye.afterToolPartId!==null);(we.length>1||Be&&we.length>0)&&ve(!0)},[y,we.length]);const Le=!!(y&&fe),Ge=c.useMemo(()=>{if(!y)return[];if(!Le)return[];if(!y.isWorking)return[];const Be=[];return ce.forEach(Ye=>{if(y.previewedPartIds.has(Ye.id)||!x&&Ye.kind!=="tool")return;const Je=Ye.part;if(Ye.kind==="tool"){const Qe=Je;if(Qr(Qe.tool)||F||!Z(Qe))return}else if(Ye.kind==="reasoning"){if(!x||W||typeof Je.time?.end!="number")return}else if(Ye.kind==="justification"&&(!x||I||typeof Je.time?.end!="number"))return;Be.push(Ye)}),Be},[ce,Z,I,W,F,x,Le,y]),Te=c.useMemo(()=>{const Be=new Set;return Ge.forEach(Ye=>{Be.add(Ye.id)}),Be},[Ge]),{isAnimating:Pe}=vw(y,Te),Ve=!!(y&&Le&&we.length>0&&ae.length>0),pt=c.useMemo(()=>P.filter(Be=>Qr(Be.tool)),[P]),et=c.useMemo(()=>{const Be=[],Ye=Qe=>{!y||!Ve||ae.filter(it=>(it.afterToolPartId??null)===Qe).forEach(it=>{const ht=x?it.parts:it.parts.filter(Q=>Q.kind==="tool");ht.length!==0&&Be.push(e.jsx(xw,{parts:ht,isExpanded:y.isGroupExpanded,onToggle:y.toggleGroup,syntaxTheme:o,isMobile:a,expandedTools:l,onToggleTool:d,onShowPopup:u,onContentChange:p,isWorking:y.isWorking,previewedPartIds:y.previewedPartIds,diffStats:y.diffStats},`progressive-group-${it.id}`))})};Ye(null),pt.forEach(Qe=>{Be.push(e.jsx(ms,{children:e.jsx(Do,{part:Qe,isExpanded:l.has(Qe.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Qe.id}`)),Ye(Qe.id)});const Je=[];return A.forEach((Qe,it)=>{const ht=$.get(Qe);if(!ht||!y)return;let Q=null,be=null;if(!Le){if(ht.kind==="tool"){const Ie=Qe;if(Qr(Ie.tool))return;const Ue=Ie.state?.time,xt=Z(Ie);if(!(!F&&xt))return;const Xe=K[Ie.id];be=e.jsx(ms,{children:e.jsx(Do,{part:Ie,isExpanded:l.has(Ie.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:Xe?.hasPrev??!1,hasNextTool:Xe?.hasNext??!1})},`tool-${Ie.id}`),Q=xt&&typeof Ue?.end=="number"?Ue.end:null}be&&Je.push({part:Qe,index:it,endTime:Q,element:be});return}if(!y.isWorking||y.isGroupExpanded||y.previewedPartIds.has(ht.id)||!x&&ht.kind!=="tool")return;const xe=Te.has(ht.id);switch(ht.kind){case"tool":{const Ie=Qe;if(Qr(Ie.tool))break;const Ue=Ie.state?.time,xt=Z(Ie);if(!(!F&&xt))break;const Xe=K[Ie.id],qe=e.jsx(ms,{children:e.jsx(Do,{part:Ie,isExpanded:l.has(Ie.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:Xe?.hasPrev??!1,hasNextTool:Xe?.hasNext??!1})},`tool-${Ie.id}`);be=xe?e.jsx(Ba,{isMigrating:Pe,children:qe},`migrating-tool-${Ie.id}`):qe,Q=xt&&typeof Ue?.end=="number"?Ue.end:null;break}case"reasoning":{if(!x)break;const Ie=Qe.time,$e=typeof Ie?.end=="number";if(!($e&&!W))break;const xt=e.jsx(ms,{children:e.jsx(wm,{part:Qe,messageId:s,onContentChange:p})},`reasoning-${it}`);be=xe?e.jsx(Ba,{isMigrating:Pe,children:xt},`migrating-reasoning-${it}`):xt,Q=$e?Ie?.end??null:null;break}case"justification":{if(!x)break;const Ie=Qe.time,$e=typeof Ie?.end=="number";if(!($e&&!I))break;const xt=e.jsx(ms,{children:e.jsx(Ub,{part:Qe,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:p,renderAsReasoning:!0})},`assistant-text-${it}`);be=xe?e.jsx(Ba,{isMigrating:Pe,children:xt},`migrating-text-${it}`):xt,Q=$e?Ie?.end??null:null;break}}be&&Je.push({part:Qe,index:it,endTime:Q,element:be})}),Je.sort((Qe,it)=>Qe.endTime===null&&it.endTime===null?Qe.index-it.index:Qe.endTime===null?1:it.endTime===null?-1:Qe.endTime-it.endTime),Je.forEach(({element:Qe})=>{Be.push(Qe)}),Be},[$,ae,l,Pe,a,Z,s,p,u,d,Te,I,W,F,Le,x,o,K,y,A,pt,Ve]),wt=y?.turnId,Nt=de(Be=>Be.currentSessionId),Pt=yt(Be=>{if(!wt||!Nt)return;const Ye=Be.messages.get(Nt);if(!Ye)return;const Je=Ye.find(ht=>ht.info?.id===wt);if(!Je)return;const it=Je.info.summary?.body;return typeof it=="string"&&it.trim().length>0?it:void 0}),St=typeof y?.summaryBody=="string"&&y.summaryBody.trim().length>0?y.summaryBody:Pt,At=c.useRef(void 0);St&&St.trim().length>0&&(At.current=St);const Jt=c.useRef(wt);Jt.current!==wt&&(Jt.current=wt,At.current=void 0);const Ee=At.current,Oe=y?.isLastAssistantInTurn&&Ee&&Ee.trim().length>0,We=!!w,Ze=H&&h&&(V||!!w),[Zt,zt]=c.useState(!1),dt=e.jsxs(e.Fragment,{children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{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:Be=>Be.stopPropagation(),onClick:te,children:e.jsx(_p,{className:"h-4 w-4"})})}),e.jsx(tt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{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:Be=>Be.stopPropagation(),onClick:ne,children:e.jsx(Xu,{className:"h-4 w-4"})})}),e.jsx(tt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),j&&e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{type:"button",variant:"ghost",size:"icon","data-visible":S||M?"true":void 0,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!pe&&"opacity-50"),disabled:!pe,"aria-label":"Copy message text","aria-hidden":!pe,onPointerDown:Be=>Be.stopPropagation(),onClick:le,onFocus:()=>{pe&&v(!0)},onBlur:()=>{M||v(!1)},children:M?e.jsx(Ot,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Bs,{className:"h-3.5 w-3.5"})})}),e.jsx(tt,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:R("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:C&&D&&pe?Y: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:[et,We&&e.jsx(ms,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Fr,{content:w??""})})},"assistant-error"),Oe&&e.jsx(ms,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>zt(!0),onMouseLeave:()=>zt(!1),children:[e.jsx(Fr,{content:Ee}),Ze&&e.jsx("div",{className:R("mt-2 mb-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",Zt&&"opacity-100 pointer-events-auto"),children:dt})]})},"summary-body")]}),e.jsx(sm,{files:r,onShowPopup:u}),!Oe&&Ze&&e.jsx("div",{className:"mt-2 mb-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",children:dt})]})})},Nw=({isUser:s,...r})=>s?e.jsx(Sw,{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(kw,{...r}),Gc=c.memo(Nw),za=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}},Cw=c.lazy(()=>ns(()=>import("./ToolOutputDialog-BXPi0SDL.js"),__vite__mapDeps([2,0,1,3,4]))),Mw=new Set(["task","edit","multiedit","write","bash"]),qc=s=>typeof s=="string"&&Mw.has(s.toLowerCase());function Wa(s){const r=c.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 nr=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},Dw=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:l,hasTouchInput:d}=$t(),{currentTheme:u}=Ur(),m=c.useRef(null),f=de(Ii(je=>({lifecyclePhase:je.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const Xe=s.info.sessionID??je.currentSessionId??null;return Xe?(je.streamingMessageIds.get(Xe)??null)===s.info.id:!1})(),currentSessionId:je.currentSessionId,getCurrentAgent:je.getCurrentAgent,getSessionAgentSelection:je.getSessionAgentSelection,getAgentModelForSession:je.getAgentModelForSession,getSessionModelSelection:je.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:h,currentSessionId:j,getCurrentAgent:g,getSessionAgentSelection:b,getAgentModelForSession:x,getSessionModelSelection:y}=f,w=at(je=>je.providers),S=Re(je=>je.showReasoningTraces),v=Re(je=>je.toolCallExpansion);c.useEffect(()=>{j&&wr.getInstance().recordSessionStart(j)},[j]);const[N,D]=c.useState(null),[M,C]=c.useState(!1),[k,A]=c.useState(new Set),[P,L]=c.useState({open:!1,title:"",content:""});c.useEffect(()=>{A(new Set)},[s.info.id,v]);const z=c.useMemo(()=>za(s.info),[s.info]).isUser,H=c.useMemo(()=>z?s.parts.map(je=>je.type==="compaction"?{type:"text",text:"/summarize"}:je):s.parts,[z,s.parts]),V=c.useMemo(()=>{if(z||!r)return null;const je=nr(r.info,"clientRole"),Xe=nr(r.info,"role");if((typeof je=="string"?je:typeof Xe=="string"?Xe:void 0)!=="user")return null;const ut=nr(r.info,"mode"),Dt=nr(r.info,"providerID"),lt=nr(r.info,"modelID"),gt=typeof ut=="string"&&ut.trim().length>0?ut:void 0,Rt=typeof Dt=="string"&&Dt.trim().length>0?Dt:void 0,hs=typeof lt=="string"&<.trim().length>0?lt:void 0;return!gt&&!Rt&&!hs?null:{agentName:gt,providerId:Rt,modelId:hs}},[z,r]),J=c.useMemo(()=>{if(z)return;const je=nr(s.info,"mode");if(typeof je=="string"&&je.trim().length>0)return je;if(V?.agentName)return V.agentName;const Xe=s.info.sessionID;if(!Xe)return;const qe=g(Xe);return qe||(b(Xe)??void 0)},[z,s.info,V,g,b]),T=s.info.sessionID,Z=z?null:nr(s.info,"providerID"),E=z?null:nr(s.info,"modelID"),B=c.useMemo(()=>{if(z||!T)return null;if(V?.providerId&&V?.modelId)return{providerId:V.providerId,modelId:V.modelId};if(J){const Xe=x(T,J);if(Xe?.providerId&&Xe?.modelId)return Xe}const je=y(T);return je?.providerId&&je?.modelId?je:null},[z,T,J,V,x,y]),X=c.useMemo(()=>z?null:typeof Z=="string"&&Z.trim().length>0?Z:B?.providerId??null,[z,Z,B]),re=c.useMemo(()=>z?null:typeof E=="string"&&E.trim().length>0?E:B?.modelId??null,[z,E,B]),q=c.useMemo(()=>{if(!z&&X&&re&&w.length>0){const je=w.find(Xe=>Xe.id===X);if(je?.models&&Array.isArray(je.models)){const ut=je.models.find(Dt=>Dt.id===re)?.name;return typeof ut=="string"?ut:void 0}}},[z,X,re,w]),oe=Wa(J),ye=Wa(X??void 0),I=Wa(q),F=oe??void 0,W=ye??null,O=I??void 0,_=c.useMemo(()=>{const je=s.info.time;return typeof je?.completed=="number"?je.completed:null},[s.info.time]),ee=c.useMemo(()=>z?!0:!!(_&&_>0),[z,_]),ue=c.useMemo(()=>{const je=s.info.finish;return typeof je=="string"?je:void 0},[s.info]),me=c.useMemo(()=>ww(H,{includeReasoning:S}),[H,S]),pe=c.useMemo(()=>z||ee?me:[],[z,ee,me]),He=c.useMemo(()=>z?[]:me.filter(je=>je.type==="text"),[z,me]),Y=c.useMemo(()=>z?[]:me.filter(Xe=>Xe.type==="tool"),[z,me]),le=c.useMemo(()=>{if(v==="collapsed"||v==="activity")return k;const je=new Set;for(const qe of Y){const ut=qe.tool;qe.id&&qc(ut)&&je.add(qe.id)}if(i?.isFirstAssistantInTurn)for(const qe of i.activityParts){if(qe.kind!=="tool")continue;const ut=qe.part;ut.id&&qc(ut.tool)&&je.add(ut.id)}const Xe=new Set(je);for(const qe of k)Xe.has(qe)?Xe.delete(qe):Xe.add(qe);return Xe},[k,v,Y,i]),te=c.useMemo(()=>{if(!z)return;const je=s.parts.find(Dt=>Dt.type==="agent");if(!je)return;const Xe=je,qe=typeof Xe.name=="string"?Xe.name:void 0;if(!qe)return;const ut=Xe.source&&typeof Xe.source.value=="string"&&Xe.source.value.trim().length>0?Xe.source.value:`#${qe}`;return{name:qe,token:ut}},[z,s.parts]),ne=typeof ue!="string",K=c.useMemo(()=>z?!1:He.length===0||Y.length===0?ne:!0,[He.length,Y.length,ne,z]),ie=u?.metadata.variant,ce=c.useMemo(()=>ie?ie==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[ie]),ae=c.useMemo(()=>u?pm(u):ce?Ab:Eb,[u,ce]),$=c.useMemo(()=>z?!1:wr.getInstance().shouldAnimateMessage(s.info,j||s.info.sessionID),[s.info,j,z]),we=c.useRef(!1),fe=c.useMemo(()=>r?za(r.info):null,[r]),ve=c.useMemo(()=>t?za(t.info):null,[t]),Le=c.useMemo(()=>z||!ve?!1:!ve.isUser&&ve.role==="assistant",[z,ve]),Ge=c.useMemo(()=>ee?"completed":p||(h?"streaming":"completed"),[ee,p,h]),Te=c.useMemo(()=>{if(z)return!0;const je=i?.headerMessageId;if(je){if(s.info.id===je){if(Ge==="completed")return!0;const qe=Ge==="streaming"||Ge==="cooldown",ut=we.current;return qe&&!ut&&(we.current=!0),ut||qe}return!1}return fe?fe.isUser:!0},[z,fe,i,Ge,s.info]),Pe=c.useCallback(je=>{navigator.clipboard.writeText(je),D(je),setTimeout(()=>D(null),2e3)},[]),Ve=i?.turnId,pt=yt(je=>{if(!Ve)return;const Xe=s.info.sessionID;if(!Xe)return;const qe=je.messages.get(Xe);if(!qe)return;const ut=qe.find(gt=>gt.info?.id===Ve);if(!ut)return;const lt=ut.info.summary?.body;return typeof lt=="string"&<.trim().length>0?lt:void 0}),et=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:pt,wt=c.useRef(void 0);et&&et.trim().length>0&&(wt.current=et);const Nt=c.useRef(Ve);Nt.current!==Ve&&(Nt.current=Ve,wt.current=void 0);const Pt=wt.current,St=c.useMemo(()=>{if(z)return;const je=s.info?.error;if(!je)return;const Xe=typeof je.data?.message=="string"?je.data.message:void 0,qe=typeof je.message=="string"?je.message:void 0,ut=typeof je.name=="string"?je.name:void 0,Dt=Xe||qe||ut;if(Dt)return`Opencode failed to send message with error:
|
|
93
|
+
\`${Dt}\``},[z,s.info]),At=c.useMemo(()=>z?pe.filter(qe=>qe.type==="text").map(qe=>(qe.text||qe.content||"").trim()).filter(qe=>qe.length>0).join(`
|
|
94
|
+
`).replace(/\n\s*\n+/g,`
|
|
95
|
+
`):St&&St.trim().length>0?St:Pt&&Pt.trim().length>0?Pt:Vi(pe),[St,Pt,pe,z]),Jt=At.length>0,Ee=c.useCallback(()=>{navigator.clipboard.writeText(At),C(!0),setTimeout(()=>C(!1),2e3)},[At]),Oe=de(je=>je.revertToMessage),We=de(je=>je.forkFromMessage),Ze=c.useCallback(()=>{!T||!s.info.id||Oe(T,s.info.id)},[T,s.info.id,Oe]),Zt=c.useCallback(()=>{!T||!s.info.id||We(T,s.info.id)},[T,s.info.id,We]),zt=c.useCallback(je=>{A(Xe=>{const qe=new Set(Xe);return qe.has(je)?qe.delete(je):qe.add(je),qe})},[]),dt=o??null,Be=c.useRef(!1),Ye=c.useRef(!1),Je=c.useRef(!1),Qe=c.useRef(!1),it=c.useRef(!1);c.useEffect(()=>{Ye.current=!1,Je.current=!1,Qe.current=!1,it.current=!1,Be.current=!1},[s.info.id]);const ht=c.useCallback(()=>{z||Be.current||(Be.current=!0,n?.("structural"))},[z,n]),Q=c.useCallback(je=>{je.image&&L(je)},[]),be=c.useCallback(je=>{L(Xe=>({...Xe,open:je}))},[]),xe=!!nr(s.info,"animationSettled"),Ie=Ge==="streaming",$e=c.useMemo(()=>z?!1:me.some(je=>je.type==="reasoning"),[z,me]),Ue=$&&!xe&&!Ie,xt=!z&&$&&He.length>0&&!K;return c.useEffect(()=>{if(dt?.onStreamingCandidate){if(!xt){Je.current&&($e&&dt?.onReasoningBlock?dt.onReasoningBlock():dt?.onReservationCancelled&&dt.onReservationCancelled(),Je.current=!1);return}it.current||(it.current=!0,dt.onStreamingCandidate(),Je.current=!0)}},[dt,xt,$e]),c.useEffect(()=>{dt?.onAnimationStart&&Ue&&(Qe.current||(dt.onAnimationStart(),Qe.current=!0))},[dt,Ue]),c.useEffect(()=>{if(z)return;const je=dt?.onAnimatedHeightChange;if(!je||!(Ue||xt))return;const qe=m.current;if(!qe)return;if(typeof window>"u"||typeof ResizeObserver>"u"){je(qe.getBoundingClientRect().height);return}let ut=null;const Dt=gt=>{if(typeof window>"u"){je(gt);return}ut!==null&&window.cancelAnimationFrame(ut),ut=window.requestAnimationFrame(()=>{je(gt)})},lt=new ResizeObserver(gt=>{const Rt=gt[0];Rt&&Dt(Rt.contentRect.height)});return lt.observe(qe),Dt(qe.getBoundingClientRect().height),()=>{ut!==null&&(window.cancelAnimationFrame(ut),ut=null),lt.disconnect()}},[Ue,z,dt,xt]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("group w-full",Te?"pt-2":"pt-0",z?"pb-2":Le?"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:z?e.jsx(ms,{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(Gc,{messageId:s.info.id,parts:me,isUser:z,isMessageCompleted:ee,messageFinish:ue,syntaxTheme:ae,isMobile:l,hasTouchInput:d,copiedCode:N,onCopyCode:Pe,expandedTools:k,onToggleTool:zt,onShowPopup:Q,streamPhase:Ge,allowAnimation:Ue,onContentChange:n,shouldShowHeader:!1,hasTextContent:Jt,onCopyMessage:Ee,copiedMessage:M,showReasoningTraces:S,onAuxiliaryContentComplete:ht,agentMention:te,onRevert:Ze,onFork:z?Zt:void 0,errorMessage:St})})})}):e.jsxs("div",{children:[Te&&e.jsx(Pb,{isUser:z,providerID:W,agentName:F,modelName:O,isDarkTheme:ce}),e.jsx(Gc,{messageId:s.info.id,parts:me,isUser:z,isMessageCompleted:ee,messageFinish:ue,syntaxTheme:ae,isMobile:l,hasTouchInput:d,copiedCode:N,onCopyCode:Pe,expandedTools:le,onToggleTool:zt,onShowPopup:Q,streamPhase:Ge,allowAnimation:Ue,onContentChange:n,shouldShowHeader:Te,hasTextContent:Jt,onCopyMessage:Ee,copiedMessage:M,onAuxiliaryContentComplete:ht,showReasoningTraces:S,agentMention:te,turnGroupingContext:i,errorMessage:St})]})})}),e.jsx(c.Suspense,{fallback:null,children:e.jsx(Cw,{popup:P,onOpenChange:be,syntaxTheme:ae,isMobile:l})})]})},Aw=c.memo(Dw),Ew=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:jm(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,i)=>e.jsxs("div",{className:R("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(lr,{style:r,language:Hr(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})})]},i))})]},o))}),Iw=({content:s,syntaxTheme:r,filePath:t})=>{const n=s.split(`
|
|
96
|
+
`),o=Hr(t??"")||"text",a=t?.split("/").pop()||"New file",i=Math.max(n.length,1),l=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${l})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(lr,{style:r,language:o,PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},Pw=s=>{const r="h-3 w-3",t=s.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(or,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(Hd,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Sr,{className:r}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(ni,{className:r}):e.jsx(Jo,{className:r})},Tw=s=>{const r=s.toLowerCase();return r==="edit"||r==="multiedit"||r==="str_replace"||r==="str_replace_based_edit_tool"?"edit":r==="write"||r==="create"||r==="file_write"?"write":r==="bash"||r==="shell"||r==="cmd"||r==="terminal"||r==="shell_command"?"bash":r==="webfetch"||r==="fetch"||r==="curl"||r==="wget"?"webfetch":s},Fw=({permission:s,onResponse:r})=>{const[t,n]=c.useState(!1),[o,a]=c.useState(!1),{respondToPermission:i}=de(),{currentTheme:l}=Ur(),d=c.useMemo(()=>pm(l),[l]),u=async x=>{n(!0);try{await i(s.sessionID,s.id,x),a(!0),r?.(x)}catch{}finally{n(!1)}};if(o)return null;const m=s.permission||"unknown",f=m.toLowerCase(),p=(x,y="")=>{const w=s.metadata[x];return typeof w=="string"?w:typeof w=="number"?String(w):y},h=x=>{const y=s.metadata[x];return typeof y=="number"?y:void 0},j=x=>!!s.metadata[x],g=Tw(m),b=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const w=p("command")||p("cmd")||p("script"),S=p("description"),v=p("cwd")||p("working_directory")||p("directory")||p("path"),N=h("timeout");return e.jsxs(e.Fragment,{children:[S&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:S}),v&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Working Directory:"})," ",e.jsx("code",{className:"px-1 py-0.5 bg-muted/30 rounded",children:v})]}),N&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",N,"ms"]}),w&&e.jsx("div",{children:e.jsx(lr,{language:"bash",style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:w})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const w=p("path")||p("file_path")||p("filename")||p("filePath"),S=p("changes")||p("diff"),v=j("replace_all")||j("replaceAll");return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),S&&e.jsx(ct,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Ew,{diff:S,syntaxTheme:d,filePath:w})})]})}if(f==="write"||f==="create"||f==="file_write"){const w=p("path")||p("file_path")||p("filename")||p("filePath"),S=p("content")||p("text")||p("data");return S?e.jsx(ct,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Iw,{content:S,syntaxTheme:d,filePath:w})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const w=p("url")||p("uri")||p("endpoint"),S=p("method")||"GET",v=s.metadata.headers&&typeof s.metadata.headers=="object"?s.metadata.headers:void 0,N=p("body")||p("data")||p("payload"),D=h("timeout"),M=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[w&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Request:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded",children:S}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:w})]})]}),v&&Object.keys(v).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(ct,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(lr,{language:"json",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:JSON.stringify(v,null,2)})})]}),N&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(ct,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(lr,{language:typeof N=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof N=="object"?JSON.stringify(N,null,2):String(N)})})]}),(D||M)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[D&&e.jsxs("span",{children:["Timeout: ",D,"ms"]}),D&&M&&e.jsx("span",{children:" • "}),M&&e.jsxs("span",{children:["Response format: ",M]})]})]})}const x=p("command")||p("content")||p("action")||p("operation"),y=p("description");return e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:y}),x&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(ct,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(x)})})]}),Object.keys(s.metadata).length>0&&!x&&!y&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(ct,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:JSON.stringify(s.metadata,null,2)})})]})]})};return e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20 bg-muted/5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-3.5 w-3.5 text-yellow-500"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Permission Required"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Pw(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:g})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[s.patterns.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Patterns:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:s.patterns.join(", ")})]}),b()]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{onClick:()=>u("once"),disabled:t,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Ot,{className:"h-3 w-3"}),"Allow Once"]}),s.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(tr,{className:"h-3 w-3"}),(()=>{const x=s.always||s.metadata.always||[];if(x.length===0)return"Always Allow";const w=x.slice(0,2).join(", ");return x.length>2?`Always: ${w}...`:`Always: ${w}`})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(tr,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(Lt,{className:"h-3 w-3"}),"Deny"]}),t&&e.jsx("div",{className:"ml-auto typography-meta text-muted-foreground",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})})]})]})})})},Rw=new Set(["task"]),Kc=s=>typeof s=="string"&&Rw.has(s.toLowerCase()),Ow=s=>{const r=[];let t=null;return s.forEach(n=>{const o=n.info.clientRole??n.info.role;o==="user"?(t={turnId:n.info.id,userMessage:n,assistantMessages:[]},r.push(t)):o==="assistant"&&t&&t.assistantMessages.push(n)}),r},$w=s=>{for(const r of s.assistantMessages)if(r.info.finish==="stop"){const n=r.parts.find(o=>o.type==="text");if(n){const o=n.text??n.content;if(typeof o=="string"&&o.trim().length>0)return o}}},Lw=s=>{const r=$w(s);let t;const o=s.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let x=0,y=0,w=0;o.forEach(S=>{if(!S)return;const v=typeof S.additions=="number"?S.additions:0,N=typeof S.deletions=="number"?S.deletions:0;(v!==0||N!==0)&&(w+=1),x+=v,y+=N}),w>0&&(t={additions:x,deletions:y,files:w})}let a=!1,i=!1;s.assistantMessages.forEach(x=>{x.parts.forEach(y=>{y.type==="tool"?a=!0:y.type==="reasoning"&&(i=!0)})});const l=[];let d=0;s.assistantMessages.forEach(x=>{const y=x.info.id;x.info.finish,x.parts.forEach(w=>{const S=typeof w.id=="string"&&w.id.trim().length>0?w.id:`${y}-activity-${d++}`;if(w.type==="tool"){const N=w.state?.time,D=typeof N?.end=="number"?N.end:void 0;l.push({id:S,turnId:s.turnId,messageId:y,kind:"tool",part:w,endedAt:D});return}if(w.type==="reasoning"){const v=w.text??w.content;if(typeof v!="string"||v.trim().length===0)return;const N=w.time,D=typeof N?.end=="number"?N.end:void 0;l.push({id:S,turnId:s.turnId,messageId:y,kind:"reasoning",part:w,endedAt:D});return}})});const u=[],m=new WeakMap;l.forEach(x=>{m.set(x.part,x)});const f=new Map,p=[],h=new Map;let j=null;s.assistantMessages.forEach(x=>{const y=x.info.id;x.parts.forEach(w=>{if(w.type==="tool"){const N=w.tool;if(Kc(N)){const D=typeof w.id=="string"&&w.id.trim().length>0?w.id:`${y}-task-${p.length+1}`;f.has(D)||(f.set(D,y),p.push(D)),j=D;return}}const S=m.get(w);if(!S)return;if(S.kind==="tool"){const N=S.part.tool;if(Kc(N))return}const v=h.get(j)??[];v.push(S),h.set(j,v)})});const g=x=>{if(x.length===0)return;const y=new Map;x.forEach(v=>{y.set(v.messageId,(y.get(v.messageId)??0)+1)});let w,S=0;for(const v of s.assistantMessages){const N=y.get(v.info.id)??0;if(N>0&&!w&&(w=v.info.id),S+=N,S>=2)return v.info.id}return w};return[null,...p].forEach(x=>{const y=h.get(x)??[];if(y.length===0)return;const w=x===null?g(y):f.get(x);w&&u.push({id:`${s.turnId}:${w}:${x??"start"}`,anchorMessageId:w,afterToolPartId:x,parts:y})}),{activityParts:l,activityGroupSegments:u,hasTools:a,hasReasoning:i,summaryBody:r,diffStats:t}},_w=s=>{const{isWorking:r}=al(),t=c.useMemo(()=>Ow(s),[s]),n=c.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=c.useMemo(()=>{const g=new Map;return t.forEach(b=>{g.set(b.userMessage.info.id,b),b.assistantMessages.forEach(x=>{g.set(x.info.id,b)})}),g},[t]),a=c.useMemo(()=>{const g=new Map;return t.forEach(b=>{g.set(b.turnId,Lw(b))}),g},[t]),[i,l]=c.useState(()=>new Map),d=Re(g=>g.toolCallExpansion),u=d==="activity"||d==="detailed";c.useEffect(()=>{l(new Map)},[d]);const m=c.useCallback(g=>{const b=i.get(g);return b||{isExpanded:u,previewedPartIds:new Set}},[i,u]),f=c.useCallback(g=>{l(b=>{const x=new Map(b),y=x.get(g)??{isExpanded:u,previewedPartIds:new Set};return x.set(g,{...y,isExpanded:!y.isExpanded}),x})},[u]),p=c.useCallback((g,b)=>{b.length!==0&&l(x=>{const y=new Map(x),w=y.get(g)??{isExpanded:u,previewedPartIds:new Set},S=new Set(w.previewedPartIds);return b.forEach(v=>{v&&v.trim().length>0&&S.add(v)}),y.set(g,{...w,previewedPartIds:S}),y})},[u]),h=c.useCallback(g=>o.get(g),[o]),j=c.useCallback(g=>{const b=o.get(g);if(!b||!b.assistantMessages.some(H=>H.info.id===g))return;const y=a.get(b.turnId),w=y?.activityParts??[],S=y?.activityGroupSegments??[],v=!!y?.hasTools,N=!!y?.hasReasoning,D=y?.summaryBody,M=y?.diffStats,C=b.assistantMessages[0]?.info.id,k=g===C,A=b.assistantMessages[b.assistantMessages.length-1]?.info.id,P=g===A,L=C,U=m(b.turnId),z=r&&n===b.turnId;return{turnId:b.turnId,isFirstAssistantInTurn:k,isLastAssistantInTurn:P,summaryBody:D,activityParts:w,activityGroupSegments:S,headerMessageId:L,hasTools:v,hasReasoning:N,diffStats:M,isWorking:z,isGroupExpanded:U.isExpanded,previewedPartIds:U.previewedPartIds,toggleGroup:()=>f(b.turnId),markPartsPreviewed:H=>p(b.turnId,H)}},[m,n,p,o,r,f,a]);return{turns:t,getTurnForMessage:h,getContextForMessage:j}},Bw=({messages:s,permissions:r,onMessageContentChange:t,getAnimationHandlers:n,hasMoreAbove:o,isLoadingOlder:a,onLoadOlder:i,scrollToBottom:l,pendingAnchorId:d})=>{c.useEffect(()=>{r.length!==0&&t("permission")},[r,t]);const u=c.useMemo(()=>{const f=new Set;return s.filter(p=>{const h=p.info?.id;if(typeof h=="string"){if(f.has(h))return!1;f.add(h)}return!0}).map(p=>({...p,parts:yb(p.parts)}))},[s]),{getContextForMessage:m}=_w(u);return e.jsxs("div",{children:[o&&e.jsx("div",{className:"flex justify-center py-3",children:a?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:i,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:u.map((f,p)=>e.jsx(Aw,{message:f,previousMessage:p>0?u[p-1]:void 0,nextMessage:p<u.length-1?u[p+1]:void 0,onContentChange:t,animationHandlers:n(f.info.id),scrollToBottom:l,isPendingAnchor:d===f.info.id,turnGroupingContext:m(f.info.id)},f.info.id))}),r.length>0&&e.jsx("div",{children:r.map(f=>e.jsx(Fw,{permission:f},f.id))})]})},zw=c.memo(Bw);function Ww(...s){return r=>{s.forEach(t=>{typeof t=="function"?t(r):t&&typeof t=="object"&&(t.current=r)})}}const Cm=c.forwardRef(({orientation:s="vertical",offset:r=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:l,children:d,...u},m)=>{const f=c.useRef(null),p=c.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const j=c.useMemo(()=>{const y={...i};return y["--scroll-shadow-size"]=`${t}px`,y},[t,i]),g=c.useCallback((y,w,S,v,N)=>{const D=`${v}${N.charAt(0).toUpperCase()}${N.slice(1)}Scroll`;w&&S?(y.dataset[D]="true",y.removeAttribute(`data-${v}-scroll`),y.removeAttribute(`data-${N}-scroll`)):(y.dataset[`${v}Scroll`]=String(w),y.dataset[`${N}Scroll`]=String(S),y.removeAttribute(`data-${v}-${N}-scroll`))},[]),b=c.useCallback(y=>{["top","bottom","top-bottom","left","right","left-right"].forEach(w=>{y.removeAttribute(`data-${w}-scroll`)})},[]),x=c.useCallback(()=>{const y=f.current;if(!y)return;if(!n){b(y);return}const w=s==="vertical"?y.scrollTop>r:y.scrollLeft>r;let S=s==="vertical"?y.scrollTop+y.clientHeight+r<y.scrollHeight:y.scrollLeft+y.clientWidth+r<y.scrollWidth;o&&s==="vertical"&&(S=!1),g(y,w,S,s==="vertical"?"top":"left",s==="vertical"?"bottom":"right");const v=w&&S?"both":w?s==="vertical"?"top":"left":S?s==="vertical"?"bottom":"right":"none";v!==p.current&&(p.current=v,a?.(v))},[b,o,n,r,a,s,g]);return c.useEffect(()=>{const y=f.current;if(!y)return;const w=()=>x(),S=typeof ResizeObserver<"u"?new ResizeObserver(()=>x()):null,v=typeof MutationObserver<"u"?new MutationObserver(()=>x()):null;return x(),y.addEventListener("scroll",w,{passive:!0}),S?.observe(y),v?.observe(y,{childList:!0,subtree:!0,characterData:!0}),()=>{y.removeEventListener("scroll",w),S?.disconnect(),v?.disconnect()}},[x]),e.jsx("div",{...u,ref:Ww(f,m),className:l,"data-orientation":s,"data-scroll-shadow":h??!0,style:j,children:d})});Cm.displayName="ScrollShadow";const Hw=160,Uw=({containerRef:s})=>{const[r,t]=c.useState(!0),n=c.useRef(!0),o=c.useRef(!1),a=c.useRef(null),i=c.useRef(null),l=c.useRef(0),d=c.useRef(0),u=c.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),m=c.useCallback(w=>{const S=s.current;if(!S){u();return}i.current===null&&(i.current=w);const v=Math.min(1,(w-i.current)/Hw),N=1-Math.pow(1-v,3),D=l.current,M=d.current,C=D+(M-D)*N;if(S.scrollTop=C,v<1){a.current=window.requestAnimationFrame(m);return}S.scrollTop=M,u(),n.current&&(n.current=!1,t(!1))},[u,s,t]),f=c.useCallback((w,S)=>{const v=s.current;if(!v)return;const N=Math.max(0,w),D=S?.instant??!1;if(o.current=!1,typeof window>"u"||D){u(),v.scrollTop=N;const C=N<=1;n.current!==C&&(n.current=C,t(C));return}if(u(),Math.abs(N-v.scrollTop)<=.5){v.scrollTop=N;const C=N<=1;n.current!==C&&(n.current=C,t(C));return}l.current=v.scrollTop,d.current=N,i.current=null,a.current=window.requestAnimationFrame(m)},[u,s,m,t]),p=c.useCallback(()=>{o.current=!0},[]),h=c.useCallback(()=>{o.current=!0},[]),j=c.useCallback(()=>o.current,[]),g=c.useCallback(()=>s.current?.scrollTop??0,[s]),b=c.useCallback(()=>s.current?.scrollHeight??0,[s]),x=c.useCallback(()=>s.current?.clientHeight??0,[s]),y=c.useCallback(()=>{const w=s.current;if(!w)return;o.current&&a.current!==null&&u();const S=w.scrollTop<=1;n.current!==S&&(n.current=S,t(S))},[u,s]);return c.useEffect(()=>{const w=s.current;if(w)return w.addEventListener("wheel",h,{passive:!0}),w.addEventListener("touchstart",h,{passive:!0}),()=>{w.removeEventListener("wheel",h),w.removeEventListener("touchstart",h)}},[s,h]),c.useEffect(()=>()=>{u()},[u]),c.useMemo(()=>({handleScroll:y,scrollToPosition:f,forceManualMode:p,isAtTop:r,isManualOverrideActive:j,getScrollTop:g,getScrollHeight:b,getClientHeight:x}),[y,f,p,r,j,g,b,x])},Yc=typeof window<"u"?c.useLayoutEffect:c.useEffect,Xc=50,Qc=40,Vw=.2,Gw=.1,qw=150,Ps=s=>{const r=s.info;return typeof r?.id=="string"?r.id:null},Kw=s=>{const r=s.info;if(r?.userMessageMarker===!0)return!0;const t=r?.clientRole,n=r?.role;return t==="user"||n==="user"},Yw=({currentSessionId:s,sessionMessages:r,updateViewportAnchor:t,updateActiveTurnAnchor:n,getActiveTurnAnchor:o,isSyncing:a,isMobile:i,sessionActivityPhase:l})=>{const d=c.useRef(null),u=Uw({containerRef:d}),[m,f]=c.useState(null),[p,h]=c.useState(0),[j,g]=c.useState(!1),[b,x]=c.useState(null),y=c.useRef(null),w=c.useRef(null),S=c.useRef(r.length),v=c.useRef(r.length>0?Ps(r[0]):null),N=c.useRef(r.length>0?Ps(r[r.length-1]):null),D=c.useRef(0),M=c.useRef(0),C=c.useRef(void 0),k=c.useRef(null),A=c.useRef(!1),P=c.useRef(!1),L=c.useRef(null),U=s?l?.get(s)??"idle":"idle",z=c.useCallback(I=>{const F=Math.max(0,I);D.current!==F&&(D.current=F,h(F))},[]),H=c.useCallback(()=>{const I=d.current;I&&(M.current=I.clientHeight)},[]),V=c.useCallback(()=>{if(!m)return null;const I=d.current;return I?I.querySelector(`[data-message-id="${m}"]`):null},[m]),J=c.useCallback(()=>{const I=d.current,F=D.current;if(!I||F<=0)return!0;const W=I.scrollHeight-F;return I.scrollTop+I.clientHeight<W},[]),T=c.useCallback((I,F)=>{const W=I.offsetHeight,O=I.offsetTop;if(W>F*Vw){const ee=F*Gw;return O+W-ee}else return O-Xc},[]),Z=c.useCallback(()=>{const I=d.current;if(!I||!k.current)return;const F=V();if(!F)return;const W=I.clientHeight,O=I.scrollHeight,ee=T(F,W)+W,ue=D.current,me=O-ue;if(!A.current&&me<ee){const pe=ee-me;pe>ue&&(z(pe),s&&k.current&&n(s,k.current,pe))}},[T,s,V,n,z]),E=c.useCallback(()=>{const I=d.current;if(!I){g(!1);return}if(b){g(!1);return}if(!(I.scrollHeight>I.clientHeight)){g(!1);return}const W=I.scrollHeight-I.scrollTop-I.clientHeight,O=D.current;if(O>0){const _=I.scrollHeight-O,ee=I.scrollTop+I.clientHeight;g(ee<_)}else g(W>Qc)},[b]),B=c.useCallback(I=>{const F=d.current;if(!F)return;const W=F.scrollHeight-F.scrollTop-F.clientHeight;if(P.current&&U==="idle"&&!a&&!I?.force&&W>Qc)return;I?.force&&(P.current=!1);const _=F.scrollHeight-F.clientHeight;u.scrollToPosition(Math.max(0,_),I)},[U,a,u]),X=c.useCallback(I=>{if(y.current===I)return;y.current=I,x(I);const F=d.current;if(!F){x(null);return}const W=F.scrollHeight,O=D.current,_=W-O,ee=M.current>0?M.current:F.clientHeight,me=_-Xc,pe=me+ee;let He=0;_<pe&&(He=pe-_),He!==O&&z(He),s&&n(s,I,He),A.current=!0,window.requestAnimationFrame(()=>{u.scrollToPosition(me,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[s,u,n,z]),re=c.useCallback(I=>{const F=d.current;if(!F||!s)return;I?.isTrusted&&(P.current=!0),u.handleScroll(),E(),U==="idle"&&D.current>0&&J()&&(z(0),k.current=null,f(null),n(s,null,0));const{scrollTop:W,scrollHeight:O,clientHeight:_}=F,ee=(W+_/2)/Math.max(O,1),ue=Math.floor(ee*r.length);t(s,ue)},[s,U,J,u,r.length,n,E,z,t]);c.useEffect(()=>{const I=d.current;if(I)return I.addEventListener("scroll",re,{passive:!0}),()=>{I.removeEventListener("scroll",re)}},[re]),Yc(()=>{if(typeof window>"u")return;H();const I=()=>{C.current!==void 0&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{H()},qw)};return window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I),C.current!==void 0&&window.clearTimeout(C.current)}},[H]),c.useEffect(()=>{if(s&&s!==w.current){w.current=s,wr.getInstance().recordSessionStart(s),S.current=r.length,v.current=r.length>0?Ps(r[0]):null,N.current=r.length>0?Ps(r[r.length-1]):null;const I=o(s);U!=="idle"&&I&&I.anchorId?(k.current=I.anchorId,y.current=I.anchorId,A.current=!0,f(I.anchorId),D.current=I.spacerHeight,h(I.spacerHeight),window.requestAnimationFrame(()=>{const W=d.current;if(!W)return;const O=W.querySelector(`[data-message-id="${I.anchorId}"]`);if(O){const _=W.clientHeight,ee=T(O,_);u.scrollToPosition(ee,{instant:!0})}})):(y.current=null,k.current=null,A.current=!1,f(null),D.current=0,h(0),window.requestAnimationFrame(()=>{B({instant:!0,force:!0})})),x(null),g(!1),P.current=!1,L.current=null}},[U,s,B,r.length,o]),Yc(()=>{if(a){S.current=r.length,v.current=r.length>0?Ps(r[0]):null,N.current=r.length>0?Ps(r[r.length-1]):null;return}if(w.current!==s)return;const I=S.current,F=r.length;if(F>I&&I>0){const W=v.current,O=Ps(r[0]),_=Ps(r[F-1]),ee=N.current,ue=W!==null&&O!==W,me=ee!==null&&_!==ee,pe=ue&&!me,He=me&&!ue;if(pe){k.current=null,A.current=!1,f(null),z(0),S.current=F,v.current=O,N.current=_;return}if(He){const le=r.slice(I,F).find(Kw);if(le){const te=Ps(le);te&&(k.current=te,f(te),X(te))}else Z()}}S.current=F,v.current=r.length>0?Ps(r[0]):null,N.current=r.length>0?Ps(r[r.length-1]):null},[s,a,Z,X,r]),c.useEffect(()=>{const I=d.current;if(!I||typeof ResizeObserver>"u")return;const F=new ResizeObserver(()=>{Z(),E()});return F.observe(I),()=>{F.disconnect()}},[Z,E]),c.useEffect(()=>{if(typeof window>"u"){E();return}const I=window.requestAnimationFrame(()=>{E()});return()=>{window.cancelAnimationFrame(I)}},[s,r.length,E]),c.useEffect(()=>{m&&(Z(),E())},[m,Z,E]),c.useEffect(()=>{const I=L.current;L.current=U,I!==null&&I!=="idle"&&U==="idle"&&D.current>0&&J()&&k.current!==null&&(z(0),k.current=null,A.current=!1,f(null),s&&n(s,null,0))},[U,s,J,n,z]),c.useEffect(()=>{E()},[p,E]);const q=c.useRef(new Map),oe=c.useCallback(()=>{Z(),E()},[Z,E]),ye=c.useCallback(I=>{const F=q.current.get(I);if(F)return F;const W={onChunk:()=>{Z()},onComplete:()=>{Z()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{Z()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return q.current.set(I,W),W},[Z]);return{scrollRef:d,handleMessageContentChange:oe,getAnimationHandlers:ye,showScrollButton:j,scrollToBottom:B,spacerHeight:p,pendingAnchorId:b,hasActiveAnchor:m!==null}};function Xw(s){const t=Date.now()-s,n=Math.floor(t/1e3),o=Math.floor(n/60),a=Math.floor(o/60),i=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:i<7?`${i}d ago`:new Date(s).toLocaleDateString()}const Qw=({open:s,onOpenChange:r,onScrollToMessage:t})=>{const n=de(g=>g.currentSessionId),o=yt(g=>n?g.messages.get(n)||[]:[]),a=de(g=>g.revertToMessage),i=de(g=>g.forkFromMessage),l=de(g=>g.loadSessions),[d,u]=c.useState(null),[m,f]=c.useState(""),p=c.useMemo(()=>o.filter(b=>b.info.role==="user").reverse(),[o]),h=c.useMemo(()=>{if(!m.trim())return p;const g=m.toLowerCase();return p.filter(b=>Jc(b.parts).toLowerCase().includes(g))},[p,m]),j=async g=>{if(n){u(g);try{await i(n,g),await l(),r(!1)}finally{u(null)}}};return n?e.jsx(ds,{open:s,onOpenChange:r,children:e.jsxs(us,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(fs,{children:[e.jsxs(ps,{className:"flex items-center gap-2",children:[e.jsx(tr,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(ys,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(ur,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(mt,{placeholder:"Search messages...",value:m,onChange:g=>f(g.target.value),className:"pl-9 w-full"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:h.length===0?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:m?"No messages found":"No messages in this session yet"}):h.map(g=>{const b=Jc(g.parts),x=g.info.time.created,y=Xw(x),w=p.length-p.indexOf(g);return e.jsxs("div",{className:"group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",onClick:()=>{t?.(g.info.id),r(!1)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:[w,"."]}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:[b||"[No text content]",b&&b.length>=80&&"…"]}),e.jsxs("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground whitespace-nowrap group-hover:hidden",children:y}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:async S=>{S.stopPropagation(),await a(n,g.info.id),r(!1)},children:e.jsx(On,{className:"h-4 w-4"})})}),e.jsx(tt,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",onClick:S=>{S.stopPropagation(),j(g.info.id)},disabled:d===g.info.id,children:d===g.info.id?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(Ft,{className:"h-4 w-4"})})}),e.jsx(tt,{sideOffset:6,children:"Fork from here"})]})]})]})]},g.info.id)})}),e.jsxs("div",{className:"mt-4 p-3 bg-muted/30 rounded-lg",children:[e.jsx("p",{className:"typography-meta text-muted-foreground font-medium mb-2",children:"Actions"}),e.jsxs("div",{className:"flex flex-col gap-1.5 typography-meta text-muted-foreground",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{children:"Click on a message to scroll to it in the conversation"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Undo to this point (message text will populate input)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function Jc(s){const r=s.find(t=>t.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const Mm=()=>{const{currentSessionId:s,messages:r,permissions:t,streamingMessageIds:n,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:l,updateActiveTurnAnchor:d,getActiveTurnAnchor:u,sessionMemoryState:m,openNewSessionDraft:f,isSyncing:p,messageStreamStates:h,trimToViewportWindow:j,sessionActivityPhase:g,newSessionDraft:b}=de(),{isTimelineDialogOpen:x,setTimelineDialogOpen:y}=Re(),w=c.useMemo(()=>s?n.get(s)??null:null,[s,n]),{isMobile:S}=$t(),v=!!b?.open;c.useEffect(()=>{!s&&!v&&f()},[s,v,f]);const N=c.useMemo(()=>s?r.get(s)||[]:[],[s,r]),D=c.useMemo(()=>s?t.get(s)||[]:[],[s,t]),{scrollRef:M,handleMessageContentChange:C,getAnimationHandlers:k,showScrollButton:A,scrollToBottom:P,spacerHeight:L,pendingAnchorId:U,hasActiveAnchor:z}=Yw({currentSessionId:s,sessionMessages:N,updateViewportAnchor:l,updateActiveTurnAnchor:d,getActiveTurnAnchor:u,isSyncing:p,isMobile:S,sessionActivityPhase:g}),V=!!c.useMemo(()=>s?m.get(s)??null:null,[s,m])?.hasMoreAbove,[J,T]=c.useState(!1);c.useEffect(()=>{T(!1)},[s]);const Z=c.useRef(null);c.useLayoutEffect(()=>{if(!(!s||s===Z.current)&&(Z.current=s,!z)){const X=M.current;X&&(X.scrollTop=X.scrollHeight-X.clientHeight)}},[s,M,z]);const E=c.useCallback(async()=>{if(!s||J)return;const X=M.current,re=X?.scrollHeight??null,q=X?.scrollTop??null;T(!0);try{if(await i(s,"up"),X&&re!==null&&q!==null){const oe=X.scrollHeight-re;X.scrollTop=q+oe}}finally{T(!1)}},[s,J,i,M]),B=c.useCallback(X=>{const re=M.current;if(!re)return;const q=re.querySelector(`[data-message-id="${X}"]`);if(q){const oe=re.getBoundingClientRect(),F=q.getBoundingClientRect().top-oe.top+re.scrollTop-50;re.scrollTo({top:F,behavior:"smooth"})}},[M]);return c.useEffect(()=>{if(!s||(r.has(s)?r.get(s)??[]:[]).length>0)return;(async()=>{try{await a(s)}finally{typeof window>"u"?P():window.requestAnimationFrame(()=>{P()})}})()},[s,a,r,P]),!s&&!v?e.jsx("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(La,{})}):!s&&v?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(La,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(fo,{scrollToBottom:P})})]}):s?o&&N.length===0&&!w&&!r.has(s)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-column space-y-4",children:[1,2,3].map(re=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx($a,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx($a,{className:"h-4 w-24"}),e.jsx($a,{className:"h-20 w-full"})]})]},re))})}),e.jsx(fo,{scrollToBottom:P})]}):N.length===0&&!w?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(La,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(fo,{scrollToBottom:P})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(Cm,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:M,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!U,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(zw,{messages:N,permissions:D,onMessageContentChange:C,getAnimationHandlers:k,hasMoreAbove:V,isLoadingOlder:J,onLoadOlder:E,scrollToBottom:P,pendingAnchorId:U}),L>0&&z&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:L},"aria-hidden":"true"})]})}),e.jsx(Gi,{containerRef:M})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[A&&N.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(ke,{variant:"outline",size:"sm",onClick:()=>P({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-accent","aria-label":"Scroll to bottom",children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsx(fo,{scrollToBottom:P})]}),e.jsx(Qw,{open:x,onOpenChange:y,onScrollToMessage:B})]}):null};class Dm extends c.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(tl,{className:"w-full max-w-md",children:[e.jsx(Wu,{className:"text-center",children:e.jsxs(Hu,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Bp,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(Uu,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data."}),this.props.sessionId&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Session: ",this.props.sessionId]}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(ke,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(ws,{className:"h-4 w-4 mr-2"}),"Reset Chat"]})}),e.jsx("div",{className:"text-xs text-muted-foreground text-center",children:"If the problem persists, try refreshing the page."})]})]})}):this.props.children}}const ji=()=>{const s=de(r=>r.currentSessionId);return e.jsx(Dm,{sessionId:s||void 0,children:e.jsx(Mm,{})})},Zc=12,Jw=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],Zw=({isActive:s,burstKey:r=0,className:t,durationMs:n=900,bursts:o=Jw,onComplete:a})=>{const i=Me.useRef(!1);Me.useEffect(()=>{!s&&i.current&&a?.(),s&&(i.current=!0)},[s,a]);const l=Me.useMemo(()=>Array.from({length:Zc},(d,u)=>{const m=Math.PI*2*u/Zc;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return s?e.jsx("div",{className:R("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":r,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:l.map((m,f)=>{const p=m.x*d.radius,h=m.y*d.radius,j={"--translate-x":`${p}px`,"--translate-y":`${h}px`,"--particle-delay":`${m.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:j},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},ev=({durationMs:s=3400}={})=>{const[r,t]=Me.useState({isActive:!1,cycle:0}),n=Me.useRef(null),o=Me.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Me.useCallback(()=>{o(),t(l=>l.isActive?{...l,isActive:!1}:l)},[o]),i=Me.useCallback(()=>{o(),t(l=>({isActive:!0,cycle:l.cycle+1})),n.current=window.setTimeout(()=>{t(l=>l.isActive?{...l,isActive:!1}:l),n.current=null},s)},[o,s]);return Me.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:i,dismissFireworks:a}},Am=c.createContext(void 0),ed=({children:s})=>{const{isActive:r,burstKey:t,triggerFireworks:n,dismissFireworks:o}=ev(),a=c.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(Am.Provider,{value:a,children:[s,e.jsx(Zw,{isActive:r,burstKey:t})]})},tv=()=>{const s=c.useContext(Am);if(!s)throw new Error("useFireworksCelebration must be used within FireworksProvider");return s},ca=Bt()(Qt(Ms((s,r)=>({selectedProfileId:null,profiles:[],globalIdentity:null,isLoading:!1,setSelectedProfile:t=>{s({selectedProfileId:t})},loadProfiles:async()=>{s({isLoading:!0});const t=r().profiles;try{const n=await _g();return s({profiles:n,isLoading:!1}),!0}catch(n){return console.error("Failed to load git identity profiles:",n),s({profiles:t,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const t=await Hg("");if(t&&t.userName&&t.userEmail){const n={id:"global",name:"Global Identity",userName:t.userName,userEmail:t.userEmail,sshKey:t.sshCommand?t.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"house"};s({globalIdentity:n})}else s({globalIdentity:null});return!0}catch(t){return console.error("Failed to load global git identity:",t),s({globalIdentity:null}),!1}},createProfile:async t=>{try{const n={...t,id:t.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:t.color||"keyword",icon:t.icon||"branch"};return await Bg(n),await r().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(t,n)=>{try{const o=r().profiles.find(i=>i.id===t);if(!o)throw new Error("Profile not found");const a={...o,...n};return await zg(t,a),await r().loadProfiles(),!0}catch(o){return console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async t=>{try{return await Wg(t),r().selectedProfileId===t&&s({selectedProfileId:null}),await r().loadProfiles(),!0}catch(n){return console.error("Failed to delete git identity profile:",n),!1}},getProfileById:t=>{const{profiles:n,globalIdentity:o}=r();return t==="global"?o||void 0:n.find(a=>a.id===t)}}),{name:"git-identities-store",storage:Ds(()=>cs()),partialize:s=>({selectedProfileId:s.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=ca);const sv=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),rv=({currentBranch:s,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:o,onCreate:a,disabled:i=!1})=>{const[l,d]=c.useState(!1),[u,m]=c.useState(""),[f,p]=c.useState(!1),[h,j]=c.useState(""),[g,b]=c.useState(!1),x=c.useRef(null),y=c.useMemo(()=>sv(h),[h]),w=c.useMemo(()=>{const C=u.toLowerCase();return C?r.filter(k=>k.toLowerCase().includes(C)):r},[u,r]),S=c.useMemo(()=>{const C=u.toLowerCase();return C?t.filter(k=>k.toLowerCase().includes(C)):t},[u,t]),v=C=>{if(C===s){d(!1);return}o(C),d(!1),m("")},N=()=>{p(!0),setTimeout(()=>x.current?.focus(),50)},D=async()=>{if(!(!y||g)){b(!0);try{await a(y),j(""),p(!1),d(!1)}finally{b(!1)}}},M=()=>{j(""),p(!1)};return c.useEffect(()=>{l||(m(""),p(!1),j(""))},[l]),e.jsxs(Kt,{open:l,onOpenChange:d,children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Yt,{asChild:!0,children:e.jsxs(ke,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:i,children:[e.jsx(Ft,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:s||"Detached HEAD"}),e.jsx(Ct,{className:"size-4 opacity-60"})]})})}),e.jsxs(tt,{sideOffset:8,children:["Switch branch (",r.length," local · ",t.length," remote)"]})]}),e.jsx(Xt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Gu,{className:"h-full min-h-0",children:[e.jsx(qu,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(Ku,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Yu,{children:"No branches found."}),e.jsx(an,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:x,placeholder:"New branch name",value:h,onChange:C=>j(C.target.value),onKeyDown:C=>{C.key==="Enter"?(C.preventDefault(),D()):C.key==="Escape"&&(C.preventDefault(),M())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:D,disabled:!y||g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:g?e.jsx(is,{className:"size-4 animate-spin"}):e.jsx(_t,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:M,disabled:g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Lt,{className:"size-4"})})]}):e.jsxs(es,{onSelect:N,children:[e.jsx(_t,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(Wo,{}),e.jsxs(an,{heading:"Local branches",children:[w.map(C=>e.jsxs(es,{onSelect:()=>v(C),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:C}),(n?.[C]?.ahead||n?.[C]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[C].ahead||0," ahead ·"," ",n[C].behind||0," behind"]})]}),s===C&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${C}`)),w.length===0&&e.jsx(es,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Wo,{}),e.jsxs(an,{heading:"Remote branches",children:[S.map(C=>e.jsx(es,{onSelect:()=>v(C),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:C})},`remote-${C}`)),S.length===0&&e.jsx(es,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},nv=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),ov=({currentBranch:s,onRename:r})=>{const[t,n]=c.useState(!1),[o,a]=c.useState(s||""),[i,l]=c.useState(!1),d=c.useRef(null),u=()=>{!s||!r||(a(s),n(!0),setTimeout(()=>d.current?.focus(),0))},m=async()=>{if(!s||!r||!o.trim())return;const h=nv(o);if(h===s){n(!1);return}l(!0);try{await r(s,h),n(!1),a("")}finally{l(!1)}},f=()=>{n(!1),a("")},p=h=>{h.key==="Enter"?(h.preventDefault(),m()):h.key==="Escape"&&(h.preventDefault(),f())};return t?e.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:e.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:h=>{h.preventDefault(),m()},children:[e.jsx(Ft,{className:"size-4 text-primary"}),e.jsx("input",{ref:d,value:o,onChange:h=>a(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:p,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:i,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:i?e.jsx(is,{className:"size-4 animate-spin"}):e.jsx(Ot,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:i,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Lt,{className:"size-4"})})]})}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 h-8",children:[e.jsx(Ft,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate typography-ui-label font-normal text-foreground",children:s||"Detached HEAD"})]}),r&&s&&e.jsx(ke,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(Zo,{className:"size-4"})})]})},av=({syncAction:s,onFetch:r,onPull:t,onPush:n,disabled:o})=>{const a=o||s!==null;return e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs(ke,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[s==="fetch"?e.jsx(is,{className:"size-4 animate-spin"}):e.jsx(qn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(tt,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs(ke,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:t,disabled:a,children:[s==="pull"?e.jsx(is,{className:"size-4 animate-spin"}):e.jsx(bn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(tt,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs(ke,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[s==="push"?e.jsx(is,{className:"size-4 animate-spin"}):e.jsx(Gn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(tt,{sideOffset:8,children:"Push changes"})]})]})},iv={branch:Ft,briefcase:Fi,house:Ti,graduation:Pi,code:er,heart:Vd,user:Ss},lv={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function Em(s){return s&&lv[s]||"var(--primary)"}const td=({icon:s,className:r,colorToken:t})=>{const n=iv[s??"branch"]??Ss;return e.jsx(n,{className:r,style:{color:Em(t)}})},cv=({activeProfile:s,identities:r,onSelect:t,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(Kt,{children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Yt,{asChild:!0,children:e.jsxs(ke,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:Em(s?.color)},disabled:o,children:[n?e.jsx(is,{className:"size-4 animate-spin"}):e.jsx(td,{icon:s?.icon,colorToken:s?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:s?.name||"No identity"}),e.jsx(Ct,{className:"size-4 opacity-60"})]})})}),e.jsxs(tt,{sideOffset:8,className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:s?.userName||"Unknown user"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:s?.userEmail||"No email configured"})]})]}),e.jsx(Xt,{align:"end",className:"w-64",children:r.length===0?e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):r.map(a=>e.jsx(jt,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(td,{icon:a.icon,colorToken:a.color,className:"size-4"}),e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:a.name}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:a.userEmail})]})]})},a.id))})]})},dv=({status:s,localBranches:r,remoteBranches:t,branchInfo:n,syncAction:o,onFetch:a,onPull:i,onPush:l,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:h,isApplyingIdentity:j,isWorktreeMode:g})=>s?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[g?e.jsx(ov,{currentBranch:s.current,onRename:m}):e.jsx(rv,{currentBranch:s.current,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:d,onCreate:u}),(!!s.tracking||s.ahead>0||s.behind>0)&&e.jsxs(nt,{delayDuration:800,children:[e.jsx(ot,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 px-1.5 typography-meta text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Gn,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.ahead})]}),!!s.tracking&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(bn,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.behind})]})]})}),e.jsx(tt,{sideOffset:8,children:s.tracking?`Upstream: ${s.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(av,{syncAction:o,onFetch:a,onPull:i,onPush:l,disabled:!s}),e.jsx("div",{className:"flex-1"}),e.jsx(cv,{activeProfile:f,identities:p,onSelect:h,isApplying:j})]}):null,uv=({behind:s,onPull:r,isPulling:t})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx(Mi,{className:"size-10 text-emerald-500/60 mb-4"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:"Working tree clean"}),e.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:"All changes have been committed"}),s>0&&e.jsxs(ke,{variant:"outline",onClick:r,disabled:t,children:[t?e.jsx(is,{className:"size-4 animate-spin"}):e.jsx(bn,{className:"size-4"}),"Pull ",s," commit",s===1?"":"s"]})]}),Im={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},mv=Im.M;function fv(s){const r=s.index?.trim(),t=s.working_dir?.trim();return r&&r!=="?"?r.charAt(0):t?t.charAt(0):r?.charAt(0)||t?.charAt(0)||"M"}function pv(s){const r=fv(s);return Im[r]??mv}const hv=c.memo(function({file:r,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:i,stats:l}){const d=Me.useMemo(()=>pv(r),[r]),u=d.description,m=l?.insertions??0,f=l?.deletions??0,p=Me.useCallback(g=>{g.key===" "?(g.preventDefault(),n()):g.key==="Enter"&&(g.preventDefault(),o())},[n,o]),h=Me.useCallback(g=>{g.preventDefault(),g.stopPropagation(),n()},[n]),j=Me.useCallback(g=>{g.preventDefault(),g.stopPropagation(),a()},[a]);return e.jsx("li",{children:e.jsxs("div",{className:"group flex items-center gap-2 px-3 py-1.5 hover:bg-sidebar/40 cursor-pointer",role:"button",tabIndex:0,onClick:o,onKeyDown:p,children:[e.jsx("button",{type:"button",onClick:h,"aria-pressed":t,"aria-label":`Select ${r.path}`,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:t?e.jsx(Ai,{className:"size-4 text-primary"}):e.jsx(Ei,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:d.color},title:u,"aria-label":u,children:d.code}),e.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left"},title:r.path,children:r.path}),e.jsxs("span",{className:"shrink-0 typography-micro",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",m]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",f]})]}),e.jsxs(nt,{delayDuration:200,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:j,disabled:i,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:i?e.jsx(is,{className:"size-3.5 animate-spin"}):e.jsx(qn,{className:"size-3.5"})})}),e.jsx(tt,{sideOffset:8,children:"Revert changes"})]})]})})}),gv=({changeEntries:s,selectedPaths:r,diffStats:t,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:i,onViewDiff:l,onRevertFile:d})=>{const u=r.size,m=s.length;return e.jsxs("section",{className:"flex flex-col rounded-xl border border-border/60 bg-background/70",children:[e.jsxs("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Changes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[u,"/",m]}),m>0&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(ke,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:i,disabled:u===0,children:"None"})]})]})]}),e.jsx(ct,{outerClassName:"flex-1 min-h-0 max-h-[30vh]",className:"w-full",children:e.jsx("ul",{className:"divide-y divide-border/60",children:s.map(f=>e.jsx(hv,{file:f,checked:r.has(f.path),stats:t?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>l(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function Or({className:s,variant:r,...t}){return e.jsx(ke,{variant:r,size:"sm",className:R("h-7 px-2 py-0",s),...t})}const Ha=38,sd=200,yv=({value:s,onChange:r,placeholder:t="Commit message",disabled:n=!1})=>{const o=c.useRef(null);return c.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${Ha}px`;const i=Math.min(Math.max(a.scrollHeight,Ha),sd);a.style.height=`${i}px`},[s]),e.jsx(js,{ref:o,value:s,onChange:a=>r(a.target.value),placeholder:t,rows:1,disabled:n,className:R("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:Ha,maxHeight:sd}})},xv=({highlights:s,onInsert:r,onClear:t})=>{if(s.length===0)return null;const n=()=>{r(),t()};return e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground",children:"AI highlights"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(bn,{className:"size-4"})})}),e.jsx(tt,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:s.map((o,a)=>e.jsx("li",{className:"typography-meta text-foreground",children:o},a))})]})},bv=({selectedCount:s,commitMessage:r,onCommitMessageChange:t,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:i,isGeneratingMessage:l,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f})=>{const p=s>0,h=r.trim()&&p&&m===null;return e.jsxs(ia,{open:p,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"flex w-full items-center justify-between px-3 py-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:p?`${s} file${s===1?"":"s"} selected`:"No files selected"})]}),e.jsx(la,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(xv,{highlights:n,onInsert:o,onClear:a}),e.jsx(yv,{value:r,onChange:t,placeholder:"Commit message",disabled:m!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:i,disabled:l||m!==null||s===0||f,"aria-label":"Generate commit message",children:l?e.jsx(is,{className:"size-4 animate-spin"}):e.jsx(zp,{className:"size-4 text-primary"})})}),e.jsx(tt,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Or,{variant:"outline",onClick:d,disabled:!h||l,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Mi,{className:"size-4"}),"Commit"]})}),e.jsx(Or,{variant:"default",onClick:u,disabled:!h||l,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Gn,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function rd(s){const r=new Date(s);return Number.isNaN(r.getTime())?s:r.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function wv(s){switch(s){case"A":return"text-emerald-500";case"D":return"text-red-500";case"M":return"text-amber-500";case"R":return"text-blue-500";default:return"text-muted-foreground"}}const vv=({entry:s,isExpanded:r,onToggle:t,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:R("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",r?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[e.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:s.message}),e.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[e.jsx("span",{className:"truncate min-w-[3ch]",title:s.author_name,children:s.author_name}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("span",{className:"truncate min-w-0",title:rd(s.date),children:rd(s.date)})]}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("code",{className:"shrink-0 font-mono",children:s.hash.slice(0,8)}),e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:i=>{i.stopPropagation(),a(s.hash)},children:e.jsx(Bs,{className:"size-3"})})}),e.jsx(tt,{sideOffset:8,children:"Copy SHA"})]})]})]})]}),r&&e.jsx("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:o?e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx(is,{className:"size-4 animate-spin text-muted-foreground"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Loading files..."})]}):n.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:"No files"}):e.jsx("ul",{className:"space-y-0.5 py-2",children:n.map(i=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:R("font-semibold w-3 text-center",wv(i.changeType)),children:i.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:i.path,children:i.path}),!i.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",i.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",i.deletions]})]}),i.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},i.path))})})]}),jv=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],Sv=({log:s,isLogLoading:r,logMaxCount:t,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:i,loadingCommitHashes:l,onCopyHash:d})=>{const[u,m]=c.useState(!0);return s?e.jsxs(ia,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(sl,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"History"}),e.jsxs("div",{className:"flex items-center gap-2",children:[u&&e.jsx("div",{onClick:f=>f.stopPropagation(),onPointerDown:f=>f.stopPropagation(),children:e.jsxs(ks,{value:String(t),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Ns,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:r,children:e.jsx(Un,{placeholder:"Commits"})}),e.jsx(Cs,{children:jv.map(f=>e.jsx(qt,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(Xo,{className:"size-4 text-muted-foreground"}):e.jsx(Ct,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(la,{children:e.jsx(ct,{outerClassName:"min-h-0 max-h-[50vh]",className:"w-full",children:s.all.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"No commits found"})}):e.jsx("ul",{className:"divide-y divide-border/60",children:s.all.map(f=>e.jsx(vv,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:i.get(f.hash)??[],isLoadingFiles:l.has(f.hash),onCopyHash:d},f.hash))})})})]}):null};let Dn=null;const kv=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=de(),{currentDirectory:n}=ft(),o=s?t.get(s)??void 0:void 0,i=r.find(l=>l.id===s)?.directory;return o?.path??i??n??void 0},Nv=()=>{const{git:s}=vn(),r=kv(),{currentSessionId:t,worktreeMetadata:n}=de(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:l,loadGlobalIdentity:d}=ca(),u=qi(r??null),m=Pu(r??null),f=Tu(r??null),p=Ry(r??null),h=Oy(r??null),j=Ut(Ee=>Ee.isLoadingStatus),g=Ut(Ee=>Ee.isLoadingLog),{setActiveDirectory:b,fetchAll:x,fetchStatus:y,fetchBranches:w,fetchLog:S,fetchIdentity:v,setLogMaxCount:N}=Ut(),D=c.useMemo(()=>!Dn||Dn.directory!==r?null:Dn,[r]),[M,C]=c.useState(D?.commitMessage??""),[k,A]=c.useState(null),[P,L]=c.useState(null),[U,z]=c.useState(25),[H,V]=c.useState(!1),{triggerFireworks:J}=tv(),[T,Z]=c.useState(()=>new Set(D?.selectedPaths??[])),[E,B]=c.useState(!1),[X,re]=c.useState(new Set),[q,oe]=c.useState(!1),[ye,I]=c.useState([]),F=c.useCallback(()=>{I([])},[]),[W,O]=c.useState(new Set),[_,ee]=c.useState(new Map),[ue,me]=c.useState(new Set),pe=c.useCallback(Ee=>{navigator.clipboard.writeText(Ee).then(()=>{se.success("Commit hash copied")}).catch(()=>{se.error("Failed to copy")})},[]),He=c.useCallback(Ee=>{O(Oe=>{const We=new Set(Oe);return We.has(Ee)?We.delete(Ee):We.add(Ee),We})},[]);c.useEffect(()=>{if(!r||!s)return;const Ee=Array.from(W).filter(Oe=>!_.has(Oe)&&!ue.has(Oe));Ee.length!==0&&(me(Oe=>{const We=new Set(Oe);return Ee.forEach(Ze=>We.add(Ze)),We}),Ee.forEach(Oe=>{s.getCommitFiles(r,Oe).then(We=>{ee(Ze=>new Map(Ze).set(Oe,We.files))}).catch(We=>{console.error("Failed to fetch commit files:",We),ee(Ze=>new Map(Ze).set(Oe,[]))}).finally(()=>{me(We=>{const Ze=new Set(We);return Ze.delete(Oe),Ze})})}))},[W,r,s,_,ue]),c.useEffect(()=>()=>{if(!r){Dn=null;return}Dn={directory:r,selectedPaths:Array.from(T),commitMessage:M}},[M,r,T]),c.useEffect(()=>{l(),d()},[l,d]),c.useEffect(()=>{r&&(b(r),Ut.getState().directories.get(r)?.status||x(r,s,{force:!0}))},[r,b,x,s]);const Y=c.useCallback(async(Ee=!0)=>{if(r)try{await Promise.all([y(r,s),w(r,s)])}catch(Oe){if(Ee){const We=Oe instanceof Error?Oe.message:"Failed to refresh repository state";se.error(We)}}},[r,s,y,w]),le=c.useCallback(async()=>{r&&await S(r,s,U)},[r,s,S,U]),te=c.useCallback(async()=>{r&&await v(r,s)},[r,s,v]),ne=c.useMemo(()=>{if(!m)return[];const Ee=m.files??[],Oe=new Map;return Ee.forEach(We=>{Oe.set(We.path,We)}),Array.from(Oe.values()).sort((We,Ze)=>We.path.localeCompare(Ze.path))},[m]);c.useEffect(()=>{if(!m||ne.length===0){Z(new Set),B(!1);return}Z(Ee=>{const Oe=new Set,We=Ee??new Set;return ne.forEach(Ze=>{We.has(Ze.path)?Oe.add(Ze.path):E||Oe.add(Ze.path)}),Oe})},[m,ne,E]);const K=async Ee=>{if(r){A(Ee);try{if(Ee==="fetch")await s.gitFetch(r),se.success("Fetched latest updates");else if(Ee==="pull"){const Oe=await s.gitPull(r);se.success(`Pulled ${Oe.files.length} file${Oe.files.length===1?"":"s"}`)}else Ee==="push"&&(await s.gitPush(r),se.success("Pushed to remote"));await Y(!1),await le()}catch(Oe){const We=Oe instanceof Error?Oe.message:`Failed to ${Ee==="pull"?"pull":Ee}`;se.error(We)}finally{A(null)}}},ie=async(Ee={})=>{if(!r)return;if(!M.trim()){se.error("Please enter a commit message");return}const Oe=Array.from(T).sort();if(Oe.length===0){se.error("Select at least one file to commit");return}const We=Ee.pushAfter?"commitAndPush":"commit";L(We);try{await s.createGitCommit(r,M.trim(),{files:Oe}),se.success("Commit created successfully"),C(""),Z(new Set),B(!1),F(),await Y(),Ee.pushAfter?(await s.gitPush(r),se.success("Pushed to remote"),J(),await Y(!1)):await Y(!1),await le()}catch(Ze){const Zt=Ze instanceof Error?Ze.message:"Failed to create commit";se.error(Zt)}finally{L(null)}},ce=c.useCallback(async()=>{if(r){if(T.size===0){se.error("Select at least one file to describe");return}oe(!0);try{const{message:Ee}=await s.generateCommitMessage(r,Array.from(T)),Oe=Ee.subject?.trim()??"",We=Array.isArray(Ee.highlights)?Ee.highlights:[];Oe&&C(Oe),I(We),se.success("Commit message generated")}catch(Ee){const Oe=Ee instanceof Error?Ee.message:"Failed to generate commit message";se.error(Oe)}finally{oe(!1)}}},[r,T,s]),ae=async Ee=>{if(!r||!m)return;const Oe=m.current??null;try{await s.createBranch(r,Ee,Oe??"HEAD"),se.success(`Created branch ${Ee}`);let We=!1;try{await s.checkoutBranch(r,Ee),await s.gitPush(r,{remote:"origin",branch:Ee,options:["--set-upstream"]}),We=!0}catch(Ze){const Zt=Ze instanceof Error?Ze.message:"Unable to push new branch to origin.";se.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Zt]})})}finally{if(Oe)try{await s.checkoutBranch(r,Oe)}catch(Ze){console.warn("Failed to restore original branch after creation:",Ze)}}await Y(),await le(),We&&se.success(`Upstream set for ${Ee}`)}catch(We){const Ze=We instanceof Error?We.message:"Failed to create branch";throw se.error(Ze),We}},$=async(Ee,Oe)=>{if(r)try{await s.renameBranch(r,Ee,Oe),se.success(`Renamed branch ${Ee} to ${Oe}`),await Y(),await le()}catch(We){const Ze=We instanceof Error?We.message:`Failed to rename branch ${Ee} to ${Oe}`;se.error(Ze)}},we=async Ee=>{if(!r)return;const Oe=Ee.replace(/^remotes\//,"");if(m?.current!==Oe)try{await s.checkoutBranch(r,Oe),se.success(`Checked out ${Oe}`),await Y(),await le()}catch(We){const Ze=We instanceof Error?We.message:`Failed to checkout ${Oe}`;se.error(Ze)}},fe=async Ee=>{if(r){V(!0);try{await s.setGitIdentity(r,Ee.id),se.success(`Applied "${Ee.name}" to repository`),await te()}catch(Oe){const We=Oe instanceof Error?Oe.message:"Failed to apply git identity";se.error(We)}finally{V(!1)}}},ve=c.useMemo(()=>f?.all?f.all.filter(Ee=>!Ee.startsWith("remotes/")).sort():[],[f]),Le=c.useMemo(()=>f?.all?f.all.filter(Ee=>Ee.startsWith("remotes/")).map(Ee=>Ee.replace(/^remotes\//,"")).sort():[],[f]),Ge=c.useMemo(()=>{const Ee=new Map;i&&Ee.set(i.id,i);for(const Oe of a)Ee.set(Oe.id,Oe);return Array.from(Ee.values())},[a,i]),Te=c.useMemo(()=>{if(h?.userName&&h?.userEmail){const Ee=a.find(Oe=>Oe.userName===h.userName&&Oe.userEmail===h.userEmail);return Ee||(i&&i.userName===h.userName&&i.userEmail===h.userEmail?i:{id:"local-config",name:h.userName,userName:h.userName,userEmail:h.userEmail,sshKey:h.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return i??null},[h,a,i]),Pe=ne.length,Ve=T.size,pt=j||k!==null||P!==null,et=Pe>0,wt=Ee=>{Z(Oe=>{const We=new Set(Oe);return We.has(Ee)?We.delete(Ee):We.add(Ee),We}),B(!0)},Nt=()=>{const Ee=new Set(ne.map(Oe=>Oe.path));Z(Ee),B(!0)},Pt=()=>{Z(new Set),B(!0)},St=c.useCallback(async Ee=>{if(r){re(Oe=>{const We=new Set(Oe);return We.add(Ee),We});try{await s.revertGitFile(r,Ee),se.success(`Reverted ${Ee}`),await Y(!1)}catch(Oe){const We=Oe instanceof Error?Oe.message:"Failed to revert changes";se.error(We)}finally{re(Oe=>{const We=new Set(Oe);return We.delete(Ee),We})}}},[r,Y,s]),At=c.useCallback(()=>{if(ye.length===0)return;const Ee=ye.map(Oe=>Oe.trim()).filter(Boolean);if(Ee.length===0){F();return}C(Oe=>{const We=Oe.trim(),Ze=We.length>0?`
|
|
97
|
+
|
|
98
|
+
`:"";return`${We}${Ze}${Ee.join(`
|
|
99
|
+
`)}`.trim()})},[ye,F]),Jt=c.useCallback(Ee=>{z(Ee),r&&(N(r,Ee),S(r,s,Ee))},[r,N,S,s]);return r?j&&u===null?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(is,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):u===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Ft,{className:"mb-3 size-6 text-muted-foreground"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:"Not a Git repository"}),e.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:"Choose a different directory or initialize Git to use this workspace."})]}):e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background","data-keyboard-avoid":"true",children:[e.jsx(dv,{status:m,localBranches:ve,remoteBranches:Le,branchInfo:f?.branches,syncAction:k,onFetch:()=>K("fetch"),onPull:()=>K("pull"),onPush:()=>K("push"),onCheckoutBranch:we,onCreateBranch:ae,onRenameBranch:$,activeIdentityProfile:Te,availableIdentities:Ge,onSelectIdentity:fe,isApplyingIdentity:H,isWorktreeMode:!!o}),e.jsx(ct,{outerClassName:"flex-1 min-h-0",className:"p-3",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[et?e.jsx(gv,{changeEntries:ne,selectedPaths:T,diffStats:m?.diffStats,revertingPaths:X,onToggleFile:wt,onSelectAll:Nt,onClearSelection:Pt,onViewDiff:Ee=>Re.getState().navigateToDiff(Ee),onRevertFile:St}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(uv,{behind:m?.behind??0,onPull:()=>K("pull"),isPulling:k==="pull"})}),ne.length>0&&e.jsx(bv,{selectedCount:Ve,commitMessage:M,onCommitMessageChange:C,generatedHighlights:ye,onInsertHighlights:At,onClearHighlights:F,onGenerateMessage:ce,isGeneratingMessage:q,onCommit:()=>ie({pushAfter:!1}),onCommitAndPush:()=>ie({pushAfter:!0}),commitAction:P,isBusy:pt})]}),e.jsx(Sv,{log:p,isLogLoading:g,logMaxCount:U,onLogMaxCountChange:Jt,expandedCommitHashes:W,onToggleCommit:He,commitFilesMap:_,loadingCommitHashes:ue,onCopyHash:pe})]})})]}):e.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"Select a session or directory to view repository details."})})},Cv=1e6;function Ar(s){let r=s.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const po=s=>({directory:s,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),nd=Bt((s,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=Ar(t);return r().sessions.get(n)},setTerminalSession:(t,n)=>{const o=Ar(t);s(a=>{const i=new Map(a.sessions),l=i.get(o),u=!l||l.terminalSessionId!==n.sessionId?po(o):l??po(o);return i.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=Ar(t);s(a=>{const i=new Map(a.sessions),l=i.get(o)??po(o);return i.set(o,{...l,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=Ar(t);s(a=>{const i=new Map(a.sessions),l=i.get(o)??po(o),d=a.nextChunkId,u={id:d,data:n},m=[...l.bufferChunks,u];let f=l.bufferLength+n.length;for(;f>Cv&&m.length>1;){const h=m.shift();if(!h)break;f-=h.data.length}const p=m.map(h=>h.data).join("");return i.set(o,{...l,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:i,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=Ar(t);s(o=>{const a=new Map(o.sessions),i=a.get(n);return i&&a.set(n,{...i,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:t=>{const n=Ar(t);s(o=>{const a=new Map(o.sessions),i=a.get(n);return i?(a.set(n,{...i,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:t=>{const n=Ar(t);s(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{s({sessions:new Map,nextChunkId:1})}})),Pm=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),Mv=[{id:"ibm-plex-sans",label:"IBM Plex Sans",description:"Humanist sans-serif for optimal readability in the interface.",stack:'"IBM Plex Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}],Dv=[{id:"ibm-plex-mono",label:"IBM Plex Mono",description:"Balanced monospace for code blocks and technical content.",stack:'"IBM Plex Mono", "SFMono-Regular", "Menlo", monospace'}],Tm=s=>Object.fromEntries(s.map(r=>[r.id,r])),od=Tm(Mv),Er=Tm(Dv),Av="ibm-plex-sans",Ao="ibm-plex-mono";function Ev(s){const{colors:r}=s,t=r.syntax.base;return{background:r.surface.background,foreground:t.foreground,cursor:r.interactive.cursor,cursorAccent:r.surface.background,selectionBackground:r.interactive.selection,selectionForeground:r.interactive.selectionForeground,selectionInactiveBackground:r.interactive.selection+"50",black:r.surface.muted,red:r.status.error,green:r.status.success,yellow:r.status.warning,blue:t.function,magenta:t.keyword,cyan:t.type,white:t.foreground,brightBlack:t.comment,brightRed:r.status.error,brightGreen:r.status.success,brightYellow:r.status.warning,brightBlue:t.function,brightMagenta:t.keyword,brightCyan:t.type,brightWhite:r.surface.elevatedForeground}}function Iv(s,r,t,n){const a=`${s}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!0,fontSize:r,lineHeight:1.15,fontFamily:a,allowTransparency:!1,theme:{background:t.background,foreground:t.foreground,cursor:t.cursor,cursorAccent:t.cursorAccent,selectionBackground:t.selectionBackground,selectionForeground:t.selectionForeground,black:t.black,red:t.red,green:t.green,yellow:t.yellow,blue:t.blue,magenta:t.magenta,cyan:t.cyan,white:t.white,brightBlack:t.brightBlack,brightRed:t.brightRed,brightGreen:t.brightGreen,brightYellow:t.brightYellow,brightBlue:t.brightBlue,brightMagenta:t.brightMagenta,brightCyan:t.brightCyan,brightWhite:t.brightWhite},scrollback:5e4,ghostty:n}}let Ua=null;function Pv(){return Ua||(Ua=Up.load()),Ua}function Tv(s){if(typeof window>"u")return null;const r=[s,...Array.from(s.querySelectorAll("*"))];let t=null;for(const n of r){const a=window.getComputedStyle(n).overflowY;if(!(a!=="auto"&&a!=="scroll")){if(n.scrollHeight-n.clientHeight>2)return n;t||(t=n)}}return t}const Si=c.forwardRef(({sessionKey:s,chunks:r,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:l,enableTouchScroll:d},u)=>{const m=c.useRef(null),f=c.useRef(null),p=c.useRef(null),h=c.useRef(null),j=c.useRef(t),g=c.useRef(n),b=c.useRef(null),x=c.useRef(""),y=c.useRef(null),w=c.useRef(!1),S=c.useRef(null),v=c.useRef(null),N=c.useRef(null),D=c.useRef(0),M=c.useRef(null),[,C]=c.useReducer(T=>T+1,0),[k,A]=c.useReducer(T=>T+1,0);j.current=t,g.current=n;const P=c.useCallback((T,Z)=>{const E=M.current,B=m.current;if(!E||!B)return;const X=B.getBoundingClientRect(),re=X.left+X.width/2,q=X.top+X.height-12,oe=typeof T=="number"?T:re,ye=typeof Z=="number"?Z:q,I=8,F=Math.max(I,Math.min(X.width-I,oe-X.left)),W=Math.max(I,Math.min(X.height-I,ye-X.top));E.style.left=`${F}px`,E.style.top=`${W}px`,E.style.bottom="";try{E.focus({preventScroll:!0})}catch{try{E.focus()}catch{}}},[]),L=c.useCallback(()=>{x.current="",y.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(y.current),y.current=null,w.current=!1,S.current=null},[]),U=c.useCallback(()=>{const T=h.current,Z=p.current,E=m.current;if(!T||!Z||!E)return;const B=E.getBoundingClientRect();if(!(B.width<24||B.height<24))try{T.fit();const X={cols:Z.cols,rows:Z.rows},re=b.current;(!re||re.cols!==X.cols||re.rows!==X.rows)&&(b.current=X,g.current(X.cols,X.rows))}catch{}},[]),z=c.useCallback(()=>{if(w.current)return;const T=p.current;if(!T){L();return}if(!x.current)return;const Z=x.current;x.current="",w.current=!0,T.write(Z,()=>{w.current=!1,x.current&&(typeof window<"u"?y.current=window.requestAnimationFrame(()=>{y.current=null,z()}):z())})},[L]),H=c.useCallback(()=>{y.current===null&&(typeof window<"u"?y.current=window.requestAnimationFrame(()=>{y.current=null,z()}):z())},[z]),V=c.useCallback(T=>{T&&(x.current+=T,H())},[H]),J=c.useCallback(()=>{if(v.current?.(),v.current=null,N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),!d){D.current=0;return}const T=m.current;if(!T)return;const Z=p.current;if(!Z)return;D.current=0;const E=2.2,B=2.8,X=25,re=.25,q=8,oe=.05,ye=.015,I={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},F=()=>typeof performance<"u"?performance.now():Date.now(),W=Math.max(12,Math.round(i*1.35));let O=0;const _=ne=>{if(!ne)return!1;const K=Z.getViewportY(),ie=O+ne,ce=Math.trunc(ie/W);return O=ie-ce*W,ce!==0&&Z.scrollLines(ce),Z.getViewportY()!==K},ee=()=>{I.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(I.rafId),I.rafId=null},ue={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const ne=Object.assign(I,{pointerId:null,startX:null,startY:null,moved:!1}),K=6,ie=we=>{if(we.pointerType==="touch"){ee(),ne.pointerId=we.pointerId,ne.startX=we.clientX,ne.startY=we.clientY,ne.moved=!1,ne.lastY=we.clientY,ne.lastTime=F(),ne.velocity=0;try{T.setPointerCapture(we.pointerId)}catch{}}},ce=we=>{if(we.pointerType!=="touch"||ne.pointerId!==we.pointerId)return;if(ne.startX!==null&&ne.startY!==null&&!ne.moved){const et=we.clientX-ne.startX,wt=we.clientY-ne.startY;Math.hypot(et,wt)>=K&&(ne.moved=!0)}if(ne.lastY===null){ne.lastY=we.clientY,ne.lastTime=F();return}const fe=ne.lastY,ve=ne.lastTime??F(),Le=F();ne.lastY=we.clientY,ne.lastTime=Le;const Ge=fe-we.clientY;if(Math.abs(Ge)<1)return;const Te=Math.max(Le-ve,8),Pe=E+Math.min(B,Math.abs(Ge)/X),Ve=Ge*Pe,pt=Ve/Te;ne.velocity=ne.velocity*(1-re)+pt*re,ne.velocity>q?ne.velocity=q:ne.velocity<-q&&(ne.velocity=-q),ne.moved&&(we.cancelable&&we.preventDefault(),we.stopPropagation()),_(Ve)},ae=we=>{if(we.pointerType!=="touch"||ne.pointerId!==we.pointerId)return;const fe=!ne.moved;ne.pointerId=null,ne.startX=null,ne.startY=null,ne.moved=!1,ne.lastY=null,ne.lastTime=null;try{T.releasePointerCapture(we.pointerId)}catch{}if(fe){P(we.clientX,we.clientY);return}if(typeof window>"u")return;if(Math.abs(ne.velocity)<oe){ne.velocity=0;return}let ve=F();const Le=()=>{const Ge=F(),Te=Math.max(Ge-ve,8);ve=Ge;const Pe=_(ne.velocity*Te)??!1,Ve=Math.sign(ne.velocity),pt=Math.max(0,Math.abs(ne.velocity)-ye*Te);if(ne.velocity=pt*Ve,!Pe||pt<=oe){ee(),ne.velocity=0;return}ne.rafId=window.requestAnimationFrame(Le)};ne.rafId=window.requestAnimationFrame(Le)};T.addEventListener("pointerdown",ie,ue),T.addEventListener("pointermove",ce,ue),T.addEventListener("pointerup",ae,ue),T.addEventListener("pointercancel",ae,ue);const $=T.style.touchAction;T.style.touchAction="manipulation",v.current=()=>{ee(),N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),D.current=0,T.removeEventListener("pointerdown",ie,ue),T.removeEventListener("pointermove",ce,ue),T.removeEventListener("pointerup",ae,ue),T.removeEventListener("pointercancel",ae,ue),T.style.touchAction=$};return}const pe=6,He=ne=>{ne.touches.length===1&&(ee(),I.lastY=ne.touches[0].clientY,I.lastTime=F(),I.velocity=0,I.startX=ne.touches[0].clientX,I.startY=ne.touches[0].clientY,I.didMove=!1)},Y=ne=>{if(ne.touches.length!==1){I.lastY=null,I.lastTime=null,I.velocity=0,I.startX=null,I.startY=null,I.didMove=!1,ee();return}const K=ne.touches[0].clientX,ie=ne.touches[0].clientY;if(I.startX!==null&&I.startY!==null&&!I.didMove){const Te=K-I.startX,Pe=ie-I.startY;Math.hypot(Te,Pe)>=pe&&(I.didMove=!0)}if(I.lastY===null){I.lastY=ie,I.lastTime=F();return}const ce=I.lastY,ae=I.lastTime??F(),$=F();I.lastY=ie,I.lastTime=$;const we=ce-ie;if(Math.abs(we)<1)return;const fe=Math.max($-ae,8),ve=E+Math.min(B,Math.abs(we)/X),Le=we*ve,Ge=Le/fe;I.velocity=I.velocity*(1-re)+Ge*re,I.velocity>q?I.velocity=q:I.velocity<-q&&(I.velocity=-q),I.didMove&&(ne.preventDefault(),ne.stopPropagation()),_(Le)},le=ne=>{const K=!I.didMove;I.lastY=null,I.lastTime=null;const ie=I.velocity;if(I.startX=null,I.startY=null,I.didMove=!1,K){const $=ne.changedTouches?.[0];P($?.clientX,$?.clientY);return}if(typeof window>"u")return;if(Math.abs(ie)<oe){I.velocity=0;return}let ce=F();const ae=()=>{const $=F(),we=Math.max($-ce,8);ce=$;const fe=_(I.velocity*we)??!1,ve=Math.sign(I.velocity),Le=Math.max(0,Math.abs(I.velocity)-ye*we);if(I.velocity=Le*ve,!fe||Le<=oe){ee(),I.velocity=0;return}I.rafId=window.requestAnimationFrame(ae)};I.rafId=window.requestAnimationFrame(ae)};T.addEventListener("touchstart",He,ue),T.addEventListener("touchmove",Y,ue),T.addEventListener("touchend",le,ue),T.addEventListener("touchcancel",le,ue);const te=T.style.touchAction;T.style.touchAction="manipulation",v.current=()=>{ee(),N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),D.current=0,T.removeEventListener("touchstart",He,ue),T.removeEventListener("touchmove",Y,ue),T.removeEventListener("touchend",le,ue),T.removeEventListener("touchcancel",le,ue),T.style.touchAction=te}},[d,P,i]);return c.useEffect(()=>{let T=!1,Z=null,E=null,B=[];const X=m.current;return X?(X.tabIndex=0,(async()=>{try{const q=await Pv();if(T)return;const oe=Iv(a,i,o,q),ye=new Wp(oe),I=new Hp;Z=ye,p.current=ye,h.current=I,ye.loadAddon(I),ye.open(X),A();const F=Tv(X);F?(F.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=F,C()):f.current=null,U(),J(),ye.focus(),B=[ye.onData(W=>{j.current(W)})],E=new ResizeObserver(()=>{U()}),E.observe(X),typeof window<"u"&&window.setTimeout(()=>{U()},0)}catch{}})(),()=>{T=!0,v.current?.(),v.current=null,B.forEach(q=>q.dispose()),E?.disconnect(),Z?.dispose(),p.current=null,h.current=null,f.current=null,b.current=null,L()}):void 0},[U,a,i,J,o,L]),c.useEffect(()=>{const T=p.current;T&&(T.reset(),L(),b.current=null,U(),T.focus())},[s,k,U,L]),c.useEffect(()=>(J(),()=>{v.current?.(),v.current=null}),[J,s]),c.useEffect(()=>{const T=p.current;if(!T)return;if(r.length===0){S.current!==null&&(T.reset(),L(),U());return}const Z=S.current;let E;if(Z===null)E=r;else{const B=r.findIndex(X=>X.id===Z);E=B>=0?r.slice(B+1):r}E.length>0&&V(E.map(B=>B.data).join("")),S.current=r[r.length-1].id},[r,k,V,U,L]),c.useImperativeHandle(u,()=>({focus:()=>{if(d){P();return}p.current?.focus()},clear:()=>{const T=p.current;T&&(T.reset(),L(),U())},fit:()=>{U()}}),[d,P,U,L]),e.jsxs("div",{ref:m,className:R("relative h-full w-full",l),style:{backgroundColor:o.background},onClick:T=>{d?P(T.clientX,T.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:M,inputMode:"text",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,"aria-hidden":"true",style:{position:"absolute",left:0,top:0,width:1,height:1,opacity:.001,zIndex:1,background:"transparent",color:"transparent",border:"none",padding:0,margin:0,outline:"none"},onInput:T=>{const Z=String(T.currentTarget.value||"");if(!Z)return;const E=Z.replace(/\r\n|\r|\n/g,"\r");j.current(E),T.currentTarget.value=""},onKeyDown:T=>{T.key==="Backspace"&&(T.currentTarget.value||j.current(""))}}):null,f.current&&!d?e.jsx(Gi,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});Si.displayName="TerminalViewport";const ad=13,Fv={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},ho={ctrl:"5",cmd:"3"},Rv={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},Ov=(s,r)=>{if(r)switch(s){case"arrow-up":return`\x1B[1;${ho[r]}A`;case"arrow-down":return`\x1B[1;${ho[r]}B`;case"arrow-right":return`\x1B[1;${ho[r]}C`;case"arrow-left":return`\x1B[1;${ho[r]}D`}return Fv[s]??null},$v=()=>{const{terminal:s}=vn(),{currentTheme:r}=Ur(),{monoFont:t}=Pm(),{isMobile:n,hasTouchInput:o}=$t(),{currentSessionId:a,sessions:i,worktreeMetadata:l}=de(),d=a?l.get(a)??void 0:void 0,u=c.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const K=i.find(ce=>ce.id===a),ie=typeof K?.directory=="string"?K.directory:null;return ie&&ie.length>0?ie:null},[a,i,d]),{currentDirectory:m,homeDirectory:f}=ft(),p=u||m||null,h=c.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),j=nd(),g=j.sessions,b=j.setTerminalSession,x=j.setConnecting,y=j.appendToBuffer,w=j.clearTerminalSession,S=j.removeTerminalSession,v=j.clearBuffer,N=c.useMemo(()=>{if(p)return g.get(p)},[g,p]),D=N?.terminalSessionId??null,M=N?.bufferChunks??[],C=N?.bufferLength??0,k=N?.isConnecting??!1,A=D,[P,L]=c.useState(null),[U,z]=c.useState(!1),[H,V]=c.useState(null),[J,T]=c.useState(!1),Z=c.useRef(null),E=c.useRef(null),B=c.useRef(A),X=c.useRef(p),re=c.useRef(null),oe=Re(K=>K.activeMainTab)==="terminal";c.useEffect(()=>{B.current=A},[A]),c.useEffect(()=>{X.current=p},[p]),c.useEffect(()=>{!n&&H!==null&&V(null)},[n,H,V]),c.useEffect(()=>{!A&&H!==null&&V(null)},[A,H,V]);const ye=c.useCallback(()=>{Z.current?.(),Z.current=null,E.current=null},[]);c.useEffect(()=>()=>{ye(),B.current=null},[ye]);const I=c.useCallback(K=>{if(E.current===K)return;ye();const ie=s.connect(K,{onEvent:ce=>{const ae=X.current;if(ae)switch(ce.type){case"connected":{(ce.runtime||ce.ptyBackend)&&console.log(`[Terminal] connected runtime=${ce.runtime??"unknown"} pty=${ce.ptyBackend??"unknown"}`),x(ae,!1),L(null),z(!1),re.current?.focus();break}case"reconnecting":{const $=ce.attempt??0,we=ce.maxAttempts??3;L(`Reconnecting (${$}/${we})...`),z(!1);break}case"data":{ce.data&&y(ae,ce.data);break}case"exit":{const $=typeof ce.exitCode=="number"?ce.exitCode:null,we=typeof ce.signal=="number"?ce.signal:null;y(ae,`\r
|
|
100
|
+
[Process exited${$!==null?` with code ${$}`:""}${we!==null?` (signal ${we})`:""}]\r
|
|
101
|
+
`),w(ae),x(ae,!1),L("Terminal session ended"),z(!1),ye();break}}},onError:(ce,ae)=>{const $=X.current;if(!$)return;const we=ae?`Connection failed: ${ce.message}`:ce.message||"Terminal stream connection error";L(we),z(!!ae),ae&&(x($,!1),ye(),S($))}},Rv);Z.current=()=>{ie.close(),E.current=null},E.current=K},[y,w,ye,S,x,s,L]);c.useEffect(()=>{let K=!1;if(!p){L(a?"No working directory available for terminal.":"Select a session to open the terminal."),ye();return}return(async()=>{const ce=p;if(!X.current||X.current!==ce)return;let $=nd.getState().getTerminalSession(ce)?.terminalSessionId??null;if(!$){L(null),z(!1),x(ce,!0);try{const we=await s.createSession({cwd:ce});if(K){try{await s.close(we.sessionId)}catch{}return}b(ce,we),$=we.sessionId}catch(we){K||(L(we instanceof Error?we.message:"Failed to start terminal session"),z(!0),x(ce,!1));return}}!$||K||(B.current=$,I($))})(),()=>{K=!0,B.current=null,ye()}},[a,p,A,S,x,b,I,ye,s]);const F=c.useCallback(async()=>{if(!p||J)return;T(!0),L(null),z(!1),ye();const K=B.current;try{if(s.restartSession&&K){const ie=await s.restartSession(K,{cwd:p});b(p,ie),B.current=ie.sessionId,I(ie.sessionId)}else{if(K)try{await s.close(K)}catch{}S(p)}}catch(ie){L(ie instanceof Error?ie.message:"Failed to restart terminal"),z(!0)}finally{T(!1)}},[p,J,ye,s,b,I,S]),W=c.useCallback(async()=>{if(p&&!J){T(!0),L(null),z(!1),ye();try{s.forceKill&&await s.forceKill({cwd:p})}catch{}S(p),v(p),re.current?.clear(),await new Promise(K=>setTimeout(K,100));try{x(p,!0);const K=await s.createSession({cwd:p});b(p,K),B.current=K.sessionId,I(K.sessionId)}catch(K){L(K instanceof Error?K.message:"Failed to create terminal"),z(!0),x(p,!1)}finally{T(!1)}}},[p,J,ye,s,S,v,x,b,I]),O=c.useCallback(()=>{if(!p)return;v(p),re.current?.clear(),re.current?.focus();const K=B.current;K&&s.sendInput(K,"\f").catch(ie=>{L(ie instanceof Error?ie.message:"Failed to refresh prompt")})},[v,p,L,s]),_=c.useCallback(K=>{if(!K)return;let ie=K,ce=!1;if(H&&K.length>0){const $=K[0];if($.length===1&&/[a-zA-Z]/.test($)){const we=$.toUpperCase();(H==="ctrl"||H==="cmd")&&(ie=String.fromCharCode(we.charCodeAt(0)&31),ce=!0)}ce||(ce=!0)}const ae=B.current;ae&&(s.sendInput(ae,ie).catch($=>{L($ instanceof Error?$.message:"Failed to send input")}),ce&&(V(null),re.current?.focus()))},[H,V,s]),ee=c.useCallback((K,ie)=>{const ce=B.current;ce&&s.resize({sessionId:ce,cols:K,rows:ie}).catch(()=>{})},[s]),ue=c.useCallback(K=>{V(ie=>ie===K?null:K),re.current?.focus()},[V]),me=c.useCallback(K=>{const ie=Ov(K,H);ie&&(_(ie),V(null),re.current?.focus())},[H,_,V]);c.useEffect(()=>{if(!n||!H||!A)return;const K=ie=>{if(ie.repeat)return;const ce=ie.key;if(!ce||ce==="Control"||ce==="Meta"||ce==="Alt"||ce==="Shift")return;const ae=ce.length===1?ce.toLowerCase():ce,$=ie.code??"",we=$.startsWith("Key")&&$.length===4?$.slice(3).toUpperCase():null,fe=ce.length===1&&/[a-zA-Z]/.test(ce)?ce.toUpperCase():we,ve={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc",tab:"tab",enter:"enter",arrowup:"arrow-up",arrowdown:"arrow-down",arrowleft:"arrow-left",arrowright:"arrow-right",escape:"esc"};if(ae in ve){ie.preventDefault(),ie.stopPropagation(),me(ve[ae]);return}if(H==="ctrl"&&fe&&fe.length===1&&fe>="A"&&fe<="Z"){const Le=String.fromCharCode(fe.charCodeAt(0)&31);ie.preventDefault(),ie.stopPropagation(),_(Le),V(null),re.current?.focus()}};return window.addEventListener("keydown",K),()=>{window.removeEventListener("keydown",K)}},[H,me,_,n,V,A]);const pe=c.useMemo(()=>{const K=Er[Ao].stack;if(typeof window>"u")return(Er[t]??Er[Ao]).stack;const ce=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return ce&&ce.trim().length>0?ce.trim():(Er[t]??Er[Ao]).stack??K},[t]),He=c.useMemo(()=>Ev(r),[r]),Y=c.useMemo(()=>`${p??"no-dir"}::${A??"pending"}`,[p,A]);c.useEffect(()=>{if(!oe)return;const K=re.current;if(!K)return;const ie=()=>{K.fit()};if(typeof window<"u"){const ce=window.requestAnimationFrame(()=>{ie(),K.focus()}),ae=[220,400].map($=>window.setTimeout(ie,$));return()=>{window.cancelAnimationFrame(ce),ae.forEach($=>window.clearTimeout($))}}ie()},[oe,Y,A]);const le=P?.includes("Reconnecting"),te=P?le?e.jsx(Vp,{size:20,className:"text-amber-400"}):e.jsx(Lt,{size:20,className:"text-destructive"}):A&&!k&&!J?e.jsx(bo,{size:20,className:"text-emerald-400"}):k||J?e.jsx(wl,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(wl,{size:20,className:"text-muted-foreground"});if(!a)return e.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal"});if(!p)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[e.jsx("p",{children:"No working directory available for this session."}),e.jsx("button",{onClick:F,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const ne=!A||k||J;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:h})}),e.jsxs("div",{className:"flex items-center gap-2",children:[te,e.jsxs(ke,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:O,disabled:!C,title:"Clear output",type:"button",children:[e.jsx(zs,{size:16}),"Clear"]}),e.jsxs(ke,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:F,disabled:J,title:"Restart terminal session",type:"button",children:[e.jsx(ws,{size:16,className:R((k||J)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(ke,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>me("esc"),disabled:ne,children:"Esc"}),e.jsxs(ke,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>me("tab"),disabled:ne,children:[e.jsx(bl,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(ke,{type:"button",size:"sm",variant:H==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ue("ctrl"),disabled:ne,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(ke,{type:"button",size:"sm",variant:H==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ue("cmd"),disabled:ne,children:[e.jsx($r,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(ke,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>me("arrow-up"),disabled:ne,children:[e.jsx(Gn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(ke,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>me("arrow-left"),disabled:ne,children:[e.jsx(Gd,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(ke,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>me("arrow-down"),disabled:ne,children:[e.jsx(bn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(ke,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>me("arrow-right"),disabled:ne,children:[e.jsx(bl,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(ke,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>me("enter"),disabled:ne,children:[e.jsx(On,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:He.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:oe?n?e.jsx(Si,{ref:K=>{re.current=K},sessionKey:Y,chunks:M,onInput:_,onResize:ee,theme:He,fontFamily:pe,fontSize:ad,enableTouchScroll:o},Y):e.jsx(ct,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Si,{ref:K=>{re.current=K},sessionKey:Y,chunks:M,onInput:_,onResize:ee,theme:He,fontFamily:pe,fontSize:ad,enableTouchScroll:o},Y)}):null}),P&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2",children:[e.jsx("span",{children:P}),U&&e.jsx(ke,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:W,disabled:J,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},Fm=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Di},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:xn},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:$r},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:Ud},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:Ln},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Ft},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:Rr}],Lv={},_v={},Bv={};Fm.forEach(s=>{Lv[s.id]=s.label,_v[s.id]=s.description,Bv[s.id]=s});const zv=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",Wv=s=>{if(!Array.isArray(s))return[];const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},id=s=>{const r=Wv(s);if(r.length===0)return;const t={};for(const i of r)i.permission&&((t[i.permission]||={})[i.pattern]=i.action);const n=t["*"]?.["*"],o=Object.keys(t);if(o.length===1&&o[0]==="*"&&Object.keys(t["*"]||{}).length===1&&t["*"]?.["*"])return t["*"]["*"];const a={};for(const i of o){const l=t[i],d=Object.keys(l);if(d.length===1&&d[0]==="*"&&i!=="*"){const u=l["*"],m=zv(i);if(n){if(u===n)continue}else if(u===m)continue;a[i]=u}else i==="*"&&d.length===1&&d[0]==="*"?a[i]=l["*"]:a[i]=l}return Object.keys(a).length>0?a:void 0},Hv=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedAgentName:a,agents:i,setSelectedAgent:l,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=zr(),{setSidebarOpen:p}=Re(),{isMobile:h}=$t(),[j,g]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const x=j?"bg-transparent":b?"bg-background":"bg-sidebar",y=()=>{const P="new-agent";let L=P,U=1;for(;i.some(z=>z.name===L);)L=`${P}-${U}`,U++;d({name:L,scope:"user"}),l(L),s?.(),h&&p(!1)},w=async P=>{if(en(P)){se.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${P.name}"?`)&&(await m(P.name)?se.success(`Agent "${P.name}" deleted successfully`):se.error("Failed to delete agent"))},S=async P=>{en(P)&&window.confirm(`Are you sure you want to reset agent "${P.name}" to its default configuration?`)&&(await m(P.name)?se.success(`Agent "${P.name}" reset to default`):se.error("Failed to reset agent"))},v=P=>{const L=P.name;let U=1,z=`${L}-copy`;for(;i.some(T=>T.name===z);)U++,z=`${L}-copy-${U}`;const H=P,V=P.model?.providerID&&P.model?.modelID?`${P.model.providerID}/${P.model.modelID}`:null,J=P;d({name:z,scope:H.scope||"user",description:P.description,model:V,temperature:P.temperature,top_p:P.topP,prompt:P.prompt,mode:P.mode,permission:id(P.permission),disable:J.disable}),l(z),h&&p(!1)},N=P=>{o(P.name),t(P)},D=async()=>{if(!r)return;const P=n.trim().replace(/\s+/g,"-");if(!P){se.error("Agent name is required");return}if(P===r.name){t(null);return}if(i.some(H=>H.name===P)){se.error("An agent with this name already exists");return}const L=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,U=r;await u({name:P,description:r.description,model:L,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:id(r.permission),disable:U.disable,scope:U.scope})?await m(r.name)?(se.success(`Agent renamed to "${P}"`),l(P)):se.error("Failed to remove old agent after rename"):se.error("Failed to rename agent"),t(null)},M=P=>{switch(P){case"primary":return e.jsx($n,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Kd,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(qd,{className:"h-3 w-3 text-primary"});default:return null}},C=i.filter(P=>!uu(P)),k=C.filter(en),A=C.filter(P=>!en(P));return e.jsxs("div",{className:R("flex h-full flex-col",x),children:[e.jsx("div",{className:R("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",C.length]}),e.jsx(ke,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:y,children:e.jsx(_t,{className:"size-4"})})]})}),e.jsx(ct,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:C.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(_n,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No agents configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[k.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Agents"}),k.map(P=>e.jsx(ld,{agent:P,isSelected:a===P.name,onSelect:()=>{l(P.name),s?.(),h&&p(!1)},onReset:()=>S(P),onDuplicate:()=>v(P),getAgentModeIcon:M},P.name))]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Agents"}),A.map(P=>e.jsx(ld,{agent:P,isSelected:a===P.name,onSelect:()=>{l(P.name),s?.(),h&&p(!1)},onRename:()=>N(P),onDelete:()=>w(P),onDuplicate:()=>v(P),getAgentModeIcon:M},P.name))]})]})}),e.jsx(ds,{open:r!==null,onOpenChange:P=>!P&&t(null),children:e.jsxs(us,{children:[e.jsxs(fs,{children:[e.jsx(ps,{children:"Rename Agent"}),e.jsxs(ys,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(mt,{value:n,onChange:P=>o(P.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:P=>{P.key==="Enter"&&D()}}),e.jsxs(Ws,{children:[e.jsx(ke,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Or,{onClick:D,children:"Rename"})]})]})})]})},ld=({agent:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i,getAgentModeIcon:l})=>{const d=s;return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick: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}),l(s.mode),(d.scope||en(s))&&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:en(s)?"system":d.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx(ke,{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(kr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Xt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(jt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(Zo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(jt,{onClick:u=>{u.stopPropagation(),i()},children:[e.jsx(Bs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(jt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(ws,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(jt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Rs({className:s,variant:r,...t}){return e.jsx(ke,{variant:r,size:"sm",className:R("h-6 px-2 text-xs",s),...t})}const Uv=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Vv=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=Uv.format(s);return r.endsWith(".0")?r.slice(0,-2):r},cl=({providerId:s,modelId:r,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=at(),i=Re(E=>E.isMobile),{toggleFavoriteModel:l,isFavoriteModel:d,addRecentModel:u}=Re(),{favoriteModelsList:m,recentModelsList:f}=nl(),{isMobile:p}=$t(),h=i||p,[j,g]=c.useState(!1),[b,x]=c.useState(new Set),[y,w]=c.useState(!1),[S,v]=c.useState(""),[N,D]=c.useState(0),M=c.useRef([]),C=()=>g(!1),k=E=>{x(B=>{const X=new Set(B);return X.has(E)?X.delete(E):X.add(E),X})};c.useEffect(()=>{y||(v(""),D(0))},[y]),c.useEffect(()=>{D(0)},[S]);const A=E=>{const B=E?.name||E?.id||"",X=String(B);return X.length>40?X.substring(0,37)+"...":X},P=(E,B)=>{const X=`${E}/${B}`;return a.get(X)},L=(E,B)=>{t(E,B),E&&B&&u(E,B),w(!1)},U=(E,B)=>{if(!S.trim())return!0;const X=S.toLowerCase();return E.toLowerCase().includes(X)||B.toLowerCase().includes(X)},z=(E,B,X,re,q,oe)=>{const ye=P(B,X),I=Vv(ye?.limit?.context),F=s===B&&r===X,W=d(B,X);return e.jsxs("div",{ref:O=>{M.current[q]=O},className:R("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",oe?"bg-accent":"hover:bg-accent/50"),onClick:()=>L(B,X),onMouseEnter:()=>D(q),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:A(E)}),I?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:I}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[F&&e.jsx(Ot,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),l(B,X)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",W?"text-yellow-500":"text-muted-foreground"),"aria-label":W?"Unfavorite":"Favorite",title:W?"Remove from favorites":"Add to favorites",children:W?e.jsx(ar,{className:"h-3.5 w-3.5"}):e.jsx(sn,{className:"h-3.5 w-3.5"})})]})]},`${re}-${B}-${X}`)},H=m.filter(({model:E,providerID:B})=>{const re=o.find(oe=>oe.id===B)?.name||B,q=A(E);return U(q,re)}),V=f.filter(({model:E,providerID:B})=>{const re=o.find(oe=>oe.id===B)?.name||B,q=A(E);return U(q,re)}),J=o.map(E=>{const X=(Array.isArray(E.models)?E.models:[]).filter(re=>{const q=A(re);return U(q,E.name||E.id||"")});return{...E,models:X}}).filter(E=>E.models.length>0),T=H.length>0||V.length>0||J.length>0,Z=()=>h?e.jsx(vs,{open:j,onClose:C,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[m.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Favorites"}),e.jsx("div",{className:"border-t border-border/20",children:m.map(({model:E,providerID:B,modelID:X})=>{const re=B===s&&X===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",re?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{L(B,X),C()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{providerId:B,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(E)})]})}),e.jsx("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),l(B,X)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-yellow-500 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Unfavorite",children:e.jsx(ar,{className:"h-4 w-4"})})]},`fav-mobile-${B}-${X}`)})})]}),f.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Recents"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:E,providerID:B,modelID:X})=>{const re=B===s&&X===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",re?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{L(B,X),C()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{providerId:B,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(E)})]})}),e.jsx("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),l(B,X)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Favorite",children:e.jsx(sn,{className:"h-4 w-4"})})]},`recent-mobile-${B}-${X}`)})})]}),o.map(E=>{const B=Array.isArray(E.models)?E.models:[];if(B.length===0)return null;const X=E.id===s,re=b.has(E.id);return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left",onClick:()=>k(E.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{providerId:E.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:E.name}),X&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),re?e.jsx(Ct,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Ls,{className:"h-3 w-3 text-muted-foreground"})]}),re&&e.jsx("div",{className:"border-t border-border/20",children:B.map(q=>{const oe=E.id===s&&q.id===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",oe?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{L(E.id,q.id),C()},children:e.jsx("span",{className:"font-medium truncate",children:A(q)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:ye=>{ye.preventDefault(),ye.stopPropagation(),l(E.id,q.id)},className:R("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(E.id,q.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(E.id,q.id)?"Unfavorite":"Favorite",children:d(E.id,q.id)?e.jsx(ar,{className:"h-4 w-4"}):e.jsx(sn,{className:"h-4 w-4"})}),oe&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},q.id)})})]},E.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{L("",""),C()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[h?e.jsxs("button",{type:"button",onClick:()=>g(!0),className:R("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[s?e.jsx(ts,{providerId:s,className:"h-3.5 w-3.5"}):e.jsx(or,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:s&&r?`${s}/${r}`:"Select model..."})]}),e.jsx(Ct,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Kt,{open:y,onOpenChange:w,children:[e.jsx(Yt,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",n),children:[s?e.jsxs(e.Fragment,{children:[e.jsx(ts,{providerId:s,className:"h-3 w-3 flex-shrink-0"}),e.jsx(or,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(or,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:s&&r?`${s}/${r}`:"Not selected"}),e.jsx(Ct,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Xt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const E=[];H.forEach(({model:q,providerID:oe,modelID:ye})=>{E.push({model:q,providerID:oe,modelID:ye,section:"fav"})}),V.forEach(({model:q,providerID:oe,modelID:ye})=>{E.push({model:q,providerID:oe,modelID:ye,section:"recent"})}),J.forEach(q=>{q.models.forEach(oe=>{E.push({model:oe,providerID:q.id,modelID:oe.id,section:"provider"})})});const B=E.length,X=q=>{if(q.key==="ArrowDown"){q.preventDefault(),q.stopPropagation();const oe=(N+1)%Math.max(1,B);D(oe),setTimeout(()=>{M.current[oe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(q.key==="ArrowUp"){q.preventDefault(),q.stopPropagation();const oe=(N-1+Math.max(1,B))%Math.max(1,B);D(oe),setTimeout(()=>{M.current[oe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(q.key==="Enter"){q.preventDefault(),q.stopPropagation();const oe=E[N];oe&&L(oe.providerID,oe.modelID)}else q.key==="Escape"&&(q.preventDefault(),q.stopPropagation(),w(!1))};let re=0;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(ur,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(mt,{type:"text",placeholder:"Search models",value:S,onChange:q=>v(q.target.value),onKeyDown:X,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(ct,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:R("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>L("",""),children:[e.jsx(Lt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!s&&!r&&e.jsx(Ot,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Xs,{}),!T&&S&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),H.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(on,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ar,{className:"h-4 w-4 text-primary"}),"Favorites"]}),H.map(({model:q,providerID:oe,modelID:ye})=>{const I=re++;return z(q,oe,ye,"fav",I,N===I)})]}),V.length>0&&e.jsxs(e.Fragment,{children:[H.length>0&&e.jsx(Xs,{}),e.jsxs(on,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(tr,{className:"h-4 w-4"}),"Recent"]}),V.map(({model:q,providerID:oe,modelID:ye})=>{const I=re++;return z(q,oe,ye,"recent",I,N===I)})]}),(H.length>0||V.length>0)&&J.length>0&&e.jsx(Xs,{}),J.map((q,oe)=>e.jsxs(c.Fragment,{children:[oe>0&&e.jsx(Xs,{}),e.jsxs(on,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ts,{providerId:q.id,className:"h-4 w-4 flex-shrink-0"}),q.name]}),q.models.map(ye=>{const I=re++;return z(ye,q.id,ye.id,"provider",I,N===I)})]},q.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()})]}),Z()]})},Gv=["read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop"],dr=s=>s==="allow"||s==="ask"||s==="deny",qv=s=>{if(dr(s))return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const r=s["*"];if(dr(r))return r}},Kv=s=>{if(dr(s))return{entries:{"*":s}};if(!s||typeof s!="object"||Array.isArray(s))return{entries:{}};const r={};for(const[t,n]of Object.entries(s)){const o=qv(n);o!==void 0&&(r[t]=o)}return{entries:r}},Yv=s=>{const r={...s},t=r["*"];return dr(t)?(delete r["*"],{defaultOverride:t,overrides:r}):{defaultOverride:"default",overrides:r}},da=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",Eo=(s,r)=>r==="default"?da(s):r,cd=(s,r)=>{const t={...s};for(const[n,o]of Object.entries(s)){if(n==="*")continue;const a=Eo(n,r),i=da(n);if(!(dr(o)&&o!==i)){if(dr(o)&&o===a){delete t[n];continue}if(o&&typeof o=="object"&&!Array.isArray(o)){const l=o,d=Object.keys(l),u=l["*"];if(u!==void 0&&u!==i)continue;d.length===1&&d[0]==="*"&&u===a&&delete t[n]}}}return t},Rm=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},Xv=s=>{const r=Rm(s);if(!r||r.length===0)return{entries:{}};const t={};for(const a of r)!a.permission||a.permission==="invalid"||a.pattern==="*"&&(t[a.permission]=a.action);const n=t["*"],o={};for(const[a,i]of Object.entries(t)){if(a==="*"){o[a]=i;continue}const l=da(a);if(n){if(i===n)continue}else if(i===l)continue;o[a]=i}return{entries:o}},Qv=()=>{const{selectedAgentName:s,getAgentByName:r,createAgent:t,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:i}=zr();at();const l=s?r(s):null,d=!!(a&&a.name===s&&!l),[u,m]=c.useState(""),[f,p]=c.useState("user"),[h,j]=c.useState(""),[g,b]=c.useState("subagent"),[x,y]=c.useState(""),[w,S]=c.useState(void 0),[v,N]=c.useState(void 0),[D,M]=c.useState(""),[C,k]=c.useState("default"),[A,P]=c.useState({}),[L,U]=c.useState(""),[z,H]=c.useState(!1),V=ft(O=>O.currentDirectory??null),[J,T]=c.useState([]),Z=Hn(O=>O.permissions);c.useEffect(()=>{let O=!1;return(async()=>{const ee=await De.listToolIds({directory:V});if(O)return;const ue=new Set(["write","patch","multiedit"]),me=ee.map(pe=>typeof pe=="string"?pe.trim():"").filter(Boolean).filter(pe=>pe!=="*").filter(pe=>pe!=="invalid").filter(pe=>!ue.has(pe));T(Array.from(new Set(me)).sort((pe,He)=>pe.localeCompare(He)))})(),()=>{O=!0}},[V]);const E=c.useMemo(()=>{const O=new Set;for(const _ of o){const ee=Rm(_.permission);if(ee)for(const ue of ee)ue.permission&&ue.permission!=="*"&&ue.permission!=="invalid"&&O.add(ue.permission)}for(const _ of Z.values())for(const ee of _){const ue=ee.permission?.trim();ue&&ue!=="invalid"&&O.add(ue)}for(const _ of J)O.add(_);return Array.from(O).sort((_,ee)=>_.localeCompare(ee))},[o,Z,J]),B=c.useCallback(O=>{const _=A[O];if(dr(_))return _;if(_&&typeof _=="object"&&!Array.isArray(_)){const ee=_["*"];if(dr(ee))return ee}},[A]),X=c.useCallback(O=>{const _=A[O];return!_||typeof _!="object"||Array.isArray(_)?0:Object.keys(_).filter(ue=>ue!=="*").length},[A]),re=c.useCallback((O,_)=>{O!=="*"&&P(ee=>{const ue={...ee},me=ue[O],pe=Eo(O,C),He=da(O),Y=_===pe&&_===He;if(me&&typeof me=="object"&&!Array.isArray(me)){const le={...me};le["*"]=_;const te=Object.keys(le).filter(ne=>ne!=="*");return Y&&te.length===0?(delete ue[O],ue):(ue[O]=le,ue)}return Y?(delete ue[O],ue):(ue[O]=_,ue)})},[C]),q=c.useCallback(O=>{P(_=>{if(!(O in _))return _;const ee={..._};return delete ee[O],ee})},[]),oe=c.useMemo(()=>{const O=Object.entries(A).filter(([_])=>_!=="*");return O.sort(([_],[ee])=>_.localeCompare(ee)),O},[A]),ye=c.useMemo(()=>{const O=new Set;for(const _ of Gv)O.add(_);for(const _ of E)O.add(_);for(const _ of Object.keys(A))O.delete(_);return Array.from(O).sort((_,ee)=>_.localeCompare(ee))},[E,A]),I=c.useCallback(O=>{const _=L.trim();if(!_)return;const ee=Eo(_,C);if(O===ee){const ue=C==="default"?"OpenCode defaults":`Default Permissions ("${C}")`;se.message(`"${_}" already matches ${ue} (${ee}).`),U("");return}re(_,O),U("")},[L,re,C]),F=c.useCallback(O=>O==="webfetch"?"WebFetch":O==="websearch"?"WebSearch":O==="codesearch"?"CodeSearch":O==="doom_loop"?"Doom Loop":O==="external_directory"?"External Directory":O==="todowrite"?"TodoWrite":O==="todoread"?"TodoRead":O.split(/[_-]+/g).filter(Boolean).map(_=>_.charAt(0).toUpperCase()+_.slice(1)).join(" "),[]);c.useEffect(()=>{U("");const O=_=>{const ee=Yv(_);k(ee.defaultOverride),P(cd(ee.overrides,ee.defaultOverride))};if(d&&a){m(a.name||""),p(a.scope||"user"),j(a.description||""),b(a.mode||"subagent"),y(a.model||""),S(a.temperature),N(a.top_p),M(a.prompt||"");const _=Kv(a.permission);O(_.entries);return}if(l&&s===l.name){j(l.description||""),b(l.mode||"subagent"),l.model?.providerID&&l.model?.modelID?y(`${l.model.providerID}/${l.model.modelID}`):y(""),S(l.temperature),N(l.topP),M(l.prompt||"");const _=Xv(l.permission);O(_.entries)}},[a,d,l,s]);const W=async()=>{const O=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!O){se.error("Agent name is required");return}if(d&&o.some(_=>_.name===O)){se.error("An agent with this name already exists");return}H(!0);try{const _=x.trim(),ee={name:O,description:h.trim()||void 0,mode:g,model:_===""?null:_,temperature:w,top_p:v,prompt:D.trim()||void 0,permission:(()=>{const me=cd(A,C),pe=C==="default"?me:{"*":C,...me},He=["doom_loop","external_directory"];for(const le of He)if(!(le in pe)){const te=A[le];dr(te)?pe[le]=te:pe[le]=Eo(le,C)}return Object.keys(pe).length===0?d?void 0:null:pe})(),scope:d?f:void 0};let ue;d?(ue=await t(ee),ue&&i(null)):ue=await n(O,ee),ue?se.success(d?"Agent created successfully":"Agent updated successfully"):se.error(d?"Failed to create agent":"Failed to update agent")}catch(_){console.error("Error saving agent:",_);const ee=_ instanceof Error&&_.message?_.message:"An error occurred while saving";se.error(ee)}finally{H(!1)}};return s?e.jsx(ct,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Agent":s})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure agent identity and behavior mode"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"@"}),e.jsx(mt,{value:u,onChange:O=>m(O.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(ks,{value:f,onValueChange:O=>p(O),children:[e.jsxs(Ns,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Ss,{className:"h-4 w-4"}):e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Cs,{align:"end",children:[e.jsx(qt,{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(Ss,{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(qt,{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(fr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(js,{value:h,onChange:O=>j(O.target.value),placeholder:"What does this agent do?",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Mode"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsxs(Rs,{variant:g==="primary"?"default":"outline",onClick:()=>b("primary"),className:R("gap-2",g==="primary"?void 0:"text-foreground"),children:[e.jsx($n,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Rs,{variant:g==="subagent"?"default":"outline",onClick:()=>b("subagent"),className:R("gap-2",g==="subagent"?void 0:"text-foreground"),children:[e.jsx(qd,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Rs,{variant:g==="all"?"default":"outline",onClick:()=>b("all"),className:R("gap-2",g==="all"?void 0:"text-foreground"),children:[e.jsx(Kd,{className:"h-3 w-3"}),"All"]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Primary: main agent, Subagent: helper agent, All: both modes"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and generation parameters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(cl,{providerId:x?x.split("/")[0]:"",modelId:x?x.split("/")[1]:"",onChange:(O,_)=>{y(O&&_?`${O}/${_}`:"")}})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Temperature",e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Controls randomness in responses.",e.jsx("br",{}),"Higher values make output more creative and unpredictable,",e.jsx("br",{}),"lower values make it more focused and deterministic."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const _=Math.max(0,(w!==void 0?w:.7)-.1);S(parseFloat(_.toFixed(1)))},className:"absolute left-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(ha,{className:"h-3.5 w-3.5"})}),e.jsx(mt,{type:"text",inputMode:"decimal",value:w!==void 0?w:"",onChange:O=>{const _=O.target.value;if(_===""){S(void 0);return}const ee=parseFloat(_);!isNaN(ee)&&ee>=0&&ee<=2&&S(ee)},onBlur:O=>{const _=O.target.value;if(_!==""){const ee=parseFloat(_);if(!isNaN(ee)){const ue=Math.max(0,Math.min(2,ee));S(parseFloat(ue.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const _=Math.min(2,(w!==void 0?w:.7)+.1);S(parseFloat(_.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(_t,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Top P",e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Controls diversity via nucleus sampling.",e.jsx("br",{}),"Lower values focus on most likely tokens,",e.jsx("br",{}),"higher values consider more possibilities."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const _=Math.max(0,(v!==void 0?v:.9)-.1);N(parseFloat(_.toFixed(1)))},className:"absolute left-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(ha,{className:"h-3.5 w-3.5"})}),e.jsx(mt,{type:"text",inputMode:"decimal",value:v!==void 0?v:"",onChange:O=>{const _=O.target.value;if(_===""){N(void 0);return}const ee=parseFloat(_);!isNaN(ee)&&ee>=0&&ee<=1&&N(ee)},onBlur:O=>{const _=O.target.value;if(_!==""){const ee=parseFloat(_);if(!isNaN(ee)){const ue=Math.max(0,Math.min(1,ee));N(parseFloat(ue.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const _=Math.min(1,(v!==void 0?v:.9)+.1);N(parseFloat(_.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(_t,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"System Prompt"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Override the default system prompt for this agent"})]}),e.jsx(js,{value:D,onChange:O=>M(O.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Tool Access"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"OpenCode v1.1.1+ configures tool access via the permissions below."})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:'This editor only updates wildcard ("*") rules; existing pattern rules are preserved.'})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Default Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Set the default behavior for all permissions for this agent."}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ke,{size:"sm",variant:C==="default"?"default":"outline",onClick:()=>k("default"),className:"h-6 px-2 text-xs",children:"Default"}),e.jsx(ke,{size:"sm",variant:C==="allow"?"default":"outline",onClick:()=>k("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ke,{size:"sm",variant:C==="ask"?"default":"outline",onClick:()=>k("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ke,{size:"sm",variant:C==="deny"?"default":"outline",onClick:()=>k("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:C==="default"?"Uses OpenCode defaults unless overridden below.":"Applies to any permission without an explicit override below."}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Default:"})," Follow OpenCode default behavior"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block the operation"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Overrides"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Add overrides for permissions that should behave differently for this agent."}),e.jsx("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs(ks,{value:L,onValueChange:U,children:[e.jsx(Ns,{className:"h-8 w-full sm:w-72",children:L?e.jsx("span",{className:"truncate",children:F(L)}):e.jsx("span",{className:"text-muted-foreground",children:"Add override…"})}),e.jsx(Cs,{children:ye.map(O=>e.jsx(qt,{value:O,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:F(O)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:O})]})},O))})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ke,{size:"sm",variant:"outline",disabled:!L,onClick:()=>I("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(ke,{size:"sm",variant:"outline",disabled:!L,onClick:()=>I("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(ke,{size:"sm",variant:"outline",disabled:!L,onClick:()=>I("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})}),oe.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:C==="default"?"No overrides configured. Everything follows OpenCode defaults.":`No overrides configured. All permissions default to "${C}" for this agent.`}):e.jsx("div",{className:"space-y-4",children:oe.map(([O])=>{const _=B(O),ee=X(O),ue=F(O);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:[e.jsx("span",{children:ue}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:O}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block this operation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Remove:"})," Return to default behavior"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Note:"}),' Buttons set the "*" rule only']}),ee>0?e.jsxs("p",{children:[e.jsx("strong",{children:"Patterns:"})," ",ee," pattern rules preserved"]}):null]})})]})]}),e.jsxs(ke,{size:"sm",variant:"outline",onClick:()=>q(O),className:"h-6 px-2 text-xs gap-1",children:[e.jsx(ha,{className:"h-3 w-3"}),"Remove"]})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ke,{size:"sm",variant:_==="allow"?"default":"outline",onClick:()=>re(O,"allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ke,{size:"sm",variant:_==="ask"?"default":"outline",onClick:()=>re(O,"ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ke,{size:"sm",variant:_==="deny"?"default":"outline",onClick:()=>re(O,"deny"),className:"h-6 px-2 text-xs",children:"Deny"})]})]},O)})})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(ke,{size:"sm",variant:"default",onClick:W,disabled:z,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ea,{className:"h-3 w-3"}),z?"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(_n,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select an agent from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})},Jv=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedCommandName:a,commands:i,setSelectedCommand:l,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=Br(),{setSidebarOpen:p}=Re(),{isMobile:h}=$t(),[j,g]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const x=j?"bg-transparent":b?"bg-background":"bg-sidebar",y=()=>{const k="new-command";let A=k,P=1;for(;i.some(L=>L.name===A);)A=`${k}-${P}`,P++;d({name:A,scope:"user"}),l(A),s?.(),h&&p(!1)},w=async k=>{if(Zr(k)){se.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${k.name}"?`)&&(await m(k.name)?se.success(`Command "${k.name}" deleted successfully`):se.error("Failed to delete command"))},S=async k=>{Zr(k)&&window.confirm(`Are you sure you want to reset command "${k.name}" to its default configuration?`)&&(await m(k.name)?se.success(`Command "${k.name}" reset to default`):se.error("Failed to reset command"))},v=k=>{const A=k.name;let P=1,L=`${A}-copy`;for(;i.some(U=>U.name===L);)P++,L=`${A}-copy-${P}`;d({name:L,scope:k.scope||"user",description:k.description,template:k.template,agent:k.agent,model:k.model,subtask:k.subtask}),l(L),h&&p(!1)},N=k=>{o(k.name),t(k)},D=async()=>{if(!r)return;const k=n.trim().replace(/\s+/g,"-");if(!k){se.error("Command name is required");return}if(k===r.name){t(null);return}if(i.some(P=>P.name===k)){se.error("A command with this name already exists");return}await u({name:k,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(se.success(`Command renamed to "${k}"`),l(k)):se.error("Failed to remove old command after rename"):se.error("Failed to rename command"),t(null)},M=i.filter(Zr),C=i.filter(k=>!Zr(k));return e.jsxs("div",{className:R("flex h-full flex-col",x),children:[e.jsx("div",{className:R("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",i.length]}),e.jsx(ke,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:y,children:e.jsx(_t,{className:"size-4"})})]})}),e.jsx(ct,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:i.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Sr,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No commands configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Commands"}),[...M].sort((k,A)=>k.name.localeCompare(A.name)).map(k=>e.jsx(dd,{command:k,isSelected:a===k.name,onSelect:()=>{l(k.name),s?.(),h&&p(!1)},onReset:()=>S(k),onDuplicate:()=>v(k)},k.name))]}),C.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Commands"}),[...C].sort((k,A)=>k.name.localeCompare(A.name)).map(k=>e.jsx(dd,{command:k,isSelected:a===k.name,onSelect:()=>{l(k.name),s?.(),h&&p(!1)},onRename:()=>N(k),onDelete:()=>w(k),onDuplicate:()=>v(k)},k.name))]})]})}),e.jsx(ds,{open:r!==null,onOpenChange:k=>!k&&t(null),children:e.jsxs(us,{children:[e.jsxs(fs,{children:[e.jsx(ps,{children:"Rename Command"}),e.jsxs(ys,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(mt,{value:n,onChange:k=>o(k.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:k=>{k.key==="Enter"&&D()}}),e.jsxs(Ws,{children:[e.jsx(ke,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Or,{onClick:D,children:"Rename"})]})]})})]})},dd=({command:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i})=>e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick: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-2",children:[e.jsxs("span",{className:"typography-ui-label font-normal truncate text-foreground",children:["/",s.name]}),(s.scope||Zr(s))&&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:Zr(s)?"system":s.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx(ke,{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(kr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Xt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(jt,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(Zo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(jt,{onClick:l=>{l.stopPropagation(),i()},children:[e.jsx(Bs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(jt,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(ws,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(jt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),Om=({agentName:s,onChange:r,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=zr(),a=o(),i=Re(j=>j.isMobile),{isMobile:l}=$t(),d=i||l,[u,m]=c.useState(!1);c.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=j=>{r(j)},h=()=>d?e.jsx(vs,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(j=>{const g=j.name===s;return e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",g?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(j.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:j.name}),j.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:j.description})]}),g&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},j.name)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{p(""),f()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No agent (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[d?e.jsxs("button",{type:"button",onClick:()=>m(!0),className:R("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",t),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:s||"Select agent..."})]}),e.jsx(Ct,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",t),children:[e.jsx(_n,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:s||"Not selected"}),e.jsx(Ct,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Xt,{className:"max-w-[300px]",children:[a.map(j=>e.jsx(jt,{className:"typography-meta",onSelect:()=>p(j.name),children:e.jsx("span",{className:"font-medium",children:j.name})},j.name)),e.jsx(jt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},Zv=()=>{const{selectedCommandName:s,getCommandByName:r,createCommand:t,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:i}=Br(),l=s?r(s):null,d=!!(a&&a.name===s&&!l),[u,m]=c.useState(""),[f,p]=c.useState("user"),[h,j]=c.useState(""),[g,b]=c.useState(""),[x,y]=c.useState(""),[w,S]=c.useState(""),[v,N]=c.useState(!1),[D,M]=c.useState(!1);c.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),j(a.description||""),b(a.agent||""),y(a.model||""),S(a.template||""),N(a.subtask||!1)):l&&(j(l.description||""),b(l.agent||""),y(l.model||""),S(l.template||""),N(l.subtask||!1))},[l,d,s,o,a]);const C=async()=>{const k=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!k){se.error("Command name is required");return}if(!w.trim()){se.error("Command template is required");return}if(d&&o.some(A=>A.name===k)){se.error("A command with this name already exists");return}M(!0);try{const A=g.trim(),P=x.trim(),L=w.trim(),U={name:k,description:h.trim()||void 0,agent:A===""?null:A,model:P===""?null:P,template:L,subtask:v,scope:d?f:void 0};let z;d?(z=await t(U),z&&i(null)):z=await n(k,U),z?se.success(d?"Command created successfully":"Command updated successfully"):se.error(d?"Failed to create command":"Failed to update command")}catch(A){console.error("Error saving command:",A),se.error("An error occurred while saving")}finally{M(!1)}};return s?e.jsx(ct,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Command":`/${s}`})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure command identity and metadata"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Command Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"/"}),e.jsx(mt,{value:u,onChange:k=>m(k.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(ks,{value:f,onValueChange:k=>p(k),children:[e.jsxs(Ns,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Ss,{className:"h-4 w-4"}):e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Cs,{align:"end",children:[e.jsx(qt,{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(Ss,{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(qt,{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(fr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(js,{value:h,onChange:k=>j(k.target.value),placeholder:"What does this command do?",rows:3})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model & Agent Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and agent for command execution"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(Om,{agentName:g,onChange:k=>b(k)}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Agent to execute this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(cl,{providerId:x?x.split("/")[0]:"",modelId:x?x.split("/")[1]:"",onChange:(k,A)=>{y(k&&A?`${k}/${A}`:"")}}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default model for this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:k=>N(k.target.checked),className:"sr-only"}),e.jsx("div",{className:R("w-5 h-5 rounded border-2 flex items-center justify-center",v?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:v&&e.jsx(Ot,{className:"w-3 h-3 text-primary-foreground"})})]}),"Force Subagent Invocation"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Force command to run in a subagent context"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["When enabled, this command will always execute in a subagent context,",e.jsx("br",{}),"even if triggered from main agent.",e.jsx("br",{}),"Useful for isolating command logic and maintaining clean separation of concerns."]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Command Template"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Define the prompt template for this command. Use $ARGUMENTS for user input."})]}),e.jsx(js,{value:w,onChange:k=>S(k.target.value),placeholder:`Your command template here...
|
|
102
|
+
|
|
103
|
+
Use $ARGUMENTS to reference user input.
|
|
104
|
+
Use !\`shell command\` to inject shell output.
|
|
105
|
+
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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{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(ke,{size:"sm",variant:"default",onClick:C,disabled:D,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ea,{className:"h-3 w-3"}),D?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Sr,{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"})]})})},ej=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedSkillName:a,skills:i,setSelectedSkill:l,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=Ks(),{setSidebarOpen:h}=Re(),{isMobile:j}=$t(),[g,b]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||b(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const y=g?"bg-transparent":x?"bg-background":"bg-sidebar",w=()=>{const k="new-skill";let A=k,P=1;for(;i.some(L=>L.name===A);)A=`${k}-${P}`,P++;d({name:A,scope:"user",description:""}),l(A),s?.(),j&&h(!1)},S=async k=>{window.confirm(`Are you sure you want to delete skill "${k.name}"?`)&&(await m(k.name)?se.success(`Skill "${k.name}" deleted successfully`):se.error("Failed to delete skill"))},v=async k=>{const A=k.name;let P=1,L=`${A}-copy`;for(;i.some(z=>z.name===L);)P++,L=`${A}-copy-${P}`;const U=await p(k.name);if(!U){se.error("Failed to load skill details for duplication");return}d({name:L,scope:k.scope||"user",description:(U.sources.md.fields.includes("description"),""),instructions:""}),l(L),j&&h(!1)},N=k=>{o(k.name),t(k)},D=async()=>{if(!r)return;const k=n.trim().replace(/\s+/g,"-").toLowerCase();if(!k){se.error("Skill name is required");return}if(k===r.name){t(null);return}if(i.some(L=>L.name===k)){se.error("A skill with this name already exists");return}if(!await p(r.name)){se.error("Failed to load skill details"),t(null);return}await u({name:k,description:"Renamed skill",scope:r.scope})?await m(r.name)?(se.success(`Skill renamed to "${k}"`),l(k)):se.error("Failed to remove old skill after rename"):se.error("Failed to rename skill"),t(null)},M=i.filter(k=>k.scope==="project"),C=i.filter(k=>k.scope==="user");return e.jsxs("div",{className:R("flex h-full flex-col",y),children:[e.jsx("div",{className:R("border-b px-3",j?"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 ",i.length]}),e.jsx(ke,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(_t,{className:"size-4"})})]})}),e.jsx(ct,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:i.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Yd,{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:[M.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"}),M.map(k=>e.jsx(ud,{skill:k,isSelected:a===k.name,onSelect:()=>{l(k.name),s?.(),j&&h(!1)},onRename:()=>N(k),onDelete:()=>S(k),onDuplicate:()=>v(k)},k.name))]}),C.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"}),C.map(k=>e.jsx(ud,{skill:k,isSelected:a===k.name,onSelect:()=>{l(k.name),s?.(),j&&h(!1)},onRename:()=>N(k),onDelete:()=>S(k),onDuplicate:()=>v(k)},k.name))]})]})}),e.jsx(ds,{open:r!==null,onOpenChange:k=>!k&&t(null),children:e.jsxs(us,{children:[e.jsxs(fs,{children:[e.jsx(ps,{children:"Rename Skill"}),e.jsxs(ys,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(mt,{value:n,onChange:k=>o(k.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:k=>{k.key==="Enter"&&D()}}),e.jsxs(Ws,{children:[e.jsx(ke,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Or,{onClick:D,children:"Rename"})]})]})})]})},ud=({skill:s,isSelected:r,onSelect:t,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsx("button",{onClick: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(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx(ke,{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(kr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Xt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(jt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(Zo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(jt,{onClick:i=>{i.stopPropagation(),a()},children:[e.jsx(Bs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(jt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function $m({tabs:s,value:r,onValueChange:t,className:n,isInteractive:o=!0,animate:a=!0}){const i=c.useRef(null),l=c.useRef(null),d=c.useCallback(()=>{const u=i.current,m=l.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:h}=m,j=Math.max(0,Math.min(100,p/f*100)),g=Math.max(0,Math.min(100,(p+h)/f*100));u.style.clipPath=`inset(0 ${Number(100-g).toFixed(2)}% 0 ${Number(j).toFixed(2)}% round 8px)`},[]);return c.useLayoutEffect(()=>{d()},[d,r,s.length]),c.useEffect(()=>{const u=i.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:R("relative isolate w-full",n),children:[e.jsx("div",{ref:i,"aria-hidden":!0,className:R("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:"flex h-9 items-center gap-1 rounded-lg bg-accent px-1.5 text-accent-foreground",children: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?l:null,type:"button",onClick:()=>{o&&t(u.value)},className:R("flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold transition-colors duration-150",m?"text-accent-foreground":"text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1 focus-visible:ring-offset-background"),"aria-pressed":m,"aria-disabled":!o,tabIndex:o?0:-1,children:[f?e.jsx(f,{className:R("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const tj=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,sj=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},rj=async()=>{try{if(ss())return await wn();const s=_r()?.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}},nj=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=Kn(),[a,i]=c.useState(""),[l,d]=c.useState(""),[u,m]=c.useState(""),[f,p]=c.useState([]),[h,j]=c.useState(null),[g,b]=c.useState(!1),[x,y]=c.useState([]),[w,S]=c.useState(null);c.useEffect(()=>{s&&(i(""),d(""),m(""),j(null),b(!1),y([]),S(null),(async()=>{const M=await rj(),C=Array.isArray(M?.skillCatalogs)?M?.skillCatalogs:[];p(C||[])})())},[s]);const v=c.useMemo(()=>{const M=l.trim(),C=u.trim();return f.some(k=>{const A=(k.source||"").trim(),P=(k.subpath||"").trim();return A===M&&P===C})},[f,l,u]),N=async()=>{const M=l.trim();if(!M){se.error("Repository source is required");return}a.trim()||i(sj(M)),b(!1),j(null);const C=await t({source:M,subpath:u.trim()||void 0,gitIdentityId:w||void 0});if(!C.ok){if(C.error?.kind==="authRequired"){if(Ht()){se.error("Private repositories are not supported in VS Code yet");return}const A=C.error.identities||[];y(A),!w&&A.length>0&&S(A[0].id),se.error("Authentication required. Select a Git identity and scan again.");return}se.error(C.error?.message||"Failed to scan repository");return}const k=C.items?.length||0;if(j(k),k===0){se.error("No skills found in this repository"),b(!1);return}y([]),b(!0),se.success(`Found ${k} skill(s)`)},D=async()=>{const M=a.trim(),C=l.trim(),k=u.trim();if(!M){se.error("Catalog name is required");return}if(!C){se.error("Repository source is required");return}if(!g){se.error("Scan the repository before adding this catalog");return}if(v){se.error("This catalog already exists");return}const A={id:tj(),label:M,source:C,...k?{subpath:k}:{},...w?{gitIdentityId:w}:{}},P=[...f,A];try{await os({skillCatalogs:P}),p(P),se.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(L){se.error(L instanceof Error?L.message:"Failed to save catalog")}};return e.jsx(ds,{open:s,onOpenChange:r,children:e.jsxs(us,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(fs,{children:[e.jsx(ps,{children:"Add skills catalog"}),e.jsxs(ys,{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(mt,{value:a,onChange:M=>i(M.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(mt,{value:l,onChange:M=>{d(M.target.value),b(!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(mt,{value:u,onChange:M=>{m(M.target.value),b(!1),j(null)},placeholder:"e.g. skills"})]}),x.length>0&&!Ht()?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:w||"",onValueChange:M=>S(M),children:[e.jsx(Ns,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:x.find(M=>M.id===w)?.name||"Choose identity"})}),e.jsx(Cs,{align:"start",children:x.map(M=>e.jsx(qt,{value:M.id,className:"pr-2 [&>span:first-child]:hidden",children:M.name},M.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,v?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Ws,{children:[e.jsx(ke,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(ke,{variant:"outline",onClick:()=>{N()},disabled:o||!l.trim(),className:"gap-2",children:[e.jsx(Gp,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(ke,{variant:"default",onClick:()=>{D()},disabled:!g||v||!a.trim()||!l.trim(),children:"Add catalog"})]})]})})},oj=({open:s,onOpenChange:r,conflicts:t,onConfirm:n})=>{const[o,a]=c.useState({});c.useEffect(()=>{if(!s)return;const d={};for(const u of t)d[u.skillName]="skip";a(d)},[s,t]);const i=d=>{const u={};for(const m of t)u[m.skillName]=d;a(u)},l=t.length>0&&t.every(d=>o[d.skillName]);return e.jsx(ds,{open:s,onOpenChange:r,children:e.jsxs(us,{className:"max-w-2xl",children:[e.jsxs(fs,{children:[e.jsx(ps,{children:"Skills already exist"}),e.jsx(ys,{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(ke,{variant:"outline",size:"sm",onClick:()=>i("skip"),children:"Skip all"}),e.jsx(ke,{variant:"outline",size:"sm",onClick:()=>i("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(qt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(qt,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Ws,{children:[e.jsx(ke,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Or,{onClick:()=>n(o),disabled:!l,children:"Continue"})]})]})})},aj=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=Kn(),[a,i]=c.useState("user"),[l,d]=c.useState(!1),[u,m]=c.useState([]),[f,p]=c.useState(null);c.useEffect(()=>{s&&(i("user"),d(!1),m([]),p(null))},[s]);const h=async j=>{const g=await n({source:j.source,subpath:j.subpath,gitIdentityId:t?.gitIdentityId,scope:j.scope,selections:[{skillDir:j.skillDir}],conflictPolicy:"prompt",conflictDecisions:j.conflictDecisions});if(g.ok){se.success("Skill installed successfully"),r(!1);return}if(g.error?.kind==="conflicts"){p({source:j.source,subpath:j.subpath,scope:j.scope,skillDir:j.skillDir}),m(g.error.conflicts),d(!0);return}if(g.error?.kind==="authRequired"){se.error(g.error.message||"Authentication required");return}se.error(g.error?.message||"Failed to install skill")};return t?e.jsxs(e.Fragment,{children:[e.jsx(ds,{open:s,onOpenChange:r,children:e.jsxs(us,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(fs,{children:[e.jsx(ps,{children:"Install skill"}),e.jsxs(ys,{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(j=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:j},j))})]}):null}),e.jsxs(Ws,{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:j=>i(j),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(Ss,{className:"h-4 w-4"}):e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Cs,{align:"start",children:[e.jsx(qt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ss,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(qt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fr,{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(ke,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(ke,{className:"w-full sm:w-auto",variant:"default",disabled:o||!t.installable,onClick:()=>{h({source:t.repoSource,subpath:t.repoSubpath,scope:a,skillDir:t.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(oj,{open:l,onOpenChange:d,conflicts:u,onConfirm:j=>{f&&(h({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:j}),d(!1))}})]}):null},ij=async()=>{try{if(ss())return await wn();const s=_r()?.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}},lj=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:i,isLoadingCatalog:l,lastCatalogError:d}=Kn(),[u,m]=c.useState(""),[f,p]=c.useState(!1),[h,j]=c.useState(!1),[g,b]=c.useState(null),[x,y]=c.useState(!1);c.useEffect(()=>{i()},[i]);const w=c.useMemo(()=>o?n[o]||[]:[],[n,o]),S=c.useMemo(()=>{const M=u.trim().toLowerCase();return M?w.filter(C=>{const k=C.skillName.toLowerCase(),A=(C.description||"").toLowerCase(),P=(C.frontmatterName||"").toLowerCase();return k.includes(M)||A.includes(M)||P.includes(M)}):w},[w,u]),v=c.useMemo(()=>t.find(M=>M.id===o)||null,[t,o]),N=!!(o&&o.startsWith("custom:")),D=async()=>{if(!(!o||!N)&&window.confirm("Remove this catalog?")){y(!0);try{const M=await ij(),k=(Array.isArray(M?.skillCatalogs)?M?.skillCatalogs:[]).filter(A=>A.id!==o);await os({skillCatalogs:k}),await i({refresh:!0})}finally{y(!1)}}};return e.jsx(ct,{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($m,{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:M=>a(M),children:[e.jsx(Ns,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:v?.label||"Select source"})}),e.jsx(Cs,{align:"start",children:t.map(M=>e.jsx(qt,{value:M.id,className:"pr-2 [&>span:first-child]:hidden",children:M.label},M.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ke,{type:"button",variant:"outline",onClick:()=>{i({refresh:!0})},disabled:l,className:"gap-2",children:[e.jsx(qn,{className:"h-4 w-4"}),"Refresh"]}),N?e.jsxs(ke,{type:"button",variant:"outline",onClick:()=>{D()},disabled:x,className:"gap-2",children:[e.jsx(zs,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(ke,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(_t,{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(mt,{value:u,onChange:M=>m(M.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:l?"Loading…":`${S.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:S.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"})]}):S.map(M=>{const C=M.installed?.isInstalled,k=M.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:M.skillName}),C?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 (",k||"unknown",")"]}):null,M.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"})]}),M.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:M.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),M.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:M.warnings.join(" · ")}):null]}),e.jsx(ke,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!M.installable,onClick:()=>{b(M),j(!0)},children:"Install"})]})},`${M.sourceId}:${M.skillDir}`)})}),e.jsx(nj,{open:f,onOpenChange:p}),e.jsx(aj,{open:h,onOpenChange:j,item:g})]})})},cj=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:i,setSkillDraft:l,setSelectedSkill:d}=Ks(),u=s?r(s):null,m=!!(i&&i.name===s&&!u),f=!!(s&&!u&&!i),[p,h]=c.useState("manual");c.useEffect(()=>{!m&&p!=="manual"&&h("manual")},[m,p]),c.useEffect(()=>{f&&d(null)},[f,d]);const j=m?e.jsx($m,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[g,b]=c.useState(""),[x,y]=c.useState("user"),[w,S]=c.useState(""),[v,N]=c.useState(""),[D,M]=c.useState([]),[C,k]=c.useState([]),[A,P]=c.useState(!1),[L,U]=c.useState(!1),[z,H]=c.useState(""),[V,J]=c.useState(""),[T,Z]=c.useState(!1),[E,B]=c.useState(""),[X,re]=c.useState(""),[q,oe]=c.useState(null),[ye,I]=c.useState(!1),[F,W]=c.useState(""),O=m?g.trim()!==""||w.trim()!==""||v.trim()!==""||C.length>0:w!==z||v!==V,_=q?X!==F:E.trim()!=="";c.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&i)b(i.name||""),y(i.scope||"user"),S(i.description||""),N(i.instructions||""),H(""),J(""),M([]),k(i.pendingFiles||[]);else if(s&&u){U(!0);try{const le=await t(s);if(le){const te=le.sources.md;S(te.description||""),N(te.instructions||""),H(te.description||""),J(te.instructions||""),M(te.supportingFiles||[])}}catch(le){console.error("Failed to load skill details:",le)}finally{U(!1)}}})()},[u,m,s,a,i,t,p]);const ee=async()=>{const Y=m?g.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!Y){se.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(Y)||Y.length>64){se.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!w.trim()){se.error("Description is required");return}if(m&&a.some(le=>le.name===Y)){se.error("A skill with this name already exists");return}P(!0);try{const le={name:Y,description:w.trim(),instructions:v.trim()||void 0,scope:m?x:void 0,supportingFiles:m&&C.length>0?C:void 0};let te;m?(te=await n(le),te&&(l(null),k([]),d(Y))):(te=await o(Y,le),te&&(H(w.trim()),J(v.trim()))),te?se.success(m?"Skill created successfully":"Skill updated successfully"):se.error(m?"Failed to create skill":"Failed to update skill")}catch(le){console.error("Error saving skill:",le),se.error("An error occurred while saving")}finally{P(!1)}},ue=()=>{oe(null),B(""),re(""),W(""),Z(!0)},me=async Y=>{if(oe(Y),B(Y),m){const te=C.find(ne=>ne.path===Y)?.content||"";re(te),W(te),Z(!0);return}if(s){I(!0),Z(!0);try{const{readSupportingFile:le}=Ks.getState(),te=await le(s,Y);re(te||""),W(te||"")}catch{se.error("Failed to load file content"),re(""),W("")}finally{I(!1)}}},pe=async()=>{if(!E.trim()){se.error("File name is required");return}const Y=E.trim(),le=q!==null;if(m){if(le)k(K=>K.map(ie=>ie.path===q?{path:Y,content:X}:ie)),se.success(`File "${Y}" updated`);else{if(C.some(K=>K.path===Y)){se.error("A file with this name already exists");return}k(K=>[...K,{path:Y,content:X}]),se.success(`File "${Y}" added`)}Z(!1),oe(null);return}if(!s){se.error("No skill selected");return}const{writeSupportingFile:te}=Ks.getState();if(await te(s,Y,X)){se.success(le?`File "${Y}" updated`:`File "${Y}" created`),Z(!1),oe(null);const K=await t(s);K&&M(K.sources.md.supportingFiles||[])}else se.error(le?"Failed to update file":"Failed to create file")},He=async Y=>{if(m){k(le=>le.filter(te=>te.path!==Y)),se.success(`File "${Y}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${Y}"?`)){const{deleteSupportingFile:le}=Ks.getState();if(await le(s,Y)){se.success(`File "${Y}" deleted`);const ne=await t(s);ne&&M(ne.sources.md.supportingFiles||[])}else se.error("Failed to delete file")}};return m&&p==="external"?e.jsx(lj,{mode:p,onModeChange:h}):!s&&!i||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(Yd,{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"})]})}):L?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(ct,{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?j: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(mt,{value:g,onChange:Y=>b(Y.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(ks,{value:x,onValueChange:Y=>y(Y),children:[e.jsxs(Ns,{className:"!h-9 w-auto gap-1.5",children:[x==="user"?e.jsx(Ss,{className:"h-4 w-4"}):e.jsx(fr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:x})]}),e.jsxs(Cs,{align:"end",children:[e.jsx(qt,{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(Ss,{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(qt,{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(fr,{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(js,{value:w,onChange:Y=>S(Y.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(js,{value:v,onChange:Y=>N(Y.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(ke,{variant:"outline",size:"sm",onClick:ue,className:"gap-1.5",children:[e.jsx(_t,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const Y=m?C:D;return Y.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:Y.map(le=>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:()=>me(le.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Qs,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:le.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(ke,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:te=>{te.stopPropagation(),He(le.path)},children:e.jsx(zs,{className:"h-3.5 w-3.5"})})]},le.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(ke,{size:"sm",variant:"default",onClick:ee,disabled:A||!O,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ea,{className:"h-3 w-3"}),A?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(ds,{open:T,onOpenChange:Y=>{Z(Y),Y||oe(null)},children:e.jsxs(us,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(fs,{className:"flex-shrink-0",children:[e.jsx(ps,{children:q?"Edit Supporting File":"Add Supporting File"}),e.jsx(ys,{children:q?"Modify the file content":"Create a new file in the skill directory"})]}),ye?e.jsx("div",{className:"flex-1 flex items-center justify-center py-8",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Loading file content..."})}):e.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"File Path"}),e.jsx(mt,{value:E,onChange:Y=>B(Y.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:q!==null}),!q&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Relative path within the skill directory. Subdirectories will be created automatically."})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-h-0 flex flex-col",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:"Content"}),e.jsx(js,{value:X,onChange:Y=>re(Y.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Ws,{children:[e.jsx(ke,{variant:"ghost",onClick:()=>{Z(!1),oe(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Or,{onClick:pe,disabled:ye||!_,children:q?"Save Changes":"Create File"})]})]})})]})})},dj="__add_provider__",uj=({onItemSelect:s})=>{const r=at(u=>u.providers),t=at(u=>u.selectedProviderId),n=at(u=>u.setSelectedProvider),{isMobile:o}=$t(),[a,i]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||i(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",d),children:[e.jsx("div",{className:R("border-b px-3",o?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",r.length]}),e.jsx(ke,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(dj),s?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(_t,{className:"size-4"})})]})}),e.jsx(ct,{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(Ln,{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:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",f?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{type:"button",onClick:()=>{n(u.id),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(ts,{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)})})]})},mj=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),md=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=mj.format(s);return r.endsWith(".0")?r.slice(0,-2):r},fd="__add_provider__",gn=s=>typeof s=="object"&&s!==null,pd=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()},fj=s=>{if(!gn(s))return{};const r={};for(const[t,n]of Object.entries(s))Array.isArray(n)&&(r[t]=n.filter(o=>gn(o)));return r},pj=s=>{if(typeof s=="string")return{id:s};if(!gn(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}},hj=s=>{let r=[];Array.isArray(s)?r=s:gn(s)&&(Array.isArray(s.all)?r=s.all:Array.isArray(s.providers)&&(r=s.providers));const t=r.map(o=>pj(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},gj=()=>{const s=at(W=>W.providers),r=at(W=>W.selectedProviderId),t=at(W=>W.setSelectedProvider),n=at(W=>W.getModelMetadata),[o,a]=c.useState({}),[i,l]=c.useState(!1),[d,u]=c.useState({}),[m,f]=c.useState(null),[p,h]=c.useState(""),[j,g]=c.useState(null),[b,x]=c.useState({}),[y,w]=c.useState({}),[S,v]=c.useState([]),[N,D]=c.useState(!1),[M,C]=c.useState(null),[k,A]=c.useState(""),[P,L]=c.useState(""),[U,z]=c.useState(!1);c.useEffect(()=>{!r&&s.length>0&&t(s[0].id)},[s,r,t]),c.useEffect(()=>{let W=!0;return(async()=>{l(!0);try{const _=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!_.ok)throw new Error(`Auth methods request failed (${_.status})`);const ee=await _.json().catch(()=>({}));if(!W)return;a(fj(ee))}catch(_){if(!W)return;console.error("Failed to load provider auth methods:",_),se.error("Failed to load provider authentication methods")}finally{W&&l(!1)}})(),()=>{W=!1}},[]),c.useEffect(()=>{let W=!0;return(async()=>{D(!0),C(null);try{const _=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!_.ok)throw new Error(`Provider list request failed (${_.status})`);const ee=await _.json().catch(()=>({}));if(!W)return;v(hj(ee))}catch(_){if(!W)return;console.error("Failed to load available providers:",_),C("Unable to load provider list")}finally{W&&D(!1)}})(),()=>{W=!1}},[]);const H=c.useMemo(()=>new Set(s.map(W=>W.id)),[s]),V=c.useMemo(()=>S.filter(W=>!H.has(W.id)),[S,H]);c.useEffect(()=>{if(r===fd){if(!k&&V.length>0){A(V[0].id);return}k&&!V.some(W=>W.id===k)&&A(V[0]?.id??"")}},[r,k,V]);const J=s.find(W=>W.id===r),T=async W=>{const O=d[W]?.trim()??"";if(!O){se.error("API key is required");return}const _=`api:${W}`;f(_);try{const ee=await fetch(`/api/auth/${encodeURIComponent(W)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:O})}),ue=await ee.json().catch(()=>null);if(!ee.ok){const me=ue?.error||"Failed to save API key";throw new Error(me)}se.success("API key saved"),u(me=>({...me,[W]:""})),await Pn({scopes:["providers"],mode:"active"}),t(W)}catch(ee){console.error("Failed to save API key:",ee),se.error("Failed to save API key")}finally{f(null)}},Z=async(W,O)=>{const _=`oauth:${W}:${O}`;f(_);try{const ee=await fetch(`/api/provider/${encodeURIComponent(W)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:O})}),ue=await ee.json().catch(()=>null);if(!ee.ok){const ne=ue?.error||"Failed to start OAuth flow";throw new Error(ne)}const me=gn(ue)?ue:{},pe=gn(me.data)?me.data:me,He=typeof pe.url=="string"&&pe.url||typeof pe.verification_uri_complete=="string"&&pe.verification_uri_complete||typeof pe.verification_uri=="string"&&pe.verification_uri||void 0,Y=typeof pe.instructions=="string"&&pe.instructions||typeof pe.message=="string"&&pe.message||void 0,le=typeof pe.user_code=="string"&&pe.user_code||typeof pe.code=="string"&&pe.code||typeof pe.userCode=="string"&&pe.userCode||void 0;if(!He&&!Y&&!le)throw new Error("No OAuth details returned");const te=`${W}:${O}`;w(ne=>({...ne,[te]:{url:He,instructions:Y,userCode:le}})),He&&window.open(He,"_blank","noopener,noreferrer"),g({providerId:W,methodIndex:O}),se.message("Complete the OAuth flow in your browser")}catch(ee){console.error("Failed to start OAuth flow:",ee),se.error("Failed to start OAuth flow")}finally{f(null)}},E=async(W,O)=>{const _=`${W}:${O}`,ee=b[_]?.trim(),ue=`oauth-complete:${W}:${O}`;f(ue);try{const me={method:O};ee&&(me.code=ee);const pe=await fetch(`/api/provider/${encodeURIComponent(W)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(me)}),He=await pe.json().catch(()=>null);if(!pe.ok){const Y=He?.error||"Failed to complete OAuth flow";throw new Error(Y)}se.success("OAuth connection completed"),x(Y=>({...Y,[_]:""})),g(null),await Pn({scopes:["providers"],mode:"active"}),t(W)}catch(me){console.error("Failed to complete OAuth flow:",me),se.error("Failed to complete OAuth flow")}finally{f(null)}},B=async W=>{try{await navigator.clipboard.writeText(W),se.success("OAuth link copied")}catch(O){console.error("Failed to copy OAuth link:",O),se.error("Failed to copy OAuth link")}},X=async W=>{try{await navigator.clipboard.writeText(W),se.success("Device code copied")}catch(O){console.error("Failed to copy device code:",O),se.error("Failed to copy device code")}},re=async W=>{const O=`disconnect:${W}`;f(O);try{const _=await fetch(`/api/provider/${encodeURIComponent(W)}/auth`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),ee=await _.json().catch(()=>null);if(!_.ok){const ue=ee?.error||"Failed to disconnect provider";throw new Error(ue)}se.success("Provider disconnected"),await Pn({scopes:["providers"],mode:"active"})}catch(_){console.error("Failed to disconnect provider:",_),se.error("Failed to disconnect provider")}finally{f(null)}},q=r===fd;if(!q&&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(Ln,{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(q)return e.jsx(ct,{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."})]}),N?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):M?e.jsx("p",{className:"typography-meta text-muted-foreground",children:M}):V.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(Kt,{open:U,onOpenChange:W=>{z(W),W||L("")},children:[e.jsx(Yt,{asChild:!0,children:e.jsxs("button",{type:"button",className:R("flex w-fit items-center justify-between gap-2 rounded-lg border border-input bg-transparent px-3 py-2 typography-ui-label","hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[e.jsx("span",{className:k?"text-foreground":"text-muted-foreground",children:k?V.find(W=>W.id===k)?.name||k:"Select provider"}),e.jsx(Ct,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(Xt,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:W=>W.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:W=>W.stopPropagation(),children:[e.jsx(ur,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:P,onChange:W=>L(W.target.value),onKeyDown:W=>W.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(ct,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const W=V.filter(O=>{const _=P.toLowerCase();return(O.name||O.id).toLowerCase().includes(_)||O.id.toLowerCase().includes(_)});return W.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):W.map(O=>e.jsxs(jt,{onSelect:()=>{A(O.id),z(!1),L("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:O.name||O.id}),k===O.id&&e.jsx(Ot,{className:"h-4 w-4 text-primary"})]},O.id))})()})]})]})]}),k&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),i?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(mt,{type:"password",value:d[k]??"",onChange:W=>u(O=>({...O,[k]:W.target.value})),placeholder:"sk-..."}),e.jsx(ke,{size:"sm",onClick:()=>T(k),disabled:m===`api:${k}`,className:"h-8",children:m===`api:${k}`?"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 O=(o[k]??[]).filter(_=>pd(_)==="oauth");return O.length===0?null:e.jsx("div",{className:"space-y-3",children:O.map((_,ee)=>{const ue=_.label||_.name||`OAuth method ${ee+1}`,me=`${k}:${ee}`,pe=j?.providerId===k&&j?.methodIndex===ee;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:ue}),(_.description||_.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(_.description||_.help)})]}),e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>Z(k,ee),disabled:m===`oauth:${k}:${ee}`,className:"h-8",children:"Connect"})]}),y[me]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:y[me]?.instructions}),y[me]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(mt,{value:y[me]?.userCode,readOnly:!0}),e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>X(y[me]?.userCode??""),className:"h-8",children:"Copy code"})]}),y[me]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(mt,{value:y[me]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:y[me]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>B(y[me]?.url??""),className:"h-8",children:"Copy link"})]})]}),pe&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(mt,{value:b[me]??"",onChange:He=>x(Y=>({...Y,[me]:He.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(ke,{size:"sm",onClick:()=>E(k,ee),disabled:m===`oauth-complete:${k}:${ee}`,className:"h-8",children:m===`oauth-complete:${k}:${ee}`?"Saving…":"Complete"})]})]},`${k}-${ue}`)})})})()]})]})]})});if(!J)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(Ln,{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 oe=Array.isArray(J.models)?J.models:[],I=(o[J.id]??[]).filter(W=>pd(W)==="oauth"),F=oe.filter(W=>{const O=typeof W?.name=="string"?W.name:"",_=typeof W?.id=="string"?W.id:"",ee=p.trim().toLowerCase();return ee?O.toLowerCase().includes(ee)||_.toLowerCase().includes(ee):!0});return e.jsx(ct,{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(ts,{providerId:J.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:J.name||J.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",J.id]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),i?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(mt,{type:"password",value:d[J.id]??"",onChange:W=>u(O=>({...O,[J.id]:W.target.value})),placeholder:"sk-..."}),e.jsx(ke,{size:"sm",onClick:()=>T(J.id),disabled:m===`api:${J.id}`,className:"h-8",children:m===`api:${J.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(ke,{size:"sm",variant:"outline",onClick:()=>re(J.id),disabled:m===`disconnect:${J.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${J.id}`?"Disconnecting…":"Disconnect provider"})}),I.length>0&&e.jsx("div",{className:"space-y-3",children:I.map((W,O)=>{const _=W.label||W.name||`OAuth method ${O+1}`,ee=`${J.id}:${O}`,ue=j?.providerId===J.id&&j?.methodIndex===O;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:_}),(W.description||W.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(W.description||W.help)})]}),e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>Z(J.id,O),disabled:m===`oauth:${J.id}:${O}`,className:"h-8",children:"Connect"})]}),y[ee]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:y[ee]?.instructions}),y[ee]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(mt,{value:y[ee]?.userCode,readOnly:!0}),e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>X(y[ee]?.userCode??""),className:"h-8",children:"Copy code"})]}),y[ee]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(mt,{value:y[ee]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:y[ee]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>B(y[ee]?.url??""),className:"h-8",children:"Copy link"})]})]}),ue&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(mt,{value:b[ee]??"",onChange:me=>x(pe=>({...pe,[ee]:me.target.value})),placeholder:"Paste authorization code"}),e.jsx(ke,{size:"sm",onClick:()=>E(J.id,O),disabled:m===`oauth-complete:${J.id}:${O}`,className:"h-8",children:m===`oauth-complete:${J.id}:${O}`?"Saving…":"Complete"})]})]},`${J.id}-${_}`)})})]})]}),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(mt,{value:p,onChange:W=>h(W.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:F.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):F.map(W=>{const O=typeof W?.id=="string"?W.id:"",_=typeof W?.name=="string"?W.name:O,ee=O?n(J.id,O):void 0,ue=md(ee?.limit?.context),me=md(ee?.limit?.output),pe=[];return ee?.tool_call&&pe.push({key:"tools",icon:Jo,label:"Tool calling"}),ee?.reasoning&&pe.push({key:"reasoning",icon:xn,label:"Reasoning"}),ee?.attachment&&pe.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:_}),(ue||me)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[ue?`${ue} ctx`:"",ue&&me?" · ":"",me?`${me} out`:""]}),pe.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:pe.map(({key:He,icon:Y,label:le})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:le,"aria-label":le,children:e.jsx(Y,{className:"h-3 w-3"})},He))})]},O)})})]})]})})},yj={branch:Ft,briefcase:Fi,house:Ti,graduation:Pi,code:er,heart:Vd},xj={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},bj=({onItemSelect:s})=>{const{selectedProfileId:r,profiles:t,globalIdentity:n,setSelectedProfile:o,deleteProfile:a,loadProfiles:i,loadGlobalIdentity:l}=ca(),{setSidebarOpen:d}=Re(),{isMobile:u}=$t(),[m,f]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),p=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||f(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{i(),l()},[i,l]);const h=m?"bg-transparent":p?"bg-background":"bg-sidebar",j=()=>{o("new"),s?.(),u&&d(!1)},g=async b=>{window.confirm(`Are you sure you want to delete profile "${b.name}"?`)&&(await a(b.id)?se.success(`Profile "${b.name}" deleted successfully`):se.error("Failed to delete profile"))};return e.jsxs("div",{className:R("flex h-full flex-col",h),children:[e.jsx("div",{className:R("border-b px-3",u?"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 ",t.length]}),e.jsx(ke,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:j,children:e.jsx(_t,{className:"size-4"})})]})}),e.jsxs(ct,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[n&&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(hd,{profile:n,isSelected:r==="global",onSelect:()=>{o("global"),s?.(),u&&d(!1)},onDelete:void 0,isReadOnly:!0})]}),t.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"}),t.length===0&&!n?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ft,{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:t.map(b=>e.jsx(hd,{profile:b,isSelected:r===b.id,onSelect:()=>{o(b.id),s?.(),u&&d(!1)},onDelete:()=>g(b)},b.id))})]})]})},hd=({profile:s,isSelected:r,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=yj[s.icon||"branch"]||Ft,i=xj[s.color||""];return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick: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-2",children:[e.jsx(a,{className:"w-4 h-4 flex-shrink-0",style:{color:i}}),e.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 text-foreground",children:s.name})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.userEmail})]}),!o&&n&&e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx(ke,{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(kr,{className:"h-3.5 w-3.5"})})}),e.jsx(Xt,{align:"end",className:"w-fit min-w-20",children:e.jsxs(jt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})},gd=[{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)"}],wj=[{key:"branch",Icon:Ft,label:"Branch"},{key:"briefcase",Icon:Fi,label:"Work"},{key:"house",Icon:Ti,label:"Personal"},{key:"graduation",Icon:Pi,label:"School"},{key:"code",Icon:er,label:"Code"}],vj=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=ca(),a=c.useMemo(()=>s&&s!=="new"?r(s):null,[s,r]),i=s==="new",l=s==="global",[d,u]=c.useState(""),[m,f]=c.useState(""),[p,h]=c.useState(""),[j,g]=c.useState(""),[b,x]=c.useState("keyword"),[y,w]=c.useState("branch"),[S,v]=c.useState(!1);c.useEffect(()=>{i?(u(""),f(""),h(""),g(""),x("keyword"),w("branch")):a&&(u(a.name),f(a.userName),h(a.userEmail),g(a.sshKey||""),x(a.color||"keyword"),w(a.icon||"branch"))},[a,i,s]);const N=async()=>{if(!m.trim()||!p.trim()){se.error("User name and email are required");return}v(!0);try{const C={name:d.trim()||m.trim(),userName:m.trim(),userEmail:p.trim(),sshKey:j.trim()||null,color:b,icon:y};let k;if(i)k=await t(C);else if(s)k=await n(s,C);else return;k?se.success(i?"Profile created successfully":"Profile updated successfully"):se.error(i?"Failed to create profile":"Failed to update profile")}catch(C){console.error("Error saving profile:",C),se.error("An error occurred while saving")}finally{v(!1)}},D=async()=>{if(!(!s||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(s)?se.success("Profile deleted successfully"):se.error("Failed to delete profile")}catch(C){console.error("Error deleting profile:",C),se.error("An error occurred while deleting")}},M=c.useMemo(()=>gd.find(k=>k.key===b)?.cssVar||"var(--syntax-keyword)",[b]);return s?e.jsx(ct,{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:i?"New Git Profile":l?"Global Identity":d||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:i?"Create a new Git identity profile for your repositories":l?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!l&&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(mt,{value:d,onChange:C=>u(C.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:gd.map(C=>e.jsx("button",{onClick:()=>x(C.key),className:R("w-8 h-8 rounded-lg border-2 transition-all",b===C.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:C.cssVar},title:C.label},C.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:wj.map(C=>{const k=C.Icon;return e.jsx("button",{onClick:()=>w(C.key),className:R("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",y===C.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:C.label,children:e.jsx(k,{className:"w-4 h-4",style:{color:M}})},C.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 ",!l&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{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(mt,{value:m,onChange:C=>f(C.target.value),placeholder:"John Doe",required:!l,readOnly:l,disabled:l}),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 ",!l&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{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(mt,{type:"email",value:p,onChange:C=>h(C.target.value),placeholder:"john@example.com",required:!l,readOnly:l,disabled:l}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email 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:["SSH Key Path",e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{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 HTTPS and SSH Git operations.",e.jsx("br",{}),"Common paths: ~/.ssh/id_rsa, ~/.ssh/id_ed25519"]})]})]}),e.jsx(mt,{value:j,onChange:C=>g(C.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:l,disabled:l}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),!l&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!i&&e.jsxs(ke,{size:"sm",variant:"destructive",onClick:D,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(zs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:R("flex gap-2",i&&"ml-auto"),children:e.jsxs(ke,{size:"sm",variant:"default",onClick:N,disabled:S,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(ea,{className:"h-3 w-3"}),S?"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(Ss,{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 Va(s,r,t){return Math.min(t,Math.max(r,s))}const Go=Me.forwardRef(({value:s,onValueChange:r,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:i,onBlur:l,onKeyDown:d,disabled:u,...m},f)=>{const p=Me.useRef(null);Me.useImperativeHandle(f,()=>p.current);const[h,j]=Me.useState(()=>String(s));Me.useEffect(()=>{document.activeElement!==p.current&&j(String(s))},[s]);const g=Me.useCallback(()=>{p.current?.focus()},[]),b=Me.useCallback(k=>{const A=Va(k,t,n);r(A),j(String(A))},[n,t,r]),x=Me.useCallback(()=>{const k=Number(h);return Number.isFinite(k)?k:s},[h,s]),y=Me.useCallback(()=>{b(x()+o),g()},[b,x,g,o]),w=Me.useCallback(()=>{b(x()-o),g()},[b,x,g,o]),S=k=>{const A=k.target.value;j(A);const P=Number(A);Number.isFinite(P)&&r(Va(P,t,n))},v=k=>{const A=Number(h);if(!Number.isFinite(A))j(String(s));else{const P=Va(A,t,n);P!==A&&r(P),j(String(P))}l?.(k)},N=k=>{if(k.key==="ArrowUp"){k.preventDefault(),y();return}if(k.key==="ArrowDown"){k.preventDefault(),w();return}d?.(k)},D=x(),M=u||D<=t,C=u||D>=n;return e.jsxs("div",{className:R("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",i),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:h,onChange:S,onBlur:v,onKeyDown:N,disabled:u,className:R("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:C,onClick:y,className:R("flex flex-1 items-center justify-center","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(Xo,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:M,onClick:w,className:R("flex flex-1 items-center justify-center border-t border-border","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(Ct,{className:"h-3.5 w-3.5"})})]})]})});Go.displayName="NumberInput";const jj=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],yd=[{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"}],xd=[{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."}],dl=({visibleSettings:s})=>{const{isMobile:r}=$t(),t=Re(w=>w.showReasoningTraces),n=Re(w=>w.setShowReasoningTraces),o=Re(w=>w.toolCallExpansion),a=Re(w=>w.setToolCallExpansion),i=Re(w=>w.fontSize),l=Re(w=>w.setFontSize),d=Re(w=>w.padding),u=Re(w=>w.setPadding),m=Re(w=>w.inputBarOffset),f=Re(w=>w.setInputBarOffset),p=Re(w=>w.diffLayoutPreference),h=Re(w=>w.setDiffLayoutPreference),j=qs(w=>w.queueModeEnabled),g=qs(w=>w.setQueueMode),{themeMode:b,setThemeMode:x}=Ur(),y=w=>s?s.includes(w):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[y("theme")&&!Ht()&&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:jj.map(w=>e.jsx(Rs,{variant:b===w.value?"default":"outline",className:R(b===w.value?void 0:"text-foreground"),onClick:()=>x(w.value),children:w.label},w.value))})]}),y("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:i,onChange:w=>l(Number(w.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(Go,{value:i,onValueChange:l,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Rs,{type:"button",variant:"ghost",onClick:()=>l(100),disabled:i===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(ws,{className:"h-3.5 w-3.5"})})]})]}),y("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:w=>u(Number(w.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Spacing percentage"}),e.jsx("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:d}),e.jsx(Rs,{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(ws,{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:w=>u(Number(w.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(Go,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Rs,{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(ws,{className:"h-3.5 w-3.5"})})]})]}),y("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:w=>f(Number(w.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Input bar offset in pixels"}),e.jsxs("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:[m,"px"]}),e.jsx(Rs,{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(ws,{className:"h-3.5 w-3.5"})})]})]}),y("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:yd.find(w=>w.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:yd.map(w=>e.jsx(Rs,{variant:o===w.value?"default":"outline",className:R(o===w.value?void 0:"text-foreground"),onClick:()=>a(w.value),children:w.label},w.value))})]}),y("diffLayout")&&!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:"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:xd.map(w=>e.jsx(Rs,{variant:p===w.id?"default":"outline",className:R(p===w.id?void 0:"text-foreground"),onClick:()=>h(w.id),children:w.label},w.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:xd.find(w=>w.id===p)?.description})]})]}),y("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:w=>n(w.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),y("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:w=>g(w.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Queue messages by default"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5",children:j?`Enter queues messages, ${Gt()}+Enter sends immediately.`:`Enter sends immediately, ${Gt()}+Enter queues messages.`})]})]})},bd="https://github.com/btriapitsyn/openchamber",Sj=800,Lm=()=>{const[s,r]=c.useState(!1),[t,n]=c.useState(!1),o=ta(),{isMobile:a}=$t(),i=o.info?.currentVersion||"unknown",l=c.useRef(!1);c.useEffect(()=>{if(o.checking)n(!0),l.current=!0;else if(t){const u=setTimeout(()=>{n(!1),l.current&&!o.available&&!o.error&&(se.success("You are on the latest version"),l.current=!1)},Sj);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:()=>Pn(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(ws,{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",i]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:R("typography-meta text-muted-foreground/60 hover:text-muted-foreground disabled:cursor-default",d&&"animate-pulse [animation-duration:1s]"),children:"Check updates"}),!d&&o.available&&e.jsxs("button",{onClick:()=>r(!0),className:"flex items-center gap-1 typography-meta text-primary hover:underline",children:[e.jsx(dn,{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:bd,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(oi,{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(Xd,{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(ai,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(fi,{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:i})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(xo,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Checking..."})]}),!o.checking&&o.available&&e.jsxs("button",{onClick:()=>r(!0),className:R("flex items-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(dn,{className:"h-4 w-4"}),"Update to ",o.info?.version]}),!o.checking&&!o.available&&!o.error&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"})]}),o.error&&e.jsx("p",{className:"typography-meta text-destructive",children:o.error}),e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:o.checking,className:R("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:"Check for updates"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("a",{href:bd,target:"_blank",rel:"noopener noreferrer",className:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(oi,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(ai,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(fi,{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})]})},kj=1440*60*1e3,_m=5,wd=1440*60*1e3,Ga=s=>s.time?.updated??s.time?.created??0,vd=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=_m,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*kj,i=[...s].sort((d,u)=>Ga(u)-Ga(d)),l=new Set(i.slice(0,n).map(d=>d.id));return i.filter(d=>{if(!d?.id||l.has(d.id)||d.id===r||d.share)return!1;const u=Ga(d);return u?u<a:!1}).map(d=>d.id)},Bm=s=>{const r=s?.autoRun!==!1,t=de(g=>g.sessions),n=de(g=>g.currentSessionId),o=de(g=>g.isLoading),a=de(g=>g.deleteSessions),i=Re(g=>g.autoDeleteEnabled),l=Re(g=>g.autoDeleteAfterDays),d=Re(g=>g.autoDeleteLastRunAt),u=Re(g=>g.setAutoDeleteLastRunAt),[m,f]=c.useState(!1),p=c.useRef(!1),h=c.useMemo(()=>l<=0?[]:vd({sessions:t,currentSessionId:n,cutoffDays:l}),[l,n,t]),j=c.useCallback(async({force:g=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!i||l<=0)&&!g)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const b=Date.now();if(!g&&d&&b-d<wd)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const x=vd({sessions:t,currentSessionId:n,cutoffDays:l,now:b});if(x.length===0)return u(b),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(x,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[l,i,d,n,a,o,t,u]);return c.useEffect(()=>{if(!r||!i||l<=0||o||t.length===0)return;const g=Date.now();d&&g-d<wd||j()},[l,i,d,r,o,t.length,j]),{candidates:h,isRunning:m,runCleanup:j,keepRecentCount:_m}},qa=1,Ka=365,zm=()=>{const{isMobile:s}=$t(),r=Re(p=>p.autoDeleteEnabled),t=Re(p=>p.autoDeleteAfterDays),n=Re(p=>p.setAutoDeleteEnabled),o=Re(p=>p.setAutoDeleteAfterDays),[a,i]=c.useState(String(t));c.useEffect(()=>{i(String(t))},[t]);const{candidates:l,isRunning:d,runCleanup:u}=Bm({autoRun:!1}),m=l.length,f=c.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){se.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&se.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&se.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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{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 h=p.target.value;if(i(h),h.trim()==="")return;const j=Number(h);if(!Number.isFinite(j))return;const g=Math.min(Ka,Math.max(qa,Math.round(j)));o(g)},onBlur:()=>{if(a.trim()===""){i(String(t));return}const p=Number(a);if(!Number.isFinite(p)){i(String(t));return}const h=Math.min(Ka,Math.max(qa,Math.round(p)));o(h),i(String(h))},"aria-label":"Retention period in days",className:"h-8 w-16 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(Go,{value:t,onValueChange:o,min:qa,max:Ka,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(Rs,{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]})]})},Wm=()=>{const s=at(y=>y.setProvider),r=at(y=>y.setModel),t=at(y=>y.setAgent),n=at(y=>y.setSettingsDefaultModel),o=at(y=>y.setSettingsDefaultAgent),a=at(y=>y.settingsAutoCreateWorktree),i=at(y=>y.setSettingsAutoCreateWorktree),l=at(y=>y.providers),[d,u]=c.useState(),[m,f]=c.useState(),[p,h]=c.useState(!0),j=c.useMemo(()=>{if(!d)return{providerId:"",modelId:""};const y=d.split("/");return y.length!==2?{providerId:"",modelId:""}:{providerId:y[0]||"",modelId:y[1]||""}},[d]);c.useEffect(()=>{(async()=>{try{let w=null;if(ss())w=await wn();else{const S=_r()?.settings;if(S)try{const N=(await S.load())?.settings;N&&(w={defaultModel:typeof N.defaultModel=="string"?N.defaultModel:void 0,defaultAgent:typeof N.defaultAgent=="string"?N.defaultAgent:void 0})}catch{}if(!w){const v=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});v.ok&&(w=await v.json())}}w&&(u(w.defaultModel),f(w.defaultAgent))}catch(w){console.warn("Failed to load defaults settings:",w)}finally{h(!1)}})()},[]);const g=c.useCallback(async(y,w)=>{const S=y&&w?`${y}/${w}`:void 0;u(S),n(S),y&&w&&l.find(N=>N.id===y)&&(s(y),r(w));try{await os({defaultModel:S??""})}catch(v){console.warn("Failed to save default model:",v)}},[l,s,r,n]),b=c.useCallback(async y=>{const w=y||void 0;f(w),o(w),y&&t(y);try{await os({defaultAgent:w??""})}catch(S){console.warn("Failed to save default agent:",S)}},[t,o]),x=c.useCallback(async y=>{const w=y.target.checked;i(w);try{await os({autoCreateWorktree:w})}catch(S){console.warn("Failed to save auto create worktree setting:",S)}},[i]);return p?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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{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(cl,{providerId:j.providerId,modelId:j.modelId,onChange:g})]}),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(Om,{agentName:m||"",onChange:b})]})]}),(d||m)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",d&&e.jsx("span",{className:"text-foreground",children:d}),d&&m&&" / ",m&&e.jsx("span",{className:"text-foreground",children:m})]}),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:a,onChange:x}),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:a?`New session (Worktree): ${Gt()} + N • New session (Standard): Shift + ${Gt()} + N`:`New session (Standard): ${Gt()} + N • New session (Worktree): Shift + ${Gt()} + N`})]})]})},Nj=()=>{const s=It(I=>I.getActiveProject()),r=It(I=>I.updateWorktreeDefaults),t=s?.path??null,n=s?.worktreeDefaults,o=qi(t),a=Tu(t),{sessions:i,getWorktreeMetadata:l}=de(),[d,u]=c.useState(n?.branchPrefix??""),[m,f]=c.useState(n?.baseBranch??"HEAD"),[p,h]=c.useState([]),[j,g]=c.useState(!1),[b,x]=c.useState(!1),[y,w]=c.useState(null),[S,v]=c.useState(null),[N,D]=c.useState([]),[M,C]=c.useState(!1),k=".openchamber",A=c.useCallback((I,F)=>{const W=I.replace(/\\/g,"/").replace(/\/+$/,""),O=!W||W==="/"?`/${k}`:`${W}/${k}`;return F?`${O}/${F}`:O},[]),P=c.useCallback(async()=>{if(!(!t||y===!1))try{const F=(await mn(t)).map(ee=>fn(t,ee)),O=`${A(t,"")}/`,_=F.filter(ee=>ee.path.startsWith(O));D(_)}catch{}},[t,y,A]);c.useEffect(()=>{if(!t)return;let I=!1;return x(!0),C(!0),w(null),v(null),D([]),(async()=>{try{const F=await Wr(t);if(I)return;if(w(F),F){const[W,O]=await Promise.all([Wi(t),mn(t).catch(()=>[])]);if(!I){W&&v({all:W.all,current:W.current});const _=O.map(pe=>fn(t,pe)),ue=`${`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/${k}`}/`,me=_.filter(pe=>pe.path.startsWith(ue));D(me)}}}catch{}finally{I||(x(!1),C(!1))}})(),()=>{I=!0}},[t]),c.useEffect(()=>{if(!t)return;let I=!1;return g(!0),(async()=>{try{const F=await Yn(t);I||h(F.length>0?F:[""])}catch{I||h([""])}finally{I||g(!1)}})(),()=>{I=!0}},[t]),c.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const L=S??a,U=y??o,z=c.useMemo(()=>{const I=[],F=L?.current?`Current (HEAD: ${L.current})`:"Current (HEAD)";return I.push({value:"HEAD",label:F,group:"special"}),L&&(L.all.filter(_=>!_.startsWith("remotes/")).sort((_,ee)=>_.localeCompare(ee)).forEach(_=>{I.push({value:_,label:_,group:"local"})}),L.all.filter(_=>_.startsWith("remotes/")).map(_=>_.replace(/^remotes\//,"")).sort((_,ee)=>_.localeCompare(ee)).forEach(_=>{I.push({value:_,label:_,group:"remote"})})),I},[L]),H=c.useRef(null),V=c.useCallback(I=>{u(I),H.current=I},[]),J=c.useCallback(I=>{s?.id&&(r(s.id,{branchPrefix:I}),H.current=null)},[s?.id,r]),T=c.useCallback(()=>{J(d)},[d,J]);c.useEffect(()=>()=>{H.current!==null&&s?.id&&r(s.id,{branchPrefix:H.current})},[s?.id,r]);const Z=c.useCallback(I=>{f(I),s?.id&&r(s.id,{baseBranch:I})},[s?.id,r]),E=c.useCallback((I,F)=>{h(W=>{const O=[...W];return O[I]=F,O})},[]),B=c.useCallback(()=>{h(I=>[...I,""])},[]),X=c.useCallback(I=>{h(F=>F.filter((W,O)=>O!==I))},[]),re=c.useCallback(async()=>{if(!t)return;const I=p.filter(F=>F.trim().length>0);await bu(t,I)},[t,p]),q=c.useCallback(()=>{re()},[re]),oe=c.useCallback(I=>{const F=I.path.replace(/\\/g,"/").replace(/\/+$/,""),W=i.filter(pe=>{if(l(pe.id)?.path===I.path)return!0;const Y=pe.directory;return!!(Y&&Y.replace(/\\/g,"/").replace(/\/+$/,"")===F)}),O=new Set(W.map(pe=>pe.id)),_=pe=>{const He=i.filter(le=>{const te=le.parentID;return te&&pe.has(te)});if(He.length===0)return[];const Y=new Set(He.map(le=>le.id));return[...He,..._(Y)]},ee=_(O),ue=new Set,me=[...W,...ee].filter(pe=>ue.has(pe.id)?!1:(ue.add(pe.id),!0));hn.requestDelete({sessions:me,mode:"worktree",worktree:I})},[i,l]),ye=c.useMemo(()=>i.map(I=>I.id).join(","),[i]);return c.useEffect(()=>{y&&t&&P()},[ye,y,t,P]),t?b?e.jsx("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:"Worktree settings"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."})]})}):U===!1?e.jsx("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:"Worktree settings"}),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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{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(mt,{value:d,onChange:I=>V(I.target.value),onBlur:T,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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{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:Z,children:[e.jsx(Ns,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Un,{placeholder:"Select a branch"})}),e.jsxs(Cs,{children:[e.jsxs(Tr,{children:[e.jsx(ln,{children:"Default"}),z.filter(I=>I.group==="special").map(I=>e.jsx(qt,{value:I.value,children:I.label},I.value))]}),z.some(I=>I.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(Uo,{}),e.jsxs(Tr,{children:[e.jsx(ln,{children:"Local branches"}),z.filter(I=>I.group==="local").map(I=>e.jsx(qt,{value:I.value,children:I.label},I.value))]})]}),z.some(I=>I.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(Uo,{}),e.jsxs(Tr,{children:[e.jsx(ln,{children:"Remote branches"}),z.filter(I=>I.group==="remote").map(I=>e.jsx(qt,{value:I.value,children:I.label},I.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."]})]}),j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[p.map((I,F)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(mt,{value:I,onChange:W=>E(F,W.target.value),onBlur:q,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{X(F),setTimeout(re,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(Lt,{className:"h-4 w-4"})})]},F)),e.jsxs("button",{type:"button",onClick:B,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(_t,{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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{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"})]}),M?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):N.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:N.map(I=>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:I.label||I.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:I.relativePath||I.path})]}),e.jsx("button",{type:"button",onClick:()=>oe(I),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 ${I.branch||I.label}`,children:e.jsx(zs,{className:"h-4 w-4"})})]},I.path))})]})]}):e.jsx("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:"Worktree settings"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})]})})},Cj=({section:s})=>{const{isMobile:r}=$t(),t=r&&Ri();if(!s)return e.jsxs(ct,{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(dl,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Wm,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(zm,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Lm,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(Mj,{});case"chat":return e.jsx(Dj,{});case"sessions":return e.jsx(Aj,{});case"worktree":return e.jsx(Nj,{});default:return null}};return e.jsx(ct,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},Mj=()=>e.jsx(dl,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),Dj=()=>e.jsx(dl,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),Aj=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wm,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(zm,{})})]}),Ej=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]},{id:"worktree",label:"Worktree",items:["Branch","Setup"]}],Ij=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=$t(),n=t&&Ri(),[o,a]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),i=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const l=o?"bg-transparent":i?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",l),children:[e.jsx(ct,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:Ej.map(d=>{const u=s===d.id;return e.jsx("div",{className:R("group relative rounded-md px-1.5 py-1 transition-all duration-200",u?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{onClick:()=>r(d.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:d.label}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 leading-tight",children:d.items.join(" · ")})]})},d.id)})}),n&&e.jsx("div",{className:"border-t px-3 py-4",children:e.jsx(Lm,{})})]})},Pj=(()=>{const s=Fm.filter(n=>n.id!=="sessions"),r=s.find(n=>n.id==="settings"),t=s.filter(n=>n.id!=="settings");return r?[r,...t]:s})(),Ya=200,Xa=500,Tj=264,Fj=700,ki=({onClose:s,forceMobile:r})=>{const t=$t(),n=r??t.isMobile,[o,a]=c.useState("settings"),[i,l]=c.useState("visual"),[d,u]=c.useState(!1),[m,f]=c.useState(()=>typeof window<"u"?Math.min(Xa,Math.max(Ya,Math.floor(window.innerWidth*.2))):Tj),[p,h]=c.useState(!1),[j,g]=c.useState(!1),[b,x]=c.useState(0),y=c.useRef(null),w=c.useRef(0),S=c.useRef(m),[v,N]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),D=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||N(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{const I=y.current;if(!I)return;const F=new ResizeObserver(W=>{for(const O of W)x(O.contentRect.width)});return F.observe(I),x(I.clientWidth),()=>F.disconnect()},[]);const C=It(I=>I.projects),k=It(I=>I.activeProjectId),A=It(I=>I.setActiveProject),P=c.useMemo(()=>[...C].sort((I,F)=>(I.label||I.path).localeCompare(F.label||F.path)),[C]),L=c.useMemo(()=>P.length===0?null:P.find(I=>I.id===k)??P[0],[k,P]),U=c.useCallback(I=>I.replace(/[-_]/g," ").replace(/\b\w/g,F=>F.toUpperCase()),[]),z=c.useMemo(()=>{if(!L)return"Project";const I=L.label&&L.label.trim().length>0?L.label:L.path.split("/").filter(Boolean).pop()||L.path;return U(I)},[L,U]),H=P.length>0,V=b===0||b>=Fj;c.useEffect(()=>{if(o==="agents"){setTimeout(()=>{zr.getState().loadAgents()},0);return}if(o==="commands"){setTimeout(()=>{Br.getState().loadCommands()},0);return}o==="skills"&&(Ks.getState().loadSkills(),Kn.getState().loadCatalog())},[k,o]),c.useEffect(()=>{if(typeof window>"u")return;const I=()=>{if(!p){const F=Math.min(Xa,Math.max(Ya,Math.floor(window.innerWidth*.2)));f(F)}};return window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[p]),c.useEffect(()=>{if(!j)return;const I=W=>{const O=W.clientX-w.current,_=Math.min(Xa,Math.max(Ya,S.current+O));f(_),h(!0)},F=()=>g(!1);return window.addEventListener("pointermove",I),window.addEventListener("pointerup",F,{once:!0}),()=>{window.removeEventListener("pointermove",I),window.removeEventListener("pointerup",F)}},[j]);const J=I=>{g(!0),w.current=I.clientX,S.current=m,I.preventDefault()},T=c.useCallback(async I=>{if(!I.target.closest("button, a, input, select, textarea")&&I.button===0&&v)try{const{getCurrentWindow:F}=await ns(async()=>{const{getCurrentWindow:O}=await import("./vendor-.bun-BEzqubWg.js").then(_=>_.co);return{getCurrentWindow:O}},__vite__mapDeps([0,1]));await F().startDragging()}catch(F){console.error("Failed to start window dragging:",F)}},[v]),Z=c.useCallback(async I=>{if(I.button===0&&v)try{const{getCurrentWindow:F}=await ns(async()=>{const{getCurrentWindow:O}=await import("./vendor-.bun-BEzqubWg.js").then(_=>_.co);return{getCurrentWindow:O}},__vite__mapDeps([0,1]));await F().startDragging()}catch(F){console.error("Failed to start window dragging:",F)}},[v]),E=c.useCallback(I=>{a(I),u(!1)},[]),B=c.useCallback(()=>{n&&u(!0)},[n]),X=()=>{switch(o){case"settings":return e.jsx(Ij,{selectedSection:i,onSelectSection:I=>{l(I),B()}});case"agents":return e.jsx(Hv,{onItemSelect:B});case"commands":return e.jsx(Jv,{onItemSelect:B});case"skills":return e.jsx(ej,{onItemSelect:B});case"providers":return e.jsx(uj,{onItemSelect:B});case"git-identities":return e.jsx(bj,{onItemSelect:B});default:return null}},re=()=>{switch(o){case"agents":return e.jsx(Qv,{});case"commands":return e.jsx(Zv,{});case"skills":return e.jsx(cj,{});case"providers":return e.jsx(gj,{});case"git-identities":return e.jsx(vj,{});case"settings":return e.jsx(Cj,{section:i});default:return null}},q=Gt(),oe=c.useMemo(()=>v&&D?"pl-[5.75rem]":"",[v,D]),ye=v&&D;return e.jsxs("div",{ref:y,className:R("flex h-full flex-col overflow-hidden",v?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:T,className:R("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&oe,v?"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(qp,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:R("flex items-center",n?"gap-1":"h-full"),children:[!n&&ye&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),Pj.map(({id:I,label:F,icon:W})=>{const O=o===I,_=W;return n?e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{onClick:()=>E(I),className:R("relative flex h-9 w-9 items-center justify-center rounded-md transition-colors","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",O?"text-foreground":"text-muted-foreground"),"aria-pressed":O,"aria-label":F,children:e.jsx(_,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(tt,{children:e.jsx("p",{children:F})})]},I):e.jsxs(c.Fragment,{children:[e.jsxs("button",{onClick:()=>E(I),onMouseDown:O?Z:void 0,className:R("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",O?"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",O?"text-foreground":"text-muted-foreground"),"aria-pressed":O,"aria-label":F,children:[e.jsx(_,{className:"h-4 w-4",weight:"regular"}),V&&e.jsx("span",{children:F})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},I)})]}),(s||H)&&e.jsxs("div",{className:R("flex items-center gap-2",n?"":"pr-3"),children:[H&&e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:z,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(fr,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:z,className:R("flex h-9 max-w-[18rem] items-center gap-1.5 bg-transparent px-2 text-foreground outline-none hover:text-foreground/80 focus-visible:ring-2 focus-visible:ring-ring",!n&&"app-region-no-drag"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:z}),e.jsx(Ct,{className:"size-4 opacity-50"})]})}),e.jsx(Xt,{align:"end",className:"w-auto",children:e.jsx(Fu,{value:L?.id??"",onValueChange:I=>{I&&A(I)},children:P.map(I=>{const F=I.label?.trim()?I.label.trim():I.path.split("/").filter(Boolean).pop()||I.path,W=U(F);return e.jsx(Ru,{value:I.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:W})},I.id)})})})]}),s&&e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close settings",className:R("inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",!n&&"app-region-no-drag"),children:e.jsx(Lt,{className:"h-5 w-5"})})}),e.jsx(tt,{children:e.jsxs("p",{children:["Close Settings (",q,"+,)"]})})]})]})]}),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(rs,{children:re()})}):e.jsx("div",{className:R("flex-1 overflow-hidden",M?"bg-background":"bg-sidebar"),children:e.jsx(rs,{children:X()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:R("relative overflow-hidden border-r",v?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":M?"bg-background":"bg-sidebar",j?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:R("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",j?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:J,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(rs,{children:X()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(rs,{children:re()})})]})})]})},Rj=()=>{const{isSidebarOpen:s,activeMainTab:r,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i,isMultiRunLauncherOpen:l,setMultiRunLauncherOpen:d,multiRunLauncherPrefillPrompt:u}=Re(),{isMobile:m}=$t(),[f,p]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");c.useEffect(()=>{typeof window>"u"||p(typeof window.opencodeDesktop<"u")},[]),Kx({enabled:!0});const h=ta(x=>x.checkForUpdates);c.useEffect(()=>{const x=setTimeout(()=>{h()},3e3);return()=>clearTimeout(x)},[h]),c.useEffect(()=>{Re.getState().isMobile!==m&&t(m)},[m,t]),c.useEffect(()=>{if(typeof window>"u")return;let x;const y=()=>{x!==void 0&&window.clearTimeout(x),x=window.setTimeout(()=>{Re.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",y),()=>{window.removeEventListener("resize",y),x!==void 0&&window.clearTimeout(x)}},[]),c.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const x=document.documentElement;let y=0,w=!1,S=0,v=null;const N=Re.getState().setKeyboardOpen,D=()=>{v&&(v.style.setProperty("--oc-keyboard-avoid-offset","0px"),v.removeAttribute("data-keyboard-avoid-active"),v=null)},M=U=>{if(!U)return null;const z=U.closest("[data-keyboard-avoid]");if(z)return z;if(U.classList.contains("overlay-scrollbar-container")){const H=U.parentElement;if(H instanceof HTMLElement)return H}return U},C=()=>{y=0,w=!0,x.style.setProperty("--oc-keyboard-inset","0px"),N(!1)},k=()=>{const U=window.visualViewport,z=U?Math.round(U.height):window.innerHeight,H=U?Math.max(0,Math.round(U.offsetTop)):0;x.style.setProperty("--oc-visual-viewport-offset-top",`${H}px`);const V=document.activeElement,J=V?.tagName,Z=J==="INPUT"||J==="TEXTAREA"||J==="SELECT"||!!V?.isContentEditable,E=Math.round(x.clientHeight||window.innerHeight),B=z+H,X=Math.max(0,E-B),q=X>=(Z?120:180)?X:0;if(w)q===0&&(w=!1),y=0;else if(y===0)q>0&&Z&&(y=q);else{const ye=!Z&&z>S+6;q===0?(y=0,N(!1)):ye?C():(q>0&&Z||q>y)&&(y=q,N(!0))}x.style.setProperty("--oc-keyboard-inset",`${y}px`),S=z;const oe=Z?M(V):null;if(!m||!oe||!V)D();else{oe!==v&&(D(),v=oe);const ye=H+z,F=V.getBoundingClientRect().bottom-ye,W=8,O=Math.max(y,q),_=F>W&&O>0?Math.min(F,O):0,ee=v;ee&&(ee.style.setProperty("--oc-keyboard-avoid-offset",`${_}px`),ee.setAttribute("data-keyboard-avoid-active","true"))}if(m&&Z){const ye=document.scrollingElement;ye&&ye.scrollTop!==0&&(ye.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};k();const A=window.visualViewport;A?.addEventListener("resize",k),A?.addEventListener("scroll",k),window.addEventListener("resize",k),window.addEventListener("orientationchange",k);const P=U=>{const z=U.target;if(!z)return;const H=z.tagName;(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||z.isContentEditable)&&(w=!1),k()};document.addEventListener("focusin",P,!0);const L=U=>{const z=U.target;if(!z)return;const H=z.tagName;if(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||z.isContentEditable){const J=U.relatedTarget,T=J?.tagName;if(T==="INPUT"||T==="TEXTAREA"||T==="SELECT"||J?.isContentEditable)return;C()}};return document.addEventListener("focusout",L,!0),()=>{A?.removeEventListener("resize",k),A?.removeEventListener("scroll",k),window.removeEventListener("resize",k),window.removeEventListener("orientationchange",k),document.removeEventListener("focusin",P,!0),document.removeEventListener("focusout",L,!0),D()}},[m]);const j=c.useMemo(()=>{switch(r){case"git":return e.jsx(Nv,{});case"diff":return e.jsx(fx,{});case"terminal":return e.jsx($v,{});default:return null}},[r]),g=r==="chat",b=a&&!m;return e.jsx(Lx,{children:e.jsxs("div",{className:R("main-content-safe-area h-[100dvh]",m?"flex flex-col":"flex",f?"bg-transparent":"bg-background"),children:[e.jsx(Nx,{}),e.jsx(Dx,{}),e.jsx(Tx,{}),m?e.jsxs(e.Fragment,{children:[!(a||l)&&e.jsx(ic,{}),e.jsx("div",{className:R("flex flex-1 overflow-hidden bg-background",(a||l)&&"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:R("absolute inset-0",!g&&"invisible"),children:e.jsx(rs,{children:e.jsx(ji,{})})}),j&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(rs,{children:j})})]})}),e.jsx(vs,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(pi,{mobileVariant:!0})}),l&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(rs,{children:e.jsx(Nc,{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(rs,{children:e.jsx(ki,{onClose:()=>i(!1)})})})]}):e.jsxs(e.Fragment,{children:[!b&&e.jsx(wx,{isOpen:s,isMobile:m,children:e.jsx(pi,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:R("absolute inset-0 flex flex-col",(b||l)&&"invisible"),children:[e.jsx(ic,{}),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:R("absolute inset-0",!g&&"invisible"),children:e.jsx(rs,{children:e.jsx(ji,{})})}),j&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(rs,{children:j})})]})})]}),l&&e.jsx("div",{className:R("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(rs,{children:e.jsx(Nc,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})})]}),b&&e.jsx("div",{className:R("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(rs,{children:e.jsx(ki,{onClose:()=>i(!1)})})})]}),!b&&e.jsx(hx,{})]})})},Oj=550,$j=()=>{const[s,r]=c.useState("chat"),[t,n]=c.useState(0),o=c.useRef(null),a=de(D=>D.currentSessionId),i=de(D=>D.sessions),l=de(D=>!!D.newSessionDraft?.open),d=de(D=>D.openNewSessionDraft),[u,m]=c.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),f=at(D=>D.isInitialized),p=at(D=>D.initializeApp),h=de(D=>D.loadSessions),j=de(D=>D.loadMessages),g=de(D=>D.messages),[b,x]=c.useState(()=>f),[y,w]=c.useState(!1),S=c.useRef(0);c.useEffect(()=>{a&&r("chat")},[a]),c.useEffect(()=>{!a&&!l&&d()},[a,l,d]);const v=c.useCallback(()=>{r("sessions")},[]);c.useEffect(()=>{const D=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&m(D);const M=C=>{const A=C.detail?.status;(A==="connected"||A==="connecting"||A==="error"||A==="disconnected")&&m(A)};return window.addEventListener("openchamber:connection-status",M),()=>window.removeEventListener("openchamber:connection-status",M)},[]),c.useEffect(()=>{const D=M=>{const k=M.detail?.view;k==="settings"?r("settings"):k==="chat"?r("chat"):k==="sessions"&&r("sessions")};return window.addEventListener("openchamber:navigate",D),()=>window.removeEventListener("openchamber:navigate",D)},[]),c.useEffect(()=>{(async()=>{if(y||b||u!=="connected")return;const M=Date.now();if(!(M-S.current<750)){S.current=M,w(!0);try{const C=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();C&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:f}),f||await p();const k=at.getState();if(!k.isInitialized||!k.isConnected||k.providers.length===0||k.agents.length===0)return;await h();const A=de.getState().error;if(C&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:k.providers.length,agents:k.agents.length,sessions:de.getState().sessions.length,sessionsError:A}),typeof A=="string"&&A.length>0)return;x(!0)}catch{}finally{w(!1)}}})()},[u,f,b,p,y,h]),c.useEffect(()=>{(async()=>{if(!b||u!=="connected"||s!=="chat"||l||!a)return;if(!(g.has(a)&&(g.get(a)?.length||0)>0))try{await j(a)}catch{}})()},[u,a,s,b,j,g,l]),c.useEffect(()=>{const D=o.current;if(!D)return;const M=new ResizeObserver(C=>{for(const k of C)n(k.contentRect.width)});return M.observe(D),n(D.clientWidth),()=>M.disconnect()},[]);const N=t>0&&t<Oj;return e.jsx("div",{ref:o,className:"h-full w-full bg-background text-foreground flex flex-col",children:s==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(jd,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(pi,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>r("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):s==="settings"?e.jsx(ki,{onClose:()=>r("sessions"),forceMobile:N}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(jd,{title:l&&!a?"New session":i.find(D=>D.id===a)?.title||"Chat",showBack:!0,onBack:v,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(rs,{children:e.jsx(ji,{})})})]})})},jd=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,onAgentManager:a,showContextUsage:i})=>{const{getCurrentModel:l}=at(),d=de(j=>j.getContextUsage),u=l(),m=u?.limit&&typeof u.limit=="object"?u.limit:null,f=typeof m?.context=="number"?m.context:0,p=typeof m?.output=="number"?m.output:0,h=d(f,p);return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border bg-background shrink-0",children:[r&&t&&e.jsx("button",{onClick:t,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":"Back to sessions",children:e.jsx(Gd,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1 h-9 w-9 items-center justify-center p-2",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(_t,{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(_n,{className:"h-5 w-5"})}),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(Rr,{className:"h-5 w-5"})}),i&&h&&h.totalTokens>0&&e.jsx(mi,{totalTokens:h.totalTokens,percentage:h.percentage,contextLimit:h.contextLimit,outputLimit:h.outputLimit??0,size:"compact"})]})},Ni=".openchamber",go=s=>{const r=It.getState(),t=r.activeProjectId,n=t?r.projects.find(l=>l.id===t)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof s=="string"?kt(s):"",a=`/${Ni}/`,i=o.indexOf(a);return i>0?o.slice(0,i):s?kt(s):null},kt=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Sd=s=>{const r=kt(s);return!r||r==="/"?`/${Ni}`:`${r}/${Ni}`},Lj=(s,r)=>{const t=kt(s);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const i=kt(o);if(i)return i}const a=typeof n.name=="string"?n.name.trim():"";return!a||!t?null:`${t}/${a}`}).filter(n=>!!n)},_j=async s=>{const r=kt(s);if(!r)return[];try{const n=(await De.listLocalDirectory(r)).filter(o=>o.isDirectory);return Lj(r,n)}catch{return[]}},br=(s,r)=>{const t=kt(s),n=kt(r);if(!t||!n)return!1;if(t===n)return!0;const o=n==="/"?"/":`${n}/`;return t.startsWith(o)},Hm=async(s,r)=>{const t=kt(r);if(!t)return t;try{const n=await s.path.get({directory:t});return kt(n.data?.directory??"")||t}catch{return t}},Um=async(s,r)=>{const t=kt(r);if(!t)return[];const n=await Hm(s,t),o=i=>i.filter(l=>{const d=kt(l.directory??"");return d?br(d,t)||n!==t&&br(d,n):!1}),a=async i=>{const l=await s.session.list({directory:i});return Array.isArray(l.data)?l.data:[]};try{const i=o(await a(t));if(i.length>0)return i}catch{}if(n&&n!==t)try{const i=o(await a(n));if(i.length>0)return i}catch{}try{const i=await s.session.list(void 0),l=Array.isArray(i.data)?i.data:[];return o(l)}catch{return[]}},Bj=async(s,r)=>{const t=new Map;s.sessions.forEach(o=>{o.worktreeMetadata&&t.set(kt(o.path),o.worktreeMetadata)});const n=Array.from(new Set(s.sessions.map(o=>kt(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(i=>[kt(i.worktree),i]));n.forEach(i=>{const l=a.get(i);l&&t.set(i,fn(r,l))})}catch{}return t},Qa=async s=>{const{apiClient:r,group:t,projectDirectory:n,worktreePaths:o}=s,a=await Bj(t,n),i=de.getState(),l=Array.from(new Set(o.map(p=>kt(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<l.length;){const p=l[u];u+=1;const h=t.sessions.filter(y=>kt(y.path)===p).map(y=>y.id),j=i.getSessionsByDirectory(p),g=Array.isArray(j)?j.map(y=>y.id):[];let b=[];if(g.length===0)try{b=(await Um(r,p)).map(w=>w.id)}catch{b=[]}const x=Array.from(new Set([...g,...b,...h].filter(Boolean)));m.push({worktreePath:p,sessionIds:x,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,l.length)},f)),m};function zj(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),i=r.length>=4&&!isNaN(a)&&String(a)===o,l=i?r.slice(2,-1):r.slice(2);if(l.length===0)return null;const d=l.join("/");return{groupSlug:t,provider:n,model:d,index:i?a:1}}const vr=Bt()(Qt((s,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const t=ft.getState().currentDirectory,n=go(t);if(!n){s({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=kt(n),a=Sd(o),i=r().groups;s({isLoading:!0,error:null});try{const l=De.getApiClient(),d=await Hm(l,o),u=Sd(d);let m=new Map,f=[];try{f=await mn(o),m=new Map(f.map(w=>[kt(w.worktree),w]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const S=await l.session.list({directory:o}),v=Array.isArray(S.data)?S.data:[];if(v.some(N=>{const D=kt(N.directory??"");return br(D,a)||br(D,u)}))return v}catch{}const w=await l.session.list(void 0);return Array.isArray(w.data)?w.data:[]},h=async w=>{const S=new Map,v=5;let N=0;const D=async()=>{for(;N<w.length;){const M=w[N];N+=1;const C=kt(M);if(C)try{(await Um(l,C)).forEach(A=>S.set(A.id,A))}catch(k){console.debug("Failed to fetch sessions from worktree:",C,k)}}};return await Promise.all(Array.from({length:Math.min(v,w.length)},D)),Array.from(S.values())};let g=(await p()).filter(w=>{const S=kt(w.directory??"");return S?br(S,a)||br(S,u):!1});if(g.length===0){const w=new Set;f.map(v=>kt(v.worktree)).filter(v=>br(v,a)||br(v,u)).forEach(v=>w.add(v));const S=Array.from(new Set([a,u].map(v=>kt(v)).filter(Boolean)));await Promise.all(S.map(async v=>{(await _j(v)).forEach(D=>w.add(D))})),w.size>0&&(g=await h(Array.from(w)))}const b=new Map;for(const w of g){const S=w.time?.updated??0;b.set(w.id,typeof S=="number"?S:0)}const x=new Map;for(const w of g){const S=zj(w.title);if(!S)continue;const v=kt(w.directory),N=m.get(v),D={id:w.id,path:v,providerId:S.provider,modelId:S.model,instanceNumber:S.index,branch:N?.branch??"",displayLabel:`${S.provider}/${S.model}`,worktreeMetadata:N?fn(o,N):void 0},M=x.get(S.groupSlug);M?M.push(D):x.set(S.groupSlug,[D])}const y=Array.from(x.entries()).map(([w,S])=>{const v=S.reduce((N,D)=>{const M=b.get(D.id)??0;return Math.max(N,M)},0);return{name:w,sessions:S.sort((N,D)=>{const M=N.providerId.localeCompare(D.providerId);if(M!==0)return M;const C=N.modelId.localeCompare(D.modelId);return C!==0?C:N.instanceNumber-D.instanceNumber}),lastActive:v||Date.now(),sessionCount:S.length}});y.sort((w,S)=>w.name.localeCompare(S.name)),s({groups:y,isLoading:!1,error:null})}catch(l){console.error("Failed to load agent groups:",l),s({groups:i.length>0?i:[],isLoading:!1,error:l instanceof Error?l.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(i=>i.name===t);if(!n)return!1;const o=ft.getState().currentDirectory,a=go(o);if(!a)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const i=De.getApiClient(),l=await Qa({apiClient:i,group:n,projectDirectory:kt(a),worktreePaths:n.sessions.map(f=>f.path)}),d=de.getState(),u=new Set;l.forEach(({worktreePath:f,sessionIds:p,metadata:h})=>{p.forEach(j=>{u.add(j),h&&(d.setWorktreeMetadata(j,h),d.setSessionDirectory(j,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(i){return s({error:i instanceof Error?i.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=kt(n);if(!a)return!1;const i=ft.getState().currentDirectory,l=go(i);if(!l)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const d=De.getApiClient(),u=await Qa({apiClient:d,group:o,projectDirectory:kt(l),worktreePaths:[a]}),m=de.getState(),f=new Set;u.forEach(({worktreePath:j,sessionIds:g,metadata:b})=>{g.forEach(x=>{f.add(x),b&&(m.setWorktreeMetadata(x,b),m.setSessionDirectory(x,j))})});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 h=r().groups.find(j=>j.name===t);if(!h)return r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===t){const j=r().selectedSessionId,g=new Set(h.sessions.map(b=>b.id));(!j||!g.has(j))&&s({selectedSessionId:h.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=kt(n);if(!a)return!1;const l=Array.from(new Set(o.sessions.map(m=>kt(m.path)).filter(Boolean))).filter(m=>m!==a);if(l.length===0)return!0;const d=ft.getState().currentDirectory,u=go(d);if(!u)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const m=De.getApiClient(),f=await Qa({apiClient:m,group:o,projectDirectory:kt(u),worktreePaths:l}),p=de.getState(),h=new Set;f.forEach(({worktreePath:g,sessionIds:b,metadata:x})=>{b.forEach(y=>{h.add(y),x&&(p.setWorktreeMetadata(y,x),p.setSessionDirectory(y,g))})});const{failedIds:j}=await p.deleteSessions(Array.from(h),{archiveWorktree:!0,silent:!0});if(j.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===t){const g=r().groups.find(x=>x.name===t),b=g?.sessions.find(x=>kt(x.path)===a)??g?.sessions[0]??null;s({selectedSessionId:b?.id??null})}return j.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"})),Wj=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`},Hj=({group:s,isSelected:r,onSelect:t})=>{const[n,o]=c.useState(!1),[a,i]=c.useState(!1),[l,d]=c.useState(!1),u=vr(f=>f.deleteGroup),m=c.useCallback(async()=>{if(l)return;if(d(!0),se.info(`Deleting "${s.name}"...`),await u(s.name))se.success(`Deleted "${s.name}"`);else{const p=vr.getState().error;se.error(p||`Failed to delete "${s.name}"`)}d(!1),i(!1)},[u,s.name,l]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1.5 cursor-pointer",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),onClick: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(Ft,{className:"h-3 w-3"}),s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:Wj(s.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(Kt,{open:n,onOpenChange:o,children:[e.jsx(Yt,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","opacity-0 group-hover:opacity-100",n&&"opacity-100"),"aria-label":"Group menu",onClick:f=>f.stopPropagation(),children:e.jsx(kr,{className:"h-3.5 w-3.5"})})}),e.jsx(Xt,{align:"end",className:"min-w-[140px]",children:e.jsx(jt,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),i(!0)},children:"Delete"})})]})})]})}),e.jsx(ds,{open:a,onOpenChange:i,children:e.jsxs(us,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(fs,{children:[e.jsx(ps,{children:"Delete agent group"}),e.jsxs(ys,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Ws,{children:[e.jsx(ke,{variant:"outline",onClick:()=>i(!1),disabled:l,children:"Cancel"}),e.jsx(ke,{variant:"destructive",onClick:()=>{m()},disabled:l,children:l?"Deleting…":"Delete"})]})]})})]})},Uj=({className:s,selectedGroupName:r,onGroupSelect:t,onNewAgent:n})=>{const[o,a]=c.useState(""),[i,l]=c.useState(!1),{groups:d,isLoading:u,loadGroups:m}=vr(),f=ft(b=>b.currentDirectory);c.useEffect(()=>{f&&m()},[f,m]);const p=5,h=c.useMemo(()=>{if(!o.trim())return d;const b=o.toLowerCase();return d.filter(x=>x.name.toLowerCase().includes(b))},[o,d]),j=i?h:h.slice(0,p),g=h.length-p;return e.jsxs("div",{className:R("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",s),children:[e.jsx("div",{className:"px-2.5 pt-3 pb-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(ur,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(mt,{value:o,onChange:b=>a(b.target.value),placeholder:"Search Agent Groups...",className:"pl-8 h-8 rounded-lg border-border/40 bg-background/50 typography-meta"})]})}),e.jsx("div",{className:"px-2.5 pb-2",children:e.jsxs(ke,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(_t,{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(Ct,{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(ct,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[j.map(b=>e.jsx(Hj,{group:b,isSelected:r===b.name,onSelect:()=>t?.(b.name)},b.name)),!i&&g>0&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",g,")"]}),i&&h.length>p&&e.jsx("button",{type:"button",onClick:()=>l(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&h.length===0&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:o.trim()?"No groups found":"No agent groups yet"}),!o.trim()&&e.jsx("p",{className:"typography-micro text-muted-foreground/60 mt-1",children:"Create a new agent group to get started"})]})]})]})},Vj=10*1024*1024,Gj=5,qj=({className:s,onCreateGroup:r,isCreating:t=!1})=>{const[n,o]=c.useState(""),[a,i]=c.useState(""),[l,d]=c.useState([]),[u,m]=c.useState(""),[f,p]=c.useState("HEAD"),[h,j]=c.useState([]),[g,b]=c.useState(!1),[x,y]=c.useState([]),[w,S]=c.useState(!1),[v,N]=c.useState(!1),D=c.useRef(null),M=c.useRef(null),C=ft(q=>q.currentDirectory??null),{isGitRepository:k,isLoading:A}=ol(C),P=c.useMemo(()=>{if(typeof window>"u")return null;const q=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof q=="string"&&q.trim().length>0?q.trim():null},[]),L=c.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),U=It(q=>q.activeProjectId),z=It(q=>q.projects),H=c.useMemo(()=>{if(L&&P)return P;if(U){const F=z.find(W=>W.id===U);if(F?.path)return F.path}const q=C??P;if(!q)return null;const oe=q.replace(/\\/g,"/").replace(/\/+$/,"")||q,I=oe.indexOf("/.openchamber/");return I>0?oe.slice(0,I):oe.endsWith("/.openchamber")?oe.slice(0,oe.length-13):oe},[U,z,C,P]);c.useEffect(()=>{if(!H)return;let q=!1;return N(!0),(async()=>{try{const oe=await Yn(H);q||y(oe)}catch{}finally{q||N(!1)}})(),()=>{q=!0}},[H]);const V=c.useCallback(q=>{l.length>=Gj||d(oe=>[...oe,q])},[l.length]),J=c.useCallback(q=>{d(oe=>oe.filter((ye,I)=>I!==q))},[]),T=async q=>{const oe=q.target.files;if(!oe)return;let ye=0;for(let I=0;I<oe.length;I++){const F=oe[I];if(F.size>Vj){se.error(`File "${F.name}" is too large (max 10MB)`);continue}try{const W=await new Promise((_,ee)=>{const ue=new FileReader;ue.onload=()=>_(ue.result),ue.onerror=ee,ue.readAsDataURL(F)}),O={id:Ho(),filename:F.name,mimeType:F.type||"application/octet-stream",size:F.size,dataUrl:W};j(_=>[..._,O]),ye++}catch(W){console.error("File attach failed",W),se.error(`Failed to attach "${F.name}"`)}}ye>0&&se.success(`Attached ${ye} file${ye>1?"s":""}`),D.current&&(D.current.value="")},Z=q=>{j(oe=>oe.filter(ye=>ye.id!==q))},E=g||t,B=!!(n.trim()&&a.trim()&&l.length>=1&&k&&!A),X=async q=>{if(q.preventDefault(),!(!B||E)){b(!0);try{const oe=l.map(({providerID:F,modelID:W,displayName:O})=>({providerID:F,modelID:W,displayName:O})),ye=h.length>0?h.map(F=>({mime:F.mimeType,filename:F.filename,url:F.dataUrl})):void 0,I=x.filter(F=>F.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:oe,agent:u||void 0,worktreeBaseBranch:f,files:ye,setupCommands:I.length>0?I:void 0}),o(""),i(""),d([]),m(""),j([]),p("HEAD")}catch(oe){console.error("Failed to create agent group:",oe),se.error("Failed to create agent group")}finally{b(!1)}}},re=q=>{rl(q)||q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),B&&!E&&X(q))};return e.jsx("div",{className:R("flex flex-col items-center justify-center h-full w-full p-4",s),children:e.jsxs("form",{onSubmit:X,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(mt,{id:"group-name",value:n,onChange:q=>o(q.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(Ft,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(em,{directory:C,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(ia,{open:w,onOpenChange:S,children:[e.jsxs(sl,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",x.filter(q=>q.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",x.filter(q=>q.trim()).length," configured)"]})]}),e.jsx(Ct,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",w&&"rotate-180")})]}),e.jsx(la,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_WORKTREE_PATH"})," for project root."]}),v?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[x.map((q,oe)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(mt,{value:q,onChange:ye=>{const I=[...x];I[oe]=ye.target.value,y(I)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const ye=x.filter((I,F)=>F!==oe);y(ye)},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(Lt,{className:"h-4 w-4"})})]},oe)),e.jsxs("button",{type:"button",onClick:()=>y([...x,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(_t,{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(tm,{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(Zu,{selectedModels:l,onAdd:V,onRemove:J,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(js,{ref:M,id:"prompt",value:a,onChange:q=>i(q.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"}),h.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:h.map(q=>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:[q.mimeType.startsWith("image/")?e.jsx(mr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Qs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:q.filename,children:q.filename}),e.jsx("button",{type:"button",onClick:()=>Z(q.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Lt,{className:"h-3.5 w-3.5"})})]},q.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:D,type:"file",multiple:!0,className:"hidden",onChange:T,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>D.current?.click(),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors","aria-label":"Add attachment",children:e.jsx(zd,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length," model",l.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!B||E,className:R("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",B?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:E?e.jsx(Kp,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Bd,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},Kj=({group:s,className:r})=>{const{selectedSessionId:t,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=vr(),{setCurrentSession:i,currentSessionId:l}=de(),[d,u]=c.useState(null),[m,f]=c.useState(!1),p=c.useMemo(()=>t?s.sessions.find(w=>w.id===t)??s.sessions[0]??null:s.sessions[0]??null,[s.sessions,t]),h=c.useCallback(w=>{n(w.id),i(w.id)},[n,i]);c.useEffect(()=>{if(s.sessions.length>0){const w=t?s.sessions.find(S=>S.id===t)??s.sessions[0]:s.sessions[0];w&&(w.id!==l&&i(w.id),t||n(w.id))}},[s.name,s.sessions,t,l,n,i]);const j=p?.id===l,g=c.useCallback(()=>{if(!p?.path){se.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{se.success("Worktree path copied")}).catch(()=>{se.error("Failed to copy path")})},[p?.path]),b=c.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),x=c.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),y=c.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(se.info("Removing worktree..."),await o(s.name,d.path))se.success("Worktree removed");else{const S=vr.getState().error;se.error(S||"Failed to remove worktree");return}else if(se.info("Removing other worktrees..."),await a(s.name,d.path))se.success("Removed other worktrees");else{const S=vr.getState().error;se.error(S||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,s.name,m,a,d]);return e.jsxs("div",{className:R("flex h-full flex-col bg-background",r),children:[e.jsxs("div",{className:"flex-shrink-0 border-b border-border/30 px-4 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"typography-heading-lg text-foreground truncate",children: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(Ft,{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(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsxs(ke,{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(ts,{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(Ct,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Xt,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:s.sessions.map(w=>e.jsxs(jt,{onClick:()=>h(w),className:"flex items-center gap-2 py-2",children:[e.jsx(ts,{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(Ft,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:w.worktreeMetadata?.label||w.branch})]})]}),p?.id===w.id&&e.jsx(Ot,{className:"h-4 w-4 text-primary flex-shrink-0"})]},w.id))})]})}),e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx(ke,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(kr,{className:"h-4 w-4"})})}),e.jsxs(Xt,{align:"end",className:"min-w-[220px]",children:[e.jsx(jt,{onSelect:w=>{w.preventDefault(),b()},variant:"destructive",children:"Remove this worktree"}),e.jsx(jt,{onSelect:w=>{w.preventDefault(),x()},children:"Leave this one, remove others"}),e.jsxs(jt,{onClick:w=>{w.stopPropagation(),g()},disabled:!p?.path,children:[e.jsx(Bs,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(ds,{open:!!d,onOpenChange:w=>{w||u(null)},children:e.jsxs(us,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(fs,{children:[e.jsx(ps,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(ys,{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(Ws,{children:[e.jsx(ke,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(ke,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{y()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?j?e.jsx(Dm,{sessionId:p.id,children:e.jsx(Mm,{})}):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(ts,{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"})})})]})},Yj=({className:s})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[t,n]=c.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=at(w=>w.isInitialized),a=at(w=>w.initializeApp),i=de(w=>w.loadSessions),l=ft(w=>w.setDirectory),d=c.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=vr(),{createMultiRun:h,isLoading:j}=Rn();c.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 S=v=>{const D=v.detail?.status;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&n(D)};return window.addEventListener("openchamber:connection-status",S),()=>window.removeEventListener("openchamber:connection-status",S)},[r]),c.useEffect(()=>{if(!r||t!=="connected")return;const w=Date.now();if(w-d.current<750)return;d.current=w;const S=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof S=="string"&&S.trim().length>0)try{l(S,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const N=at.getState();if(!N.isInitialized||!N.isConnected||N.providers.length===0||N.agents.length===0)return;await i(),Wt()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:N.providers.length,agents:N.agents.length,sessions:de.getState().sessions.length})}catch{}})()},[t,o,a,r,i,l]);const g=c.useCallback(w=>{m(w)},[m]),b=c.useCallback(()=>{m(null)},[m]),x=c.useCallback(async w=>{se.info(`Creating agent group "${w.name}" with ${w.models.length} model(s)...`);const S=await h(w);if(S){se.success(`Agent group "${w.name}" created with ${S.sessionIds.length} session(s)`);const v=S.groupSlug,N=async(D=6)=>{for(let M=0;M<D;M+=1){if(await p(),vr.getState().groups.some(k=>k.name===v))return!0;await new Promise(k=>setTimeout(k,500))}return!1};try{await de.getState().loadSessions()}catch{}await N(),m(v)}else{const v=Rn.getState().error;se.error(v||"Failed to create agent group")}},[h,p,m]),y=f();return e.jsxs("div",{className:R("flex h-full w-full bg-background",s),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(Uj,{selectedGroupName:u,onGroupSelect:g,onNewAgent:b})}),e.jsx("div",{className:"flex-1 min-w-0",children:y?e.jsx(Kj,{group:y}):e.jsx(qj,{onCreateGroup:x,isCreating:j})})]})},Ja=({...s})=>{const{theme:r="system"}=Yp();return e.jsx(Xp,{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})},Xj=(s=5e3)=>{const[r,t]=Me.useState(null);return Me.useEffect(()=>{if(!ss())return;let n=!1,o=null;const a=async()=>{const i=await gh();n||(t(i),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},Qj=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=de(),l=Xj(4e3),d=c.useMemo(()=>{let f=0;return t.forEach(p=>{f+=p.length}),f},[t]),u=c.useMemo(()=>r.map(f=>{const p=t.get(f.id)?.length||0,h=n.get(f.id);return{id:f.id,title:f.title||"Untitled",messageCount:p,isStreaming:h?.isStreaming||!1,isZombie:h?.isZombie||!1,backgroundCount:h?.backgroundMessageCount||0,lastAccessed:h?.lastAccessedAt||0,isCurrent:f.id===o}}).sort((f,p)=>p.lastAccessed-f.lastAccessed),[r,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(Qp,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),s&&e.jsx(ke,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:s,children:e.jsx(Lt,{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," / ",ls.MAX_SESSIONS]})]})]}),l&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:l.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[l.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:l.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[ls.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:[ls.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:[ls.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(ct,{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(Jp,{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>ls.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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs(ke,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(zs,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(tt,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"})}),e.jsx(tt,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ke,{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(tt,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},Jj="openchamber-message-cursors",yn="cursors",Zj=1,Vm="openchamber.messageCursors",ul=()=>typeof window<"u",ml=()=>ul()&&typeof indexedDB<"u",Gm=()=>ml()?new Promise((s,r)=>{const t=indexedDB.open(Jj,Zj);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(yn)||n.createObjectStore(yn)},t.onerror=()=>{r(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{s(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),qm=()=>{if(!ul())return{};try{const s=window.localStorage.getItem(Vm);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},e0=s=>{if(ul())try{window.localStorage.setItem(Vm,JSON.stringify(s))}catch{}},t0=async(s,r,t)=>{if(!s||!r)return;if(ml())try{const o=await Gm();await new Promise((a,i)=>{const l=o.transaction(yn,"readwrite");l.objectStore(yn).put({messageId:r,completedAt:t},s),l.oncomplete=()=>a(),l.onerror=()=>i(l.error??new Error("Cursor write failed")),l.onabort=()=>i(l.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=qm();n[s]={messageId:r,completedAt:t},e0(n)},s0=async s=>{if(!s)return null;if(ml())try{const t=await Gm(),n=await new Promise((o,a)=>{const i=t.transaction(yn,"readonly"),d=i.objectStore(yn).get(s);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),i.onerror=()=>a(i.error??new Error("Cursor read failed")),i.onabort=()=>a(i.error??new Error("Cursor read aborted"))});return t.close(),n}catch{}return qm()[s]??null},r0=50,n0=750,kd=new WeakMap,Nd=s=>{if(!s||!Array.isArray(s))return 0;const r=kd.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 kd.set(s,t),t},o0=10,Cd=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<o0?null:n},Md=(s,r)=>{const t=Cd(s),n=Cd(r);return!t||!n||t.length!==n.length?!0:t>n},Ci=new Map,Dd=(s,r)=>{const t=`${s}:${r}`,n=Ci.get(t);if(n&&n.sessionId===s)return n.message;const i=(de.getState().messages.get(s)||[]).find(l=>l.info.id===r)||null;return Ci.set(t,{sessionId:s,message:i}),i},a0=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:l,getWorktreeMetadata:d,loadMessages:u,loadSessions:m,updateSession:f,removeSessionFromStore:p}=de(),{checkConnection:h}=at(),j=ft(ae=>ae.currentDirectory),g=c.useMemo(()=>{if(!a)return;try{const $=d?.(a);if($?.path)return $.path}catch($){console.warn("Failed to inspect worktree metadata for session directory:",$)}const ae=l.find($=>$.id===a);if(ae&&typeof ae.directory=="string"&&ae.directory.trim().length>0)return ae.directory.trim()},[a,d,l]),b=c.useMemo(()=>{if(g&&g.length>0)return g;if(typeof j=="string"&&j.trim().length>0)return j.trim()},[g,j]);c.useEffect(()=>{let ae=!1;return(async()=>{try{const we=await De.listPendingPermissions();if(ae||we.length===0)return;we.forEach(fe=>{o(fe)})}catch{}})(),()=>{ae=!0}},[o]);const x=c.useCallback(ae=>{if(typeof ae!="string")return null;const $=ae.trim();if(!$)return null;const we=$.replace(/\\/g,"/");return we.length>1?we.replace(/\/+$/,""):we},[]),y=c.useCallback(ae=>{if(!ae)return null;try{const we=d?.(ae),fe=x(we?.path??null);if(fe)return fe}catch{}const $=l.find(we=>we.id===ae);return x($?.directory??null)},[d,x,l]),w=Re(ae=>ae.setEventStreamStatus),S=c.useRef(null),v=c.useCallback((ae,$)=>{const we=$??null,fe=S.current;if(!(fe&&fe.status===ae&&fe.hint===we)){if(S.current={status:ae,hint:we},Wt()){const Le={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[ae]??"[INFO]",Ge=we?`${Le} SSE ${ae}: ${we}`:`${Le} SSE ${ae}`;console.info(Ge)}w(ae,we)}},[w]),N=c.useCallback((ae,$)=>{if(!ae)return Promise.resolve();const we=Date.now();if(H.current)return H.current;if(we-V.current<n0)return Promise.resolve();const fe=u(ae).catch(ve=>{console.warn(`[useEventStream] Failed to resync messages (${$}):`,ve)}).finally(()=>{H.current=null,V.current=Date.now()});return H.current=fe,fe},[u]),D=c.useCallback(async ae=>{Wt()&&console.info("[useEventStream] Bootstrapping state:",ae);try{await Promise.all([m(),a?N(a,ae):Promise.resolve()])}catch($){console.warn("[useEventStream] Bootstrap failed:",ae,$)}},[a,m,N]),M=c.useCallback((ae,$,we)=>{Wt()&&console.debug(`[MessageTracker] ${ae}: ${$}`,we)},[]),C=c.useCallback(ae=>{Wt()&&console.debug(`[MessageTracker] ${ae}: reported`)},[]),k=c.useRef(null),A=c.useRef(null),P=c.useRef(0);c.useRef(new Set);const L=c.useRef(new Map),U=c.useRef(null),z=c.useRef(!1),H=c.useRef(null),V=c.useRef(0),J=c.useRef(new Set),T=c.useCallback(()=>{if(typeof document>"u")return"visible";const ae=document.visibilityState;return ae==="hidden"&&document.hasFocus()?"visible":ae},[]),Z=c.useRef(T()),E=c.useRef(typeof navigator>"u"?!0:navigator.onLine),B=c.useRef(!1),X=c.useRef(null),re=c.useRef(null),q=c.useRef(Date.now()),oe=c.useRef(!1),ye=c.useCallback(ae=>{const $=Date.now();$-q.current>25e3&&(D(ae),q.current=$)},[D]);c.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(oe.current=!0)},[]);const I=c.useRef(new Map),F=c.useRef(new Map),W=c.useRef(0),O=c.useRef(null),_=c.useRef(a),ee=c.useRef(null),ue=c.useRef(null);c.useEffect(()=>{_.current=a},[a]);const me=c.useCallback((ae,$)=>{if(!ae)return;const we=Date.now(),fe=L.current,ve=fe.get(ae);if(ve&&we-ve<3e3)return;fe.set(ae,we);const Le=Ge=>{if(typeof $=="string"&&$.trim().length>0)return $.trim();try{const Pe=d?.(Ge);if(Pe?.path)return Pe.path}catch{}const Te=l.find(Pe=>Pe.id===Ge);return Te&&typeof Te.directory=="string"&&Te.directory.trim().length>0?Te.directory.trim():null};setTimeout(async()=>{try{const Ge=Le(ae),Te=Ge?await De.withDirectory(Ge,()=>De.getSession(ae)):await De.getSession(ae);if(Te){const Pe={};typeof Te.title=="string"&&Te.title.length>0&&(Pe.title=Te.title),Te.summary!==void 0&&(Pe.summary=Te.summary),Object.keys(Pe).length>0&&i(ae,Pe)}}catch(Ge){console.warn("Failed to refresh session metadata:",Ge)}},100)},[i,d,l]),pe=c.useCallback((ae,$)=>{if(de.getState().sessionActivityPhase?.get(ae)===$){F.current=new Map(de.getState().sessionActivityPhase??new Map);return}const fe=I.current.get(ae);fe&&(clearTimeout(fe),I.current.delete(ae));const ve=new Map(de.getState().sessionActivityPhase??new Map);if(ve.set(ae,$),F.current=ve,de.setState({sessionActivityPhase:ve}),$==="cooldown"){const Le=setTimeout(()=>{if(I.current.delete(ae),de.getState().sessionActivityPhase?.get(ae)==="cooldown"){const Te=new Map(de.getState().sessionActivityPhase??new Map);Te.set(ae,"idle"),F.current=Te,de.setState({sessionActivityPhase:Te})}},2e3);I.current.set(ae,Le)}},[]),He=c.useCallback(async()=>{const ae=Date.now();if(O.current)return O.current;if(ae-W.current<1500)return;W.current=ae;const $=fe=>{const ve=new Set,Le=new Set(l.map(Te=>Te.id));Object.entries(fe).forEach(([Te,Pe])=>{if(!Te||!Pe)return;ve.add(Te);const Ve=Pe.type==="busy"||Pe.type==="retry"?"busy":"idle";pe(Te,Ve)});const Ge=de.getState().sessionActivityPhase;if(Ge)for(const[Te,Pe]of Ge.entries())Le.has(Te)&&(Pe==="busy"||Pe==="cooldown")&&!ve.has(Te)&&pe(Te,"idle")},we=(async()=>{try{const fe=await De.getGlobalSessionStatus();if(fe&&Object.keys(fe).length>0){$(fe);return}const ve=new Set;l.forEach(Ve=>{const pt=y(Ve.id);pt&&ve.add(pt)});const Le=x(b??null);Le&&ve.add(Le);const Ge=Array.from(ve);if(Ge.length===0){const Ve=await De.getSessionStatus();Ve&&$(Ve);return}const Te=await Promise.allSettled(Ge.map(Ve=>De.getSessionStatusForDirectory(Ve))),Pe={};if(Te.forEach(Ve=>{Ve.status!=="fulfilled"||!Ve.value||Object.assign(Pe,Ve.value)}),Object.keys(Pe).length===0&&Array.from(de.getState().sessionActivityPhase?.values?.()??[]).some(pt=>pt==="busy"||pt==="cooldown")&&!await De.checkHealth().catch(()=>!1))return;$(Pe)}catch{}})().finally(()=>{O.current=null});return O.current=we,we},[b,x,y,l,pe]);c.useEffect(()=>{const ae=a??null,$=ee.current,we=y(ae),fe=ue.current;$&&ae&&$!==ae&&fe&&we&&fe!==we&&He(),ee.current=ae,ue.current=we},[a,He,y]);const Y=c.useCallback(ae=>{if(q.current=Date.now(),Wt()&&console.debug("[useEventStream] Received event:",ae.type,ae.properties),!ae.properties)return;const $=ae.properties;if(!new Set(["session.abort","session.error"]).has(ae.type)){const fe=(typeof $.session=="object"&&$.session!==null?$.session:null)||(typeof $.sessionInfo=="object"&&$.sessionInfo!==null?$.sessionInfo:null);if(fe){const ve=fe,Le=typeof ve.id=="string"&&ve.id.length>0?ve.id:typeof ve.sessionID=="string"&&ve.sessionID.length>0?ve.sessionID:typeof $.sessionID=="string"&&$.sessionID.length>0?$.sessionID:typeof $.id=="string"&&$.id.length>0?$.id:void 0;if(Le){const Ge=typeof ve.title=="string"?ve.title:typeof $.title=="string"?$.title:void 0,Te=typeof ve.summary=="object"&&ve.summary!==null?ve.summary:typeof $.summary=="object"&&$.summary!==null?$.summary:void 0;if(Ge!==void 0||Te!==void 0){const Pe={};Ge!==void 0&&(Pe.title=Ge),Te!==void 0&&(Pe.summary=Te),i(Le,Pe)}}}}switch(ae.type){case"server.connected":h();break;case"global.disposed":case"server.instance.disposed":{D("server_disposed_event");break}case"openchamber:session-activity":{const fe=typeof $.sessionId=="string"?$.sessionId:null,ve=typeof $.phase=="string"?$.phase:null;fe&&(ve==="idle"||ve==="busy"||ve==="cooldown")&&(pe(fe,ve),me(fe,typeof $.directory=="string"?$.directory:null));break}case"session.status":if(oe.current)break;{const fe=typeof $.sessionID=="string"?$.sessionID:null,ve=typeof $.status=="object"&&$.status!==null?$.status:null,Le=typeof ve?.type=="string"?ve.type:null;fe&&Le&&(pe(fe,Le==="busy"||Le==="retry"?"busy":"idle"),me(fe,typeof $.directory=="string"?$.directory:null))}break;case"message.part.updated":{const fe=typeof $.part=="object"&&$.part!==null?$.part:null;if(!fe)break;const ve=fe,Le=typeof $.info=="object"&&$.info!==null?$.info:$,Ge=typeof Le.sessionID=="string"?Le.sessionID:null,Te=typeof ve.sessionID=="string"&&ve.sessionID.length>0?ve.sessionID:typeof Ge=="string"&&Ge.length>0?Ge:typeof $.sessionID=="string"&&$.sessionID.length>0?$.sessionID:null,Pe=typeof Le.id=="string"?Le.id:null,Ve=typeof ve.messageID=="string"&&ve.messageID.length>0?ve.messageID:typeof Pe=="string"&&Pe.length>0?Pe:typeof $.messageID=="string"&&$.messageID.length>0?$.messageID:null;if(!Te||!Ve){Wt()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:ve.sessionID??Ge??$.sessionID,messageID:ve.messageID??Pe??$.messageID});break}const pt=Te,et=Ve,wt=de.getState().sessionMemoryState.get(pt)?.trimmedHeadMaxId;if(wt&&!Md(et,wt)){Wt()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:pt,messageId:et,trimmedHeadMaxId:wt});break}let Nt="assistant";if(Le&&typeof Le.role=="string")Nt=Le.role;else{const St=Dd(pt,et);if(St){const At=St.info.role;typeof At=="string"&&(Nt=At)}}if(M(et,"part_received",{role:Nt}),Nt==="user"&&ve.synthetic===!0){M(et,"skipped_synthetic_user_part");break}const Pt={...fe,type:fe.type||"text"};M(et,"addStreamingPart_called"),s(pt,et,Pt,Nt);break}case"message.updated":{const fe=typeof $.info=="object"&&$.info!==null?$.info:$,ve=fe,Le=typeof ve.sessionID=="string"&&ve.sessionID.length>0?ve.sessionID:typeof $.sessionID=="string"&&$.sessionID.length>0?$.sessionID:null,Ge=typeof ve.id=="string"&&ve.id.length>0?ve.id:typeof $.messageID=="string"&&$.messageID.length>0?$.messageID:null;if(!Le||!Ge){Wt()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:ve.sessionID??$.sessionID,messageID:ve.id??$.messageID});break}const Te=Le,Pe=Ge,Ve=de.getState().sessionMemoryState.get(Te)?.trimmedHeadMaxId;if(Ve&&!Md(Pe,Ve)){Wt()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Te,messageId:Pe,trimmedHeadMaxId:Ve});break}if(oe.current&&Wt())try{const Ye=$.parts||ve.parts||[],Qe=(Array.isArray(Ye)?Ye.filter(it=>it?.type==="text"):[]).map(it=>{const ht=it;return typeof ht?.text=="string"?ht.text:typeof ht?.content=="string"?ht.content:""}).join(`
|
|
106
|
+
`);console.info("[STREAM-TRACE] message.updated",{messageId:Pe,role:ve.role,status:ve.status,textLen:Qe.length,textPreview:Qe.slice(0,120),partsCount:Array.isArray(Ye)?Ye.length:0})}catch{}if(M(Pe,"message_updated",{role:ve.role}),ve.role==="user"){const Ye=$.parts||ve.parts,Je=Array.isArray(Ye)?Ye:[],Qe={...fe,userMessageMarker:!0,clientRole:"user"};if(t(Te,Pe,Qe),Je.length>0)for(let it=0;it<Je.length;it++){const ht=Je[it];if(ht.synthetic===!0)continue;const Q={...ht,type:ht?.type||"text",sessionID:ht?.sessionID||Te,messageID:ht?.messageID||Pe};s(Te,Pe,Q,"user")}M(Pe,"user_message_created_from_event",{partsCount:Je.length});break}const pt=Dd(Te,Pe),et=Nd(pt?.parts||[]),wt=pt?.info?.finish==="stop",Nt=$.parts||ve.parts,Pt=Array.isArray(Nt)?Nt:[],St=Pt.length>0,Jt=typeof(ve.time||{})?.completed=="number";if(!St&&!Jt)break;const Ee=fe.finish,Oe=typeof Ee=="string"?Ee:null,We=Oe==="stop";if(ve.role==="assistant"&&St){const Ye=Nd(Pt);if(et>0&&Ye+r0<et&&!We){M(Pe,"skipped_shrinking_update",{incomingLen:Ye,existingLen:et});break}if(oe.current){const Qe=et>0&&Ye<et,it=Pt.some(Q=>{if(!Q||Q.type!=="text")return!1;const be=Q;return typeof be.text=="string"&&be.text.length>0});if(Qe&&!(We&&it)){M(Pe,"desktop_shrinking_update_suppressed",{incomingLen:Ye,existingLen:et});break}}}if(t(Te,Pe,fe),St&&ve.role!=="user"){const Qe=(de.getState().messages.get(Te)||[]).find(Q=>Q.info.id===Pe),it=!Qe||Qe.parts.length===0;M(Pe,it?"server_parts_injected":"server_parts_refreshed",{count:Pt.length});const ht=oe.current&&ve.role==="assistant"?Pt.filter(Q=>Q?.type!=="text"):Pt;for(let Q=0;Q<ht.length;Q++){const be=ht[Q],xe={...be,type:be?.type||"text",sessionID:be?.sessionID||Te,messageID:be?.messageID||Pe};s(Te,Pe,xe,ve.role),M(Pe,`server_part_${Q}`)}}const Ze=fe.time,Zt=Ze?.completed,zt=typeof Zt=="number"&&Number.isFinite(Zt),dt=Oe==="stop"||wt;if(fe.role==="assistant"&&(zt||dt)&&fe.role==="assistant"){const Je=de.getState().messages.get(Te)||[];let Qe=null,it="";for(let $e=0;$e<Je.length;$e++){const Ue=Je[$e];Ue.info.role==="assistant"&&Ue.info.id>it&&(it=Ue.info.id,Qe=Ue.info.id)}if(a===Te&&Pe!==Qe)break;if(!dt&&oe.current){M(Pe,"desktop_completion_without_stop");break}const Q=zt?Zt:Date.now();zt||t(Te,Pe,{...fe,time:{...Ze??{},completed:Q}}),M(Pe,"completed",{timeCompleted:Q}),C(Pe),t0(Te,Pe,Q),r(Te,Pe),oe.current||Oe==="stop"&&de.getState().sessionActivityPhase?.get(Te)==="busy"&&pe(Te,"cooldown");const be=fe.sessionID,xe=typeof be=="string"&&be.length>0?be:Te;me(xe,typeof $.directory=="string"?$.directory:null),fe.summary&&typeof xe=="string"&&n(xe,null)}break}case"session.created":case"session.updated":{const fe=typeof $.info=="object"&&$.info!==null?$.info:typeof $.sessionInfo=="object"&&$.sessionInfo!==null?$.sessionInfo:typeof $.session=="object"&&$.session!==null?$.session:$,ve=typeof fe.id=="string"&&fe.id.length>0?fe.id:typeof fe.sessionID=="string"&&fe.sessionID.length>0?fe.sessionID:typeof $.sessionID=="string"&&$.sessionID.length>0?$.sessionID:typeof $.id=="string"&&$.id.length>0?$.id:void 0;if(ve){const Le=typeof fe.time=="object"&&fe.time!==null?fe.time:typeof $.time=="object"&&$.time!==null?$.time:null,Ge=Le&&typeof Le.compacting=="number"?Le.compacting:null;n(ve,Ge);const Te=typeof fe.directory=="string"?fe.directory:typeof $.directory=="string"?$.directory:null,Pe={...fe,id:ve,...Te?{directory:Te}:{}};f(Pe)}break}case"session.deleted":{const fe=typeof $.sessionID=="string"?$.sessionID:typeof $.id=="string"?$.id:null;fe&&p(fe);break}case"session.abort":{const fe=typeof $.sessionID=="string"&&$.sessionID.length>0?$.sessionID:null,ve=typeof $.messageID=="string"&&$.messageID.length>0?$.messageID:null;fe&&ve&&r(fe,ve);break}case"permission.asked":{if(!("sessionID"in $)||typeof $.sessionID!="string")break;const fe=$;o(fe);const ve=`${fe.sessionID}:${fe.id}`;J.current.has(ve)||setTimeout(()=>{if(_.current===fe.sessionID||!de.getState().permissions.get(fe.sessionID)?.some(Pe=>Pe.id===fe.id))return;J.current.add(ve);const Te=de.getState().sessions.find(Pe=>Pe.id===fe.sessionID)?.title||"Session";ns(async()=>{const{toast:Pe}=await import("./vendor-.bun-BEzqubWg.js").then(Ve=>Ve.cn);return{toast:Pe}},__vite__mapDeps([0,1])).then(({toast:Pe})=>{Pe.warning("Permission required",{description:Te,action:{label:"Open",onClick:()=>{Re.getState().setActiveMainTab("chat"),de.getState().setCurrentSession(fe.sessionID)}}})})},0);break}case"permission.replied":break;case"todo.updated":{const fe=typeof $.sessionID=="string"?$.sessionID:null,ve=Array.isArray($.todos)?$.todos:null;fe&&ve&&mb(fe,ve);break}}},[a,s,r,t,o,h,me,n,i,M,C,pe,f,p,D]),le=c.useCallback(()=>{const ae=T();return Z.current=ae,ae==="visible"&&E.current},[T]),te=c.useCallback(()=>{Wt()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:oe.current,hasUnsubscribe:!!k.current,currentSessionId:_.current,effectiveDirectory:b,onlineStatus:E.current,visibilityState:Z.current,lastEventTimestamp:q.current,reconnectAttempts:P.current})},[b]),ne=c.useCallback(async()=>!0,[]),K=c.useCallback(()=>{if(z.current){Wt()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(z.current=!0,A.current&&(clearTimeout(A.current),A.current=null),k.current){const ae=k.current;k.current=null;try{ae()}catch($){console.warn("[useEventStream] Error during unsubscribe:",$)}}z.current=!1},[]),ie=c.useCallback(async ae=>{if(te(),!le()){B.current=!0,E.current?v("paused","Paused while hidden"):v("offline","Waiting for network");return}oe.current&&(await ne()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),ae?.resetAttempts&&(P.current=0),K(),q.current=Date.now(),v("connecting",null),Wt()&&console.info("[useEventStream] Starting event stream...");const $=fe=>{console.warn("Event stream error:",fe)},we=()=>{const fe=B.current;if(P.current=0,B.current=!1,q.current=Date.now(),v("connected",null),h(),Array.from(de.getState().sessionActivityPhase?.values?.()??[]).some(Le=>Le==="busy"||Le==="cooldown")&&He(),fe)D("sse_reconnected");else{const Le=_.current;Le&&setTimeout(()=>{N(Le,"sse_reconnected").then(()=>me(Le)).catch(Ge=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Ge)})},0)}};if(Wt()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:b,isCleaningUp:z.current}),z.current){Wt()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const fe=De.subscribeToGlobalEvents(Le=>{const Ge=Le.payload,Te=Le.payload,Pe=typeof Te.properties=="object"&&Te.properties!==null?Te.properties:{},Ve=Le.directory&&Le.directory!=="global"?{...Pe,directory:Le.directory}:Pe;Y({type:typeof Ge.type=="string"?Ge.type:"",properties:Ve})},$,we),ve=()=>{try{fe()}catch(Le){console.warn("[useEventStream] Error during unsubscribe:",Le)}};z.current?ve():k.current=ve}catch(fe){console.error("[useEventStream] Error during subscription:",fe),$(fe)}},[le,K,v,h,N,me,Y,b,He,ne,te,D]),ce=c.useCallback(ae=>{if(!le()){B.current=!0,K(),E.current?v("paused","Paused while hidden"):v("offline","Waiting for network");return}const $=P.current+1;P.current=$;const we=ae??`Retrying (${$})`;v("reconnecting",we);const fe=$<=3?Math.min(1e3*Math.pow(2,$-1),8e3):Math.min(2e3*Math.pow(2,$-3),32e3),ve=Math.floor(Math.random()*250),Le=fe+ve;A.current&&clearTimeout(A.current),A.current=setTimeout(()=>{ie({resetAttempts:!1})},Le)},[le,K,v,ie]);c.useEffect(()=>{const ae=I.current;typeof window<"u"&&(window.__messageTracker=M);let $=null;oe.current&&typeof window<"u"&&($=Ve=>{const pt=typeof Ve.detail?.sessionId=="string"?Ve.detail.sessionId:null,et=typeof Ve.detail?.phase=="string"?Ve.detail.phase:null;pt&&(et==="idle"||et==="busy"||et==="cooldown")&&(pe(pt,et),me(pt))},window.addEventListener("openchamber:session-activity",$));const we=()=>{X.current&&(clearTimeout(X.current),X.current=null)},fe=()=>{X.current||(X.current=setTimeout(()=>{const Ve=T();Z.current=Ve,Ve!=="visible"?(K(),B.current=!0,v("paused","Paused while hidden")):we()},5e3))},ve=()=>{if(Z.current=T(),Z.current==="visible"){if(we(),ye("visibility_restore"),B.current||!k.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ve=_.current;Ve&&(N(Ve,"visibility_restore").catch(()=>{}),me(Ve)),He(),v("connecting","Resuming stream"),ie({resetAttempts:!0})}}else v("paused","Paused while hidden"),fe()},Le=()=>{if(Z.current=T(),Z.current==="visible"&&(we(),ye("window_focus"),B.current||!k.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ve=_.current;Ve&&(me(Ve),N(Ve,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(pt=>console.warn("[useEventStream] Failed to refresh messages:",pt))),He(),v("connecting","Resuming stream"),ie({resetAttempts:!0})}},Ge=()=>{E.current=!0,ye("network_restored"),(B.current||!k.current)&&(v("connecting","Network restored"),ie({resetAttempts:!0}))},Te=()=>{E.current=!1,B.current=!0,v("offline","Waiting for network"),K()};typeof document<"u"&&document.addEventListener("visibilitychange",ve),typeof window<"u"&&(window.addEventListener("online",Ge),window.addEventListener("offline",Te),window.addEventListener("focus",Le));const Pe=setTimeout(()=>{ie({resetAttempts:!0})},100);return re.current&&clearInterval(re.current),re.current=setInterval(()=>{if(!le())return;const Ve=Date.now();Array.from(de.getState().sessionActivityPhase?.values?.()??[]).some(et=>et==="busy"||et==="cooldown")&&He(),Ve-q.current>25e3&&Promise.resolve().then(async()=>{try{await De.checkHealth()?q.current=Date.now():ce("Refreshing stalled stream")}catch(et){console.warn("Health check after stale stream failed:",et),ce("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Pe),$&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",$),typeof document<"u"&&document.removeEventListener("visibilitychange",ve),typeof window<"u"&&(window.removeEventListener("online",Ge),window.removeEventListener("offline",Te),window.removeEventListener("focus",Le)),we(),re.current&&(clearInterval(re.current),re.current=null),ae.forEach(Ve=>clearTimeout(Ve)),ae.clear(),Ci.clear(),B.current=!1,Z.current=T(),E.current=typeof navigator>"u"?!0:navigator.onLine,K(),U.current&&(clearTimeout(U.current),U.current=null),v("idle",null)}},[b,M,T,K,v,ie,ce,u,me,pe,He,le,m,ye,N])},i0=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=de(),{toggleCommandPalette:a,toggleHelpDialog:i,toggleSidebar:l,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=Re(),{themeMode:p,setThemeMode:h}=Ur(),{working:j}=mm(),g=c.useRef(null),b=c.useRef(null),x=c.useRef(!1),y=c.useCallback(()=>{b.current&&(clearTimeout(b.current),b.current=null),g.current=null,n()},[n]);c.useEffect(()=>{const w=S=>{if(bs(S)&&S.key==="k"&&(S.preventDefault(),a()),bs(S)&&S.shiftKey&&S.key.toLowerCase()==="l"){const N=_r()?.diagnostics;if(!N||(S.preventDefault(),x.current))return;x.current=!0,N.downloadLogs().then(({fileName:D,content:M})=>{const C=D||"openchamber.log",k=new Blob([M],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(k),P=document.createElement("a");P.href=A,P.download=C,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(A)}).finally(()=>{x.current=!1});return}if(bs(S)&&S.key==="."&&(S.preventDefault(),i()),bs(S)&&S.key.toLowerCase()==="n"){if(S.preventDefault(),at.getState().settingsAutoCreateWorktree?!S.shiftKey:S.shiftKey){u("chat"),d(!1),oa();return}u("chat"),d(!1),s()}if(bs(S)&&S.key==="/"){S.preventDefault();const v=["light","dark","system"],D=(v.indexOf(p)+1)%v.length;h(v[D])}if(bs(S)&&!S.shiftKey&&S.key.toLowerCase()==="t"){S.preventDefault();const{isTimelineDialogOpen:v,setTimelineDialogOpen:N}=Re.getState();N(!v);return}if(bs(S)&&!S.shiftKey&&S.key===","){S.preventDefault();const{isSettingsDialogOpen:v}=Re.getState();m(!v);return}if(bs(S)&&!S.shiftKey&&S.key.toLowerCase()==="l"){S.preventDefault();const{isMobile:v,isSessionSwitcherOpen:N}=Re.getState();v?d(!N):l();return}if(bs(S)&&!S.shiftKey&&S.key.toLowerCase()==="i"){S.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(bs(S)&&S.shiftKey&&S.key.toLowerCase()==="m"){const{isSettingsDialogOpen:v,isCommandPaletteOpen:N,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isAboutDialogOpen:C,activeMainTab:k,isModelSelectorOpen:A}=Re.getState();if(v||N||D||M||C||!(k==="chat"))return;S.preventDefault(),f(!A);return}if(S.key==="Escape"){const{isSettingsDialogOpen:v,isCommandPaletteOpen:N,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isAboutDialogOpen:C,activeMainTab:k}=Re.getState();if(v){S.preventDefault(),m(!1),y();return}if(N||D||M||C||!(k==="chat")){y();return}const L=o;if(!(j.canAbort&&!!L)){y();return}const z=Date.now(),H=g.current;if(H&&z<H){S.preventDefault(),y(),r();return}S.preventDefault();const V=t(3e3)??z+3e3;g.current=V,b.current&&clearTimeout(b.current);const J=Math.max(V-z,0);b.current=setTimeout(()=>{g.current&&Date.now()>=g.current&&y()},J||0);return}};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[s,r,a,i,l,d,u,m,f,h,p,j,t,y,o]),c.useEffect(()=>()=>{y()},[y])},Ad="openchamber:menu-action",l0=s=>{const{openNewSessionDraft:r}=de(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:i,setSettingsDialogOpen:l,setAboutDialogOpen:d}=Re(),{addProject:u}=It(),{requestAccess:m,startAccessing:f}=aa(),{setThemeMode:p}=Ur(),h=c.useRef(!1),j=c.useCallback(()=>{ss()?m("").then(async g=>{if(!g.success||!g.path){g.error&&g.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:g.error});return}const b=await f(g.path);if(!b.success){se.error("Failed to open directory",{description:b.error||"Desktop could not grant file access."});return}u(g.path,{id:g.projectId})||se.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(g=>{console.error("Desktop: Error selecting directory:",g),se.error("Failed to select directory")}):hn.requestDirectoryDialog()},[u,m,f]);c.useEffect(()=>{const g=b=>{switch(b.detail){case"about":d(!0);break;case"settings":l(!0);break;case"command-palette":t();break;case"new-session":i("chat"),a(!1),r();break;case"new-worktree-session":i("chat"),a(!1),oa();break;case"change-workspace":j();break;case"open-git-tab":{const{activeMainTab:y}=Re.getState();i(y==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:y}=Re.getState();i(y==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:y}=Re.getState();i(y==="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=_r()?.diagnostics;if(!w||h.current)break;h.current=!0,w.downloadLogs().then(({fileName:S,content:v})=>{const N=S||"openchamber.log",D=new Blob([v],{type:"text/plain;charset=utf-8"}),M=URL.createObjectURL(D),C=document.createElement("a");C.href=M,C.download=N,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(M),se.success("Logs saved",{description:`Downloaded to ~/Downloads/${N}`})}).catch(()=>{se.error("Failed to download logs")}).finally(()=>{h.current=!1});break}}};return window.addEventListener(Ad,g),()=>window.removeEventListener(Ad,g)},[r,t,n,o,a,i,l,d,p,s,j])},c0=s=>s.role==="assistant",Ed=s=>{const r=s.info;if(!c0(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},Io=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},Id=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>Tn(n)).join(" ").replace(/\s+/g," ").trim(),d0=(s,r)=>{if(!s||!Io(s.info))return-1;const t=Id(s),n=typeof s.info?.time?.created=="number"?s.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((i,l)=>{if(!Io(i.info))return;const d=Id(i),u=!!(t&&d&&d===t),m=typeof i.info?.time?.created=="number"?i.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=l,a=p);return}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=l,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(i=>{if(!Io(i.info))return!1;const l=typeof i.info?.time?.created=="number"?i.info.time.created:void 0;return typeof l!="number"?!1:Math.abs(l-n)<1e3}):-1},u0=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=de(),n=c.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=c.useRef(void 0),a=c.useRef(0),i=c.useCallback(async()=>{if(!s||n)return;const l=Date.now();if(!(l-a.current<2e3)){a.current=l;try{const d=r.get(s)||[],u=await De.getSessionMessages(s),m=await s0(s);if(!u)return;const f=d[d.length-1];if(f){const p=u.findIndex(g=>g.info.id===f.info.id),j=p===-1?d0(f,u):p;if(j!==-1)if(j<u.length-1){const g=u.slice(j+1);console.log(`[SYNC] Found ${g.length} new messages to append`);const b=[...d,...g],{syncMessages:x}=de.getState();x(s,b)}else{const g=u[j],b=d[d.length-1],x=Ed(g),y=Ed(b);if(x&&!y){console.log("[SYNC] Last message completed on server");const w=[...d.slice(0,-1),g],{syncMessages:S}=de.getState();S(s,w)}}else if(Io(f.info)){const g=u.slice(-ls.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:b}=de.getState();b(s,g)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(m){const p=u.findIndex(h=>h.info.id===m.messageId);if(p!==-1){if(p<u.length-1){const j=u.slice(p+1).slice(-ls.VIEWPORT_MESSAGES);if(j.length>0){console.log(`[SYNC] Restoring ${j.length} messages after cursor`);const{syncMessages:g}=de.getState();g(s,j)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const h=u.slice(-ls.VIEWPORT_MESSAGES),{syncMessages:j}=de.getState();j(s,h)}}else if(u.length>0){const p=u.slice(-ls.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:h}=de.getState();h(s,p)}}catch(d){console.debug("Background sync failed:",d)}}},[s,r,n]);c.useEffect(()=>{const l=()=>{console.log("[FOCUS] Window focused - checking for updates"),i()};return window.addEventListener("focus",l),()=>window.removeEventListener("focus",l)},[i]),c.useEffect(()=>{if(!s||n)return;const l=()=>{document.visibilityState==="visible"&&i(),o.current=setTimeout(l,3e4)};return o.current=setTimeout(l,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,n,i]),c.useEffect(()=>{const l=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),i())};return document.addEventListener("visibilitychange",l),()=>document.removeEventListener("visibilitychange",l)},[i])},m0=()=>{c.useEffect(()=>{let s=!1;return(async()=>{try{const t=await De.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const i=a,l=i.type==="busy"||i.type==="retry"?"busy":"idle";n.set(o,l)}),n.size>0&&de.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function f0(){const{git:s}=vn(),r=ft(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=de(),{setActiveDirectory:a,startPolling:i,stopPolling:l,fetchAll:d}=Ut(),u=c.useMemo(()=>{const m=t?o.get(t)??void 0:void 0,p=n.find(h=>h.id===t)?.directory??null;return m?.path??p??r??null},[t,n,o,r]);c.useEffect(()=>{if(!u||!s){l();return}return a(u),d(u,s),i(s),()=>{l()}},[u,s,a,i,l,d])}function p0({children:s}){return f0(),e.jsx(e.Fragment,{children:s})}const h0=()=>{const[{isUpdating:s,message:r},t]=c.useState(()=>Oh());return c.useEffect(()=>Rh(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(il,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},g0=({open:s,onOpenChange:r})=>{const[t,n]=c.useState(null);c.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:l}=await ns(async()=>{const{getVersion:u}=await import("./vendor-.bun-BEzqubWg.js").then(m=>m.cp);return{getVersion:u}},__vite__mapDeps([0,1])),d=await l();n(d)}catch{n("1.4.4")}})():n("1.4.4")},[s]);const o=t;return e.jsx(ds,{open:s,onOpenChange:r,children:e.jsx(us,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(il,{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(oi,{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(Xd,{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(ai,{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 Za({apis:s,children:r}){return e.jsx(Yi.Provider,{value:s,children:r})}const y0="curl -fsSL https://opencode.ai/install | bash",x0=3e3;function b0({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(Bs,{className:"h-4 w-4"})})]})}const w0=3e4;function v0({onCliAvailable:s}){const[r,t]=c.useState(!1),[n,o]=c.useState(!1),[a,i]=c.useState(!1);c.useEffect(()=>{const m=setTimeout(()=>o(!0),w0);return()=>clearTimeout(m)},[]),c.useEffect(()=>{i(typeof window.opencodeDesktop<"u")},[]);const l=c.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await ns(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-BEzqubWg.js").then(j=>j.co);return{getCurrentWindow:h}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=c.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=c.useCallback(async()=>{try{await navigator.clipboard.writeText(y0),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return c.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,x0);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:l,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(Po,{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(Ot,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(b0,{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(Po,{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 j0=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=Re();return e.jsx(g0,{open:s,onOpenChange:r})};function S0({apis:s}){const{initializeApp:r,isInitialized:t,isConnected:n}=at(),{error:o,clearError:a,loadSessions:i}=de(),l=ft(v=>v.currentDirectory),d=ft(v=>v.isSwitchingDirectory),[u,m]=c.useState(!1),{uiFont:f,monoFont:p}=Pm(),[h,j]=c.useState(()=>s.runtime.isDesktop),[g,b]=c.useState(()=>s.runtime.isVSCode),[x,y]=c.useState(()=>s.runtime.isDesktop?yh():!0);c.useEffect(()=>{j(s.runtime.isDesktop),b(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),c.useEffect(()=>(Cl(s),()=>Cl(null)),[s]),c.useEffect(()=>{if(typeof document>"u")return;const v=document.documentElement,N=od[f]?.stack??od[Av].stack,D=Er[p]?.stack??Er[Ao].stack;v.style.setProperty("--font-sans",N),v.style.setProperty("--font-heading",N),v.style.setProperty("--font-family-sans",N),v.style.setProperty("--font-mono",D),v.style.setProperty("--font-family-mono",D),v.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=N)},[f,p]),c.useEffect(()=>{if(t){const N=setTimeout(()=>{const D=document.getElementById("initial-loading");D&&(D.classList.add("fade-out"),setTimeout(()=>{D.remove()},300))},150);return()=>clearTimeout(N)}},[t]),c.useEffect(()=>{const v=setTimeout(()=>{const N=document.getElementById("initial-loading");N&&!t&&(N.classList.add("fade-out"),setTimeout(()=>{N.remove()},300))},5e3);return()=>clearTimeout(v)},[t]),c.useEffect(()=>{(async()=>g||await r())()},[r,g]),c.useEffect(()=>{if(d)return;(async()=>g||n&&(De.setDirectory(l),await i()))()},[l,d,i,n,g]),a0(),i0();const w=c.useCallback(()=>{m(v=>!v)},[]);l0(w),u0(),m0(),Bm(),c.useEffect(()=>{const v=N=>{bs(N)&&N.shiftKey&&N.key==="D"&&(N.preventDefault(),m(D=>!D))};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[]),c.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const S=c.useCallback(()=>{y(!0),window.location.reload()},[]);return h&&!x?e.jsx(rs,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(v0,{onCliAvailable:S})})}):g?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(rs,{children:e.jsx(Za,{apis:s,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Yj,{}),e.jsx(Ja,{})]})})}):e.jsx(rs,{children:e.jsx(Za,{apis:s,children:e.jsx(ed,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx($j,{}),e.jsx(Ja,{})]})})})}):e.jsx(rs,{children:e.jsx(Za,{apis:s,children:e.jsx(p0,{children:e.jsx(ed,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx(Rj,{}),e.jsx(Ja,{}),e.jsx(h0,{}),e.jsx(j0,{}),u&&e.jsx(Qj,{onClose:()=>m(!1)})]})})})})})}const Km=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=ft.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&t.setDirectory(r,{showOverlay:!1})},Ym="/auth/session",k0=async()=>fetch(Ym,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Pd=async s=>fetch(Ym,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),fl=({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})]}),N0=({message:s="Preparing workspace…"})=>e.jsx(fl,{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})})}),C0=({onRetry:s})=>e.jsx(fl,{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(ke,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),M0=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},D0=()=>{try{const s=new URL(window.location.href);s.searchParams.delete("token"),window.history.replaceState({},"",s.toString())}catch{}},A0=({children:s})=>{const r=c.useMemo(()=>ss(),[]),t=c.useMemo(()=>Ht(),[]),n=r||t,[o,a]=c.useState(()=>n?"authenticated":"pending"),[i,l]=c.useState(""),[d,u]=c.useState(!1),[m,f]=c.useState(""),p=c.useRef(null),h=c.useRef(n),j=c.useRef(!1),g=c.useCallback(async()=>{if(n){a("authenticated");return}a(x=>x==="authenticated"?x:"pending");try{const x=await k0();if(x.ok){a("authenticated"),f("");return}if(x.status===401){a("locked");return}a("error")}catch(x){console.warn("Failed to check session status:",x),a("error")}},[n]);c.useEffect(()=>{n||g()},[g,n]),c.useEffect(()=>{!n&&o==="locked"&&(h.current=!1)},[n,o]),c.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),c.useEffect(()=>{if(n||o!=="locked"||j.current||d)return;const x=M0();x&&(j.current=!0,D0(),u(!0),f(""),Pd(x).then(y=>{if(y.ok){l(""),a("authenticated");return}if(y.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(y=>{console.warn("Failed to submit URL token:",y),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),c.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await nu(),await ou(),await Km()))())},[n,o]);const b=async x=>{if(x.preventDefault(),!(!i||d)){u(!0),f("");try{const y=await Pd(i);if(y.ok){l(""),a("authenticated");return}if(y.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(y){console.warn("Failed to submit UI password:",y),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(N0,{}):o==="error"?e.jsx(C0,{onRetry:()=>{g()}}):o==="locked"?e.jsx(fl,{children:e.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold text-foreground",children:"Unlock OpenChamber"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"This session is password-protected."})]}),e.jsxs("form",{onSubmit:b,className:"w-full space-y-2","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zp,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(mt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:x=>{l(x.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(ke,{type:"submit",size:"icon",disabled:!i||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(is,{className:"h-4 w-4 animate-spin"}):e.jsx(eh,{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})},ei=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(l=>l+l).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,i=n&255;return`${o} ${a} ${i}`};class E0{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(`
|
|
107
|
+
`)}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=ei(r.colors.surface.muted),o=ei(r.colors.surface.subtle),a=ei(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 i=r.metadata.variant==="dark",l=i?.8:.95,d=i?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${l}) !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,l)} !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 {
|
|
108
|
+
${t}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
.dark {
|
|
112
|
+
${t}
|
|
113
|
+
}`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
|
|
114
|
+
${t}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
:root:not(.dark) {
|
|
118
|
+
${t}
|
|
119
|
+
}`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),n.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(n),document.documentElement.setAttribute("data-theme",r.metadata.variant)}generatePrimaryColors(r){const t=[];return t.push(` --primary-base: ${r.base};`),t.push(` --primary-hover: ${r.hover||this.darken(r.base,10)};`),t.push(` --primary-active: ${r.active||this.darken(r.base,20)};`),t.push(` --primary-foreground: ${r.foreground||"#ffffff"};`),t.push(` --primary-muted: ${r.muted||this.opacity(r.base,.5)};`),t.push(` --primary-emphasis: ${r.emphasis||this.lighten(r.base,10)};`),t}generateSurfaceColors(r){const t=[];return t.push(` --surface-background: ${r.background};`),t.push(` --surface-foreground: ${r.foreground};`),t.push(` --surface-muted: ${r.muted};`),t.push(` --surface-muted-foreground: ${r.mutedForeground};`),t.push(` --surface-elevated: ${r.elevated};`),t.push(` --surface-elevated-foreground: ${r.elevatedForeground};`),t.push(` --surface-overlay: ${r.overlay};`),t.push(` --surface-subtle: ${r.subtle};`),t}generateInteractiveColors(r){const t=[];return t.push(` --interactive-border: ${r.border};`),t.push(` --interactive-border-hover: ${r.borderHover};`),t.push(` --interactive-border-focus: ${r.borderFocus};`),t.push(` --interactive-selection: ${r.selection};`),t.push(` --interactive-selection-foreground: ${r.selectionForeground};`),t.push(` --interactive-focus: ${r.focus};`),t.push(` --interactive-focus-ring: ${r.focusRing};`),t.push(` --interactive-cursor: ${r.cursor};`),t.push(` --interactive-hover: ${r.hover};`),t.push(` --interactive-active: ${r.active};`),t}generateStatusColors(r){const t=[];return t.push(` --status-error: ${r.error};`),t.push(` --status-error-foreground: ${r.errorForeground};`),t.push(` --status-error-background: ${r.errorBackground};`),t.push(` --status-error-border: ${r.errorBorder};`),t.push(` --status-warning: ${r.warning};`),t.push(` --status-warning-foreground: ${r.warningForeground};`),t.push(` --status-warning-background: ${r.warningBackground};`),t.push(` --status-warning-border: ${r.warningBorder};`),t.push(` --status-success: ${r.success};`),t.push(` --status-success-foreground: ${r.successForeground};`),t.push(` --status-success-background: ${r.successBackground};`),t.push(` --status-success-border: ${r.successBorder};`),t.push(` --status-info: ${r.info};`),t.push(` --status-info-foreground: ${r.infoForeground};`),t.push(` --status-info-background: ${r.infoBackground};`),t.push(` --status-info-border: ${r.infoBorder};`),t}generateSyntaxColors(r){const t=[];t.push(` --syntax-background: ${r.base.background};`),t.push(` --syntax-foreground: ${r.base.foreground};`),t.push(` --syntax-comment: ${r.base.comment};`),t.push(` --syntax-keyword: ${r.base.keyword};`),t.push(` --syntax-string: ${r.base.string};`),t.push(` --syntax-number: ${r.base.number};`),t.push(` --syntax-function: ${r.base.function};`),t.push(` --syntax-variable: ${r.base.variable};`),t.push(` --syntax-type: ${r.base.type};`),t.push(` --syntax-operator: ${r.base.operator};`);const n=this.generateSyntaxTokens(r);for(const[o,a]of Object.entries(n))t.push(` --syntax-${this.kebabCase(o)}: ${a};`);return t}generateSyntaxTokens(r){const t=r.base,n=r.tokens||{};return{commentDoc:n.commentDoc||this.lighten(t.comment,10),stringEscape:n.stringEscape||this.darken(t.string,20),stringInterpolation:n.stringInterpolation||t.variable,stringRegex:n.stringRegex||this.adjustHue(t.string,15),keywordControl:n.keywordControl||t.keyword,keywordOperator:n.keywordOperator||t.operator,keywordImport:n.keywordImport||this.lighten(t.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(t.keyword),functionCall:n.functionCall||this.lighten(t.function,5),functionBuiltin:n.functionBuiltin||this.darken(t.function,10),method:n.method||t.function,methodCall:n.methodCall||this.lighten(t.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(t.variable),variableProperty:n.variableProperty||this.lighten(t.variable,10),variableReadonly:n.variableReadonly||t.number,parameter:n.parameter||t.variable,typePrimitive:n.typePrimitive||this.darken(t.type,10),typeInterface:n.typeInterface||t.type,className:n.className||this.emphasize(t.type),enum:n.enum||t.type,boolean:n.boolean||t.number,null:n.null||this.opacity(t.number,.7),constant:n.constant||t.number,punctuation:n.punctuation||this.opacity(t.foreground,.7),delimiter:n.delimiter||this.opacity(t.foreground,.8),bracket:n.bracket||t.foreground,tag:n.tag||t.keyword,tagAttribute:n.tagAttribute||t.variable,tagAttributeValue:n.tagAttributeValue||t.string,tagBracket:n.tagBracket||this.opacity(t.foreground,.8),decorator:n.decorator||t.function,annotation:n.annotation||t.function,namespace:n.namespace||this.opacity(t.type,.8),module:n.module||this.opacity(t.type,.8),...n}}generateComponentColors(r,t){const n=[];return r.markdown?n.push(...this.generateMarkdownColors(r.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),r.chat?n.push(...this.generateChatColors(r.chat,t)):n.push(...this.generateDefaultChatColors(t)),r.tools?n.push(...this.generateToolColors(r.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(r,t){const n=[],o=t.colors.primary.base,a=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${r.heading1||o};`),n.push(` --markdown-heading2: ${r.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${r.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${r.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${r.link||o};`),n.push(` --markdown-link-hover: ${r.linkHover||t.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${r.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${r.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${r.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${r.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${r.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${r.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${r.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${r.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(r){const t=[],n=r.colors.primary.base,o=r.colors.chat?.background||r.colors.surface.background;return t.push(` --markdown-heading1: ${n};`),t.push(` --markdown-heading2: ${this.opacity(n,.9)};`),t.push(` --markdown-heading3: ${this.opacity(n,.8)};`),t.push(` --markdown-heading4: ${r.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${r.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${r.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${o};`),t.push(` --markdown-blockquote: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${r.colors.interactive.border};`),t.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),t.push(` --markdown-bold: ${r.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(r.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${r.colors.interactive.border};`),t}generateChatColors(r,t){const n=[],o=r.background||t.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${r.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${r.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${r.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${r.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${r.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${r.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${r.typing||t.colors.surface.mutedForeground};`),n}generateDefaultChatColors(r){const t=[];return t.push(` --chat-background: ${r.colors.surface.background};`),t.push(` --chat-user-message: ${r.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${r.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${r.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${r.colors.surface.muted};`),t.push(` --chat-timestamp: ${r.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${r.colors.interactive.border};`),t.push(` --chat-typing: ${r.colors.surface.mutedForeground};`),t}generateToolColors(r,t){const n=[];return n.push(` --tools-background: ${r?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${r?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${r?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${r?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${r?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${r?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),r?.edit?(n.push(` --tools-edit-added: ${r.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${r.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${r.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${r.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${r.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${r.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${r.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(r){const t=[];return t.push(` --tools-background: ${this.opacity(r.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(r.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(r.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${r.colors.surface.mutedForeground};`),t.push(` --tools-title: ${r.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${r.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${r.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${r.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(r){const t=[];return r&&(r.fonts&&(r.fonts.sans&&(t.push(` --font-sans: ${r.fonts.sans};`),t.push(` --font-family-sans: ${r.fonts.sans};`)),r.fonts.mono&&(t.push(` --font-mono: ${r.fonts.mono};`),t.push(` --font-family-mono: ${r.fonts.mono};`)),r.fonts.heading&&t.push(` --font-heading: ${r.fonts.heading};`)),r.radius&&(r.radius.none&&t.push(` --radius-none: ${r.radius.none};`),r.radius.sm&&t.push(` --radius-sm: ${r.radius.sm};`),r.radius.md&&t.push(` --radius-md: ${r.radius.md};`),r.radius.lg&&t.push(` --radius-lg: ${r.radius.lg};`),r.radius.xl&&t.push(` --radius-xl: ${r.radius.xl};`),r.radius.full&&t.push(` --radius-full: ${r.radius.full};`)),r.transitions&&(r.transitions.fast&&t.push(` --transition-fast: ${r.transitions.fast};`),r.transitions.normal&&t.push(` --transition-normal: ${r.transitions.normal};`),r.transitions.slow&&t.push(` --transition-slow: ${r.transitions.slow};`))),t}generateTypographyVariables(){const r=[],t=Ht()?Mh:Oi;return r.push(" /* Semantic Typography Variables */"),r.push(" --ui-regular-font-weight: 400;"),r.push(" /* Markdown content - all markdown elements use same size */"),r.push(` --text-markdown: ${t.markdown};`),r.push(" /* Code content - all code elements use same size */"),r.push(` --text-code: ${t.code};`),r.push(" /* UI headers - dialog titles, panel headers */"),r.push(` --text-ui-header: ${t.uiHeader};`),r.push(" /* UI labels - buttons, menus, navigation */"),r.push(` --text-ui-label: ${t.uiLabel};`),r.push(" /* Metadata - timestamps, status, helper text */"),r.push(` --text-meta: ${t.meta};`),r.push(" /* Micro text - badges, shortcuts, indicators */"),r.push(` --text-micro: ${t.micro};`),r.push(" /* Heading line height and letter spacing */"),r.push(" --h1-line-height: 1.25rem;"),r.push(" --h2-line-height: 1.25rem;"),r.push(" --h3-line-height: 1.5rem;"),r.push(" --h4-line-height: 1.5rem;"),r.push(" --h5-line-height: 1.5rem;"),r.push(" --h6-line-height: 1.5rem;"),r.push(" --h1-letter-spacing: -0.025em;"),r.push(" --h2-letter-spacing: -0.02em;"),r.push(" --h3-letter-spacing: -0.015em;"),r.push(" --h4-letter-spacing: -0.01em;"),r.push(" --h5-letter-spacing: 0;"),r.push(" --h6-letter-spacing: 0.01em;"),r.push(" /* UI element line height and letter spacing */"),r.push(" --ui-button-line-height: 1.375rem;"),r.push(" --ui-button-letter-spacing: 0.02em;"),r.push(" --ui-button-font-weight: 500;"),r.push(" --ui-label-line-height: 1rem;"),r.push(" --ui-label-letter-spacing: 0.03em;"),r.push(" --ui-label-font-weight: 500;"),r.push(" --ui-caption-line-height: 1rem;"),r.push(" --ui-caption-letter-spacing: 0.025em;"),r.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Markdown line height and letter spacing */"),r.push(" --markdown-body-line-height: 1.5rem;"),r.push(" --markdown-body-letter-spacing: 0;"),r.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-h1-line-height: 1.25rem;"),r.push(" --markdown-h1-letter-spacing: -0.025em;"),r.push(" --markdown-h2-line-height: 1.25rem;"),r.push(" --markdown-h2-letter-spacing: -0.02em;"),r.push(" --markdown-h3-line-height: 1.5rem;"),r.push(" --markdown-h3-letter-spacing: -0.015em;"),r.push(" --markdown-h4-line-height: 1.5rem;"),r.push(" --markdown-h4-letter-spacing: -0.01em;"),r.push(" --markdown-h5-line-height: 1.5rem;"),r.push(" --markdown-h5-letter-spacing: 0;"),r.push(" --markdown-h6-line-height: 1.5rem;"),r.push(" --markdown-h6-letter-spacing: 0.01em;"),r.push(" --markdown-list-line-height: 1.375rem;"),r.push(" --markdown-code-block-line-height: 1rem;"),r.push(" --ui-button-small-line-height: 1.25rem;"),r.push(" --ui-button-small-letter-spacing: 0.02em;"),r.push(" --ui-button-small-font-weight: 500;"),r.push(" --markdown-body-small-line-height: 1.375rem;"),r.push(" --markdown-body-small-letter-spacing: 0;"),r.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-button-large-line-height: 1.5rem;"),r.push(" --ui-button-large-letter-spacing: 0.02em;"),r.push(" --ui-button-large-font-weight: 500;"),r.push(" --markdown-body-large-line-height: 1.625rem;"),r.push(" --markdown-body-large-letter-spacing: 0;"),r.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Code line height and letter spacing */"),r.push(" --code-inline-line-height: 1rem;"),r.push(" --code-inline-letter-spacing: 0;"),r.push(" --code-inline-font-weight: 400;"),r.push(" --code-block-line-height: 1.4rem;"),r.push(" --code-block-letter-spacing: 0;"),r.push(" --code-block-font-weight: 400;"),r.push(" --code-line-numbers-line-height: 1.25rem;"),r.push(" --code-line-numbers-letter-spacing: 0;"),r.push(" --code-line-numbers-font-weight: 400;"),r.push(" /* Additional UI element line height and letter spacing */"),r.push(" --ui-badge-line-height: 1rem;"),r.push(" --ui-badge-letter-spacing: 0.025em;"),r.push(" --ui-badge-font-weight: 500;"),r.push(" --ui-tooltip-line-height: 1rem;"),r.push(" --ui-tooltip-letter-spacing: 0.025em;"),r.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-input-line-height: 1.375rem;"),r.push(" --ui-input-letter-spacing: 0.02em;"),r.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-helper-text-line-height: 1rem;"),r.push(" --ui-helper-text-letter-spacing: 0.025em;"),r.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Additional markdown line height and letter spacing */"),r.push(" --markdown-blockquote-line-height: 1.5rem;"),r.push(" --markdown-blockquote-letter-spacing: 0;"),r.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-list-letter-spacing: 0;"),r.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-link-line-height: 1.5rem;"),r.push(" --markdown-link-letter-spacing: 0;"),r.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-code-line-height: 1.35;"),r.push(" --markdown-code-letter-spacing: 0;"),r.push(" --markdown-code-font-weight: 400;"),r.push(" --markdown-code-block-letter-spacing: 0;"),r.push(" --markdown-code-block-font-weight: 400;"),r}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(r,t){return r.startsWith("#")?`${r}${Math.round(t*255).toString(16).padStart(2,"0")}`:r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}removeTransparency(r){return r.startsWith("#")?r.length===9?r.slice(0,7):r.length===5?r.slice(0,4):r:r.startsWith("rgba")?r.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):r}addTransparency(r,t){if(r.startsWith("#")){const n=r.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),i=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${i}, ${t})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),i=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${i}, ${t})`}}return r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}darken(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)-o,i=(n>>8&255)-o,l=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}lighten(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)+o,i=(n>>8&255)+o,l=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}adjustHue(r,t){return this.lighten(r,t/10)}emphasize(r){return this.lighten(r,15)}kebabCase(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const pl={metadata:{id:"flexoki-light",name:"Flexoki Light",description:"An inky color scheme for prose and code - light variant",author:"Steph Ango",version:"1.0.0",variant:"light",tags:["light","warm","natural","paper"]},colors:{primary:{base:"#EC8B49",hover:"#F9AE77",active:"#DA702C",foreground:"#FFFCF0",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#FFFCF0",foreground:"#100F0F",muted:"#F2F0E5",mutedForeground:"#6F6E69",elevated:"#E6E4D9",elevatedForeground:"#100F0F",overlay:"#100F0F20",subtle:"#DAD8CE"},interactive:{border:"#DAD8CE",borderHover:"#CECDC3",borderFocus:"#EC8B49",selection:"#100F0F44",selectionForeground:"#100F0F",focus:"#EC8B49",focusRing:"#EC8B4940",cursor:"#100F0F",hover:"#DAD8CE",active:"#CECDC3"},status:{error:"#AF3029",errorForeground:"#FFFCF0",errorBackground:"#D14D4120",errorBorder:"#D14D4150",warning:"#BC5215",warningForeground:"#FFFCF0",warningBackground:"#DA702C20",warningBorder:"#DA702C50",success:"#66800B",successForeground:"#FFFCF0",successBackground:"#879A3920",successBorder:"#879A3950",info:"#205EA6",infoForeground:"#FFFCF0",infoBackground:"#4385BE20",infoBorder:"#4385BE50"},syntax:{base:{background:"#F2F0E5",foreground:"#100F0F",comment:"#6F6E69",keyword:"#205EA6",string:"#24837B",number:"#5E409D",function:"#BC5215",variable:"#100F0F",type:"#AD8301",operator:"#AF3029"},tokens:{commentDoc:"#B7B5AC",stringEscape:"#100F0F",keywordImport:"#AF3029",storageModifier:"#205EA6",functionCall:"#BC5215",method:"#66800B",variableProperty:"#205EA6",variableOther:"#66800B",variableGlobal:"#A02F6F",variableLocal:"#E6E4D9",parameter:"#100F0F",constant:"#100F0F",class:"#BC5215",className:"#BC5215",interface:"#AD8301",struct:"#BC5215",enum:"#BC5215",typeParameter:"#BC5215",namespace:"#AD8301",module:"#AF3029",tag:"#205EA6",jsxTag:"#A02F6F",tagAttribute:"#AD8301",tagAttributeValue:"#24837B",boolean:"#AD8301",decorator:"#AD8301",label:"#A02F6F",punctuation:"#6F6E69",macro:"#205EA6",preprocessor:"#A02F6F",regex:"#24837B",url:"#205EA6",key:"#BC5215",exception:"#A02F6F"},highlights:{diffAdded:"#66800B",diffAddedBackground:"#879A3920",diffRemoved:"#AF3029",diffRemovedBackground:"#D14D4120",diffModified:"#205EA6",diffModifiedBackground:"#4385BE20",lineNumber:"#CECDC3",lineNumberActive:"#100F0F"}},markdown:{heading1:"#AD8301",heading2:"#BC5215",heading3:"#205EA6",heading4:"#100F0F",link:"#205EA6",linkHover:"#4385BE",inlineCode:"#24837B",inlineCodeBackground:"#F2F0E5",blockquote:"#6F6E69",blockquoteBorder:"#DAD8CE",listMarker:"#AD830199"},chat:{userMessage:"#100F0F",userMessageBackground:"#F2F0E5",assistantMessage:"#100F0F",assistantMessageBackground:"#FFFCF0",timestamp:"#6F6E69",divider:"#DAD8CE"},tools:{background:"#F2F0E550",border:"#DAD8CE80",headerHover:"#DAD8CE",icon:"#6F6E69",title:"#100F0F",description:"#6F6E69",edit:{added:"#66800B",addedBackground:"#66800B25",removed:"#AF3029",removedBackground:"#AF302925",lineNumber:"#CECDC3"}}},config:{fonts:{sans:'"IBM Plex Mono", monospace',mono:'"IBM Plex Mono", monospace',heading:'"IBM Plex Mono", monospace'},radius:{none:"0",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},transitions:{fast:"150ms ease",normal:"250ms ease",slow:"350ms ease"}}},hl={metadata:{id:"flexoki-dark",name:"Flexoki Dark",description:"An inky color scheme for prose and code - dark variant",author:"Steph Ango",version:"1.0.0",variant:"dark",tags:["dark","warm","natural","ink"]},colors:{primary:{base:"#EC8B49",hover:"#DA702C",active:"#F9AE77",foreground:"#100F0F",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#100F0F",foreground:"#CECDC3",muted:"#1C1B1A",mutedForeground:"#878580",elevated:"#282726",elevatedForeground:"#CECDC3",overlay:"#00000080",subtle:"#343331"},interactive:{border:"#343331",borderHover:"#403E3C",borderFocus:"#EC8B49",selection:"#CECDC330",selectionForeground:"#CECDC3",focus:"#EC8B49",focusRing:"#EC8B4950",cursor:"#CECDC3",hover:"#343331",active:"#403E3C"},status:{error:"#D14D41",errorForeground:"#100F0F",errorBackground:"#AF302920",errorBorder:"#AF302950",warning:"#DA702C",warningForeground:"#100F0F",warningBackground:"#BC521520",warningBorder:"#BC521550",success:"#A0AF54",successForeground:"#100F0F",successBackground:"#66800B20",successBorder:"#66800B50",info:"#4385BE",infoForeground:"#100F0F",infoBackground:"#205EA620",infoBorder:"#205EA650"},syntax:{base:{background:"#1C1B1A",foreground:"#CECDC3",comment:"#878580",keyword:"#4385BE",string:"#3AA99F",number:"#8B7EC8",function:"#DA702C",variable:"#CECDC3",type:"#D0A215",operator:"#D14D41"},tokens:{commentDoc:"#575653",stringEscape:"#CECDC3",keywordImport:"#D14D41",storageModifier:"#4385BE",functionCall:"#DA702C",method:"#879A39",variableProperty:"#4385BE",variableOther:"#879A39",variableGlobal:"#CE5D97",variableLocal:"#282726",parameter:"#CECDC3",constant:"#CECDC3",class:"#DA702C",className:"#DA702C",interface:"#D0A215",struct:"#DA702C",enum:"#DA702C",typeParameter:"#DA702C",namespace:"#D0A215",module:"#D14D41",tag:"#4385BE",jsxTag:"#CE5D97",tagAttribute:"#D0A215",tagAttributeValue:"#3AA99F",boolean:"#D0A215",decorator:"#D0A215",label:"#CE5D97",punctuation:"#878580",macro:"#4385BE",preprocessor:"#CE5D97",regex:"#3AA99F",url:"#4385BE",key:"#DA702C",exception:"#CE5D97"},highlights:{diffAdded:"#879A39",diffAddedBackground:"#66800B20",diffRemoved:"#D14D41",diffRemovedBackground:"#AF302920",diffModified:"#4385BE",diffModifiedBackground:"#205EA620",lineNumber:"#403E3C",lineNumberActive:"#CECDC3"}},markdown:{heading1:"#D0A215",heading2:"#DA702C",heading3:"#4385BE",heading4:"#CECDC3",link:"#4385BE",linkHover:"#205EA6",inlineCode:"#A0AF54",inlineCodeBackground:"#1C1B1A",blockquote:"#878580",blockquoteBorder:"#343331",listMarker:"#D0A21599"},chat:{userMessage:"#CECDC3",userMessageBackground:"#282726",assistantMessage:"#CECDC3",assistantMessageBackground:"#100F0F",timestamp:"#878580",divider:"#343331"},tools:{background:"#1C1B1A50",border:"#34333180",headerHover:"#34333150",icon:"#878580",title:"#CECDC3",description:"#878580",edit:{added:"#879A39",addedBackground:"#66800B25",removed:"#D14D41",removedBackground:"#AF302925",lineNumber:"#403E3C"}}},config:{fonts:{sans:'"IBM Plex Mono", monospace',mono:'"IBM Plex Mono", monospace',heading:'"IBM Plex Mono", monospace'},radius:{none:"0",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},transitions:{fast:"150ms ease",normal:"250ms ease",slow:"350ms ease"}}},Vn=[pl,hl];function qo(s){return Vn.find(r=>r.metadata.id===s)}const Xm=pl.metadata.id,Qm=hl.metadata.id,I0=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Jm=s=>s==="dark"?hl:pl,P0=s=>(Vn.find(t=>t.metadata.variant===s)??Jm(s)).metadata.id,yo=(s,r)=>{const t=qo(s);return t&&t.metadata.variant===r?t:Vn.find(o=>o.metadata.variant===r)??Jm(r)},T0=typeof window<"u"?c.useLayoutEffect:c.useEffect,Ko=(s,r)=>{if(!s)return r==="light"?Xm:Qm;const t=qo(s);return t&&t.metadata.variant===r?t.metadata.id:P0(r)},F0=s=>{let r=Xm,t=Qm,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),l=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(l!==null){if(l==="true")n="system";else if(d){const f=qo(d);f&&(n=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?t=f.metadata.id:r=f.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);r=Ko(a,"light"),t=Ko(i,"dark")}if(s){const o=qo(s);o&&(o.metadata.variant==="light"?r=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:t}};function R0({children:s,defaultThemeId:r}){const t=Me.useMemo(()=>new E0,[]),[n,o]=Me.useState(()=>F0(r)),[a,i]=Me.useState(()=>I0()),[l,d]=Me.useState(()=>typeof window>"u"||!Ht()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Me.useMemo(()=>Ht(),[]),m=Me.useMemo(()=>u&&l?l:n.themeMode==="light"?yo(n.lightThemeId,"light"):n.themeMode==="dark"||a?yo(n.darkThemeId,"dark"):yo(n.lightThemeId,"light"),[u,n,a,l]),f=Me.useMemo(()=>u&&l?[l,...Vn]:Vn,[u,l]);Me.useEffect(()=>{if(!u)return;const S=D=>{d(D);const M=D.metadata.variant==="dark"?"dark":"light",C=Re.getState();C.theme!==M&&C.setTheme(M)},v=D=>{const M=D.detail;M?.theme&&S(M.theme)},N=window.__OPENCHAMBER_VSCODE_THEME__;return N&&S(N),window.addEventListener("openchamber:vscode-theme",v),()=>window.removeEventListener("openchamber:vscode-theme",v)},[u]);const p=Me.useCallback(S=>{if(typeof document>"u")return;const v=S.colors.surface.background;ss()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=v;let N=document.querySelector('meta[name="theme-color"]');N||(N=document.createElement("meta"),N.setAttribute("name","theme-color"),document.head.appendChild(N)),N.setAttribute("content",v);const D=S.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let M=document.querySelector(`meta[name="theme-color"][media="${D}"]`);M||(M=document.createElement("meta"),M.setAttribute("name","theme-color"),M.setAttribute("media",D),document.head.appendChild(M)),M.setAttribute("content",v)},[]),h=Me.useCallback(S=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",S)},[]);T0(()=>{if(typeof window>"u")return;t.apply(m),h(u),p(m);const S=document.documentElement;S.classList.remove("light","dark"),S.classList.add(m.metadata.variant)},[h,t,m,u,p]),Me.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const S=window.matchMedia("(prefers-color-scheme: dark)"),v=N=>{i(N.matches)};return i(S.matches),S.addEventListener("change",v),()=>S.removeEventListener("change",v)},[n.themeMode]),Me.useEffect(()=>{typeof window>"u"||(localStorage.setItem("themeMode",n.themeMode),localStorage.setItem("lightThemeId",n.lightThemeId),localStorage.setItem("darkThemeId",n.darkThemeId),localStorage.setItem("useSystemTheme",String(n.themeMode==="system")),localStorage.setItem("selectedThemeId",m.metadata.id),localStorage.setItem("selectedThemeVariant",m.metadata.variant==="light"?"light":"dark"))},[n,m]),Me.useEffect(()=>{os({themeId:m.metadata.id,themeVariant:m.metadata.variant==="light"?"light":"dark",useSystemTheme:n.themeMode==="system",lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId})},[m.metadata.id,m.metadata.variant,n.themeMode,n.lightThemeId,n.darkThemeId]),Me.useEffect(()=>{if(typeof window>"u")return;const S=v=>{const N=v.detail;N&&o(D=>{let M=D.themeMode;N.useSystemTheme===!0?M="system":N.useSystemTheme===!1&&(N.themeVariant==="dark"||N.themeVariant==="light")&&(M=N.themeVariant);let C=D.lightThemeId;typeof N.lightThemeId=="string"&&N.lightThemeId.length>0&&(C=Ko(N.lightThemeId,"light"));let k=D.darkThemeId;return typeof N.darkThemeId=="string"&&N.darkThemeId.length>0&&(k=Ko(N.darkThemeId,"dark")),M===D.themeMode&&C===D.lightThemeId&&k===D.darkThemeId?D:{themeMode:M,lightThemeId:C,darkThemeId:k}})};return window.addEventListener("openchamber:settings-synced",S),()=>window.removeEventListener("openchamber:settings-synced",S)},[]);const j=Me.useCallback(S=>{const v=f.find(N=>N.metadata.id===S);v&&o(N=>v.metadata.variant==="dark"?N.darkThemeId===v.metadata.id&&N.themeMode==="dark"?N:{...N,darkThemeId:v.metadata.id,themeMode:"dark"}:N.lightThemeId===v.metadata.id&&N.themeMode==="light"?N:{...N,lightThemeId:v.metadata.id,themeMode:"light"})},[f]),g=Me.useCallback(S=>{o(v=>v.themeMode===S?v:{...v,themeMode:S})},[]),b=Me.useCallback(S=>{if(S){o(N=>N.themeMode==="system"?N:{...N,themeMode:"system"});return}const v=m.metadata.variant==="dark"?"dark":"light";o(N=>N.themeMode===v?N:{...N,themeMode:v})},[m.metadata.variant]),x=Me.useCallback(S=>{const v=f.find(N=>N.metadata.id===S&&N.metadata.variant==="light");v&&o(N=>N.lightThemeId===v.metadata.id?N:{...N,lightThemeId:v.metadata.id})},[f]),y=Me.useCallback(S=>{const v=f.find(N=>N.metadata.id===S&&N.metadata.variant==="dark");v&&o(N=>N.darkThemeId===v.metadata.id?N:{...N,darkThemeId:v.metadata.id})},[f]),w={currentTheme:m,availableThemes:f,setTheme:j,isSystemPreference:n.themeMode==="system",setSystemPreference:b,themeMode:n.themeMode,setThemeMode:g,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:x,setDarkThemePreference:y};return e.jsx(Xi.Provider,{value:w,children:s})}const O0=({children:s})=>{const{theme:r,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:i}=Re();return c.useLayoutEffect(()=>{t(),o(),i()},[r,t,n,o,a,i]),c.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&t()};return l.addEventListener("change",d),()=>{l.removeEventListener("change",d)}},[r,t]),e.jsx(e.Fragment,{children:s})},$0={getLastAssistantMessage(){const s=de.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const t=s.messages.get(r);if(!t||t.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=t.length-1;n>=0;n--){const o=t[n];if(o.info.role==="assistant"){const a=o.parts.map(p=>{const h={id:p.id,type:p.type};return p.type==="text"?(h.text=p.text,h.textLength=p.text?.length||0):p.type==="tool"?(h.tool=p.tool,h.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(h.isStepMarker=!0),h}),i=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),l=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!i&&!l&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:i,hasTools:l,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!l}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!i&&!l&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(s,r=80){return!s||typeof s!="string"||s.length<=r?s:s.substring(0,r)+"…"},truncateMessages(s){return s.map(r=>({...r,parts:(r.parts||[]).map(t=>{const n={...t};return"text"in t&&(n.text=this.truncateString(t.text)),"textPreview"in t&&(n.textPreview=this.truncateString(t.textPreview)),t.state&&(n.state={...t.state},"output"in t.state&&(n.state.output=this.truncateString(t.state.output)),"error"in t.state&&(n.state.error=this.truncateString(t.state.error)),t.state.metadata&&"preview"in t.state.metadata&&(n.state.metadata={...t.state.metadata,preview:this.truncateString(t.state.metadata.preview)})),n})}))},getAllMessages(s=!1){const r=de.getState(),t=r.currentSessionId;if(!t)return console.log("[ERROR] No active session"),[];const n=r.messages.get(t)||[];return console.log(`[MESSAGES] Total messages in session: ${n.length}`),n.forEach((o,a)=>{console.log(`[${a}] ${o.info.role} - ${o.info.id} - ${o.parts.length} parts`)}),s?this.truncateMessages(n):n},async getAppStatus(){const s=ft.getState(),r=de.getState(),t=s.currentDirectory||null,n=De.getDirectory()??null,o=r.sessions||[],a=new Set,i={};o.forEach(N=>{const D=N.directory;typeof D=="string"&&D.trim().length>0?(a.add(D),i[D]=(i[D]??0)+1):i["(none)"]=(i["(none)"]??0)+1});const l=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(N){return{available:!1,error:N instanceof Error?N.message:String(N)}}})(),d=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,u=typeof window<"u"?window.__OPENCHAMBER_DESKTOP_SERVER__:null,m=!!(d?.runtime?.isDesktop||typeof window<"u"&&window.opencodeDesktop),f=async N=>{try{return await N.json()}catch{return null}},p=async N=>{try{return await N.text()}catch{return null}},h=async N=>{try{const D=await fetch(N);return D.ok?await f(D):{status:D.status}}catch(D){return{error:D instanceof Error?D.message:String(D)}}};let j=null,g=null,b=null,x=null;const y=t?`/api/path?directory=${encodeURIComponent(t)}`:"/api/path";j=await h(y);const w=t?`/api/project/current?directory=${encodeURIComponent(t)}`:"/api/project/current";g=await h(w),b=await h("/api/config/settings");try{const N=await fetch("/api/health"),D=N.headers.get("content-type")||"",M=await p(N);x={status:N.status,ok:N.ok,contentType:D,type:D.includes("application/json")?"json":"html",preview:M?M.slice(0,120):null}}catch(N){x={error:N instanceof Error?N.message:String(N)}}let S={isGitRepo:null};if(t)try{S.isGitRepo=await Wr(t)}catch(N){S={isGitRepo:null,error:N instanceof Error?N.message:String(N)}}const v={runtime:{isDesktop:m,hasRuntimeApis:!!d,desktopServerOrigin:u?.origin??null},location:typeof window<"u"?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:t,opencodeDirectory:j?.directory||j?.worktree||n,homeDirectory:s.homeDirectory||null,isHomeReady:s.isHomeReady,hasPersistedDirectory:s.hasPersistedDirectory,isSwitchingDirectory:s.isSwitchingDirectory},sessions:{total:o.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:a.size,directorySamples:Array.from(a).slice(0,5),directoryCounts:i},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:S,localStorage:l,opencode:{pathInfo:j,projectInfo:g,health:x},openchamber:{settingsInfo:b}};return console.log("[DEBUG] App status snapshot:",v),v},checkLastMessage(){const s=this.getLastAssistantMessage();if(!s)return!1;const r=s.isEmpty||s.isEmptyResponse;return r?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:s.messageId,isEmpty:s.isEmpty,isEmptyResponse:s.isEmptyResponse,partsCount:s.partsCount}),s.parts.length>0&&console.log("Parts:",s.parts)):console.log("[OK] Last message looks good!"),r},getStreamingState(){const s=de.getState(),r=s.currentSessionId?s.streamingMessageIds.get(s.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:r,streamingMessageIds:Array.from(s.streamingMessageIds.entries()),messageStreamStates:Array.from(s.messageStreamStates.entries())}),{streamingMessageId:r,streamingMessageIds:s.streamingMessageIds,streamStates:s.messageStreamStates}},findEmptyMessages(){const s=de.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=(s.messages.get(r)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],i=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),l=a.some(d=>d.type==="tool");return a.length===0||!i&&!l});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
|
|
120
|
+
`),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
|
|
121
|
+
`),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
|
|
122
|
+
`),console.log("3. To retry, you can:"),console.log(" - Edit your last user message and resend"),console.log(' - Send a follow-up message like "Please provide the response"'),console.log(` - Try a different model (OpenAI models tend to be more reliable)
|
|
123
|
+
`),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(s={}){const{includeNonAssistant:r=!1,verbose:t=!0,maxTableRows:n=25}=s,o=de.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const i=o.messages.get(a)||[],l=r?i:i.filter(p=>p.info.role==="assistant"),d={totalMessages:i.length,analyzedMessages:l.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const h=p.filter(j=>typeof j=="number");return h.length>0?Math.max(...h):null},f=l.map((p,h)=>{const j=p.info??{},g=Array.isArray(p.parts)?p.parts:[],b=j.time??{},x=u(b.completed),y=x!==null,w=g.filter(P=>P.type==="tool"),S=g.filter(P=>P.type==="reasoning"),v=m(w.map(P=>u(P.state?.time?.end??P.state?.time?.start))),N=m(S.map(P=>u(P.time?.end??P.time?.start))),D=m([v,N].filter(P=>P!==null)),M=w.some(P=>["pending","running","started"].includes(P.state?.status)),C=S.some(P=>typeof P.time?.end!="number");w.length>0&&(d.withTools+=1),S.length>0&&(d.withReasoning+=1),y||(d.completedMissing+=1);const k=!!(y&&typeof v=="number"&&x<v);k&&(d.completedBeforeTool+=1);const A=!!(y&&typeof N=="number"&&x<N);return A&&(d.completedBeforeReasoning+=1),y&&M&&(d.runningToolsWhenCompleted+=1),y&&C&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:j.id,role:j.role,completedAt:x,latestToolTimestamp:v,latestReasoningTimestamp:N,latestPartTimestamp:D,completed_missing:!y,completed_before_tool:k,completed_before_reasoning:A,running_tools_when_completed:!!(y&&M),reasoning_open_when_completed:!!(y&&C),has_tools:w.length>0,has_reasoning:S.length>0}});return t&&(console.table(f.slice(0,n)),f.length>n&&console.log(`Displayed first ${n} rows out of ${f.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:f}},checkCompletionStatus(){const s=de.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const n=(s.messages.get(r)||[]).filter(b=>b.info.role==="assistant");if(n.length===0)return console.log("[ERROR] No assistant messages"),null;const o=n[n.length-1],a=o.parts.filter(b=>b.type==="step-finish"),i=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&i),p=s.messageStreamStates,h=o.info.sessionID?s.streamingMessageIds.get(o.info.sessionID)??null:null,j=p.get(o.info.id),g=o.info.id===h;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",m),console.log("hasStopReason:",i),console.log("messageIsComplete:",f),console.log("lifecycle phase:",j?.phase),console.log("isStreamingCandidate:",g),console.log("streamingMessageId:",h),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:m,hasStopReason:i,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=$0,Wt()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",s=>{try{const r=s.message||"",t=s.filename||"";typeof r=="string"&&r.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(t))&&s.preventDefault()}catch{}}));let Td=!1;const L0=()=>{if(Td||typeof window>"u")return;Td=!0;let s={showReasoningTraces:Re.getState().showReasoningTraces,autoDeleteEnabled:Re.getState().autoDeleteEnabled,autoDeleteAfterDays:Re.getState().autoDeleteAfterDays},r=null,t=null;const n=()=>{const a=r;r=null,t=null,a&&Object.keys(a).length>0&&os(a)},o=a=>{r={...r??{},...a},!t&&(t=setTimeout(n,150))};Re.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},l={};i.showReasoningTraces!==s.showReasoningTraces&&(l.showReasoningTraces=i.showReasoningTraces),i.autoDeleteEnabled!==s.autoDeleteEnabled&&(l.autoDeleteEnabled=i.autoDeleteEnabled),i.autoDeleteAfterDays!==s.autoDeleteAfterDays&&(l.autoDeleteAfterDays=i.autoDeleteAfterDays),s=i,Object.keys(l).length>0&&o(l)})};let Fd=!1;const Rd="openchamber-typography-base",_0=()=>{if(typeof document>"u")return;const r=`:root {
|
|
124
|
+
${Object.entries(Oi).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
|
|
125
|
+
`)}
|
|
126
|
+
}
|
|
127
|
+
`,t=document.getElementById(Rd);if(t){t.textContent=r;return}const n=document.createElement("style");n.id=Rd,n.textContent=r,document.head.appendChild(n)},B0=()=>{Fd||typeof window>"u"||(Fd=!0,_0())},z0=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await nu();await ou();L0();B0();await Km();typeof window<"u"&&(window.debugContextTokens=()=>{const s=window.__zustand_session_store__;if(!s)return;const r=s.getState(),t=r.currentSessionId;if(!t)return;const o=(r.messages.get(t)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const i=o[o.length-1].info.tokens;i&&typeof i=="object"&&console.debug("Token breakdown:",{base:(i.input||0)+(i.output||0)+(i.reasoning||0),cache:i.cache?(i.cache.read||0)+(i.cache.write||0):0}),r.sessionContextUsage.get(t);const l=window.__zustand_config_store__;if(l){const d=l.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const Zm=document.getElementById("root");if(!Zm)throw new Error("Root element not found");th.createRoot(Zm).render(e.jsx(Me.StrictMode,{children:e.jsx(R0,{children:e.jsx(O0,{children:e.jsx(A0,{children:e.jsx(S0,{apis:z0})})})})}));if(typeof window<"u"){const s=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(r){console.warn("Failed to notify desktop runtime that renderer is ready:",r)}};s(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&s()})}const U0=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{ds as D,Fr as S,us as a,Vy as b,R as c,Xb as d,Qb as e,Uc as f,Hr as g,Jb as h,ew as i,U0 as m,jm as p,Zb as r,wo as t};
|