@openchamber/web 1.4.1 → 1.4.2
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/dist/assets/{ToolOutputDialog-CBMeCbbW.js → ToolOutputDialog-zILn8Ed6.js} +1 -1
- package/dist/assets/{index-CbGhBA-v.js → index-5Ree9Z_i.js} +2 -2
- package/dist/assets/index-msMCcGYO.css +1 -0
- package/dist/assets/main-DF2J5RAs.js +122 -0
- package/dist/assets/{vendor-.bun-CpaXrlrC.js → vendor-.bun-COPXsM7o.js} +525 -525
- package/dist/index.html +3 -3
- package/package.json +2 -1
- package/server/lib/opencode-config.js +4 -3
- package/dist/assets/index-Cx6NUrC-.css +0 -1
- package/dist/assets/main-BJvFwyGz.js +0 -122
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-COPXsM7o.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-zILn8Ed6.js","assets/index-5Ree9Z_i.js","assets/index-msMCcGYO.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as Gu,c as qu,j as e,R as Ku,T as Yu,P as Xu,C as Qu,A as Ju,a as Zu,b as Tt,d as _t,p as ws,e as vs,f as em,_ as Kt,g as l,r as tm,i as Wt,I as sm,k as rm,l as nm,m as om,n as am,o as im,q as lm,s as cm,u as Dt,v as dm,S as um,L as mm,w as Vc,x as fm,y as pm,z as hm,B as Ne,D as Li,E as Ca,F as gm,G as Nt,K as Ja,H as xm,U as Qt,Z as ym,Y as Vs,Q as mr,W as Vt,O as Do,J as bm,M as Cr,N as Dr,V as Gr,X as Ma,$ as xs,a0 as Gc,a1 as wm,a2 as vm,a3 as jm,a4 as Sm,a5 as km,a6 as Nm,a7 as Cm,a8 as Yn,a9 as Mm,aa as Dm,ab as Da,ac as qr,ad as se,ae as zt,af as lr,ag as Ar,ah as Nn,ai as Gt,aj as tr,ak as Am,al as Em,am as qc,an as Za,ao as Jr,ap as Kc,aq as Kr,ar as Im,as as Ao,at as As,au as Ho,av as Cn,aw as Qs,ax as qs,ay as Tm,az as Ls,aA as gs,aB as Yc,aC as Fm,aD as Pm,aE as Rm,aF as Lm,aG as Om,aH as $m,aI as _m,aJ as Bm,aK as zm,aL as Hm,aM as Um,aN as Wm,aO as Vm,aP as Hr,aQ as Uo,aR as Gm,aS as ei,aT as ti,aU as qm,aV as Km,aW as Ym,aX as io,aY as cr,aZ as er,a_ as Xm,a$ as Js,b0 as Qm,b1 as Eo,b2 as Jm,b3 as Mn,b4 as si,b5 as Zm,b6 as ef,b7 as tf,b8 as yn,b9 as sf,ba as rf,bb as nf,bc as of,bd as af,be as Aa,bf as Xn,bg as Io,bh as lf,bi as cf,bj as bn,bk as $r,bl as df,bm as uf,bn as mf,bo as ff,bp as bs,bq as Xc,br as pf,bs as Qc,bt as hf,bu as gf,bv as Ea,bw as xf,bx as Jc,by as Bs,bz as wn,bA as yf,bB as Zr,bC as bf,bD as Zc,bE as ri,bF as ni,bG as oi,bH as wf,bI as vf,bJ as jf,bK as Sf,bL as kf,bM as Nf,bN as Cf,bO as Oi,bP as ed,bQ as Mf,bR as $i,bS as lo,bT as ai,bU as td,bV as sd,bW as dr,bX as _i,bY as To,bZ as rd,b_ as Ia,b$ as nd,c0 as Ta,c1 as Df,c2 as Af,c3 as Ef,c4 as If,c5 as Tf,c6 as Ff,c7 as Pf,c8 as Rf}from"./vendor-.bun-COPXsM7o.js";import{c as Lf,l as Of,g as $f,r as _f,d as Bf,a as zf,b as Hf,e as Uf,u as Wf,f as Vf,h as Gf,i as qf,j as Kf,k as Yf}from"./index-5Ree9Z_i.js";const Ht=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Et=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,ii=()=>typeof window>"u"?!1:!Ht()&&!Et(),fr=()=>Ht()?window.opencodeDesktop??null:null,od=()=>{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},ad=async()=>{const s=fr();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},Xf=async()=>{const s=fr();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},Qf=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,en=async()=>{const s=od();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},Jf=async s=>{const r=od();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},Zf=async s=>{const r=fr();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)}}},ep=async s=>{const r=fr();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)}}},tp=async s=>{const r=fr();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)}}},sp=async()=>{const s=fr();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},rp=async s=>{const r=fr();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},np=async()=>{const s=fr();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 O(...s){return Gu(qu(s))}const id=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),hs=s=>id()&&Ht()?s.metaKey:s.ctrlKey,ss=()=>id()&&Ht()?"⌘":"Ctrl",ld=(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 c="";for(const d of o){if(!d)continue;const u=c?`${c}/${d}`:d;if(u.length>i)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,i):""}return c?`${c}…/${a}`:`…/${a}`},co=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function fs(s,r){if(!s)return"";const t=co(s);if(t==="/")return"/";const n=r?co(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 Wo(s,r){if(!s)return"/";const t=co(s);if(!t||t==="/")return"/";const n=r?co(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function op({delayDuration:s=0,...r}){return e.jsx(Zu,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function Xe({delayDuration:s=0,...r}){return e.jsx(op,{delayDuration:s,children:e.jsx(Ku,{"data-slot":"tooltip",...r})})}function Qe({...s}){return e.jsx(Yu,{"data-slot":"tooltip-trigger",...s})}function Ye({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(Xu,{children:e.jsxs(Qu,{"data-slot":"tooltip-content",sideOffset:r,className:O("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(Ju,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Vo=null;const Bi=()=>{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}}},ap=()=>{if(typeof window>"u"||!window.localStorage)return Bi();const s=window.localStorage,r=Bi();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}}},ls=()=>(Vo||(Vo=ap()),Vo),li={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},ip={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function zi(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Zs={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)"}}},Qn={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Zs.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qn.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Zs.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qn.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Zs.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Qn.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Zs.tool.inline})},Fe=Tt()(_t(ws((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(li);if(o===1){for(const[i]of a)n.style.removeProperty(zi(i));return}for(const[i,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(zi(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:vs(()=>ls()),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 lp(){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 cp(){return Ht()?"desktop":ii()?"web":null}const Hi={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Fo=Tt()((s,r)=>({...Hi,checkForUpdates:async()=>{const t=cp();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await sp():t==="web"&&(n=await lp()),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 rp(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 np()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(Hi)}})),dp="/api",up=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,mp=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(up.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}},fp=()=>{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},En=s=>s.replace(/\\/g,"/"),Go=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class pp{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(r=dp){const n=fp()||r;this.baseUrl=mp(n),this.client=em({baseUrl:this.baseUrl})}normalizeCandidatePath(r){if(typeof r!="string")return null;const t=r.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const t=r.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[1],c=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,t){if(r==null)return t();const n=this.currentDirectory;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,t=o=>{const a=this.normalizeCandidatePath(o);a&&r.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(t(a.directory),t(a.worktree),t(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!r.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(process.cwd()),!r.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(r);return this.deriveHomeDirectory(n)}async listSessions(){const r=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(r.data)?r.data:[]}async createSession(r){const t=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(r){const t=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,t){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:t});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||[]}async getSessionTodos(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/${encodeURIComponent(r)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(r){if(!r)return!1;const t=r.toLowerCase();return t.startsWith("text/")&&t!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript"].includes(t)}isHeicMime(r){if(!r)return!1;const t=r.toLowerCase();return t==="image/heic"||t==="image/heif"}async convertHeicToJpeg(r){try{const t=(await Kt(async()=>{const{default:f}=await import("./vendor-.bun-COPXsM7o.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 c=new Blob([i],{type:r.mime}),d=await t({blob:c,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const h=new FileReader;h.onload=()=>f(h.result),h.onerror=p,h.readAsDataURL(d)});let m=r.filename;return m&&(m=m.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:m,url:u}}catch(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),c={type:"file",mime:i.mime,filename:i.filename,url:i.url};o.push(c)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text}),a.files&&a.files.length>0)for(const i of a.files){const c=await this.normalizeFilePart(i),d={type:"file",mime:c.mime,filename:c.filename,url:c.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,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 respondToPermission(r,t,n){return(await this.client.permission.respond({sessionID:r,permissionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{},response:n})).data||!1}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[]}}subscribeToEvents(r,t,n,o){this.sseAbortController&&this.sseAbortController.abort();const a=new AbortController;this.sseAbortController=a;let i;return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const c=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",c);const d=async u=>{try{const m=c?{directory:c}:void 0,f={signal:a.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:h=>{h instanceof Error&&h.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",h),t&&!a.signal.aborted&&t(h))},onSseEvent:h=>{if(a.signal.aborted)return;h.id&&typeof h.id=="string"&&(i=h.id);const w=h.data;w&&typeof w=="object"&&r(w)}};i&&(f.headers={...f.headers||{},"Last-Event-ID":i});const p=await this.client.event.subscribe(m,f);n&&!a.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const h of p.stream)if(a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}if(!a.signal.aborted){const h=Math.min(3e3*Math.pow(2,u),3e4);await new Promise(w=>setTimeout(w,h)),await d(u+1)}}catch(m){if(m?.name==="AbortError"||a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",m),t&&t(m);const f=Math.min(3e3*Math.pow(2,u),3e4);await new Promise(p=>setTimeout(p,f)),a.signal.aborted||await d(u+1)}};try{await d(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortController===a&&(this.sseAbortController=null)}})(),()=>{this.sseAbortController===a&&(this.sseAbortController=null),a.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}
|
|
3
|
+
// 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=Go();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=Go();if(t)try{const n=await t.listDirectory(r||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:En(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 c=await a.json().catch(()=>({})),d=typeof c.error=="string"?c.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=Go(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?En(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=En(f.path),h=p.split("/").filter(Boolean).pop()||p,w=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?En(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:w,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 c=`${this.baseUrl}/fs/search${i.toString()?`?${i.toString()}`:""}`,d=await fetch(c,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await ad();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 Re=new pp,Fa=new Set;function Po(s){return Fa.add(s),()=>{Fa.delete(s)}}function ys(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 Fa)try{const i=a(o);i instanceof Promise&&i.catch(c=>{console.error("[ConfigSync] Async listener failed:",c)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function vn(s,r){return s.scopes.includes("all")||s.scopes.includes(r)}const ci="Updating OpenCode configuration...";let Ws=0,ur=ci;const Pa=new Set;function uo(){const s={isUpdating:Ws>0,message:ur};Pa.forEach(r=>r(s))}function Es(s){Ws+=1,Ws===1?(ur=s||ci,uo()):s&&(ur=s,uo())}function os(){Ws!==0&&(Ws-=1,Ws===0&&(ur=ci,uo()))}function Is(s){ur===s&&Ws>0||(ur=s,Ws>0&&uo())}function hp(s){return Pa.add(s),s({isUpdating:Ws>0,message:ur}),()=>{Pa.delete(s)}}function gp(){return{isUpdating:Ws>0,message:ur}}const In=()=>{try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},_r=s=>{const r=s;return r.native===!0||r.builtIn===!0},cd=s=>{const r=s;return r.hidden===!0||r.options?.hidden===!0},dd=s=>s.filter(r=>!cd(r)),fn="useAgentsStore",mo=s=>new Promise(r=>setTimeout(r,s)),xp=2e4,Ui=300,Wi=4,yp=800,bp=200,wp=2e3,tn=Tt()(_t(ws((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;let n=null;for(let o=0;o<3;o++)try{const a=await Re.listAgents(),i=In(),c=i?`?directory=${encodeURIComponent(i)}`:"",d=await Promise.all(a.map(async u=>{try{const m=await fetch(`/api/config/agents/${encodeURIComponent(u.name)}${c}`);if(m.ok){const f=await m.json(),p=f.scope??f.sources?.md?.scope??f.sources?.json?.scope;return{...u,scope:p}}}catch{}return u}));return s({agents:d,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),s({agents:t,isLoading:!1}),!1},createAgent:async t=>{Es("Creating agent configuration…");let n=!1;try{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.tools&&Object.keys(t.tools).length>0&&(o.tools=t.tools),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),t.scope&&(o.scope=t.scope);const a=In(),i=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await Ur({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadAgents();return m&&ys("agents",{source:fn}),m}catch{return!1}finally{n||os()}},updateAgent:async(t,n)=>{Es("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.tools!==void 0&&(a.tools=n.tools),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const i=In(),c=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(t)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json"},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 Ur({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadAgents();return f&&ys("agents",{source:fn}),f}catch{return!1}finally{o||os()}},deleteAgent:async t=>{Es("Deleting agent configuration…");let n=!1;try{const o=In(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/agents/${encodeURIComponent(t)}${a}`,{method:"DELETE"}),c=await i.json().catch(()=>null);if(!i.ok){const m=c?.error||"Failed to delete agent";throw new Error(m)}if(c?.requiresReload??!0)return n=!0,await Ur({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadAgents();return u&&ys("agents",{source:fn}),r().selectedAgentName===t&&s({selectedAgentName:null}),u}catch{return!1}finally{n||os()}},getAgentByName:t=>{const{agents:n}=r();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=r();return dd(t)}}),{name:"agents-store",storage:vs(()=>ls()),partialize:s=>({selectedAgentName:s.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=tn);async function vp(s){const r=typeof s=="number"&&s>0?Math.min(s,Ui):0;r>0&&await mo(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<xp;){n+=1,Is(`Waiting for OpenCode… (attempt ${n})`);try{if(await Re.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=Wi&&a<1200?Ui:Math.min(yp+Math.max(0,n-Wi)*bp,wp);await mo(i)}throw o||new Error("OpenCode did not become ready in time")}async function Ur(s={}){const{message:r,delayMs:t}=s;try{Is(r||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("agents-store"),window.localStorage.removeItem("config-store"))}catch{}try{await vp(t),Is("Refreshing providers and agents…");const n=ut.getState(),o=tn.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),ys("agents",{source:fn})}catch{Is("OpenCode reload failed. Please retry refreshing configuration manually."),await mo(1500)}finally{os()}}async function jp(s){await Ur(s)}async function pn(s){Es("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 n=t?.error||"Failed to reload configuration";throw new Error(n)}t?.requiresReload?await Ur({message:t.message,delayMs:t.reloadDelayMs}):await Ur(s)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),Is("Failed to reload configuration. Please try again."),await mo(2e3),os(),r}}let Vi=null;Vi||(Vi=Po(s=>{if(s.source!==fn&&vn(s,"agents")){const{loadAgents:r}=tn.getState();r()}}));let ud=null;const Gi=s=>{ud=s},Er=()=>ud,zs=Tt()(_t(ws((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 c=i.queuedMessages[t]??[];return{queuedMessages:{...i.queuedMessages,[t]:[...c,a]}}})},removeFromQueue:(t,n)=>{s(o=>{const i=(o.queuedMessages[t]??[]).filter(c=>c.id!==n);if(i.length===0){const{[t]:c,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[t]:i}}})},popToInput:(t,n)=>{const i=(r().queuedMessages[t]??[]).find(c=>c.id===n);return i?(s(c=>{const u=(c.queuedMessages[t]??[]).filter(m=>m.id!==n);if(u.length===0){const{[t]:m,...f}=c.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...c.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}),ns({queueModeEnabled:t})},getQueueForSession:t=>r().queuedMessages[t]??[]}),{name:"message-queue-store",storage:vs(()=>ls()),partialize:s=>({queuedMessages:s.queuedMessages,queueModeEnabled:s.queueModeEnabled})}),{name:"message-queue-store"})),qi=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},Sp=s=>!s||typeof s!="object"?null:{showReasoningTraces:s.showReasoningTraces},kp=s=>{const r=Fe.getState();typeof s.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(s.showReasoningTraces)},Np=async()=>{if(typeof window>"u")return null;if(Ht()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const t=await r.load();return qi(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=Sp(r);return qi(t)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}},Jn=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.pinnedDirectories)&&s.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(s.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"))},Cp=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():"",c=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!i||!c||t.has(a)||(t.add(a),r.push({id:a,label:i,source:c,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},md=()=>{const s=Fe.persist;if(s&&typeof s=="object")return s},fd=()=>Er()?.settings??null,Zn=s=>{const r=Fe.getState(),t=zs.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)},Ki=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),Array.isArray(r.approvedDirectories)&&(t.approvedDirectories=r.approvedDirectories.filter(o=>typeof o=="string"&&o.length>0)),Array.isArray(r.securityScopedBookmarks)&&(t.securityScopedBookmarks=r.securityScopedBookmarks.filter(o=>typeof o=="string"&&o.length>0)),Array.isArray(r.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(o=>typeof o=="string"&&o.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.queueModeEnabled=="boolean"&&(t.queueModeEnabled=r.queueModeEnabled);const n=Cp(r.skillCatalogs);return n&&(t.skillCatalogs=n),t},Mp=async()=>{const s=fd();if(s)try{const r=await s.load();return Ki(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 Ki(t)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},pd=async()=>{if(typeof window>"u")return;const s=md(),r=t=>{Jn(t);const n=()=>Zn(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=Ht()?await en():await Mp();t&&r(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},ns=async s=>{if(typeof window>"u")return;if(Ht()){try{const t=await Jf(s);t&&(Jn(t),Zn(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const r=fd();if(r)try{const t=await r.save(s);t&&(Jn(t),Zn(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&&(Jn(n),Zn(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},hd=async()=>{if(typeof window>"u")return;const s=md();try{const r=await Np();if(!r)return;const t=()=>kp(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)}},Dp="https://models.dev/api.json",Ap="/api/openchamber/models-metadata",Yi="opencode",Xi="big-pickle",Ep=async()=>{try{if(Ht()){const n=await en();return{defaultModel:n?.defaultModel,defaultAgent:n?.defaultAgent}}const s=Er()?.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}}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}}catch{return{}}},Qi=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]}},Ip=s=>s?.toLowerCase?.()??"",Tp=s=>s==="primary"||s==="all"||s===void 0||s===null,jn=s=>typeof s=="object"&&s!==null,fo=s=>Array.isArray(s)&&s.every(r=>typeof r=="string"),Fp=s=>{if(!jn(s))return!1;const r=s;if(r.modalities){const{input:t,output:n}=r.modalities;if(t&&!fo(t)||n&&!fo(n))return!1}return!0},Pp=s=>{if(!jn(s))return!1;const r=s;return r.models===void 0||jn(r.models)},gd=(s,r)=>{const t=Ip(s);return!t||!r?"":`${t}/${r}`},Rp=s=>{const r=new Map;if(!jn(s))return r;for(const[t,n]of Object.entries(s)){if(!Pp(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!jn(a)))for(const[i,c]of Object.entries(a)){if(!Fp(c))continue;const d=typeof i=="string"&&i.length>0?i:c.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof c.id=="string"&&c.id.length>0?c.id:d,providerId:o,name:typeof c.name=="string"?c.name:void 0,tool_call:typeof c.tool_call=="boolean"?c.tool_call:void 0,reasoning:typeof c.reasoning=="boolean"?c.reasoning:void 0,temperature:typeof c.temperature=="boolean"?c.temperature:void 0,attachment:typeof c.attachment=="boolean"?c.attachment:void 0,modalities:c.modalities?{input:fo(c.modalities.input)?c.modalities.input:void 0,output:fo(c.modalities.output)?c.modalities.output:void 0}:void 0,cost:c.cost,limit:c.limit,knowledge:typeof c.knowledge=="string"?c.knowledge:void 0,release_date:typeof c.release_date=="string"?c.release_date:void 0,last_updated:typeof c.last_updated=="string"?c.last_updated:void 0},m=gd(o,d);m&&r.set(m,u)}}return r},Lp=async()=>{if(typeof fetch!="function")return new Map;const s=[Ap,Dp];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 c=await i.json();return Rp(c)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map},Op=s=>new Promise(r=>setTimeout(r,s)),ut=Tt()(_t(ws((s,r)=>({providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultAgent:void 0,loadProviders:async()=>{const t=r().providers,n=r().defaultProviders;let o=null;for(let a=0;a<3;a++)try{const i=Lp(),c=await Re.getProviders(),d=Array.isArray(c?.providers)?c.providers:[],u=c?.default||{},m=d.map(p=>{const h=p.models??{},w=Object.keys(h).map(g=>h[g]);return{...p,models:w}});s({providers:m,defaultProviders:u});const f=await i;f.size>0&&s({modelsMetadata:f});return}catch(i){o=i;const c=200*(a+1);await new Promise(d=>setTimeout(d,c))}console.error("Failed to load providers:",o),s({providers:t,defaultProviders:n})},setProvider:t=>{const{providers:n}=r(),o=n.find(a=>a.id===t);if(o){const i=o.models[0]?.id||"";s({currentProviderId:t,currentModelId:i,selectedProviderId:t})}},setModel:t=>{s({currentModelId:t})},setSelectedProvider:t=>{s({selectedProviderId:t})},saveAgentModelSelection:(t,n,o)=>{s(a=>({agentModelSelections:{...a.agentModelSelections,[t]:{providerId:n,modelId:o}}}))},getAgentModelSelection:t=>{const{agentModelSelections:n}=r();return n[t]||null},loadAgents:async()=>{const t=r().agents;let n=null;for(let o=0;o<3;o++)try{const[a,i]=await Promise.all([Re.listAgents(),Ep()]),c=Array.isArray(a)?a:[];s({agents:c,settingsDefaultModel:i.defaultModel,settingsDefaultAgent:i.defaultAgent});const{providers:d}=r();if(c.length===0)return s({currentAgentName:void 0}),!0;const u=c.filter(x=>Tp(x.mode)),f=u.find(x=>x.name==="build")||u[0]||c[0];let p;const h=(x,v)=>{const S=d.find(N=>N.id===x);return S?S.models.some(N=>N.id===v):!1},w={};if(i.defaultAgent){const x=c.find(v=>v.name===i.defaultAgent);x?p=x:w.defaultAgent=""}p||(p=f),s({currentAgentName:p.name});let g,y;if(i.defaultModel){const x=Qi(i.defaultModel);x&&h(x.providerId,x.modelId)?(g=x.providerId,y=x.modelId):w.defaultModel=""}if(!g&&p?.model?.providerID&&p?.model?.modelID&&h(p.model.providerID,p.model.modelID)&&(g=p.model.providerID,y=p.model.modelID),!g)if(h(Yi,Xi))g=Yi,y=Xi;else{const x=d[0];x&&x.models[0]&&(g=x.id,y=x.models[0].id)}return g&&y&&s({currentProviderId:g,currentModelId:y}),Object.keys(w).length>0&&(s({settingsDefaultModel:w.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultAgent:w.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),ns(w).catch(()=>{})),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),s({agents:t}),!1},setAgent:t=>{const{agents:n,providers:o,settingsDefaultModel:a}=r();if(s({currentAgentName:t}),t&&typeof window<"u"){const i=window.__zustand_session_store__;if(i){const c=i.getState(),{currentSessionId:d,isOpenChamberCreatedSession:u,initializeNewOpenChamberSession:m,getAgentModelForSession:f}=c;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=Qi(a);if(d&&o.find(m=>m.id===d.providerId)?.models.some(m=>m.id===d.modelId)){s({currentProviderId:d.providerId,currentModelId:d.modelId});return}}const c=n.find(d=>d.name===t);if(c?.model?.providerID&&c?.model?.modelID){const d=o.find(u=>u.id===c.model.providerID);d&&d.models.find(m=>m.id===c.model.modelID)&&s({currentProviderId:c.model.providerID,currentModelId:c.model.modelID,selectedProviderId:c.model.providerID})}}},setSettingsDefaultModel:t=>{s({settingsDefaultModel:t})},setSettingsDefaultAgent:t=>{s({settingsDefaultAgent:t})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Re.checkHealth();return s({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await Op(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),s({isConnected:!1}),!1},initializeApp:async()=>{try{console.log("Starting app initialization...");const t=await r().checkConnection();if(console.log("Connection check result:",t),!t){console.log("Server not connected"),s({isConnected:!1});return}console.log("Initializing app..."),await Re.initApp(),console.log("Loading providers..."),await r().loadProviders(),console.log("Loading agents..."),await r().loadAgents(),s({isInitialized:!0,isConnected:!0}),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=gd(t,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=r();return dd(t)}}),{name:"config-store",storage:vs(()=>ls()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=ut);let Ji=null;Ji||(Ji=Po(async s=>{const r=[];if(vn(s,"agents")){const{loadAgents:t}=ut.getState();r.push(t().then(()=>{}))}if(vn(s,"providers")){const{loadProviders:t}=ut.getState();r.push(t())}r.length>0&&await Promise.all(r)}));const Yt={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},$p=180,ms=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function sn(s){const r=ms();return r?r.checkIsGitRepository(s):Lf(s)}async function _p(s){const r=ms();return r?r.getGitStatus(s):$f(s)}async function xd(s){const r=ms();return r?r.getGitBranches(s):Yf(s)}async function Bp(s,r){const t=ms();return t?t.deleteGitBranch(s,r):Bf(s,r)}async function zp(s,r){const t=ms();return t?t.deleteRemoteBranch(s,r):zf(s,r)}async function Hp(s){const r=ms();return r?r.listGitWorktrees(s):Of(s)}async function Up(s,r){const t=ms();return t?t.addGitWorktree(s,r):Hf(s,r)}async function yd(s,r){const t=ms();return t?t.removeGitWorktree(s,r):_f(s,r)}async function Wp(s){const r=ms();return r?r.ensureOpenChamberIgnored(s):Kf(s)}async function Vp(){const s=ms();return s?s.getGitIdentities():qf()}async function Gp(s){const r=ms();return r?r.createGitIdentity(s):Vf(s)}async function qp(s,r){const t=ms();return t?t.updateGitIdentity(s,r):Wf(s,r)}async function Kp(s){const r=ms();return r?r.deleteGitIdentity(s):Uf(s)}async function Yp(s){const r=ms();return r?r.getCurrentGitIdentity(s):Gf(s)}const Xp=".openchamber",sr=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Zi=(s,r)=>{const t=sr(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},bd=s=>s?s.startsWith("refs/heads/")?s.substring(11):s.startsWith("heads/")?s.substring(6):s.startsWith("refs/")?s.substring(5):s:"",Qp=async s=>{try{await Re.createDirectory(s)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function Jp(s,r){const t=sr(s),n=Zi(t,Xp);return await Qp(n),Zi(n,r)}async function wd(s){const{projectDirectory:r,worktreeSlug:t,branch:n,createBranch:o,startPoint:a}=s,i=sr(r),c=await Jp(i,t),d={path:c,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await Up(i,d),{path:c,branch:n,label:bd(n),projectDirectory:i,relativePath:c.startsWith(`${i}/`)?c.slice(i.length+1):c}}async function el(s){const{projectDirectory:r,path:t,force:n}=s,o=sr(r);await yd(o,{path:t,force:n})}async function vd(s){const{projectDirectory:r,path:t,branch:n,force:o,deleteRemote:a,remote:i}=s,c=sr(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await yd(c,{path:t,force:o}),d&&(await Bp(c,{branch:d,force:!0}),a))try{await zp(c,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function po(s){const r=sr(s);return Hp(r)}async function Ra(s){const r=sr(s),t=await _p(r);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function ho(s,r){const t=sr(s),n=sr(r.worktree);return{path:n,branch:r.branch??"",label:bd(r.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}const Zp=new Set(["init","review"]),Br=s=>Zp.has(s.name),hn="useCommandsStore",La=s=>new Promise(r=>setTimeout(r,s)),eh=2e4,tl=300,sl=4,th=800,sh=200,rh=2e3,rn=Tt()(_t(ws((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=await Re.listCommandsWithDetails(),i=wt.getState().currentDirectory,c=i?`?directory=${encodeURIComponent(i)}`:"",d=await Promise.all(a.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${c}`);if(m.ok){const f=await m.json(),p=f.scope??f.sources?.md?.scope;return{...u,scope:p}}}catch{}return u}));return s({commands:d,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load commands:",n),s({commands:t,isLoading:!1}),!1},createCommand:async t=>{Es("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=wt.getState().currentDirectory,i=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await qo({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&ys("commands",{source:hn}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||os()}},updateCommand:async(t,n)=>{Es("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=wt.getState().currentDirectory,c=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(t)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json"},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 qo({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&ys("commands",{source:hn}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||os()}},deleteCommand:async t=>{Es("Deleting command configuration…");let n=!1;try{const o=wt.getState().currentDirectory,a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/commands/${encodeURIComponent(t)}${a}`,{method:"DELETE"}),c=await i.json().catch(()=>null);if(!i.ok){const m=c?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),c?.requiresReload??!0)return n=!0,await qo({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&ys("commands",{source:hn}),r().selectedCommandName===t&&s({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||os()}},getCommandByName:t=>{const{commands:n}=r();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:vs(()=>ls()),partialize:s=>({selectedCommandName:s.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=rn);async function nh(s){const r=typeof s=="number"&&s>0?Math.min(s,tl):0;r>0&&await La(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<eh;){n+=1,Is(`Waiting for OpenCode… (attempt ${n})`);try{if(await Re.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=sl&&a<1200?tl:Math.min(th+Math.max(0,n-sl)*sh,rh);await La(i)}throw o||new Error("OpenCode did not become ready in time")}async function qo(s={}){const{message:r,delayMs:t}=s;try{Is(r||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("commands-store"),window.localStorage.removeItem("config-store"))}catch(n){console.warn("[CommandsStore] Failed to prepare config refresh:",n)}try{await nh(t),Is("Refreshing providers and commands…");const n=ut.getState(),o=rn.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),ys("commands",{source:hn})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Is("OpenCode reload failed. Please retry refreshing configuration manually."),await La(1500)}finally{os()}}let rl=null;rl||(rl=Po(s=>{if(s.source!==hn&&vn(s,"commands")){const{loadCommands:r}=rn.getState();r()}}));const oh=3e4,ah=40,ih=60,lh=(s,r,t)=>{const n=s.trim(),o=r.trim().toLowerCase();return`${n}::${o}::${t}`},di=Tt()(_t((s,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=ih){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",c=lh(a,i,o),d=Date.now(),u=r().cache[c];if(u&&d-u.timestamp<oh)return u.files;const m=r().inFlight[c];if(m)return m;const f=Re.searchFiles(i,{directory:a,limit:o}).then(p=>(s(h=>{const w={...h.cache,[c]:{files:p,timestamp:Date.now()}},g=h.cacheKeys.filter(y=>y!==c);for(g.push(c);g.length>ah;){const y=g.shift();y&&delete w[y]}return{cache:w,cacheKeys:g}}),p)).finally(()=>{s(p=>{const h={...p.inFlight};return delete h[c],{inFlight:h}})});return s(p=>({inFlight:{...p.inFlight,[c]: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},c=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:c,inFlight:u}})}}),{name:"file-search-store"})),Bt=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var ch={};let Ds=null;const Ms=ls(),nl=Ms.getItem("lastDirectory"),dh=typeof nl=="string"&&nl.length>0,Tn=(s,r)=>((r?.showOverlay??!0)&&Es("Switching project directory…"),Re.setOpenCodeWorkingDirectory(s).catch(n=>{throw console.warn("Failed to synchronize OpenCode working directory:",n),n})),Fn=(s,r,t)=>{const{showOverlay:n}=r,o=()=>{try{he.getState().loadSessions()}catch(a){console.error("Failed to reload sessions after directory change:",a)}};(async()=>{let a=null;try{a=await s}catch(i){console.error("Failed to update OpenCode working directory:",i),n&&(Is("Failed to switch directory. Please try again."),await new Promise(c=>setTimeout(c,1500)),os()),t?.(a),o();return}try{if(a&&a.restarted){try{typeof window<"u"&&window.localStorage&&window.localStorage.removeItem("commands-store")}catch(i){console.warn("Failed to reset commands-store cache:",i)}await jp({message:"Refreshing OpenCode configuration…"});try{await rn.getState().loadCommands();try{ys("commands",{source:"useCommandsStore"})}catch(i){console.warn("Failed to emit command configuration change:",i)}}catch(i){console.warn("Failed to reload commands after directory change:",i)}}else n&&os()}catch(i){console.error("Failed to refresh configuration after directory change:",i),n&&(Is("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),os())}finally{t?.(a),o()}})()},Pn=s=>{try{di.getState().invalidateDirectory(s)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},uh=s=>{const r=s.trim();if(!r)return r;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},mh=(s,r)=>{const t=s.trim();return t.startsWith("~")?t==="~"?r||t:(t.startsWith("~/")||t.startsWith("~\\"))&&r?`${r}${t.slice(1)}`:t:t},eo=(s,r)=>{const t=mh(s,r);return uh(t)},go=()=>{if(typeof window<"u"){const r=Ms.getItem("homeDirectory")||Ds||null,t=Ms.getItem("lastDirectory");if(t)return eo(t,r);if(Ds)return Ds;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 Ds=n,Ms.setItem("homeDirectory",n),n;if(r)return Ds=r,r}const s=typeof process<"u"&&ch?.HOME;return s||process?.cwd?.()||"/"},fh=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},ph=s=>(Ds=s,typeof window<"u"&&Ms.setItem("homeDirectory",s),ns({homeDirectory:s}),s),jd=async()=>{const s=n=>{const o=fh(n);return o?ph(o):null};try{const n=await Re.getFilesystemHome(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Re.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 ad(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=go(),t=s(r);return t||r},kr=go();kr&&Re.setDirectory(kr);const hh=!!(kr&&kr!=="/"),wt=Tt()(_t((s,r)=>({currentDirectory:kr,directoryHistory:[kr],historyIndex:0,homeDirectory:kr,hasPersistedDirectory:dh,isHomeReady:hh,isSwitchingDirectory:!1,setDirectory:(t,n)=>{const o=Ds||r().homeDirectory||Ms.getItem("homeDirectory"),a=eo(t,o);Bt()&&console.log("[DirectoryStore] setDirectory called with path:",a);const i=n?.showOverlay??!0;Re.setDirectory(a),Pn();const c=Tn(a,{showOverlay:i});Bt()&&console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),s(d=>{const u=[...d.directoryHistory.slice(0,d.historyIndex+1),a];return Ms.setItem("lastDirectory",a),ns({lastDirectory:a}),{currentDirectory:a,directoryHistory:u,historyIndex:u.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}}),Fn(c,{showOverlay:i},()=>{s(d=>d.currentDirectory!==a?{}:d.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})},goBack:()=>{const t=r();if(t.historyIndex>0){const n=t.historyIndex-1,o=t.directoryHistory[n];Re.setDirectory(o),Pn();const a=Tn(o);Ms.setItem("lastDirectory",o),ns({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Fn(a,{showOverlay:!0},()=>{s(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goForward:()=>{const t=r();if(t.historyIndex<t.directoryHistory.length-1){const n=t.historyIndex+1,o=t.directoryHistory[n];Re.setDirectory(o),Pn();const a=Tn(o);Ms.setItem("lastDirectory",o),ns({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Fn(a,{showOverlay:!0},()=>{s(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=r(),o=Ds||r().homeDirectory||go();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=Ds||go();n(c)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=Ds||r().homeDirectory||await jd();r().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=r(),o=t;Ds=o;const a=n.homeDirectory!==o,i=Ms.getItem("lastDirectory"),c=typeof i=="string"&&i.length>0,d=!c&&(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?eo(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(g=>eo(g,o)),p=f.some((g,y)=>g!==n.directoryHistory[y]),h=!!(m&&m!==n.currentDirectory),w={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d?(w.currentDirectory=o,w.directoryHistory=[o],w.historyIndex=0,w.isSwitchingDirectory=!0):(h||p)&&(w.currentDirectory=m,w.directoryHistory=f,w.historyIndex=Math.min(n.historyIndex,f.length-1),w.isSwitchingDirectory=!0),s(()=>w),(d||h)&&u){const g=d?o:m;Re.setDirectory(g),Pn(),Ms.setItem("lastDirectory",g),ns({lastDirectory:g});const y=Tn(g,{showOverlay:!1});Fn(y,{showOverlay:!1},()=>{s(x=>x.currentDirectory!==g?{}:x.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}ns({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&jd().then(s=>{wt.getState().synchronizeHomeDirectory(s)});const Sd=ls(),kd="oc.sessionSelectionByDirectory",Ko=".openchamber",gh=()=>{try{const s=Sd.getItem(kd);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 to=null;const ui=()=>(to||(to=gh()),to),Nd=s=>{to=s;try{Sd.setItem(kd,JSON.stringify(s))}catch{}},Cd=s=>{if(!s)return null;const t=ui()[s];return typeof t=="string"?t:null},gr=(s,r)=>{if(!s)return;const t={...ui()};r?t[s]=r:delete t[s],Nd(t)},ol=(s,r)=>{if(!s)return;const t=Cd(s);if(!t)return;if(!new Set(r).has(t)){const o={...ui()};delete o[s],Nd(o)}},al=async(s,r)=>{const t=s.status??await Ra(s.path).catch(()=>{});await vd({projectDirectory:s.projectDirectory,path:s.path,branch:s.branch,force:!!t?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},qt=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},rr=(s,r)=>{const t=s.find(n=>n.id===r);return t?qt(t.directory??null):null},xh=async(s,r,t)=>{const n=qt(r);if(!n||s.length===0)return null;const o=s.map(u=>({id:u.id,directory:qt(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await po(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=ho(n,u),f=qt(m.path)??m.path;f!==n&&i.set(f,m)});let c=!1;const d=new Map(t);return o.forEach(({id:u,directory:m})=>{const f=i.get(m);if(!f){d.delete(u)&&(c=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),c=!0)}),c?d:null},Je=Tt()(_t(ws((s,r)=>({sessions:[],currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],loadSessions:async()=>{s({isLoading:!0,error:null});try{const n=wt.getState().currentDirectory??Re.getDirectory()??null,o=Re.getApiClient(),a=async b=>{const C=await o.session.list(b?{directory:b}:void 0);return Array.isArray(C.data)?C.data:[]},i=qt(n),c=i?await sn(i).catch(()=>!1):!1,d=await a(i||null),u=[];let m=[];if(n&&c&&i){const b=`${i}/${Ko}`;try{const C=new Set;(await Re.listLocalDirectory(i)).some(L=>L.isDirectory&&L.name===Ko)&&(await Re.listLocalDirectory(b)).filter(q=>q.isDirectory).forEach(q=>{const le=/^([A-Za-z]:)?\//.test(q.path)?q.path:`${b}/${q.name}`;C.add(qt(le)??le)});const R=await po(i);Array.isArray(R)&&(m=R.map(L=>ho(i,L)).filter(L=>L.path.includes(`/${Ko}/`)),m.forEach(L=>C.add(L.path))),C.size>0&&(await Promise.allSettled(Array.from(C).map(q=>a(q)))).forEach(q=>{q.status==="fulfilled"&&Array.isArray(q.value)&&u.push(...q.value)})}catch{m=[]}}const f=new Set;i&&f.add(i),m.forEach(b=>{const C=qt(b.path);C&&f.add(C)});const p=[...d,...u].filter(b=>{const C=b.directory??i??null,D=qt(C);return D?f.has(D):!1}),h=r(),w=h.lastLoadedDirectory??null,g=n!==w;let y=[...p],x=h.currentSessionId;const v=b=>{y=[b,...y.filter(C=>C.id!==b.id)]};if(g)x=y.length>0?y[0].id:null;else if(x){if(!y.some(C=>C.id===x)){const C=h.sessions.find(D=>D.id===x);if(C)v(C);else try{const D=await Re.getSession(x);v(D)}catch{x=y.length>0?y[0].id:null}}}else x=y.length>0?y[0].id:null;const S=y.reduce((b,C)=>(b.some(D=>D.id===C.id)||b.push(C),b),[]);x&&!S.some(b=>b.id===x)&&(x=S.length>0?S[0].id:null);const N=new Set(S.map(b=>b.id)),k=(b=>{if(!b)return null;const C=rr(S,b);if(C)return C;const D=rr(h.sessions,b);return D||null})(x)??i??n??null;if(n&&ol(n,N),k){ol(k,N);const b=Cd(k);b&&N.has(b)&&(x=b)}let F=null;try{F=await xh(S,n,h.worktreeMetadata)}catch(b){console.debug("Failed to refresh worktree metadata during session load:",b)}const A=(()=>{const b=F??h.worktreeMetadata;if(!g||!i)return b;const C=new Map;return b.forEach((D,P)=>{qt(D.projectDirectory)===i&&C.set(P,D)}),C})(),M=(()=>{if(!x)return i??null;const b=A.get(x)?.path;if(b)return qt(b)??b;const C=rr(S,x);return C||(i??null)})();try{Re.setDirectory(M??void 0)}catch(b){console.warn("Failed to sync OpenCode directory after session load:",b)}s({sessions:S,currentSessionId:x,lastLoadedDirectory:n,isLoading:!1,worktreeMetadata:A,availableWorktrees:m}),gr(M??n,x)}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=wt.getState(),i=qt(a.currentDirectory),c=qt(n??Re.getDirectory()??i),d=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,u=r(),m=new Set(u.sessions.map(w=>w.id)),f={id:d,title:t||"New session",parentID:o??void 0,directory:c??null,projectID:u.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(s(w=>({sessions:[f,...w.sessions],currentSessionId:d,webUICreatedSessions:new Set([...w.webUICreatedSessions,d]),isLoading:!1})),c)try{Re.setDirectory(c)}catch(w){console.warn("Failed to sync OpenCode directory after session creation:",w)}const p=w=>{s(g=>({sessions:g.sessions.map(x=>x.id===d?w:x),currentSessionId:w.id,webUICreatedSessions:new Set([...Array.from(g.webUICreatedSessions).filter(x=>x!==d),w.id])})),gr(c??null,w.id)},h=async()=>{const w=Re.getApiClient(),g=20;for(let y=0;y<g;y+=1){try{const x=await w.session.list(c?{directory:c}:void 0),S=(Array.isArray(x.data)?x.data:[]).find(N=>!(m.has(N.id)||t&&N.title&&N.title!==t));if(S)return S}catch(x){console.debug("Session poll attempt failed:",x)}await new Promise(x=>setTimeout(x,2e3))}return null};try{const w=()=>Re.createSession({title:t,parentID:o??void 0});let g=null;try{g=c?await Re.withDirectory(c,w):await w()}catch(y){console.warn("Direct session create failed or timed out, falling back to polling:",y)}return g||(g=await h()),g?(p(g),g):(s(y=>({sessions:y.sessions.filter(x=>x.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(x=>x!==d)),isLoading:!1,error:"Failed to create session"})),null)}catch(w){return s(g=>({sessions:g.sessions.filter(y=>y.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(g.webUICreatedSessions).filter(y=>y!==d)),isLoading:!1,error:w instanceof Error?w.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{s({isLoading:!0,error:null});const o=r().worktreeMetadata.get(t),a=rr(r().sessions,t),i=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await al(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Re.deleteSession(t);if(!(i?await Re.withDirectory(i,d):await d()))return s(p=>{const h={isLoading:!1,error:"Failed to delete session"};if(c){const w=new Map(p.worktreeMetadata);w.delete(t),h.worktreeMetadata=w}return h}),!1;let m=null;s(p=>{const h=p.sessions.filter(y=>y.id!==t);m=p.currentSessionId===t?null:p.currentSessionId;const w=new Map(p.worktreeMetadata);w.delete(t);const g=n?.archiveWorktree&&o?p.availableWorktrees.filter(y=>qt(y.path)!==qt(o.path)):p.availableWorktrees;return{sessions:h,currentSessionId:m,isLoading:!1,worktreeMetadata:w,availableWorktrees:g}});const f=i??Re.getDirectory()??null;return gr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return s(c?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(y=>typeof y=="string"&&y.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||s({isLoading:!0,error:null});const i=[],c=[],d=new Set,u=[],m=new Set;for(const y of o)try{const x=r().worktreeMetadata.get(y),v=rr(r().sessions,y),S=x?.path??v;x&&n?.archiveWorktree&&!m.has(x.path)&&(await al(x,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(y),u.push({path:x.path,projectDirectory:x.projectDirectory}),m.add(x.path));const N=()=>Re.deleteSession(y);(S?await Re.withDirectory(S,N):await N())?(i.push(y),x?.path&&!u.some(k=>k.path===x.path)&&u.push({path:x.path,projectDirectory:x.projectDirectory})):c.push(y)}catch{c.push(y)}const f=wt.getState();u.forEach(({path:y,projectDirectory:x})=>{f.currentDirectory===y&&f.setDirectory(x,{showOverlay:!1})});const p=new Set(i),h=c.length>0?c.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let w=null;s(y=>{const x=y.sessions.filter(j=>!p.has(j.id));y.currentSessionId&&p.has(y.currentSessionId)?w=null:w=y.currentSessionId;const v=new Map(y.worktreeMetadata);for(const j of p)v.delete(j);for(const j of d)v.delete(j);const S=new Set(u.map(j=>qt(j.path)).filter(j=>!!j)),N=S.size>0?y.availableWorktrees.filter(j=>!S.has(qt(j.path)??j.path)):y.availableWorktrees;return{sessions:x,currentSessionId:w,...a?{}:{isLoading:!1,error:h},worktreeMetadata:v,availableWorktrees:N}});const g=Re.getDirectory()??null;return gr(g,w),{deletedIds:i,failedIds:c}},updateSessionTitle:async(t,n)=>{try{const o=rr(r().sessions,t),a=r().worktreeMetadata.get(t),i=()=>Re.updateSession(t,n),c=a?.path??o,d=c?await Re.withDirectory(c,i):await i();s(u=>({sessions:u.sessions.map(m=>m.id===t?d:m)}))}catch(o){s({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=rr(r().sessions,t),o=Re.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Re.getDirectory();return o.session.share({sessionID:t,...u?{directory:u}:{}})},d=i?await Re.withDirectory(i,c):await c();return d.data?(s(u=>({sessions:u.sessions.map(m=>m.id===t?d.data: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=rr(r().sessions,t),o=Re.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Re.getDirectory();return o.session.unshare({sessionID:t,...u?{directory:u}:{}})},d=i?await Re.withDirectory(i,c):await c();return d.data?(s(u=>({sessions:u.sessions.map(m=>m.id===t?d.data: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=Re.getDirectory()??null;gr(n,t)},clearError:()=>{s({error:null})},getSessionsByDirectory:()=>{const{sessions:t}=r();return t},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],c=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:c,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,f?{sessions:p}:o})},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 c=o[a].directory??null,d=n??void 0;c!==(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}}),c&&gr(c,null),n&&gr(n,t))},updateSession:t=>{s(n=>({sessions:n.sessions.map(o=>o.id===t.id?t:o)}))}}),{name:"session-store",storage:vs(()=>ls()),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}),merge:(s,r)=>{if(!(u=>typeof u=="object"&&u!==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:[],c=Array.isArray(s.availableWorktrees)?s.availableWorktrees:r.availableWorktrees,d=typeof s.lastLoadedDirectory=="string"?s.lastLoadedDirectory:r.lastLoadedDirectory??null;return{...r,...s,sessions:n,currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:c,lastLoadedDirectory:d}}}),{name:"session-store"})),Md="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.",yh="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: ",Yo=s=>typeof s=="string"&&s.trim()===Md.trim(),Xo=(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},on=(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},il=new Map,Dd=s=>{const r=il.get(s);r&&(clearTimeout(r),il.delete(s))},xr=s=>{for(const r of s)Dd(r)},Sn=s=>{if(!s)return"";if(typeof s=="string")return s;if(Array.isArray(s))return s.map(r=>Sn(r)).join("");if(typeof s=="object"){if(typeof s.text=="string")return s.text;if(Array.isArray(s.content))return s.content.map(r=>Sn(r)).join("")}return""},gn=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:gn(n)).join("");const t=Sn(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||Sn(o.delta)||""}return""}).join(""):"")},an=(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=Sn(s.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},ll=10*1024*1024,bh=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"}},wh=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"}},vh=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},jh=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],c=o<<16|(a??0)<<8|(i??0);t+=r[c>>18&63],t+=r[c>>12&63],t+=typeof a=="number"?r[c>>6&63]:"=",t+=typeof i=="number"?r[c&63]:"="}return t},Hs=Tt()(_t(ws((s,r)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=r();if(n.some(w=>w.filename===t.name&&w.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=ll;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"],c=wh(t);!i.some(w=>c.startsWith(w)||c===w||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const u=new FileReader,m=await new Promise((w,g)=>{u.onload=()=>w(u.result),u.onerror=g,u.readAsDataURL(t)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${c}`):m,p=w=>{const g=w.replace(/\\/g,"/").split("/");return g[g.length-1]||w},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:f,mimeType:c,filename:p(t.name),size:t.size,source:"local"};s(w=>({attachedFiles:[...w.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 c=o,d,u;if(!c)try{const x=Re.getApiClient(),v=t.lastIndexOf("/"),S=v>0?t.substring(0,v):"/",N=v>0?t.substring(v+1):t,j=await x.file.read({path:N,directory:S});j.data&&"content"in j.data?(c=j.data.content,d=j.data.encoding??void 0,u=j.data.mimeType??void 0):c=""}catch(x){console.error("Failed to read server file:",x),c=`[File: ${n}]`}const m=u||bh(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const v=new TextEncoder().encode(c||"");return jh(v)})(),h=d==="base64"?vh(p):new TextEncoder().encode(c||"").length;if(h>ll)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const w=new File([],n,{type:f}),g=`data:${f};base64,${p}`,y={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:w,dataUrl:g,mimeType:f,filename:n,size:h,source:"server",serverPath:t};s(x=>({attachedFiles:[...x.attachedFiles,y]}))},removeAttachedFile:t=>{s(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{s({attachedFiles:[]})}}),{name:"file-store",storage:vs(()=>ls()),partialize:s=>({attachedFiles:s.attachedFiles})}),{name:"file-store"})),Sh=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),kh=s=>s?Sh.has(s.toLowerCase()):!1,Nh=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Ch=s=>{if(s)try{const r=Nh();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===s)}catch{}},so=s=>{const r=Ch(s);if(!r)return"ask";const t=r.permission?.edit;return t==="allow"||t==="ask"||t==="deny"||t==="full"?t:(r.tools?r.tools.edit!==!1:!0)?"ask":"deny"},cl=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},Qo=s=>{const r=s.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return cl(r);const t=s.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:cl(t.tokens)},Jo=(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),c=Math.min(i,n),d=n>0?Math.max(n-c,1):0,u=d>0?s/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},ln=["ask","allow","full"],gt=Tt()(_t(ws((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 c=new Map(i.sessionAgentModelSelections);let d=c.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(t,d),{sessionAgentModelSelections:c}})},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,c=(f,p)=>{if("mode"in f&&f.mode&&typeof f.mode=="string"&&n.find(y=>y.name===f.mode))return f.mode;if(f.providerID&&f.modelID){const g=n.find(y=>y.model?.providerID===f.providerID&&y.model?.modelID===f.modelID);if(g)return g.name}const{currentAgentContext:h}=r(),w=h.get(t);if(w&&n.find(g=>g.name===w))return w;if(p>0&&f.providerID&&f.modelID){const y=(o.get(t)||[]).filter(x=>x.info.role==="assistant").sort((x,v)=>x.info.time.created-v.info.time.created);for(let x=p-1;x>=0;x--){const S=y[x].info;if(S.providerID===f.providerID&&S.modelID===f.modelID){if(S.mode&&typeof S.mode=="string"&&n.find(k=>k.name===S.mode))return S.mode;const N=n.find(j=>j.model?.providerID===S.providerID&&j.model?.modelID===S.modelID);if(N)return N.name}}}return f.providerID&&f.modelID&&n.find(y=>y.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,w=h;if(w.providerID&&w.modelID){const g=c(w,m.indexOf(p));if(g&&n.find(y=>y.name===g)){const y={providerId:w.providerID,modelId:w.modelID,timestamp:h.time.created},x=i.get(g);(!x||y.timestamp>x.timestamp)&&i.set(g,y)}}}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=Jo(0,n,o),c=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(c===0||u===0)return null;const f=(a.get(t)||[]).filter(S=>S.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],h=p.info.id,w=S=>{const N=()=>{s(j=>{const k=j.sessionContextUsage.get(t);if(k&&k.totalTokens===S.totalTokens&&k.percentage===S.percentage&&k.contextLimit===S.contextLimit&&(k.outputLimit??0)===(S.outputLimit??0)&&(k.normalizedOutput??0)===(S.normalizedOutput??0)&&k.thresholdLimit===S.thresholdLimit&&k.lastMessageId===S.lastMessageId)return j;const F=new Map(j.sessionContextUsage);return F.set(t,S),{sessionContextUsage:F}})};typeof queueMicrotask=="function"?queueMicrotask(N):typeof window<"u"?window.setTimeout(N,0):setTimeout(N,0)},g=r().sessionContextUsage.get(t);if(g&&g.lastMessageId===h){const S=g.normalizedOutput??g.outputLimit??0,N=g.contextLimit!==c||S!==d||g.thresholdLimit!==u;if(N&&g.totalTokens>0){const j=g.totalTokens/u*100,k={totalTokens:g.totalTokens,percentage:Math.min(j,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return w(k),k}if(!N&&g.totalTokens>0)return g}const y=Qo(p);if(y===0)return g||null;const x=Jo(y,n,o),v={totalTokens:y,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit,normalizedOutput:x.normalizedOutput,thresholdLimit:x.thresholdLimit,lastMessageId:h};return w(v),v},updateSessionContextUsage:(t,n,o,a)=>{const c=(a.get(t)||[]).filter(f=>f.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=Qo(d);if(u===0)return;const m=Jo(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 c=r().sessionContextUsage.get(t);(!c||c.totalTokens===0)&&r().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let i=0;const c=()=>{i++;const u=(o.get(t)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&Qo(u)>0){r().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=r();return n.get(t)},getSessionAgentEditMode:(t,n,o=so(n))=>!t||!n?o:r().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=so(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||ln.includes(o)&&s(c=>{const d=new Map(c.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=so(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=r().getSessionAgentEditMode(t,n,a),c=ln.indexOf(i),d=ln.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%ln.length,f=ln[m];r().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:vs(()=>ls()),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"})),dl=(s,r)=>{const t=new Map(s);return t.delete(r),t};let Zo=[],ea=null;const Mh=50,Dh=3e4,yr=new Map,Rn=new Map,Rr=new Map,Ah=10,xo=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<Ah?null:n},Ln=(s,r)=>{const t=xo(s),n=xo(r);return!t||!n||t.length!==n.length?!0:t>n},Eh=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},zr=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),yo=s=>s?.finish==="stop",ul=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??""}`}}},ml=new Set,bo=(s=[],r=[])=>{if(!r.length)return[...s];const t=[...s],n=new Set(s.map(ul).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=ul(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},Ih=(s,r)=>{const t=Array.isArray(s.parts)?s.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=zr(t),a=zr(n),i=yo(s.info),c=yo(r.info);let d=n;return i&&o>=a?d=bo(t,n):c&&a>=o?d=bo(n,t):o>=a&&(d=t),{...r,info:{...s.info,...r.info},parts:d}},ta=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]=Ih(r[a],n)}return r},Th=(s,r)=>{let t=r,n=r?xo(r):null;for(const o of s){const a=o?.info?.id,i=xo(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},$s=(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},Lr=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return o.set(r,t),o},On=(s,r)=>{const t=new Map(s);let n=!1;for(const o of r)t.delete(o)&&(n=!0);return n?t:s},Fh=(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},fl=(s,r,t)=>s.streamingMessageIds.get(r)===t?!0:s.messageSessionIndex.get(t)===r&&s.messageStreamStates.has(t),Ph=async s=>{if(s)try{const r=Je.getState(),t=r.getWorktreeMetadata(s);if(t?.path)return t.path;const n=r.sessions.find(a=>a.id===s);return typeof n?.directory=="string"&&n.directory.length>0?n.directory:void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},pl=s=>{if(!s)return null;try{return Je.getState().sessions.find(n=>n.id===s)?.revert?.messageID??null}catch{return null}},hl=(s,r)=>{if(!r)return s;const t=s.findIndex(n=>n.info.id===r);return t===-1?s:s.slice(0,t)},sa=async(s,r)=>{const t=await Ph(s);return t?Re.withDirectory(t,r):r()},at=Tt()(_t(ws((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=Yt.VIEWPORT_MESSAGES)=>{const o=await sa(t,()=>Re.getSessionMessages(t)),a=pl(t),i=hl(o,a),c=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,u=(c?i.filter(m=>{const f=m?.info?.id;return f?Ln(f,c):!0}):i).slice(-n);s(m=>{const f=new Map(m.messages),p=m.messages.get(t)||[],h=new Map(p.filter(M=>typeof M.info?.id=="string").map(M=>[M.info.id,M])),w=u.map(M=>{const b={...M.info,clientRole:M.info?.clientRole??M.info.role,userMessageMarker:M.info.role==="user"?!0:M.info?.userMessageMarker},C=(Array.isArray(M.parts)?M.parts:[]).map(P=>{if(P?.type==="text"){const R=P.text??P.content??"";if(Yo(R))return{...P,synthetic:!0}}return P}),D=b?.id?h.get(b.id):void 0;if(D&&D.info.role==="assistant"){const P=Array.isArray(D.parts)?D.parts:[],R=zr(P),L=zr(C);if(yo(D.info)&&R>L){const te=bo(P,C);return{...M,info:b,parts:te}}}return{...M,info:b,parts:C}}),g=ta(w),y=new Set(p.map(M=>M.info.id)),x=new Set(g.map(M=>M.info.id)),v=[];y.forEach(M=>{x.has(M)||v.push(M)}),f.set(t,g);const S=new Map(m.sessionMemoryState),N=m.sessionMemoryState.get(t);S.set(t,{...N,viewportAnchor:g.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>u.length,trimmedHeadMaxId:N?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const j={messages:f,sessionMemoryState:S};xr(v);const k=on(m.messageStreamStates,v);if(k!==m.messageStreamStates&&(j.messageStreamStates=k),v.length>0){const M=m.streamingMessageIds.get(t);M&&v.includes(M)&&(j.streamingMessageIds=$s(j.streamingMessageIds??m.streamingMessageIds,t,null))}if(v.length>0){const M=On(j.messageSessionIndex??m.messageSessionIndex,v);M!==(j.messageSessionIndex??m.messageSessionIndex)&&(j.messageSessionIndex=M)}if(v.length>0){const M=new Map(m.pendingAssistantParts);let b=!1;v.forEach(C=>{M.delete(C)&&(b=!0)}),b&&(j.pendingAssistantParts=M)}const F=j.messageSessionIndex??m.messageSessionIndex;let A=F;return g.forEach(M=>{const b=M?.info?.id;typeof b=="string"&&b.length>0&&(A=Lr(A,b,t))}),A!==F&&(j.messageSessionIndex=A),j})},sendMessage:async(t,n,o,a,i,c,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 sa(m,async()=>{try{let f=t;if(t.startsWith("/")){const h=t.indexOf(" "),w=h===-1?t.substring(1):t.substring(1,h),g=h===-1?"":t.substring(h+1).trim(),y=Re.getApiClient(),x=Re.getDirectory();if(w==="init"){const v=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await y.session.init({sessionID:m,...x?{directory:x}:{},messageID:v,providerID:n,modelID:o});return}if(w==="summarize"){await y.session.summarize({sessionID:m,...x?{directory:x}:{},providerID:n,modelID:o});return}try{const v=await Re.getCommandDetails(w);v?.template?f=v.template.replace(/\$ARGUMENTS/g,g):f=t}catch(v){console.error("Command template resolution failed:",v),f=t}}s({lastUsedProvider:{providerID:n,modelID:o}}),s(h=>{const w=h.sessionMemoryState.get(m)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},g=Rr.get(m);g&&(clearTimeout(g),Rr.delete(m));const y=new Map(h.sessionMemoryState);return y.set(m,{...w,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:y}});try{const h=new AbortController;s(y=>{const x=new Map(y.abortControllers);return x.set(m,h),{abortControllers:x}});const w=(c??[]).map(y=>({type:"file",mime:y.mimeType,filename:y.filename,url:y.dataUrl}));s(y=>{const x=new Set(y.pendingAssistantHeaderSessions);x.add(m);const v=new Map(y.pendingUserMessageMetaBySession);return v.set(m,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o}),{pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:v}});const g=u?.map(y=>({text:y.text,files:y.attachments?.map(x=>({type:"file",mime:x.mimeType,filename:x.filename,url:x.dataUrl}))}));if(await Re.sendMessage({id:m,providerID:n,modelID:o,text:f,agent:a,files:w.length>0?w:void 0,additionalParts:g,agentMentions:d?[{name:d}]:void 0}),w.length>0)try{Hs.getState().clearAttachedFiles()}catch(y){console.error("Failed to clear attached files after send",y)}s(y=>{const x=new Map(y.abortControllers);return x.delete(m),{abortControllers:x}})}catch(h){let w="Network error while sending message. The message may still be processing.";if(h.name==="AbortError")w="Request timed out. The message may still be processing.";else if(h.message?.includes("504")||h.message?.includes("Gateway")){w="Gateway timeout - your message is being processed. Please wait for response.",s(g=>{const y=new Map(g.abortControllers);return y.delete(m),{abortControllers:y}});return}else h.message&&(w=h.message);throw s(g=>{const y=new Map(g.abortControllers);y.delete(m);const x=new Set(g.pendingAssistantHeaderSessions);x.delete(m);const v=new Map(g.pendingUserMessageMetaBySession);return v.delete(m),{abortControllers:y,pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:v}}),new Error(w)}}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 w=new Map(h.abortControllers);w.delete(m);const g=new Set(h.pendingAssistantHeaderSessions);g.delete(m);const y=new Map(h.pendingUserMessageMetaBySession);return y.delete(m),{abortControllers:w,pendingAssistantHeaderSessions:g,pendingUserMessageMetaBySession:y}}),new Error(p)}})},abortCurrentOperation:async t=>{if(!t)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const c=Fh(n,t);if(c.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(w=>w.type==="reasoning"||w.type==="tool"||w.type==="step-start")){c.add(p.info.id);break}}c.size===0&&m&&c.add(m)}for(const u of c){const m=yr.get(u);m&&(clearTimeout(m),yr.delete(u),Rn.delete(u))}c.size>0&&xr(c);const d=Date.now();s(u=>{const m=on(u.messageStreamStates,c),f=u.messages.get(t)??[];let p=!1,h=u.messages;if(f.length>0&&c.size>0){const x=f.map(v=>{if(!c.has(v.info.id)&&c.size>0)return v;const S=(v.parts??[]).map(N=>{if(N.type==="reasoning"){const j=N,k={...j.time??{}};return typeof k.end!="number"&&(k.end=d),{...j,time:k}}if(N.type==="tool"){const j=N,k={...j.state??{}};return(k.status==="running"||k.status==="pending")&&(k.status="aborted"),{...j,state:k}}return N.type==="step-start"?{...N,type:"step-finish",aborted:!0}:N});return p=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:S}});p&&(h=new Map(u.messages),h.set(t,x))}const w=u.sessionMemoryState.get(t);let g=u.sessionMemoryState;if(w){const x=new Map(u.sessionMemoryState);x.set(t,{...w,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),g=x}const y=new Map(u.sessionAbortFlags);return y.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:g,sessionAbortFlags:y,abortControllers:(()=>{const x=new Map(u.abortControllers);return x.delete(t),x})(),streamingMessageIds:$s(u.streamingMessageIds,t,null),...p?{messages:h}:{}}}),Re.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const c=r();if(ml.has(n))return;const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!Ln(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=c.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>Yt.ZOMBIE_TIMEOUT){p.isZombie||s(w=>{const g=new Map(w.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)||[]],y={},x=Lr(h.messageSessionIndex,n,t);x!==h.messageSessionIndex&&(y.messageSessionIndex=x);const v=M=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(t)))return M;const C=new Map(h.sessionAbortFlags);return C.delete(t),{...M,sessionAbortFlags:C}},S=M=>{const b=M||"",C=Rn.get(n);if(b&&C===b){const R=r();if(fl(R,t,n)){const L=yr.get(n);L&&(clearTimeout(L),yr.delete(n)),setTimeout(()=>{const q=r();typeof q.forceCompleteMessage=="function"&&q.forceCompleteMessage(t,n,"timeout"),q.completeStreamingMessage(t,n)},100)}}Rn.set(n,b);const D=yr.get(n);D&&clearTimeout(D);const P=setTimeout(()=>{const R=r();typeof R.forceCompleteMessage=="function"&&R.forceCompleteMessage(t,n,"timeout"),fl(R,t,n)&&R.completeStreamingMessage(t,n),yr.delete(n),Rn.delete(n)},8e3);yr.set(n,P)},N=t!==i,j=h.sessionMemoryState.get(t);if(N&&j?.isStreaming){g.length>=Yt.BACKGROUND_STREAMING_BUFFER&&g.shift();const M=new Map(h.sessionMemoryState);M.set(t,{...j,backgroundMessageCount:(j.backgroundMessageCount||0)+1}),h.sessionMemoryState=M}if(f==="assistant"){const M=h.sessionMemoryState.get(t);if(M){const b=Date.now(),C=new Map(h.sessionMemoryState);C.set(t,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??b,lastAccessedAt:b,isZombie:!1}),h.sessionMemoryState=C}}const k=gn(o);if(Yo(k)&&(o.synthetic=!0),Eh()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:k.length,snapshotParts:u.length})}catch{}const F=y.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const M=$s(F,t,n);M!==F&&(y.streamingMessageIds=M,window.__messageTracker?.(n,"streamingId_set_latest"))}const A=g.findIndex(M=>M.info.id===n);if(A!==-1&&f==="user"){const M=g[A],b=M.parts.findIndex(L=>L.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const C=an(o,b!==-1?M.parts[b]:void 0);window.__messageTracker?.(n,`user_part_type:${C.type||"unknown"}`);const D={...M};b!==-1?D.parts=D.parts.map((L,q)=>q===b?C:L):D.parts=[...D.parts,C];const P=[...g];P[A]=D;const R=new Map(h.messages);return R.set(t,P),v({messages:R})}if(f==="assistant"&&A!==-1){const M=g[A],b=M.parts.findIndex(q=>q.id===o.id),C=an(o,b!==-1?M.parts[b]:void 0);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`);const D={...M};b!==-1?D.parts=D.parts.map((q,te)=>te===b?C:q):D.parts=[...D.parts,C];const P=[...g];P[A]=D;const R=new Map(h.messages);R.set(t,P),y.messageStreamStates=Xo(h.messageStreamStates,n);const L=$s(y.streamingMessageIds??h.streamingMessageIds,t,n);return L!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=L,window.__messageTracker?.(n,"streamingId_set")),C.type==="text"?S(C.text||""):S(""),v({messages:R,...y})}if(A===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const pe=an(o);window.__messageTracker?.(n,`new_user_part_type:${pe.type||"unknown"}`);const je=h.pendingUserMessageMetaBySession.get(t),U=gt.getState(),ee=je?.mode??U.getSessionAgentSelection(t)??U.getCurrentAgent(t),oe=typeof ee=="string"&&ee.trim().length>0?ee.trim():void 0,W=je?.providerID??(h.lastUsedProvider?.providerID||void 0),me=je?.modelID??(h.lastUsedProvider?.modelID||void 0);je&&(y.pendingUserMessageMetaBySession=dl(h.pendingUserMessageMetaBySession,t));const ye={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,...oe?{mode:oe}:{},...W?{providerID:W}:{},...me?{modelID:me}:{},time:{created:Date.now()}},parts:[pe]},ce=[...g,ye];ce.sort((Ee,Pe)=>{const V=Ee.info?.time?.created||0,K=Pe.info?.time?.created||0;return V-K});const Me=new Map(h.messages);return Me.set(t,ce),v({messages:Me})}if(o?.type==="text"){const pe=gn(o).trim();if(pe.length>0){const je=[...g].reverse().find(U=>U.info.role==="user");if(je){const U=je.parts.map(ee=>gn(ee)).join("").trim();if(U.length>0&&U===pe)return ml.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const M=an(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?S(M.text||""):S("");const b=h.pendingAssistantParts.get(n),C=b?[...b.parts]:[],D=C.findIndex(pe=>pe.id===M.id);D!==-1?C[D]=M:C.push(M);const P=new Map(h.pendingAssistantParts);P.set(n,{sessionId:t,parts:C});const R=h.lastUsedProvider?.providerID||"",L=h.lastUsedProvider?.modelID||"",q=Date.now(),te=Re.getDirectory()??"/",le=gt.getState(),$=le.getSessionAgentSelection(t)??le.getCurrentAgent(t),z=typeof $=="string"&&$.trim().length>0?$.trim():void 0,E=h.pendingAssistantHeaderSessions.has(t);if(E){const pe=new Set(h.pendingAssistantHeaderSessions);pe.delete(t),y.pendingAssistantHeaderSessions=pe}const Y={info:f==="user"?{id:n,sessionID:t,role:"user",time:{created:q},agent:z||"default",model:{providerID:R,modelID:L},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:t,role:"assistant",time:{created:q},parentID:n,modelID:L,providerID:R,mode:z||"default",...E?{openchamberHeaderAnchor:!0}:{},path:{cwd:te,root:te},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:C},fe=[...g,Y],ne=new Map(h.messages);if(ne.set(t,fe),f==="assistant"){y.messageStreamStates=Xo(h.messageStreamStates,n);const pe=$s(y.streamingMessageIds??h.streamingMessageIds,t,n);pe!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=pe,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:ne,pendingAssistantParts:P,...y})}else{const M=g[A],b=M.parts.findIndex(L=>L.id===o.id),C=an(o,b!==-1?M.parts[b]:void 0);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`);const D={...M};b!==-1?D.parts=D.parts.map((L,q)=>q===b?C:L):D.parts=[...D.parts,C];const P=[...g];P[A]=D;const R=new Map(h.messages);if(R.set(t,P),D.info.role==="assistant"){y.messageStreamStates=Xo(h.messageStreamStates,n);const L=$s(y.streamingMessageIds??h.streamingMessageIds,t,n);L!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=L,window.__messageTracker?.(n,"streamingId_set"))}return C.type==="text"?S(C.text||""):S(""),v({messages:R,...y})}})},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){r()._addStreamingPartImmediate(t,n,o,a,i);return}Zo.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),ea||(ea=setTimeout(()=>{const c=[...Zo];Zo=[],ea=null;const d=r();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Mh))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[c,d]of i.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};s(i=>{const c=a(i);if(!c)return i;const d=i.messages.get(c)??[],u=d.findIndex(j=>j.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 w=!1;const g={...p};h||(g.time={...p.time??{},completed:f},w=!0),g.status!=="completed"&&(g.status="completed",w=!0),g.streaming&&(g.streaming=!1,w=!0);let y=!1;const x=m.parts.map(j=>{if(!j)return j;if(j.type==="tool"){const k=j.state;if(!k)return j;const F=k.status,A=F==="running"||F==="pending"||F==="started",M=!k.time||typeof k.time?.end!="number";if(A||M){const b={...k};return A&&(b.status="completed"),M&&(b.time={...k.time??{},end:f}),y=!0,{...j,state:b}}return j}if(j.type==="reasoning"){const k=j.time;return!k||typeof k.end!="number"?(y=!0,{...j,time:{...k??{},end:f}}):j}if(j.type==="text"){const k=j.time;return k&&typeof k.end!="number"?(y=!0,{...j,time:{...k,end:f}}):j}return j});if(!w&&!y)return i;window.__messageTracker?.(n,`force_complete:${o}`);const v={...m,info:g,parts:y?x:m.parts},S=[...d];S[u]=v;const N=new Map(i.messages);return N.set(c,S),{messages:N}})},markMessageStreamSettled:t=>{s(n=>{Dd(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 w=new Map(n.messages);w.set(u,h),a=w,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),xr([t])},updateMessageInfo:(t,n,o)=>{s(c=>{const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!Ln(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(t)??[]],f=m.findIndex(A=>A.info.id===n),p=c.pendingAssistantParts.get(n),h=(A=[],M=[])=>{if(!M.length)return A;const b=[...A];return M.forEach(C=>{const D=b.findIndex(P=>P.id===C.id);D===-1?b.push(C):b[D]=C}),b},w=A=>{if(!A)return A;const M=A.clientRole??A.role,b=M==="user"?!0:A.userMessageMarker;return{...A,clientRole:M,...b?{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 te=m[0]?.info,le=typeof te?.time?.created=="number"?te.time.created:null,$=typeof te?.id=="string"?te.id:null,z=o,E=typeof z?.time?.created=="number"?z.time.created:null,H=typeof z?.id=="string"?z.id:n;let Y=!1;if(E!==null&&le!==null&&(Y=E<le),!Y&&H&&$&&(Y=H.localeCompare($)<0),Y)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const A=w(o);if(A&&A.role==="user"){const q=p?.parts??[],te=c.pendingUserMessageMetaBySession.get(t),le={info:{...A,userMessageMarker:!0,clientRole:"user",...te?.mode?{mode:te.mode}:{},...te?.providerID?{providerID:te.providerID}:{},...te?.modelID?{modelID:te.modelID}:{}},parts:q.length>0?[...q]:[]},$=new Map(c.messages),z=[...m,le];z.sort((Y,fe)=>{const ne=Y.info?.time?.created||0,pe=fe.info?.time?.created||0;return ne-pe}),$.set(t,z);const E={messages:$,...te?{pendingUserMessageMetaBySession:dl(c.pendingUserMessageMetaBySession,t)}:{}},H=Lr(E.messageSessionIndex??c.messageSessionIndex,n,t);if(H!==(E.messageSessionIndex??c.messageSessionIndex)&&(E.messageSessionIndex=H),p){const Y=new Map(c.pendingAssistantParts);Y.delete(n),E.pendingAssistantParts=Y}return E}if(!A||A.role!=="assistant")return c;const M=p?.parts??[],b=c.pendingAssistantHeaderSessions.has(t),C={info:{...A,animationSettled:A?.animationSettled??!1,...b?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},D=new Map(c.messages),P=[...m,C];D.set(t,P);const R={messages:D,...b?{pendingAssistantHeaderSessions:(()=>{const q=new Set(c.pendingAssistantHeaderSessions);return q.delete(t),q})()}:{}},L=Lr(R.messageSessionIndex??c.messageSessionIndex,n,t);if(L!==(R.messageSessionIndex??c.messageSessionIndex)&&(R.messageSessionIndex=L),p){const q=new Map(c.pendingAssistantParts);q.delete(n),R.pendingAssistantParts=q}return R}const g=m[f],y=g.info;if(y.userMessageMarker===!0||y.clientRole==="user"||y.role==="user"){const A={...g.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:y.providerID||void 0,modelID:y.modelID||void 0},M=c.pendingUserMessageMetaBySession.get(t);M&&!A.mode&&M.mode&&(A.mode=M.mode);const b={...g,info:A},C=new Map(c.messages),D=[...m];if(D[f]=b,C.set(t,D),M){const P=new Map(c.pendingUserMessageMetaBySession);return P.delete(t),{messages:C,pendingUserMessageMetaBySession:P}}return{messages:C}}const v={...g.info,...o};o.role&&o.role!==g.info.role&&(v.role=g.info.role),v.clientRole=v.clientRole??g.info.clientRole??g.info.role,v.clientRole==="user"&&(v.userMessageMarker=!0);const S=p?.parts?h(g.parts,p.parts):g.parts,N={...g,info:v,parts:S},j=new Map(c.messages),k=[...m];k[f]=N,j.set(t,k);const F={messages:j};if(p){const A=new Map(c.pendingAssistantParts);A.delete(n),F.pendingAssistantParts=A}return F});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=$s(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}}),xr([n]);let c=!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),c=!0,{sessionMemoryState:m}}),c){const d=Rr.get(t);d&&(clearTimeout(d),Rr.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,...w}=f;return p.set(t,w),{sessionMemoryState:p}}),Rr.delete(t)},2e3);Rr.set(t,u)}},syncMessages:(t,n)=>{const o=pl(t),a=hl(n,o),i=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=i?a.filter(d=>{const u=d?.info?.id;return u?Ln(u,i):!0}):a;s(d=>{const u=new Map(d.messages),m=d.messages.get(t)||[],f=new Map(m.filter(j=>typeof j.info?.id=="string").map(j=>[j.info.id,j])),p=c.map(j=>{const k={...j.info,clientRole:j.info?.clientRole??j.info.role,userMessageMarker:j.info.role==="user"?!0:j.info?.userMessageMarker,animationSettled:j.info.role==="assistant"?j.info?.animationSettled??!0:j.info?.animationSettled},F=(Array.isArray(j.parts)?j.parts:[]).map(b=>{if(b?.type==="text"){const C=b.text??b.content??"";if(Yo(C))return{...b,synthetic:!0}}return b}),A=typeof k?.id=="string"?k.id:void 0,M=A?f.get(A):void 0;if(M&&M.info.role==="assistant"){const b=Array.isArray(M.parts)?M.parts:[],C=zr(b),D=zr(F);if(yo(M.info)&&C>D){const R=bo(b,F);return{...j,info:k,parts:R}}}return{...j,info:k,parts:F}}),h=ta(p),w=new Set(m.map(j=>j.info.id)),g=new Set(h.map(j=>j.info.id)),y=[];w.forEach(j=>{g.has(j)||y.push(j)}),u.set(t,h);const x={messages:u,isSyncing:!0};xr(y);const v=on(d.messageStreamStates,y);if(v!==d.messageStreamStates&&(x.messageStreamStates=v),y.length>0){const j=d.streamingMessageIds.get(t);j&&y.includes(j)&&(x.streamingMessageIds=$s(x.streamingMessageIds??d.streamingMessageIds,t,null))}if(y.length>0){const j=On(x.messageSessionIndex??d.messageSessionIndex,y);j!==(x.messageSessionIndex??d.messageSessionIndex)&&(x.messageSessionIndex=j)}if(y.length>0){const j=new Map(d.pendingAssistantParts);let k=!1;y.forEach(F=>{j.delete(F)&&(k=!0)}),k&&(x.pendingAssistantParts=j)}const S=x.messageSessionIndex??d.messageSessionIndex;let N=S;return h.forEach(j=>{const k=j?.info?.id;typeof k=="string"&&k.length>0&&(N=Lr(N,k,t))}),N!==S&&(x.messageSessionIndex=N),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+Dh;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},c=new Map(a.sessionMemoryState);return c.set(t,{...i,activeTurnAnchorId:n??void 0,activeTurnSpacerHeight:o}),{sessionMemoryState:c}})},getActiveTurnAnchor:t=>{const n=r().sessionMemoryState.get(t);return n?{anchorId:n.activeTurnAnchorId??null,spacerHeight:n.activeTurnSpacerHeight??0}:null},trimToViewportWindow:(t,n=Yt.VIEWPORT_MESSAGES,o)=>{const a=r(),i=a.messages.get(t);if(!i||i.length<=n)return;const c=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(c.isStreaming&&t===o)return;const d=c.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)),w=i.filter(g=>!h.has(g.info.id)).map(g=>g.info.id);s(g=>{const y=new Map(g.messages);y.set(t,f);const x=new Map(g.sessionMemoryState),v={...c,viewportAnchor:d-u,trimmedHeadMaxId:Th(p,c.trimmedHeadMaxId)};x.set(t,v);const S={messages:y,sessionMemoryState:x};xr(w);const N=on(g.messageStreamStates,w);if(N!==g.messageStreamStates&&(S.messageStreamStates=N),w.length>0){const F=g.streamingMessageIds.get(t);F&&w.includes(F)&&(S.streamingMessageIds=$s(S.streamingMessageIds??g.streamingMessageIds,t,null))}if(w.length>0){const F=On(S.messageSessionIndex??g.messageSessionIndex,w);F!==(S.messageSessionIndex??g.messageSessionIndex)&&(S.messageSessionIndex=F)}const j=S.messageSessionIndex??g.messageSessionIndex;let k=j;return f.forEach(F=>{const A=F?.info?.id;typeof A=="string"&&A.length>0&&(k=Lr(k,A,t))}),k!==j&&(S.messageSessionIndex=k),S})},evictLeastRecentlyUsed:t=>{const n=r();if(n.messages.size<=Yt.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 c=i[0][0];s(d=>{const m=(d.messages.get(c)||[]).map(N=>N.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(c),p.delete(c);const h={messages:f,sessionMemoryState:p},w=new Map(d.pendingAssistantParts);let g=!1;w.forEach((N,j)=>{N.sessionId===c&&(w.delete(j),g=!0)}),g&&(h.pendingAssistantParts=w);const y=new Map(d.sessionCompactionUntil);y.delete(c)&&(h.sessionCompactionUntil=y),xr(m);const x=on(d.messageStreamStates,m);x!==d.messageStreamStates&&(h.messageStreamStates=x);const v=On(h.messageSessionIndex??d.messageSessionIndex,m);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const S=$s(d.streamingMessageIds,c,null);if(S!==d.streamingMessageIds&&(h.streamingMessageIds=S),d.abortControllers.has(c)){const N=new Map(d.abortControllers);N.delete(c),h.abortControllers=N}return h})},loadMoreMessages:async(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 c=await sa(t,()=>Re.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=c.findIndex(m=>m.info.id===d.info.id);if(u>0){const m=Math.min(Yt.VIEWPORT_MESSAGES,u),f=c.slice(u-m,u);s(p=>{const h=[...f,...a],w=ta(h),g=new Map(p.messages);g.set(t,w);const y=Math.max(0,w.length-a.length),x=new Map(p.sessionMemoryState);return x.set(t,{...i,viewportAnchor:i.viewportAnchor+y,hasMoreAbove:u-m>0,totalAvailableMessages:c.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:vs(()=>ls()),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"})),Rh=s=>typeof s=="object"&&s!==null,Lh=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},Oh=async(s,r)=>{try{const t=Je.getState(),n=t.getWorktreeMetadata(s);if(n?.path)return Re.withDirectory(n.path,r);const o=t.sessions.find(i=>i.id===s),a=typeof o?.directory=="string"&&o.directory.length>0?o.directory:void 0;if(a)return Re.withDirectory(a,r)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return r()},wo=Tt()(_t(ws((s,r)=>({permissions:new Map,addPermission:(t,n)=>{const o=t.sessionID;if(!o)return;const a=t.type?.toLowerCase?.()??null;let i=n?.currentAgentContext?.get(o);if(i||(i=n?.sessionAgentSelections?.get(o)??void 0),!i&&typeof window<"u"){const m=window.__zustand_config_store__;m?.getState&&(i=m.getState().currentAgentName??void 0)}const c=so(i),d=n?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&kh(a)){r().respondToPermission(o,t.id,"once").catch(()=>{});return}s(m=>{const f=m.permissions.get(o)||[],p=new Map(m.permissions);return p.set(o,[...f,t]),{permissions:p}})},respondToPermission:async(t,n,o)=>{await Oh(t,()=>Re.respondToPermission(t,n,o)),o==="reject"&&await at.getState().abortCurrentOperation(t),s(a=>{const c=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,c),{permissions:d}})}}),{name:"permission-store",storage:vs(()=>ls()),partialize:s=>({permissions:Array.from(s.permissions.entries())}),merge:(s,r)=>{if(!Rh(s))return r;const t=Lh(s.permissions);return{...r,permissions:new Map(t)}}}),{name:"permission-store"})),mi=s=>s.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
|
|
4
|
+
`).replace(/\n\s*\n+/g,`
|
|
5
|
+
`),xn=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},gl=(s,r,t)=>{if(!r)return null;const n=t(r)?.path;if(typeof n=="string"&&n.trim().length>0)return xn(n);const o=s.find(a=>a.id===r);return o?xn(o.directory??null):null},he=Tt()(_t((s,r)=>({sessions:[],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:[],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)=>gt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>gt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>gt.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>Je.getState().loadSessions(),openNewSessionDraft:t=>{s({newSessionDraft:{open:!0,directoryOverride:t?.directoryOverride??null,parentID:t?.parentID??null,title:t?.title},currentSessionId:null,error:null});try{const n=ut.getState(),o=n.getVisibleAgents();let a;if(n.settingsDefaultAgent){const i=o.find(c=>c.name===n.settingsDefaultAgent);i&&(a=i.name)}a||(a=o.find(i=>i.name==="build")?.name||o[0]?.name),a&&n.setAgent(a)}catch{}},closeNewSessionDraft:()=>{const t=Je.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 Je.getState().createSession(t,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=at.getState(),{messages:o,lastUsedProvider:a}=n;let i,c;if(o.forEach((x,v)=>{const S=x.find(N=>N.info?.id===t);S&&!i&&(i=S,c=v)}),!i||i.info.role!=="assistant")return;const d=mi(i.parts);if(!d.trim())return;const u=Je.getState(),m=gl(u.sessions,c??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:w}=ut.getState(),g=p||a?.providerID,y=h||a?.modelID;!g||!y||await Re.sendMessage({id:f.id,providerID:g,modelID:y,text:d,prefaceText:Md,agent:w??void 0})},deleteSession:(t,n)=>Je.getState().deleteSession(t,n),deleteSessions:(t,n)=>Je.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>Je.getState().updateSessionTitle(t,n),shareSession:t=>Je.getState().shareSession(t),unshareSession:t=>Je.getState().unshareSession(t),setCurrentSession:async t=>{t&&r().closeNewSessionDraft();const n=Je.getState().currentSessionId,o=gl(Je.getState().sessions,t,Je.getState().getWorktreeMetadata),a=Re.getDirectory()??wt.getState().currentDirectory??null,i=o??a;try{Re.setDirectory(i??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}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,Yt.VIEWPORT_MESSAGES)}Je.getState().setCurrentSession(t),t&&(r().messages.get(t)||await r().loadMessages(t),r().trimToViewportWindow(t,$p)),r().evictLeastRecentlyUsed()},loadMessages:t=>at.getState().loadMessages(t),sendMessage:async(t,n,o,a,i,c,d)=>{const u=r().newSessionDraft,m=typeof a=="string"&&a.trim().length>0?a.trim():void 0,f=x=>{s(v=>{const S=new Map(v.sessionActivityPhase??new Map);return S.set(x,"busy"),{sessionActivityPhase:S}})},p=x=>{s(v=>{const S=new Map(v.sessionActivityPhase??new Map);return S.set(x,"idle"),{sessionActivityPhase:S}})};if(u?.open){const x=await Je.getState().createSession(u.title,u.directoryOverride??null,u.parentID??null);if(!x?.id)throw new Error("Failed to create session");const v=ut.getState(),S=v.currentAgentName,N=m??S,j=v.currentProviderId,k=v.currentModelId;if(j&&k)try{gt.getState().saveSessionModelSelection(x.id,j,k)}catch{}if(N){try{gt.getState().saveSessionAgentSelection(x.id,N)}catch{}if(j&&k)try{gt.getState().saveAgentModelForSession(x.id,N,j,k)}catch{}}try{Je.getState().initializeNewOpenChamberSession(x.id,v.agents)}catch{}r().closeNewSessionDraft(),f(x.id);try{return await at.getState().sendMessage(t,n,o,N,x.id,i,c,d)}catch(F){throw p(x.id),F}}const h=Je.getState().currentSessionId,w=h?gt.getState().getSessionAgentSelection(h):null,g=ut.getState().currentAgentName,y=m||w||g||void 0;if(h&&y)try{gt.getState().saveSessionAgentSelection(h,y)}catch{}h&&f(h);try{return await at.getState().sendMessage(t,n,o,y,h||void 0,i,c,d)}catch(x){throw h&&p(h),x}},abortCurrentOperation:()=>{const t=Je.getState().currentSessionId;return at.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=Je.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&&at.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=Je.getState().currentSessionId||t;return at.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>at.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>at.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>at.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>at.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:gt.getState().currentAgentContext,sessionAgentSelections:gt.getState().sessionAgentSelections,getSessionAgentEditMode:gt.getState().getSessionAgentEditMode};return wo.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>wo.getState().respondToPermission(t,n,o),clearError:()=>Je.getState().clearError(),getSessionsByDirectory:t=>Je.getState().getSessionsByDirectory(t),getLastMessageModel:t=>at.getState().getLastMessageModel(t),getCurrentAgent:t=>gt.getState().getCurrentAgent(t),syncMessages:(t,n)=>at.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>Je.getState().applySessionMetadata(t,n),addAttachedFile:t=>Hs.getState().addAttachedFile(t),addServerFile:(t,n,o)=>Hs.getState().addServerFile(t,n,o),removeAttachedFile:t=>Hs.getState().removeAttachedFile(t),clearAttachedFiles:()=>Hs.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>at.getState().updateViewportAnchor(t,n),updateActiveTurnAnchor:(t,n,o)=>at.getState().updateActiveTurnAnchor(t,n,o),getActiveTurnAnchor:t=>at.getState().getActiveTurnAnchor(t),trimToViewportWindow:(t,n)=>{const o=Je.getState().currentSessionId;return at.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=Je.getState().currentSessionId;return at.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>at.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>gt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>gt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>gt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>gt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>gt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>gt.getState().getAgentModelForSession(t,n),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=at.getState().messages;return gt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>Je.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>Je.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>Je.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>Je.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>Je.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>Je.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{if(r().newSessionDraft?.open)return null;const o=Je.getState().currentSessionId;if(!o)return null;const a=at.getState().messages;return gt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=at.getState().messages;return gt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=at.getState().messages;return gt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=at.getState().messages.get(t)||[],o=Je.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=at.getState().messages;return gt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>Je.getState().updateSession(t),revertToMessage:async(t,n)=>{const a=(at.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(`
|
|
6
|
+
`).trim());const c=await Re.revertSession(t,n);Je.getState().updateSession(c);const d=at.getState().messages.get(t)||[],u=c.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);at.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 c=i?.revert?.messageID;let d;if(c){const p=o.findIndex(h=>h.info.id===c);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,d.info.id);const{toast:f}=await Kt(async()=>{const{toast:p}=await import("./vendor-.bun-COPXsM7o.js").then(h=>h.c9);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 c=(r().messages.get(t)||[]).filter(m=>m.info.role==="user"),d=c.findIndex(m=>m.info.id===a),u=c[d-1];if(u){const m=u.parts.find(h=>h.type==="text"),f=typeof m=="object"&&m&&"text"in m?String(m.text).slice(0,50)+(String(m.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,u.info.id);const{toast:p}=await Kt(async()=>{const{toast:h}=await import("./vendor-.bun-COPXsM7o.js").then(w=>w.c9);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await Re.unrevertSession(t);await Je.getState().updateSession(m),await r().loadMessages(t);const{toast:f}=await Kt(async()=>{const{toast:p}=await import("./vendor-.bun-COPXsM7o.js").then(h=>h.c9);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 Re.forkSession(t,n);if(!i||!i.id){const{toast:f}=await Kt(async()=>{const{toast:p}=await import("./vendor-.bun-COPXsM7o.js").then(h=>h.c9);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 Kt(async()=>{const{toast:p}=await import("./vendor-.bun-COPXsM7o.js").then(h=>h.c9);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 Kt(async()=>{const{toast:f}=await import("./vendor-.bun-COPXsM7o.js").then(p=>p.c9);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(i){console.error("Failed to fork session:",i);const{toast:c}=await Kt(async()=>{const{toast:d}=await import("./vendor-.bun-COPXsM7o.js").then(u=>u.c9);return{toast:d}},__vite__mapDeps([0,1]));c.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"}));Je.subscribe((s,r)=>{if(s.sessions===r.sessions&&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)return;const t=he.getState().newSessionDraft?.open;he.setState({sessions:s.sessions,currentSessionId:t?null:s.currentSessionId,lastLoadedDirectory:s.lastLoadedDirectory,isLoading:s.isLoading,error:s.error,webUICreatedSessions:s.webUICreatedSessions,worktreeMetadata:s.worktreeMetadata,availableWorktrees:s.availableWorktrees})});at.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 c=i.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=c.time&&typeof c.time.created=="number"?c.time.created:null;t.set(o,{title:u,createdAt:m});break}}}}}),he.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})});Hs.subscribe((s,r)=>{s.attachedFiles!==r.attachedFiles&&he.setState({attachedFiles:s.attachedFiles})});gt.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||he.setState({sessionModelSelections:s.sessionModelSelections,sessionAgentSelections:s.sessionAgentSelections,sessionAgentModelSelections:s.sessionAgentModelSelections,currentAgentContext:s.currentAgentContext,sessionContextUsage:s.sessionContextUsage,sessionAgentEditModes:s.sessionAgentEditModes})});wo.subscribe((s,r)=>{s.permissions!==r.permissions&&he.setState({permissions:s.permissions})});wt.subscribe((s,r)=>{const t=xn(s.currentDirectory??null),n=xn(r.currentDirectory??null);if(t===n)return;const o=he.getState().newSessionDraft;if(!o?.open)return;const a=xn(o.directoryOverride);a&&a!==n||he.setState(i=>({newSessionDraft:{...i.newSessionDraft,directoryOverride:t,parentID:null}}))});const $h=he.getState().newSessionDraft?.open;he.setState({sessions:Je.getState().sessions,currentSessionId:$h?null:Je.getState().currentSessionId,lastLoadedDirectory:Je.getState().lastLoadedDirectory,isLoading:Je.getState().isLoading,error:Je.getState().error,webUICreatedSessions:Je.getState().webUICreatedSessions,worktreeMetadata:Je.getState().worktreeMetadata,availableWorktrees:Je.getState().availableWorktrees,messages:at.getState().messages,sessionMemoryState:at.getState().sessionMemoryState,messageStreamStates:at.getState().messageStreamStates,sessionCompactionUntil:at.getState().sessionCompactionUntil,sessionAbortFlags:at.getState().sessionAbortFlags,streamingMessageIds:at.getState().streamingMessageIds,abortControllers:at.getState().abortControllers,lastUsedProvider:at.getState().lastUsedProvider,isSyncing:at.getState().isSyncing,permissions:wo.getState().permissions,attachedFiles:Hs.getState().attachedFiles,sessionModelSelections:gt.getState().sessionModelSelections,sessionAgentSelections:gt.getState().sessionAgentSelections,sessionAgentModelSelections:gt.getState().sessionAgentModelSelections,currentAgentContext:gt.getState().currentAgentContext,sessionContextUsage:gt.getState().sessionContextUsage,sessionAgentEditModes:gt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=he);const fi=({containerRef:s,minThumbSize:r=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=l.useState(!1),[c,d]=l.useState({length:0,offset:0}),[u,m]=l.useState({length:0,offset:0}),f=l.useRef(null),p=l.useRef(null),h=l.useRef(!1),w=l.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),g=l.useRef(null),y=l.useCallback(()=>{const M=s.current;if(!M)return;const{scrollHeight:b,clientHeight:C,scrollTop:D,scrollWidth:P,clientWidth:R,scrollLeft:L}=M,q=8;if(b>C){const te=Math.max(C-q*2,0),le=C/b*te,$=Math.max(r,Math.min(te,le)),z=Math.max(te-$,0),E=Math.max(b-C,1),H=D/E*z;d({length:$,offset:H})}else d({length:0,offset:0});if(!o&&P>R){const te=Math.max(R-q*2,0),le=R/P*te,$=Math.max(r,Math.min(te,le)),z=Math.max(te-$,0),E=Math.max(P-R,1),H=L/E*z;m({length:$,offset:H})}else m({length:0,offset:0})},[s,r,o]),x=l.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>i(!1),t)},[t]),v=l.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{y(),i(!0),x()})},[x,y]);l.useEffect(()=>{const M=s.current;if(!M)return;y(),i(!0),x(),M.addEventListener("scroll",v,{passive:!0});const b=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null;b?.observe(M);const C=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return C?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",v),b?.disconnect(),C?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[s,v,x,y]);const S=(M,b)=>{const C=s.current;C&&(h.current=!0,w.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:C.scrollTop,scrollLeft:C.scrollLeft},g.current=b,i(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},N=M=>{if(!h.current)return;const b=s.current;if(!b)return;const C=g.current;if(C==="vertical"){const{pointerY:D,scrollTop:P}=w.current,R=M.clientY-D,L=b.clientHeight,q=Math.max(L-c.length,1),te=Math.max(b.scrollHeight-b.clientHeight,1),le=R/q*te;b.scrollTop=P+le}else if(C==="horizontal"){const{pointerX:D,scrollLeft:P}=w.current,R=M.clientX-D,L=b.clientWidth,q=Math.max(L-u.length,1),te=Math.max(b.scrollWidth-b.clientWidth,1),le=R/q*te;b.scrollLeft=P+le}},j=M=>{h.current&&(h.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),x())},k=c.length>0,F=u.length>0;if(!k&&!F)return null;const A=8;return e.jsxs("div",{className:O("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[k&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${A+c.offset}px`,right:`${A/2}px`},onPointerDown:M=>S(M,"vertical"),onPointerMove:N,onPointerUp:j,onPointerCancel:j}),F&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${A+u.offset}px`,bottom:`${A/2}px`},onPointerDown:M=>S(M,"horizontal"),onPointerMove:N,onPointerUp:j,onPointerCancel:j})]})},tt=l.forwardRef(({className:s,outerClassName:r,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const h=l.useRef(null);return l.useImperativeHandle(p,()=>h.current,[]),e.jsxs("div",{className:O("relative flex flex-col min-h-0 w-full overflow-hidden",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(i,{ref:h,className:O("overlay-scrollbar-target overlay-scrollbar-container",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(fi,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});tt.displayName="ScrollableOverlay";const xl="mobile-overlay-root",_h=()=>{if(typeof document>"u")return null;let s=document.getElementById(xl);return s||(s=document.createElement("div"),s.id=xl,document.body.appendChild(s)),s},ps=({open:s,title:r,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:i,renderHeader:c})=>{const d=l.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=_h()),l.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:O("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(Wt,{className:"h-4 w-4"})});return c?c(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(tt,{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 tm.createPortal(m,d.current)},Oa=({totalTokens:s,percentage:r,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[i,c]=l.useState(!1),d=l.useRef(void 0),u=y=>y>=1e6?`${(y/1e6).toFixed(1)}M`:y>=1e3?`${(y/1e3).toFixed(1)}K`:y.toFixed(1).replace(/\.0$/,""),m=y=>y>=90?"text-status-error":y>=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=l.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{c(!0)},500)},[]),w=l.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);l.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=e.jsxs("div",{className:O("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?w:void 0,children:[e.jsx(sm,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:O(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[g,e.jsx(ps,{open:i,onClose:()=>c(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(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:O("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:g}),e.jsx(Ye,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(y=>e.jsx("p",{className:"typography-micro leading-tight",children:y},y))})})]})},cn={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Ad=(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 ra(){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,c=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,w="desktop";c?(f=!1,p=!1,h=!0,w="desktop"):f?w="mobile":p?w="tablet":(h=!0,w="desktop"),Ad(c,w,d);let g="xs";for(const[y,x]of Object.entries(cn))s>=x&&(g=y);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:w,screenWidth:s,breakpoint:g,hasTouchInput:d}}function Ct(){const[s,r]=l.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:ra());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{r(ra())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(ra())},a=[],i=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return i(t),i(n),()=>{a.forEach(c=>c())}},[]),l.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,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=i||c||d>0;Ad(t,s.deviceType,u)},[s.deviceType,s.hasTouchInput]),s}const $n=5e3,Bh=1e4,zh=5e3,Hh=1e4,Uh=25,Wh=4,yl=15e3,_s=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),Vh=(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},Gh=(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!!Vh(s.diffStats,r.diffStats)},qh=(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])),c=new Set([...a.keys(),...i.keys()]);for(const f of c){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},It=Tt()(_t((s,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:$n,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=r();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,_s()),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 c=i.get(t);c||(c=_s()),a||s({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const f=new Map(i);return f.set(t,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),s({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(t);if(Gh(c.status,m)){d=!0;const f=new Map(r().directories),p=f.get(t)??_s(),h=qh(p.status,m),w=new Set((p.status?.files??[]).map(v=>v.path)),g=new Set((m.files??[]).map(v=>v.path)),y=new Map(p.diffCache);for(const v of w)g.has(v)||y.delete(v);for(const v of h)y.delete(v);const x=h.size>0;f.set(t,{...p,isGitRepo:!0,status:m,diffCache:y,lastStatusFetch:Date.now(),lastStatusChange:x?Date.now():p.lastStatusChange}),s({directories:f})}else{const f=new Map(r().directories),p=f.get(t)??_s();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)??_s();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),c=o??i?.logMaxCount??25;s({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:c}),u=new Map(r().directories),m=u.get(t)??_s();u.set(t,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:c}),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)??_s();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=_s();const f=new Map(a);f.set(t,i),s({directories:f})}const{force:c=!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);(c||m>Hh||!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)??_s(),c=new Map(i.diffCache);c.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...i,diffCache:c}),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 c=o.status.files.filter(v=>!o.diffCache.has(v.path)).slice(0,Uh);if(c.length===0)return;let d=0;const u=[],m=()=>{const v=d;return d+=1,v<c.length?c[v]:null},f=async v=>{const S=n.getGitFileDiff(t,{path:v}),N=new Promise((k,F)=>{setTimeout(()=>F(new Error(`Timed out after ${yl}ms`)),yl)}),j=await Promise.race([S,N]);return{path:v,diff:{original:j.original??"",modified:j.modified??""}}},p=async()=>{for(;;){const v=m();if(!v)return;try{u.push(await f(v.path))}catch{}}},h=Math.min(Wh,c.length);await Promise.allSettled(Array.from({length:h},()=>p()));const w=new Map(r().directories),g=w.get(t);if(!g)return;const y=new Map(g.diffCache),x=Date.now();u.forEach(v=>{y.set(v.path,{...v.diff,fetchedAt:x})}),w.set(t,{...g,diffCache:y}),s({directories:w})},setLogMaxCount:(t,n)=>{const o=new Map(r().directories),a=o.get(t)??_s();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:c}=r();if(!c){s({pollIntervalId:o()});return}if(await r().fetchStatus(c,t,{silent:!0}))await r().fetchLog(c,t),r().fetchAllDiffs(c,t),s({currentPollInterval:$n});else{const m=Math.min(a+zh,Bh);s({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&s({pollIntervalId:o()})},a)};s({pollIntervalId:o(),currentPollInterval:$n})},stopPolling:()=>{const{pollIntervalId:t}=r();t&&(clearTimeout(t),s({pollIntervalId:null,currentPollInterval:$n}))},refresh:async(t,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,t,n)}}),{name:"git-store"})),Ed=s=>It(r=>s?r.directories.get(s)?.status??null:null),Kh=s=>It(r=>s?r.directories.get(s)?.branches??null:null),Yh=s=>It(r=>s?r.directories.get(s)?.log??null:null),Xh=s=>It(r=>s?r.directories.get(s)?.identity??null:null),Id=s=>It(r=>s?r.directories.get(s)?.isGitRepo??null:null),Qh=s=>It(r=>s?r.directories.get(s)?.status?.files?.length??0:0);function Jt({...s}){return e.jsx(rm,{"data-slot":"dropdown-menu",...s})}function Zt({...s}){return e.jsx(nm,{"data-slot":"dropdown-menu-trigger",...s})}function es({className:s,sideOffset:r=4,...t}){return e.jsx(om,{children:e.jsx(am,{"data-slot":"dropdown-menu-content",sideOffset:r,className:O("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 kt({className:s,inset:r,variant:t="default",...n}){return e.jsx(dm,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":t,className:O("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 Jh({...s}){return e.jsx(im,{"data-slot":"dropdown-menu-radio-group",...s})}function Zh({className:s,children:r,...t}){return e.jsxs(lm,{"data-slot":"dropdown-menu-radio-item",className:O("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(cm,{children:e.jsx(Dt,{className:"size-3"})})}),r]})}function Wr({className:s,inset:r,...t}){return e.jsx(mm,{"data-slot":"dropdown-menu-label","data-inset":r,className:O("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",s),...t})}function Us({className:s,...r}){return e.jsx(um,{"data-slot":"dropdown-menu-separator",className:O("bg-border -mx-1 my-0.5 h-px",s),...r})}const eg={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 pi(s){return eg[s]||{displayName:s.charAt(0).toUpperCase()+s.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function tg(s,r,t){const n=pi(s);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=Ir(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 Ir(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 sg=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function Td(s){const r=s.split(".").pop()?.toLowerCase();return sg.includes(r||"")}function rg(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 ng(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 c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${i}: ${c}`}).join(`
|
|
7
|
+
`):String(s)}const hi=l.createContext(null),Tr=()=>{const s=l.useContext(hi);if(!s)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return s},Fd=s=>{const r=Tr();return s(r)},og=()=>Fd(s=>s.runtime.isDesktop),Pd=()=>Fd(s=>s.runtime.isVSCode),ag=fm("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 ve({className:s,variant:r,size:t,asChild:n=!1,...o}){const a=n?Vc:"button";return e.jsx(a,{"data-slot":"button",className:O(ag({variant:r,size:t,className:s})),...o})}const ig=({mode:s,onModeChange:r,className:t})=>{const n=l.useCallback(o=>{o.stopPropagation(),r(s==="side-by-side"?"unified":"side-by-side")},[s,r]);return e.jsx(ve,{size:"sm",variant:"ghost",className:O("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(pm,{className:"h-3 w-3"}):e.jsx(hm,{className:"h-3 w-3"})})},gi=Ne.createContext(void 0);function Fr(){const s=Ne.useContext(gi);if(!s)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return s}function Ro(){return Ne.useContext(gi)}const lg="Flexoki",cg="dark",dg={"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"},ug=[{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"}}],mg={name:lg,type:cg,colors:dg,tokenColors:ug},fg="Flexoki",pg="light",hg={"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"},gg=[{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"}}],xg={name:fg,type:pg,colors:hg,tokenColors:gg},xi="flexoki-dark",yi="flexoki-light",yg=mg,bg=xg;function Rd(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 Ld(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 bi=Ld(yg,xi,"dark"),wi=Ld(bg,yi,"light");Rd(bi,xi);Rd(wi,yi);const Yr={dark:xi,light:yi},bl=[wi,bi];let wl=!1;function Od(){wl||(Li(Yr.dark,async()=>bi),Li(Yr.light,async()=>wi),wl=!0)}const wg=`
|
|
8
|
+
:host {
|
|
9
|
+
font-family: var(--font-mono);
|
|
10
|
+
font-size: var(--text-code);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
:host, pre, [data-diffs], [data-code] {
|
|
14
|
+
transform: translateZ(0);
|
|
15
|
+
-webkit-transform: translateZ(0);
|
|
16
|
+
-webkit-backface-visibility: hidden;
|
|
17
|
+
backface-visibility: hidden;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
pre, [data-code] {
|
|
21
|
+
font-family: var(--font-mono);
|
|
22
|
+
font-size: var(--text-code);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
[data-code] {
|
|
26
|
+
-webkit-overflow-scrolling: touch;
|
|
27
|
+
}
|
|
28
|
+
/* Reduce hunk separator height */
|
|
29
|
+
[data-separator-content] {
|
|
30
|
+
height: 24px !important;
|
|
31
|
+
}
|
|
32
|
+
[data-expand-button] {
|
|
33
|
+
height: 24px !important;
|
|
34
|
+
width: 24px !important;
|
|
35
|
+
}
|
|
36
|
+
[data-separator-multi-button] {
|
|
37
|
+
row-gap: 0 !important;
|
|
38
|
+
}
|
|
39
|
+
[data-expand-up] {
|
|
40
|
+
height: 12px !important;
|
|
41
|
+
min-height: 12px !important;
|
|
42
|
+
max-height: 12px !important;
|
|
43
|
+
margin: 0 !important;
|
|
44
|
+
margin-top: 3px !important;
|
|
45
|
+
padding: 0 !important;
|
|
46
|
+
border-radius: 4px 4px 0 0 !important;
|
|
47
|
+
}
|
|
48
|
+
[data-expand-down] {
|
|
49
|
+
height: 12px !important;
|
|
50
|
+
min-height: 12px !important;
|
|
51
|
+
max-height: 12px !important;
|
|
52
|
+
margin: 0 !important;
|
|
53
|
+
margin-top: -3px !important;
|
|
54
|
+
padding: 0 !important;
|
|
55
|
+
border-radius: 0 0 4px 4px !important;
|
|
56
|
+
}
|
|
57
|
+
`;function vg(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 vl=({original:s,modified:r,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const c=Ro()?.currentTheme?.metadata?.variant==="dark";Od();const d=Ne.useRef(null),u=Ne.useMemo(()=>{const f=vg(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}`},w=Ca(p,h);return d.current={key:f,fileDiff:w},w},[n,s,r,t]),m=Ne.useMemo(()=>({theme:{dark:Yr.dark,light:Yr.light},themeType:c?"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:wg}),[c,o,a]);return typeof window>"u"?null:e.jsx(tt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(gm,{fileDiff:u,options:m})})},jg=1100,Sg=s=>{const{index:r,working_dir:t}=s;return r==="A"||t==="A"||r==="?"||t==="?"},jl=(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]})},kg=l.memo(({changedFiles:s,selectedFile:r,selectedFileEntry:t,onSelectFile:n,isMobile:o})=>{const a=l.useCallback(i=>{if(!o)return i;const c=i.lastIndexOf("/");return c>=0?i.slice(c+1):i},[o]);return s.length===0?null:e.jsxs(Jt,{children:[e.jsx(Zt,{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)}),jl(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Nt,{className:"size-4 opacity-50"})]})}),e.jsx(es,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(Jh,{value:r??"",onValueChange:n,children:s.map(i=>e.jsx(Zh,{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:jl(i.insertions,i.deletions)})]})},i.path))})})]})}),Ng=l.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",c=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:i,children:[o&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${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:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Cg=l.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=l.useMemo(()=>Ir(s)||"text",[s]);return Td(s)?e.jsx(Ng,{filePath:s,diff:r,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(vl,{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(vl,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})})}),Mg=l.memo(({directory:s,filePath:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=It(l.useCallback(c=>c.directories.get(s)?.diffCache.get(r)??null,[s,r])),i=l.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return i?e.jsx(Cg,{filePath:r,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),Dg=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=he(),{currentDirectory:n}=wt(),o=s?t.get(s)??void 0:void 0,i=r.find(c=>c.id===s)?.directory;return o?.path??i??n??void 0},Ag=()=>{const{git:s}=Tr(),r=Dg(),{screenWidth:t,isMobile:n}=Ct(),o=Id(r??null),a=Ed(r??null),i=It($=>$.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=It(),[m,f]=l.useState(null),[p,h]=l.useState(0),[w,g]=l.useState(null),y=l.useRef(null),x=Fe($=>$.pendingDiffFile),v=Fe($=>$.setPendingDiffFile),S=Fe($=>$.diffLayoutPreference),N=Fe($=>$.diffFileLayout),j=Fe($=>$.setDiffFileLayout),k=Fe($=>$.diffWrapLines),F=Fe($=>$.setDiffWrapLines),A=n||k,M=l.useMemo(()=>{if(!a?.files)return[];const $=a.diffStats??{};return a.files.map(z=>({...z,insertions:$[z.path]?.insertions??0,deletions:$[z.path]?.deletions??0,isNew:Sg(z)})).sort((z,E)=>z.path.localeCompare(E.path))},[a]),b=l.useMemo(()=>m?M.find($=>$.path===m)??null:null,[M,m]),C=l.useMemo(()=>{if(!b)return null;const $=N[b.path];if($)return $;if(S==="inline")return"inline";if(S==="side-by-side")return"side-by-side";const z=t<jg;return b.isNew||z?"inline":"side-by-side"},[b,N,S,t]);l.useEffect(()=>{r&&(c(r),It.getState().directories.get(r)?.status||d(r,s))},[r,c,d,s]),l.useEffect(()=>{x&&(f(x),v(null))},[x,v]),l.useEffect(()=>{!m&&!x&&M.length>0&&f(M[0].path)},[M,m,x]),l.useEffect(()=>{m&&M.length>0&&(M.some(z=>z.path===m)||f(M[0]?.path??null))},[M,m]);const D=l.useCallback($=>{f($)},[]),P=(C??"side-by-side")==="side-by-side",R=It(l.useCallback($=>!r||!m?null:$.directories.get(r)?.diffCache.get(m)??null,[r,m])),L=!!R,q=!!m&&!L;l.useEffect(()=>{if(g(null),!r||!m){y.current=null;return}if(R){y.current=null;return}const $=`${r}::${m}::${p}`;if(y.current===$)return;y.current=$;let z=!1;return(async()=>{try{const E=s.getGitFileDiff(r,{path:m}),H=15e3,Y=new Promise((ne,pe)=>{setTimeout(()=>pe(new Error(`Timed out after ${H}ms`)),H)}),fe=await Promise.race([E,Y]);if(z)return;u(r,m,{original:fe.original??"",modified:fe.modified??""})}catch(E){if(z)return;const H=E instanceof Error?E.message:String(E);g(H)}})(),()=>{z=!0,y.current===$&&(y.current=null)}},[r,m,R,s,u,p]);const te=()=>!r||M.length===0?null:M.map($=>e.jsx(Mg,{directory:r,filePath:$.path,isVisible:$.path===m,renderSideBySide:P,wrapLines:A},$.path)),le=()=>r?i&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Qt,{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."}):M.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:[te(),q&&!L&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:w?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:w}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{g(null),h($=>$+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Qt,{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(Ja,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:i&&!a?"Loading changes…":`${M.length} ${M.length===1?"file":"files"} changed`})]}),e.jsx(kg,{changedFiles:M,selectedFile:m,selectedFileEntry:b,onSelectFile:D,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),b&&e.jsx("button",{type:"button",onClick:()=>F(!k),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${A?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:A?"Disable line wrap":"Enable line wrap",children:e.jsx(xm,{className:"size-4"})}),b&&C&&e.jsx(ig,{mode:C==="side-by-side"?"side-by-side":"unified",onModeChange:$=>{if(!b)return;const z=$==="side-by-side"?"side-by-side":"inline";j(b.path,z)}})]}),le()]})},Eg=()=>{const{git:s}=Tr(),{currentSessionId:r,sessions:t,worktreeMetadata:n}=he(),{currentDirectory:o}=wt(),a=r?n.get(r)??void 0:void 0,c=t.find(p=>p.id===r)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:u,fetchStatus:m}=It(),f=Qh(d??null);return l.useEffect(()=>{d&&(u(d),It.getState().directories.get(d)?.status||m(d,s))},[d,u,m,s]),f},Ig=()=>{const s=Fe(d=>d.setSessionSwitcherOpen),r=Fe(d=>d.toggleSidebar),{isMobile:t}=Ct(),[n,o]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const i=l.useCallback(()=>{t?s(!0):r()},[t,s,r]),c="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:c,children:e.jsx(Do,{className:"h-5 w-5"})})})},Sl=()=>{const s=Fe(E=>E.setSessionSwitcherOpen),r=Fe(E=>E.toggleSidebar),t=Fe(E=>E.setSettingsDialogOpen),n=Fe(E=>E.toggleCommandPalette),o=Fe(E=>E.toggleHelpDialog),a=Fe(E=>E.isSidebarOpen),i=Fe(E=>E.sidebarWidth),c=Fe(E=>E.activeMainTab),d=Fe(E=>E.setActiveMainTab),{getCurrentModel:u}=ut(),m=he(E=>E.getContextUsage),{isMobile:f}=Ct(),p=Eg(),h=Fo(E=>E.available),w=l.useRef(null),[g,y]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Ne.useEffect(()=>{if(typeof window>"u")return;const E=typeof window.opencodeDesktop<"u";y(E)},[]);const v=u(),S=v&&typeof v.limit=="object"&&v.limit!==null?v.limit:null,N=S&&typeof S.context=="number"?S.context:0,j=S&&typeof S.output=="number"?S.output:0,k=m(N,j),F=Fe(E=>E.isSessionSwitcherOpen),A=l.useCallback(()=>{if(typeof document>"u")return;const E=document.activeElement;if(!E)return;const H=E.tagName;(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||E.isContentEditable)&&E.blur()},[]),M=l.useCallback(()=>{if(f){A(),s(!F);return}r()},[A,f,F,s,r]),b=l.useCallback(()=>{f&&A(),s(!1),t(!0)},[A,f,s,t]),C="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",D=l.useMemo(()=>g&&x?a?"pl-0":"pl-[8.0rem]":"pl-3",[g,x,a]),P=l.useCallback(()=>{if(typeof document>"u")return;const E=w.current?.getBoundingClientRect().height;E&&document.documentElement.style.setProperty("--oc-header-height",`${E}px`)},[]);Ne.useEffect(()=>{if(typeof window>"u")return;P();const E=w.current;if(!E||typeof ResizeObserver>"u")return()=>{};const H=new ResizeObserver(()=>{P()});return H.observe(E),window.addEventListener("resize",P),window.addEventListener("orientationchange",P),()=>{H.disconnect(),window.removeEventListener("resize",P),window.removeEventListener("orientationchange",P)}},[P]),Ne.useEffect(()=>{P()},[P,f]);const R=l.useCallback(async E=>{if(!E.target.closest("button, a, input, select, textarea")&&E.button===0&&g)try{const{getCurrentWindow:H}=await Kt(async()=>{const{getCurrentWindow:fe}=await import("./vendor-.bun-COPXsM7o.js").then(ne=>ne.ca);return{getCurrentWindow:fe}},__vite__mapDeps([0,1]));await H().startDragging()}catch(H){console.error("Failed to start window dragging:",H)}},[g]),L=l.useCallback(async E=>{if(E.button===0&&g)try{const{getCurrentWindow:H}=await Kt(async()=>{const{getCurrentWindow:fe}=await import("./vendor-.bun-COPXsM7o.js").then(ne=>ne.ca);return{getCurrentWindow:fe}},__vite__mapDeps([0,1]));await H().startDragging()}catch(H){console.error("Failed to start window dragging:",H)}},[g]),q=l.useMemo(()=>[{id:"chat",label:"Chat",icon:ym},{id:"diff",label:"Diff",icon:Vs,badge:!f&&p>0?p:void 0},{id:"terminal",label:"Terminal",icon:mr},{id:"git",label:"Git",icon:Vt,showDot:f&&p>0}],[p,f]);Ne.useEffect(()=>{const E=H=>{if(hs(H)&&!H.shiftKey&&!H.altKey){const Y=parseInt(H.key,10);Y>=1&&Y<=q.length&&(H.preventDefault(),d(q[Y-1].id))}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[q,d]);const te=(E,H)=>{const Y=c===E.id,fe=E.icon,ne=E.id==="chat",pe=E.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(E.id),onMouseDown:Y?L:void 0,className:O("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",Y?"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",Y?"text-foreground":"text-muted-foreground",Y&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",Y&&ne&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",ne&&!(g&&x&&a)&&"border-l",pe&&"border-r",ne&&!f&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...Y&&ne&&a?{"--sidebar-w":g&&x?`${i}px`:"64px"}:{},...ne&&!(g&&x&&a)||pe?{borderColor:"var(--interactive-border)"}:{}},"aria-label":E.label,"aria-selected":Y,role:"tab",children:[f?e.jsx(fe,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),e.jsx("span",{className:"header-tab-label",children:E.label})]}),ne&&!f&&k&&k.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Oa,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact"})}),E.badge!==void 0&&E.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:E.badge})]}),!H&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},E.id)},le=()=>e.jsxs("div",{onMouseDown:R,className:O("app-region-drag relative flex h-12 select-none items-center",D),role:"tablist","aria-label":"Main navigation",children:[!(g&&x)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:M,"aria-label":"Open sessions",className:`${C} mr-2.5`,children:e.jsx(Do,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:q.map((E,H)=>te(E,H===q.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:C,children:e.jsx(Dr,{className:"h-5 w-5"})})}),e.jsx(Ye,{children:e.jsxs("p",{children:["Command Palette (",ss(),"+K)"]})})]}),e.jsxs(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:C,children:e.jsx(Gr,{className:"h-5 w-5"})})}),e.jsx(Ye,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",ss(),"+.)"]})})]})]})]}),$=()=>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:M,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(bm,{className:"h-5 w-5"})}),k&&k.totalTokens>0&&c==="chat"&&e.jsx(Oa,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.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:q.map(E=>{const H=c===E.id,Y=E.icon;return e.jsxs(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{f&&A(),d(E.id)},"aria-label":E.label,"aria-selected":H,role:"tab",className:O(C,"relative",H&&"text-foreground"),children:[e.jsx(Y,{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(Ye,{children:e.jsx("p",{children:E.label})})]},E.id)})}),e.jsxs(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:b,"aria-label":"Open settings",className:O(C,"relative"),children:[e.jsx(Cr,{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(Ye,{children:e.jsx("p",{children:h?"Settings (Update available)":"Settings"})})]})]})]}),z=O("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:w,className:z,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:f?$():le()})};function vi({className:s,...r}){return e.jsx("div",{"data-slot":"card",className:O("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",s),...r})}function $d({className:s,...r}){return e.jsx("div",{"data-slot":"card-header",className:O("@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 _d({className:s,...r}){return e.jsx("div",{"data-slot":"card-title",className:O("leading-none font-semibold",s),...r})}function Bd({className:s,...r}){return e.jsx("div",{"data-slot":"card-content",className:O("px-6",s),...r})}class Ut extends l.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(vi,{className:"w-full max-w-md",children:[e.jsx($d,{className:"text-center",children:e.jsxs(_d,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Ma,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(Bd,{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(ve,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(xs,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let _n=0;function as({...s}){return e.jsx(wm,{"data-slot":"dialog",...s})}function Tg({...s}){return e.jsx(Sm,{"data-slot":"dialog-portal",...s})}const zd=Ne.forwardRef(({className:s,...r},t)=>(Ne.useEffect(()=>(_n+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{_n=Math.max(0,_n-1),_n===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(Gc,{ref:t,"data-slot":"dialog-overlay",className:O("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",s),...r})));zd.displayName=Gc.displayName;function is({className:s,children:r,showCloseButton:t=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Tg,{"data-slot":"dialog-portal",children:[e.jsx(zd,{className:"rounded-none"}),e.jsxs(vm,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:O("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(jm,{"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(Wt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function ds({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:O("flex flex-col gap-2 text-center sm:text-left",s),...r})}function Gs({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:O("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",s),...r})}function us({className:s,...r}){return e.jsx(km,{"data-slot":"dialog-title",className:O("typography-markdown leading-none font-semibold text-foreground",s),...r})}function js({className:s,...r}){return e.jsx(Nm,{"data-slot":"dialog-description",className:O("text-muted-foreground typography-ui-label",s),...r})}const kl="https://github.com/btriapitsyn/openchamber/releases";async function Fg(){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 Pg(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 $a=({open:s,onOpenChange:r,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Ne.useState(!1),[p,h]=Ne.useState("idle"),[w,g]=Ne.useState(null),y=t?.version?`${kl}/tag/v${t.version}`:kl,x=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",S=t?.updateCommand||"openchamber update";Ne.useEffect(()=>{s||(h("idle"),g(null))},[s]);const N=async()=>{try{await navigator.clipboard.writeText(S),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},j=Ne.useCallback(async()=>{h("updating"),g(null);const F=await Fg();if(!F.success){h("error"),g(F.error||"Update failed");return}h("restarting"),await new Promise(M=>setTimeout(M,2e3)),h("reconnecting"),await Pg()?window.location.reload():(h("error"),g("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),k=p!=="idle"&&p!=="error";return e.jsx(as,{open:s,onOpenChange:k?void 0:r,children:e.jsxs(is,{className:"max-w-md",children:[e.jsx(ds,{children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(Cm,{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})]}),v&&k&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Yn,{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&&!k&&e.jsx(tt,{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((F,A)=>/^\d+\.\d+\.\d+$/.test(F.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",F.trim(),`
|
|
58
|
+
`]},A):F.replace(/^- /gm,"• ").trim()+`
|
|
59
|
+
|
|
60
|
+
`)})}),v&&p==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Mm,{className:"h-4 w-4"}),e.jsx("span",{children:"Or update via terminal:"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 px-3 py-2 bg-muted rounded-md font-mono text-sm text-foreground overflow-x-auto",children:S}),e.jsx("button",{onClick:N,className:O("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(Dt,{className:"h-4 w-4"}):e.jsx(Dm,{className:"h-4 w-4"})})]})]}),!v&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[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||w)&&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||w})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:O("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(Da,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!n&&e.jsxs("button",{onClick:c,className:O("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(qr,{className:"h-4 w-4"}),"Download Update"]}),!v&&n&&e.jsxs("button",{disabled:!0,className:O("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(Yn,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&o&&e.jsxs("button",{onClick:d,className:O("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(xs,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!k&&e.jsxs("button",{onClick:j,className:O("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(qr,{className:"h-4 w-4"}),"Update Now"]}),v&&k&&e.jsxs("button",{disabled:!0,className:O("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(Yn,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Nl=264,Cl=200,Ml=500,Rg=40,Dl="openchamber:check-for-updates",Lg=({isOpen:s,isMobile:r,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:i}=Fe(),[c,d]=l.useState(!1),u=l.useRef(0),m=l.useRef(n||Nl),[f,p]=l.useState(!1),h=Fo(),w=l.useRef(!1),g=h.checkForUpdates,{available:y,downloaded:x,checking:v}=h,[S,N]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const b=typeof window.opencodeDesktop<"u";N(b)},[]),l.useEffect(()=>{if(typeof window>"u")return;const b=()=>{typeof window.opencodeDesktop<"u"&&(w.current=!0,g())};return window.addEventListener(Dl,b),()=>{window.removeEventListener(Dl,b)}},[g]),l.useEffect(()=>{w.current&&(v||(y||x?p(!0):se.success("No updates available",{description:"You are running the latest version."}),w.current=!1))},[y,x,v]),l.useEffect(()=>{if(r||!c)return;const b=D=>{const P=D.clientX-u.current,R=Math.min(Ml,Math.max(Cl,m.current+P));o(R)},C=()=>{d(!1)};return window.addEventListener("pointermove",b),window.addEventListener("pointerup",C,{once:!0}),()=>{window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",C)}},[r,c,o]),l.useEffect(()=>{r&&c&&d(!1)},[r,c]);const k=l.useCallback(async b=>{if(b.button===0&&S)try{const{getCurrentWindow:C}=await Kt(async()=>{const{getCurrentWindow:P}=await import("./vendor-.bun-COPXsM7o.js").then(R=>R.ca);return{getCurrentWindow:P}},__vite__mapDeps([0,1]));await C().startDragging()}catch(C){console.error("Failed to start window dragging from sidebar:",C)}},[S]);if(r)return null;const F=s?Math.min(Ml,Math.max(Cl,n||Nl)):0,A=S&&j,M=b=>{s&&(d(!0),u.current=b.clientX,m.current=F,b.preventDefault())};return e.jsxs("aside",{className:O("relative flex h-full overflow-hidden border-r",S?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",c?"transition-none":"",!s&&"border-r-0"),style:{width:`${F}px`,minWidth:`${F}px`,maxWidth:`${F}px`,pointerEvents:s?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!s||F===0,children:[s&&e.jsx("div",{className:O("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",c?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:M,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:O("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:`${F}px`,overflowX:"hidden"},"aria-hidden":!s,children:[A&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${Rg}px`},onMouseDown:k,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ut,{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:O("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(Cr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),y||x?e.jsxs("button",{onClick:()=>p(!0),className:O("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(qr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!S&&e.jsxs(Xe,{children:[e.jsx(Qe,{asChild:!0,children:e.jsx("button",{onClick:()=>i(!0),className:O("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(zt,{className:"h-4 w-4"})})}),e.jsx(Ye,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx($a,{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 Hd({className:s,...r}){return e.jsx(Ar,{"data-slot":"command",className:O("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",s),...r})}function Og({title:s="Command Palette",description:r="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(as,{...a,children:[e.jsxs(ds,{className:"sr-only",children:[e.jsx(us,{children:s}),e.jsx(js,{children:r})]}),e.jsx(is,{className:O("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Hd,{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 Ud({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(lr,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Ar.Input,{"data-slot":"command-input",className:O("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 Wd({className:s,children:r,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(tt,{as:Ar.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:O("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 Vd({...s}){return e.jsx(Ar.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...s})}function Vr({className:s,...r}){return e.jsx(Ar.Group,{"data-slot":"command-group",className:O("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 vo({className:s,...r}){return e.jsx(Ar.Separator,{"data-slot":"command-separator",className:O("bg-border -mx-1 h-px",s),...r})}function $t({className:s,...r}){return e.jsx(Ar.Item,{"data-slot":"command-item",className:O("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 Ks({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(Dr,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(Nn,{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:O("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",s),...r,children:o.length>0?o.map((a,i)=>e.jsxs(Ne.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):r.children})}const $g=()=>{const{isCommandPaletteOpen:s,setCommandPaletteOpen:r,setHelpDialogOpen:t,setSessionCreateDialogOpen:n,setActiveMainTab:o,setSettingsDialogOpen:a,setSessionSwitcherOpen:i,setTimelineDialogOpen:c,toggleSidebar:d}=Fe(),{openNewSessionDraft:u,setCurrentSession:m,getSessionsByDirectory:f}=he(),{currentDirectory:p}=wt(),{themeMode:h,setThemeMode:w}=Fr(),g=()=>{r(!1)},y=async()=>{o("chat"),i(!1),u(),g()},x=L=>{m(L),g()},v=L=>{w(L),g()},S=()=>{t(!0),g()},N=()=>{n(!0),g()},{isMobile:j}=Ct(),k=()=>{if(j){const{isSessionSwitcherOpen:L}=Fe.getState();i(!L)}else d();g()},F=()=>{o("diff"),g()},A=()=>{o("git"),g()},M=()=>{o("terminal"),g()},b=()=>{a(!0),g()},C=()=>{pn(),g()},D=()=>{c(!0),g()},P=f(p??""),R=l.useMemo(()=>P.slice(0,5),[P]);return e.jsxs(Og,{open:s,onOpenChange:r,children:[e.jsx(Ud,{placeholder:"Type a command or search..."}),e.jsxs(Wd,{children:[e.jsx(Vd,{children:"No results found."}),e.jsxs(Vr,{heading:"Actions",children:[e.jsxs($t,{onSelect:k,children:[e.jsx(Do,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(Ks,{children:[ss()," + L"]})]}),e.jsxs($t,{onSelect:y,children:[e.jsx(Gt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsxs(Ks,{children:[ss()," + N"]})]}),e.jsxs($t,{onSelect:N,children:[e.jsx(Vt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsxs(Ks,{children:["Shift + ",ss()," + N"]})]}),e.jsxs($t,{onSelect:S,children:[e.jsx(Gr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(Ks,{children:[ss()," + ."]})]}),e.jsxs($t,{onSelect:F,children:[e.jsx(Vs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(Ks,{children:[ss()," + 2"]})]}),e.jsxs($t,{onSelect:M,children:[e.jsx(mr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(Ks,{children:[ss()," + 3"]})]}),e.jsxs($t,{onSelect:A,children:[e.jsx(Vt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(Ks,{children:[ss()," + 4"]})]}),e.jsxs($t,{onSelect:D,children:[e.jsx(tr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(Ks,{children:[ss()," + T"]})]}),e.jsxs($t,{onSelect:b,children:[e.jsx(Cr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(Ks,{children:[ss()," + ,"]})]}),e.jsxs($t,{onSelect:C,children:[e.jsx(xs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(vo,{}),e.jsxs(Vr,{heading:"Theme",children:[e.jsxs($t,{onSelect:()=>v("light"),children:[e.jsx(Am,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx(Dt,{className:"ml-auto h-4 w-4"})]}),e.jsxs($t,{onSelect:()=>v("dark"),children:[e.jsx(Em,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx(Dt,{className:"ml-auto h-4 w-4"})]}),e.jsxs($t,{onSelect:()=>v("system"),children:[e.jsx(qc,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx(Dt,{className:"ml-auto h-4 w-4"})]})]}),R.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(vo,{}),e.jsx(Vr,{heading:"Recent Sessions",children:R.map(L=>e.jsxs($t,{onSelect:()=>x(L.id),children:[e.jsx(Za,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:L.title||"Untitled Session"})]},L.id))})]})]})]})},_g=(s,r)=>{const t=s.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(Ao,{className:"h-3.5 w-3.5"},`ctrl-${r}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(Dr,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:s.trim()},`key-${r}`)},Bg=s=>{const r=s.split("+").map(t=>t.trim()).filter(Boolean);return r.length===0?s.trim():r.map((t,n)=>e.jsxs(l.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),_g(t,n)]},`${t}-${n}`))},zg=()=>{const{isHelpDialogOpen:s,setHelpDialogOpen:r}=Fe(),t=ss(),n=[{category:"Navigation & Commands",items:[{keys:[`${t} + K`],description:"Open Command Palette",icon:Dr},{keys:[`${t} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:Gr},{keys:[`${t} + L`],description:"Toggle Session Sidebar",icon:Do},{keys:[`Shift + ${t} + M`],description:"Open Model Selector",icon:Jr}]},{category:"Session Management",items:[{keys:[`${t} + N`],description:"Create New Session",icon:Gt},{keys:[`Shift + ${t} + N`],description:"Open Worktree Creator",icon:Vt},{keys:[`${t} + I`],description:"Focus Chat Input",icon:Kc},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Kr}]},{category:"Interface",items:[{keys:[`${t} + /`],description:"Cycle Theme (Light → Dark → System)",icon:Im},{keys:[`${t} + 2`],description:"Open Diff Panel",icon:Vs},{keys:[`${t} + 3`],description:"Open Terminal",icon:mr},{keys:[`${t} + 4`],description:"Open Git Panel",icon:Vt},{keys:[`${t} + T`],description:"Open Timeline",icon:tr},{keys:[`${t} + ,`],description:"Open Settings",icon:Cr}]}];return e.jsx(as,{open:s,onOpenChange:r,children:e.jsxs(is,{className:"max-w-2xl",children:[e.jsxs(ds,{children:[e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(Cr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(js,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsx("div",{className:"space-y-4 mt-3",children:n.map(o=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:o.category}),e.jsx("div",{className:"space-y-1",children:o.items.map((a,i)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a.icon&&e.jsx(a.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:a.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(a.keys)?a.keys:a.keys.split(" / ")).map((c,d)=>e.jsxs(l.Fragment,{children:[d>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:Bg(c)})]},`${c}-${d}`))})]},i))})]},o.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(Gr,{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 (",t," + 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"})]})]})]})})]})})},na=new Set,oa=new Set,aa=new Set,vr={onDeleteRequest(s){return na.add(s),()=>{na.delete(s)}},requestDelete(s){!s.sessions.length&&s.mode!=="worktree"||na.forEach(r=>r(s))},onCreateRequest(s){return oa.add(s),()=>{oa.delete(s)}},requestCreate(s){const r=s??{};oa.forEach(t=>t(r))},onDirectoryRequest(s){return aa.add(s),()=>{aa.delete(s)}},requestDirectoryDialog(){aa.forEach(s=>s())}};function Gd(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 Hg=".openchamber",Al="oc.sessions.groupCollapse",El="oc.sessions.expandedParents",Il=s=>{const r=new Date(s),t=new Date,n=(i,c)=>i.getFullYear()===c.getFullYear()&&i.getMonth()===c.getMonth()&&i.getDate()===c.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(",","")},Xs=s=>{if(!s)return null;const r=s.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},Ug=(s,r)=>{const t=Xs(s),n=Array.from(r.values())[0];if(n?.projectDirectory)return Xs(n.projectDirectory);if(!t)return null;const o=`/${Hg}`,a=t.indexOf(o);return a>0?t.slice(0,a):t},_a=({mobileVariant:s=!1,onSessionSelected:r,allowReselect:t=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,i]=l.useState(null),[c,d]=l.useState(""),[u,m]=l.useState(null),f=l.useRef(null),[p,h]=l.useState(new Set),[w,g]=l.useState(()=>new Map),y=l.useRef(new Set),x=l.useMemo(()=>ls(),[]),[v,S]=l.useState(new Set),[N,j]=l.useState(null),[k,F]=l.useState(new Set),[A,M]=l.useState(null),[b,C]=l.useState(new Set),D=l.useRef(new Map),P=wt(Q=>Q.currentDirectory),R=wt(Q=>Q.homeDirectory),L=wt(Q=>Q.setDirectory),q=Fe(Q=>Q.setActiveMainTab),te=Fe(Q=>Q.setSessionSwitcherOpen),le=Fe(Q=>Q.openMultiRunLauncher),$=he(Q=>Q.getSessionsByDirectory),z=he(Q=>Q.currentSessionId),E=he(Q=>Q.setCurrentSession),H=he(Q=>Q.updateSessionTitle),Y=he(Q=>Q.shareSession),fe=he(Q=>Q.unshareSession),ne=he(Q=>Q.sessionMemoryState),pe=he(Q=>Q.sessionActivityPhase),je=he(Q=>Q.worktreeMetadata),U=he(Q=>Q.availableWorktrees),ee=he(Q=>Q.openNewSessionDraft),[oe,W]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{try{const Q=x.getItem(Al);if(Q){const re=JSON.parse(Q);Array.isArray(re)&&S(new Set(re.filter(ae=>typeof ae=="string")))}const De=x.getItem(El);if(De){const re=JSON.parse(De);Array.isArray(re)&&h(new Set(re.filter(ae=>typeof ae=="string")))}}catch{}},[x]),l.useEffect(()=>{typeof window>"u"||W(typeof window.opencodeDesktop<"u")},[]);const me=$(P),ye=l.useMemo(()=>[...me].sort((Q,De)=>(De.time?.created||0)-(Q.time?.created||0)),[me]);l.useEffect(()=>{if(!P){j(null);return}let Q=!1;return sn(P).then(De=>{Q||j(De)}).catch(()=>{Q||j(null)}),()=>{Q=!0}},[P]);const ce=l.useMemo(()=>new Map(ye.map(Q=>[Q.id,Q])),[ye]),Me=l.useMemo(()=>{const Q=new Map;return ye.forEach(De=>{const re=De.parentID;re&&Q.set(De.id,re)}),Q},[ye]),Ee=l.useMemo(()=>{const Q=new Map;return ye.forEach(De=>{const re=De.parentID;if(!re)return;const ae=Q.get(re)??[];ae.push(De),Q.set(re,ae)}),Q.forEach(De=>De.sort((re,ae)=>(ae.time?.created||0)-(re.time?.created||0))),Q},[ye]);l.useEffect(()=>{z&&h(Q=>{const De=new Set(Q);let re=Me.get(z)||null,ae=!1;for(;re;)De.has(re)||(De.add(re),ae=!0),re=Me.get(re)||null;return ae?De:Q})},[z,Me]);const Pe=l.useMemo(()=>Ug(P,je),[P,je]);l.useEffect(()=>{const Q=new Set;ye.forEach(De=>{const re=Xs(De.directory??null);re&&Q.add(re)}),Pe&&Q.add(Pe),Q.forEach(De=>{const re=w.get(De);re&&re!=="unknown"||y.current.has(De)||(y.current.add(De),Re.listLocalDirectory(De).then(()=>{g(ae=>{const Ie=new Map(ae);return Ie.get(De)==="exists"?ae:(Ie.set(De,"exists"),Ie)})}).catch(()=>{g(ae=>{const Ie=new Map(ae);return Ie.get(De)==="missing"?ae:(Ie.set(De,"missing"),Ie)})}).finally(()=>{y.current.delete(De)}))})},[ye,Pe,w]),l.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const V=l.useMemo(()=>Wo(P,R),[P,R]),K=l.useMemo(()=>fs(P,R),[P,R]),T=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."})]}),X=l.useCallback((Q,De)=>{if(!De){if(s&&(q("chat"),te(!1)),!t&&Q===z){r?.(Q);return}E(Q),r?.(Q)}},[t,z,s,r,q,E,te]),I=l.useCallback(async()=>{a&&c.trim()&&(await H(a,c.trim()),i(null),d(""))},[a,c,H]),B=l.useCallback(()=>{i(null),d("")},[]),G=l.useCallback(async Q=>{const De=await Y(Q.id);De&&De.share?.url?se.success("Session shared",{description:"You can copy the link from the menu."}):se.error("Unable to share session")},[Y]),be=l.useCallback((Q,De)=>{navigator.clipboard.writeText(Q).then(()=>{m(De),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{se.error("Failed to copy URL")})},[]),J=l.useCallback(async Q=>{await fe(Q)?se.success("Session unshared"):se.error("Unable to unshare session")},[fe]),ge=l.useCallback(Q=>{const De=[],re=ae=>{(Ee.get(ae)??[]).forEach(_e=>{De.push(_e),re(_e.id)})};return re(Q),De},[Ee]),He=he(Q=>Q.deleteSession),We=he(Q=>Q.deleteSessions),Be=l.useCallback(async Q=>{const De=ge(Q.id);if(De.length===0)await He(Q.id)?se.success("Session deleted"):se.error("Failed to delete session");else{const re=[Q.id,...De.map(_e=>_e.id)],{deletedIds:ae,failedIds:Ie}=await We(re);ae.length>0&&se.success(`Deleted ${ae.length} session${ae.length===1?"":"s"}`),Ie.length>0&&se.error(`Failed to delete ${Ie.length} session${Ie.length===1?"":"s"}`)}},[ge,He,We]),Ze=l.useCallback(Q=>{q("chat"),s&&te(!1),ee({directoryOverride:Q??null})},[ee,q,te,s]),it=l.useCallback(()=>{vr.requestCreate({worktreeMode:"create"})},[]),lt=l.useCallback(()=>{oe&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(Q=>{Q.success&&Q.path?L(Q.path,{showOverlay:!0}):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")}):vr.requestDirectoryDialog()},[oe,L]),ct=l.useCallback(Q=>{h(De=>{const re=new Set(De);re.has(Q)?re.delete(Q):re.add(Q);try{x.setItem(El,JSON.stringify(Array.from(re)))}catch{}return re})},[x]),mt=l.useCallback(Q=>{const De=Ee.get(Q.id)??[];return{session:Q,children:De.map(re=>mt(re))}},[Ee]),xt=l.useMemo(()=>{const Q=new Map,De=Xs(Pe??null),re=new Map,ae=new Set;U.forEach(ze=>{if(ze.path){const Ge=Xs(ze.path)??ze.path;ae.add(Ge),re.set(Ge,ze)}});const Ie=ze=>{const Ge=Xs(ze.directory??null),rt=je.get(ze.id),ue=((rt?.path?ae.has(Xs(rt.path)??rt.path):!1)?rt:null)??(Ge?re.get(Ge)??null:null),Se=!ue&&(Ge&&De?Ge===De:!Ge&&!!De),Ce=Se?"main":ue?.path??Ge??ze.id,Te=ue?.path??Ge??De??null;if(!Q.has(Ce)){const Ue=Se?"Main workspace":ue?.label||ue?.branch||Wo(Te||"",R)||"Worktree",bt=ue?.relativePath?fs(ue.relativePath,R):Te?fs(Te,R):null;Q.set(Ce,{id:Ce,label:Ue,description:bt,isMain:Se,worktree:ue,directory:Te,sessions:[]})}return Q.get(Ce)};return ye.filter(ze=>{const Ge=ze.parentID;return Ge?!ce.has(Ge):!0}).forEach(ze=>{const Ge=Ie(ze),rt=mt(ze);Ge.sessions.push(rt)}),Q.has("main")||Q.set("main",{id:"main",label:"Main workspace",description:De?fs(De,R):null,isMain:!0,worktree:null,directory:De,sessions:[]}),re.forEach((ze,Ge)=>{const rt=ze.path;Q.has(rt)||Q.set(rt,{id:rt,label:ze.label||ze.branch||Wo(Ge,R)||"Worktree",description:ze.relativePath?fs(ze.relativePath,R):fs(Ge,R),isMain:!1,worktree:ze,directory:Ge,sessions:[]})}),Q.forEach(ze=>{ze.sessions.sort((Ge,rt)=>(rt.session.time?.created||0)-(Ge.session.time?.created||0))}),Array.from(Q.values()).sort((ze,Ge)=>ze.isMain!==Ge.isMain?ze.isMain?-1:1:(ze.label||"").localeCompare(Ge.label||""))},[ye,je,U,Pe,R,mt,ce]),vt=l.useCallback(Q=>{S(De=>{const re=new Set(De);re.has(Q)?re.delete(Q):re.add(Q);try{x.setItem(Al,JSON.stringify(Array.from(re)))}catch{}return re})},[x]),ht=l.useCallback(Q=>{F(De=>{const re=new Set(De);return re.has(Q)?re.delete(Q):re.add(Q),re})},[]);l.useEffect(()=>{if(!oe)return;const Q=new IntersectionObserver(De=>{De.forEach(re=>{const ae=re.target.dataset.groupId;ae&&C(Ie=>{const _e=new Set(Ie);return re.isIntersecting?_e.delete(ae):_e.add(ae),_e})})},{threshold:0});return D.current.forEach(De=>{De&&Q.observe(De)}),()=>Q.disconnect()},[oe,xt]);const yt=l.useCallback((Q,De=0,re)=>{const ae=Q.session,Ie=Xs(ae.directory??null)??Xs(re??null),ze=(Ie?w.get(Ie):null)==="missing",Ge=ne.get(ae.id),rt=z===ae.id,ie=ae.title||"Untitled Session",ue=Q.children.length>0,Se=p.has(ae.id),Ce=ae.summary?.additions,Te=ae.summary?.deletions,Ue=typeof Ce=="number"||typeof Te=="number";if(a===ae.id)return e.jsx("div",{className:O("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",De>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[e.jsxs("form",{className:"flex w-full items-center gap-2","data-keyboard-avoid":"true",onSubmit:pt=>{pt.preventDefault(),I()},children:[e.jsx("input",{value:c,onChange:pt=>d(pt.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename session",onKeyDown:pt=>{pt.key==="Escape"&&B()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Dt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:B,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Wt,{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:[ue?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:Se?e.jsx(Nt,{className:"h-3 w-3"}):e.jsx(As,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Il(ae.time?.created||Date.now())}),ae.share?e.jsx(Ho,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Ue&&((Ce??0)!==0||(Te??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,Ce??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Te??0)]})]}):null,ue?e.jsxs("span",{className:"truncate",children:[Q.children.length," ",Q.children.length===1?"task":"tasks"]}):null]})]})},ae.id);const bt=pe?.get(ae.id)??"idle",At=bt==="busy"||bt==="cooldown",Mt=Ge&&Ge.isZombie?e.jsx(Ma,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(l.Fragment,{children:[e.jsx("div",{className:O("group relative flex items-center rounded-md px-1.5 py-1",rt?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",ze?"opacity-75":"",De>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:ze,onClick:()=>X(ae.id,ze),className:O("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.jsx("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:e.jsx("span",{className:O("truncate typography-ui-label font-normal text-foreground",At&&"animate-pulse [animation-duration:1.8s]"),children:ie})}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[ue?e.jsx("span",{role:"button",tabIndex:0,onClick:pt=>{pt.stopPropagation(),ct(ae.id)},onKeyDown:pt=>{(pt.key==="Enter"||pt.key===" ")&&(pt.preventDefault(),pt.stopPropagation(),ct(ae.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":Se?"Collapse subsessions":"Expand subsessions",children:Se?e.jsx(Nt,{className:"h-3 w-3"}):e.jsx(As,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Il(ae.time?.created||Date.now())}),ae.share?e.jsx(Ho,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Ue&&((Ce??0)!==0||(Te??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,Ce??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Te??0)]})]}):null,ue?e.jsxs("span",{className:"truncate",children:[Q.children.length," ",Q.children.length===1?"task":"tasks"]}):null,ze?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(Ma,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Mt,e.jsxs(Jt,{children:[e.jsx(Zt,{asChild:!0,children:e.jsx("button",{type:"button",className:O("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:pt=>pt.stopPropagation(),onKeyDown:pt=>pt.stopPropagation(),children:e.jsx(Cn,{className:s?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(es,{align:"end",className:"min-w-[180px]",children:[e.jsxs(kt,{onClick:()=>{i(ae.id),d(ie)},className:"[&>svg]:mr-1",children:[e.jsx(Qs,{className:"mr-1 h-4 w-4"}),"Rename"]}),ae.share?e.jsxs(e.Fragment,{children:[e.jsx(kt,{onClick:()=>{ae.share?.url&&be(ae.share.url,ae.id)},className:"[&>svg]:mr-1",children:u===ae.id?e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(qs,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(kt,{onClick:()=>J(ae.id),className:"[&>svg]:mr-1",children:[e.jsx(Tm,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(kt,{onClick:()=>G(ae),className:"[&>svg]:mr-1",children:[e.jsx(Ho,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(kt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Be(ae),children:[e.jsx(Ls,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),ue&&Se?Q.children.map(pt=>yt(pt,De+1,Ie??re)):null]},ae.id)},[w,ne,pe,z,p,a,c,I,B,ct,X,G,be,J,Be,u,s]);return e.jsxs("div",{className:O("flex h-full flex-col text-foreground overflow-x-hidden",s?"":oe?"bg-transparent":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-14 select-none px-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center gap-0",children:[e.jsxs("button",{type:"button",onClick:lt,className:O("group flex min-w-0 flex-1 items-center gap-2 rounded-md px-0 py-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!oe&&"hover:bg-sidebar/20"),"aria-label":"Change project directory",title:K||"/",children:[e.jsx("span",{className:O("flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground group-hover:text-foreground",!oe&&"bg-sidebar/60"),children:e.jsx(gs,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}),e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("p",{className:"truncate whitespace-nowrap typography-ui font-semibold text-muted-foreground group-hover:text-foreground",children:V||"/"})})]}),N?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:it,className:O("inline-flex h-10 w-7 flex-shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!oe&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Manage worktrees",title:"Manage worktrees",children:e.jsx(Yc,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}),e.jsx("button",{type:"button",onClick:le,className:O("inline-flex h-10 w-7 flex-shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!oe&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"New Multi-Run",title:"New Multi-Run",children:e.jsx(Gd,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})})]}):null]})}),e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:O("space-y-1 pb-1 pl-2.5 pr-1",""),children:xt.length===0?T:n&&xt.length===1&&xt[0].isMain||o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const Q=xt.find(ze=>ze.isMain)??xt[0],De=n?10:7,re=Q.sessions.length,ae=k.has(Q.id),Ie=ae?Q.sessions:Q.sessions.slice(0,De),_e=re-Ie.length;return re===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."}):e.jsxs(e.Fragment,{children:[Ie.map(ze=>yt(ze,0,Q.directory)),_e>0&&!ae?e.jsxs("button",{type:"button",onClick:()=>ht(Q.id),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 ",_e," more ",_e===1?"session":"sessions"]}):null,ae&&re>De?e.jsx("button",{type:"button",onClick:()=>ht(Q.id),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]})})()}):xt.map(Q=>e.jsxs("div",{className:"relative",children:[oe&&e.jsx("div",{ref:De=>{D.current.set(Q.id,De)},"data-group-id":Q.id,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("button",{type:"button",onClick:()=>vt(Q.id),className:O("sticky top-0 z-10 pt-1.5 pb-1 w-full text-left cursor-pointer group/header border-b transition-colors duration-150",oe?b.has(Q.id)?"bg-sidebar":"bg-transparent":"bg-sidebar"),style:{borderColor:A===Q.id?"var(--color-border)":v.has(Q.id)?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>M(Q.id),onMouseLeave:()=>M(null),"aria-label":v.has(Q.id)?"Expand group":"Collapse group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 px-1",children:[e.jsx("span",{className:"typography-micro font-medium text-muted-foreground truncate group-hover/header:text-foreground",children:Q.label}),!n&&e.jsx("span",{role:"button",tabIndex:0,className:O("inline-flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground"),"aria-label":"Create session in this group",onClick:De=>{De.stopPropagation(),Ze(Q.directory)},onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.stopPropagation(),Ze(Q.directory))},children:e.jsx(Gt,{className:"h-4.5 w-4.5"})})]})}),v.has(Q.id)?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const De=k.has(Q.id),re=n?10:7,ae=Q.sessions.length,Ie=De?Q.sessions:Q.sessions.slice(0,re),_e=ae-Ie.length;return e.jsxs(e.Fragment,{children:[Ie.map(ze=>yt(ze,0,Q.directory)),ae===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this worktree yet."}):null,_e>0&&!De?e.jsxs("button",{type:"button",onClick:()=>ht(Q.id),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 ",_e," more ",_e===1?"session":"sessions"]}):null,De&&ae>re?e.jsx("button",{type:"button",onClick:()=>ht(Q.id),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]})})()})]},Q.id))})]})};function dt({className:s,type:r,...t}){return e.jsx("input",{type:r,"data-slot":"input",className:O("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})}function Fs({...s}){return e.jsx(Fm,{"data-slot":"select",...s})}function jr({...s}){return e.jsx(Bm,{"data-slot":"select-group",...s})}function jo({...s}){return e.jsx(Lm,{"data-slot":"select-value",...s})}function Ps({className:s,size:r="default",children:t,...n}){return e.jsxs(Pm,{"data-slot":"select-trigger","data-size":r,className:O("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(Rm,{asChild:!0,children:e.jsx(Nt,{className:"size-4 opacity-50"})})]})}function Rs({className:s,children:r,position:t="popper",fitContent:n=!1,...o}){return e.jsx(Om,{children:e.jsx($m,{"data-slot":"select-content",className:O("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(tt,{as:_m,outerClassName:O("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:O("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 Sr({className:s,...r}){return e.jsx(zm,{"data-slot":"select-label",className:O("text-muted-foreground px-2 py-1.5 typography-meta",s),...r})}function Ot({className:s,children:r,...t}){return e.jsxs(Hm,{"data-slot":"select-item",className:O("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(Um,{children:e.jsx(Dt,{className:"size-4"})})}),e.jsx(Wm,{children:r})]})}function So({className:s,...r}){return e.jsx(Vm,{"data-slot":"select-separator",className:O("bg-border pointer-events-none -mx-1 my-1 h-px",s),...r})}function ji({tabs:s,value:r,onValueChange:t,className:n,isInteractive:o=!0,animate:a=!0}){const i=l.useRef(null),c=l.useRef(null),d=l.useCallback(()=>{const u=i.current,m=c.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:h}=m,w=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(w).toFixed(2)}% round 8px)`},[]);return l.useLayoutEffect(()=>{d()},[d,r,s.length]),l.useEffect(()=>{const u=i.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:O("relative isolate w-full",n),children:[e.jsx("div",{ref:i,"aria-hidden":!0,className:O("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:"flex h-9 items-center gap-1 rounded-lg bg-accent px-1.5 text-accent-foreground",children:s.map(u=>{const m=u.icon;return e.jsxs("div",{className:"flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold",children:[m?e.jsx(m,{className:"h-4 w-4"}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})}),e.jsx("div",{className:"relative z-20 flex h-9 items-center gap-1 rounded-lg bg-muted/20 px-1.5",children:s.map(u=>{const m=r===u.value,f=u.icon;return e.jsxs("button",{ref:m?c:null,type:"button",onClick:()=>{o&&t(u.value)},className:O("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:O("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const qd=()=>{const[s,r]=Ne.useState(!1);Ne.useEffect(()=>{r(Ht())},[]);const t=Ne.useCallback(async a=>s?await Zf(a):{success:!0,path:a},[s]),n=Ne.useCallback(async a=>s?await ep(a):{success:!0},[s]),o=Ne.useCallback(async a=>s?await tp(a):{success:!0},[s]);return{isDesktop:s,requestAccess:t,startAccessing:n,stopAccessing:o}},Tl=({currentPath:s,onSelectPath:r,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=l.useMemo(()=>Ht(),[]),[p,h]=l.useState([]),[w,g]=l.useState(new Set),[y,x]=l.useState(!0),[v,S]=l.useState(!1),[N,j]=l.useState(""),[k,F]=l.useState(new Set),[A,M]=l.useState(null),[b,C]=l.useState(""),[D,P]=l.useState(!0),R=l.useRef(null),{requestAccess:L,startAccessing:q,isDesktop:te}=qd(),le=l.useRef(c),$=l.useCallback(V=>{if(!V)return V;if(V==="/"||V.length===0)return"/";let K=V;for(;K.length>1&&K.endsWith("/");)K=K.slice(0,-1);return K.length===0?"/":K},[]),z=l.useMemo(()=>{if(!N)return null;const V=N.replace(/\\/g,"/");return $(V)},[N,$]),E=l.useMemo(()=>{if(typeof d=="string"&&d.length>0){const V=d.replace(/\\/g,"/"),K=$(V);if(K&&K!=="/")return K}return z&&z!=="/"?z:null},[d,z,$]),H=l.useMemo(()=>typeof u=="boolean"?!!(u&&E):!!E,[u,E]);l.useEffect(()=>{H||(x(!0),h([]))},[H]);const Y=l.useCallback(V=>{if(!V||!H||!E)return!1;const K=V.replace(/\\/g,"/"),T=$(K)??K;if(T===E)return!0;const X=`${E}/`;return T.startsWith(X)},[H,E,$]),fe=async V=>{if(H){if(a==="deferred"){r(V);return}if(te){const K=await L(V);K.success&&K.path?(await q(K.path),r(K.path)):(console.error("Failed to get directory access:",K.error),r(V))}else r(V)}};l.useEffect(()=>{let V=!1;const K=I=>{if(!I)return!1;const B=$(I.replace(/\\/g,"/"));return!B||B==="/"?!1:(j(typeof B=="string"?B:I.replace(/\\/g,"/")),!0)};return d&&K(d)||(async()=>{try{const I=await Re.getFilesystemHome();if(!V&&K(I))return}catch(I){console.warn("Failed to resolve filesystem home directory:",I)}try{const I=await Re.getSystemInfo();if(!V&&K(I?.homeDirectory))return}catch(I){console.warn("Failed to resolve home directory from system info:",I)}})(),()=>{V=!0}},[d,$]),l.useEffect(()=>{let V=!1;const K=B=>{if(V)return;const G=B.filter(be=>typeof be=="string"&&be.length>0).map(be=>{const J=be.replace(/\\/g,"/");return $(J)??J});F(new Set(G))},T=()=>{try{const B=localStorage.getItem("pinnedDirectories");if(!B)return;const G=JSON.parse(B);Array.isArray(G)&&K(G)}catch(B){console.warn("Failed to load pinned directories from local storage:",B)}},X=async()=>{try{let B=[];if(f){const G=await en();B=Array.isArray(G?.pinnedDirectories)?G.pinnedDirectories:[]}else{const G=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(G.ok){const be=await G.json();B=Array.isArray(be?.pinnedDirectories)?be.pinnedDirectories:[]}}if(V)return;K(B)}catch(B){console.warn("Failed to load pinned directories:",B)}};T();const I=B=>{const G=B.detail;G&&Array.isArray(G.pinnedDirectories)&&K(G.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",I),X(),()=>{V=!0,window.removeEventListener("openchamber:settings-synced",I)}},[f,$]);const ne=l.useRef(!0);l.useEffect(()=>{if(ne.current){ne.current=!1;return}const V={pinnedDirectories:Array.from(k)};ns(V)},[k]),l.useEffect(()=>{E&&F(V=>{const K=Array.from(V).map(T=>$(T.replace(/\\/g,"/"))??T).filter(T=>Y(T));return new Set(K)})},[E,Y,$]),l.useEffect(()=>{le.current!==c&&(le.current=c,g(new Set))},[c]);const pe=V=>{F(K=>{if(!Y(V))return K;const T=$(V.replace(/\\/g,"/"))??V.replace(/\\/g,"/"),X=new Set(K);return X.has(T)?X.delete(T):X.add(T),X})},je=l.useMemo(()=>Array.from(k).map(V=>$(V.replace(/\\/g,"/"))??V).filter(V=>Y(V)).map(V=>({path:V,name:V.split("/").pop()||V})).sort((V,K)=>V.name.localeCompare(K.name)),[k,Y,$]),U=l.useCallback(async V=>{const K=G=>c||!G.startsWith("."),T=E;if(!H||!T)return[];const X=V&&V.length>0?V:T,I=X?X.replace(/\\/g,"/"):null,B=I?$(I)??I:null;if(B){const G=`${T}/`;if(!(B===T||B.startsWith(G)))return[]}try{return(await Re.listLocalDirectory(V)).filter(be=>{if(!be.isDirectory||!K(be.name))return!1;const J=be.path.replace(/\\/g,"/"),ge=$(J)??J,He=ge===T?T:`${T}/`;return ge===T||ge.startsWith(He)}).map(be=>({name:be.name,path:be.path.replace(/\\/g,"/"),isDirectory:!0})).sort((be,J)=>be.name.localeCompare(J.name))}catch{try{const be=await Re.getApiClient().file.list({path:".",directory:V});return be.data?be.data.filter(J=>{if(J.type!=="directory"||!J.name||!K(J.name))return!1;const ge=String(J.absolute||J.path||J.name).replace(/\\/g,"/"),He=$(ge)??ge,We=He===T?T:`${T}/`;return He===T||He.startsWith(We)}).map(J=>({name:J.name||"",path:String(J.absolute||J.path||J.name).replace(/\\/g,"/"),isDirectory:!0})).filter(J=>J.name!=="").sort((J,ge)=>J.name.localeCompare(ge.name)):[]}catch{return[]}}},[c,E,$,H]),ee=l.useCallback(async()=>{if(!H||!E){x(!0),h([]);return}x(!0);try{const V=await U(E);h(V)}catch{}finally{x(!1)}},[H,E,U]);l.useEffect(()=>{H&&(n==="inline"||v)&&ee()},[n,v,H,ee]);const oe=async V=>{if(!H)return;const K=w.has(V.path),T=new Set(w);if(K){T.delete(V.path),g(T);return}T.add(V.path),g(T);const X=await U(V.path),I=B=>B.map(G=>G.path===V.path?{...G,children:X}:G.children?{...G,children:I(G.children)}:G);h(B=>I(B))};l.useEffect(()=>{A&&R.current&&(R.current.focus(),R.current.select())},[A]);const W=(V,K=[])=>{const T="new_directory",X=K.map(be=>be.name);if(!X.includes(T))return T;let I=1;const B=new RegExp(`^${T}(\\d+)$`);for(const be of X){const J=be.match(B);if(J){const ge=parseInt(J[1],10);ge>I&&(I=ge)}}let G=2;for(;X.includes(`${T}${G}`);)G++;return`${T}${Math.max(G,I+1)}`},me=async V=>{if(H){if(w.has(V.path)){const K=W(V.path,V.children);C(K)}else{const K=new Set(w);if(K.add(V.path),g(K),V.children){const T=W(V.path,V.children);C(T)}else{const T=await U(V.path),X=B=>B.map(G=>G.path===V.path?{...G,children:T}:G.children?{...G,children:X(G.children)}:G);h(B=>X(B));const I=W(V.path,T);C(I)}}M(V.path)}},ye=async()=>{if(!A||!H)return;const V=b.trim()||"new_directory",K=`${A}/${V}`;try{await Re.createDirectory(K);const T=await U(A),X=I=>I.map(B=>B.path===A?{...B,children:T}:B.children?{...B,children:X(B.children)}:B);h(I=>X(I)),M(null),C("")}catch(T){console.error("Failed to create directory:",T)}},ce=()=>{M(null),C("")},Me=(V,K=0)=>{const T=w.has(V.path),X=V.isDirectory,I=k.has(V.path),B=s===V.path,G=n==="inline",be=e.jsxs(e.Fragment,{children:[X&&e.jsx("button",{onClick:J=>{J.stopPropagation(),oe(V)},className:"p-0.5 hover:bg-accent rounded",children:T?e.jsx(Nt,{className:"h-3 w-3"}):e.jsx(As,{className:"h-3 w-3"})}),!X&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:J=>{J.stopPropagation(),fe(V.path),n==="dropdown"&&a==="immediate"&&S(!1)},onDoubleClick:J=>{J.stopPropagation(),i&&i(V.path)},className:O("flex items-center gap-1.5 flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",G&&B?"text-primary":"text-foreground"),children:[T?e.jsx(gs,{className:O("h-3.5 w-3.5 text-muted-foreground",G&&B&&"text-primary")}):e.jsx(gs,{className:O("h-3.5 w-3.5 text-muted-foreground",G&&B&&"text-primary")}),e.jsx("span",{className:O("typography-ui-label font-medium truncate",G&&B?"text-primary":"text-foreground"),children:V.name})]}),e.jsx("button",{onClick:J=>{J.stopPropagation(),me(V)},className:O("p-1 hover:bg-accent rounded transition-opacity",m?"opacity-70":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("button",{onClick:J=>{J.stopPropagation(),pe(V.path)},className:O("p-1 hover:bg-accent rounded transition-opacity",m?"opacity-70":"opacity-0 group-hover:opacity-100"),title:I?"Unpin directory":"Pin directory",children:I?e.jsx(Uo,{className:"h-3 w-3 text-primary"}):e.jsx(Gm,{className:"h-3 w-3 text-muted-foreground"})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:O("group flex items-center gap-1 rounded px-2 py-1.5 text-left hover:bg-accent/40",B?"text-primary":"text-foreground"),style:{paddingLeft:`${K*12+8}px`},children:be}),T&&e.jsxs(e.Fragment,{children:[A===V.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(K+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(gs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{ref:R,value:b,onChange:J=>C(J.target.value),onKeyDown:J=>{J.key==="Enter"?(J.preventDefault(),J.stopPropagation(),ye()):J.key==="Escape"&&(J.preventDefault(),J.stopPropagation(),ce())},onBlur:ye,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:J=>{J.preventDefault(),J.stopPropagation(),ye()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Dt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:J=>{J.preventDefault(),J.stopPropagation(),ce()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Wt,{className:"h-3 w-3 text-muted-foreground"})})]}),V.children&&V.children.map(J=>Me(J,K+1))]})]},V.path):e.jsxs("div",{children:[e.jsxs(kt,{className:O("flex items-center gap-1 cursor-pointer group",s===V.path&&"bg-accent"),style:{paddingLeft:`${K*12+8}px`},onSelect:J=>{J.preventDefault()},children:[X&&e.jsx("button",{onClick:J=>{J.stopPropagation(),oe(V)},className:"p-0.5 hover:bg-accent rounded",children:T?e.jsx(Nt,{className:"h-3 w-3"}):e.jsx(As,{className:"h-3 w-3"})}),!X&&e.jsx("div",{className:"w-4"}),be]}),T&&e.jsxs("div",{children:[A===V.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(K+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(gs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{ref:R,value:b,onChange:J=>C(J.target.value),onKeyDown:J=>{J.key==="Enter"?(J.preventDefault(),J.stopPropagation(),ye()):J.key==="Escape"&&(J.preventDefault(),J.stopPropagation(),ce())},onBlur:ye,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:J=>{J.preventDefault(),J.stopPropagation(),ye()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Dt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:J=>{J.preventDefault(),J.stopPropagation(),ce()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Wt,{className:"h-3 w-3 text-muted-foreground"})})]}),V.children&&V.children.map(J=>Me(J,K+1))]})]},V.path)},Ee=(V,K)=>{if(n==="inline"){const T=s===K;return e.jsxs("div",{className:O("group flex items-center gap-2 px-2 py-1.5 hover:bg-accent/40"),children:[e.jsxs("button",{onClick:()=>fe(K),onDoubleClick:X=>{X.stopPropagation(),i&&i(K)},className:O("flex flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",T?"text-primary":"text-foreground"),children:[e.jsx(gs,{className:O("h-3.5 w-3.5 text-muted-foreground",T&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:O("typography-ui-label font-medium truncate",T?"text-primary":"text-foreground"),children:V}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:fs(K,N)})]})]}),e.jsx("button",{onClick:()=>pe(K),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Uo,{className:"h-3 w-3 text-primary"})})]},K)}return e.jsxs(kt,{onSelect:T=>{T.preventDefault(),fe(K),a==="immediate"&&S(!1)},className:O("flex items-start gap-2 cursor-pointer group py-2",s===K&&"bg-accent"),children:[e.jsx(gs,{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:V}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:fs(K,N)})]}),e.jsx("button",{onClick:T=>{T.stopPropagation(),T.preventDefault(),pe(K)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Uo,{className:"h-3 w-3 text-primary"})})]},K)},Pe=e.jsx(e.Fragment,{children:H?e.jsxs(e.Fragment,{children:[je.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>P(V=>!V),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:[D?e.jsx(Nt,{className:"h-3.5 w-3.5"}):e.jsx(As,{className:"h-3.5 w-3.5"}),e.jsx(Hr,{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:je.length})]}),D&&je.map(({name:V,path:K})=>Ee(V,K)),n==="dropdown"&&e.jsx(Us,{}),n==="inline"&&D&&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(gs,{className:"h-3.5 w-3.5"}),"Browse"]}),y?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):p.map(V=>Me(V)),!y&&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:O("overflow-hidden rounded-xl border border-border/40 bg-sidebar/70",o),children:e.jsx(tt,{outerClassName:"max-h-full",className:"w-full",children:Pe})}):e.jsxs(Jt,{open:v,onOpenChange:S,children:[e.jsx(Zt,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",className:O("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(gs,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:s,children:fs(s,N)})]}),e.jsx(Nt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(es,{align:"start",className:"w-[350px]",children:e.jsx(tt,{outerClassName:"h-full",className:"w-full",children:Pe})})]})},Fl="directoryTreeShowHidden",Wg=({open:s,onOpenChange:r})=>{const{currentDirectory:t,homeDirectory:n,setDirectory:o,isHomeReady:a}=wt(),[i,c]=l.useState(null),[d,u]=l.useState(""),[m,f]=l.useState(!1),[p,h]=l.useState(!1),[w,g]=l.useState(()=>{if(typeof window>"u")return!1;try{const z=window.localStorage.getItem(Fl);if(z==="true")return!0;if(z==="false")return!1}catch{}return!1}),{isDesktop:y,requestAccess:x,startAccessing:v}=qd(),{isMobile:S}=Ct(),N=l.useCallback(z=>z?fs(z,n):"",[n]);l.useEffect(()=>{if(s){f(!1),h(!1);const z=t||n||"";c(z),u(N(z))}},[s,t,n,N]),l.useEffect(()=>{!s||m||i||n&&a&&(c(n),f(!0),u("~"))},[s,m,i,n,a]),l.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Fl,w?"true":"false")}catch{}},[w]);const j=l.useCallback(()=>{r(!1)},[r]),k=l.useCallback(async z=>{if(!(!z||p)){if(z===t){j();return}h(!0);try{let E=z;if(y){const H=await x(z);if(!H.success){se.error("Unable to access directory",{description:H.error||"Desktop denied directory access."});return}E=H.path??z;const Y=await v(E);if(!Y.success){se.error("Failed to open directory",{description:Y.error||"Desktop could not grant file access."});return}}o(E),j()}catch(E){se.error("Failed to select directory",{description:E instanceof Error?E.message:"Unknown error occurred."})}finally{h(!1)}}},[t,j,y,x,o,v,p]),F=l.useCallback(async()=>{const z=d.trim()||i;z&&await k(z)},[k,d,i]),A=l.useCallback(z=>{c(z),f(!0),u(N(z))},[N]),M=l.useCallback(async z=>{c(z),f(!0),u(N(z)),await k(z)},[k,N]),b=l.useCallback(z=>{const E=z.target.value;if(u(E),f(!0),E.startsWith("/")||E.startsWith("~")){const H=E.startsWith("~")&&n?E.replace(/^~/,n):E;c(H)}},[n]),C=l.useCallback(z=>{z.key==="Enter"&&(z.preventDefault(),F())},[F]),D=l.useCallback(()=>{g(z=>!z)},[]),P=e.jsxs(ds,{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(us,{children:"Select project directory"}),e.jsx(js,{className:"hidden sm:block",children:"Choose the working directory for sessions and OpenCode operations."})]}),R=e.jsx(dt,{value:d,onChange:b,onKeyDown:C,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),L=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(Tl,{variant:"inline",currentPath:i??t,onSelectPath:A,onDoubleClickPath:M,className:"h-full sm:min-h-[280px] sm:h-[380px]",selectionBehavior:"deferred",showHidden:w,rootDirectory:a?n:null,isRootReady:a})}),q=e.jsxs("button",{type:"button",onClick:D,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:[w?e.jsx(ei,{className:"h-4 w-4 text-primary"}):e.jsx(ti,{className:"h-4 w-4"}),"Show hidden"]}),te=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:R}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:q}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 p-1.5 overflow-hidden",children:e.jsx(Tl,{variant:"inline",currentPath:i??t,onSelectPath:A,onDoubleClickPath:M,className:"h-full",selectionBehavior:"deferred",showHidden:w,rootDirectory:a?n:null,isRootReady:a,alwaysShowActions:!0})})]}),le=e.jsxs(tt,{outerClassName:"flex-1 min-h-0 overflow-hidden",className:"directory-dialog-body sm:px-0 sm:pb-0 flex flex-col gap-3",children:[R,e.jsx("div",{className:"flex items-center justify-end",children:q}),L]}),$=()=>e.jsxs(e.Fragment,{children:[e.jsx(ve,{variant:"ghost",onClick:j,disabled:p,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(ve,{onClick:F,disabled:p||!m||!i&&!d.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:p?"Applying...":"Open Directory"})]});return S?e.jsx(ps,{open:s,onClose:()=>r(!1),title:"Select 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:$()}),children:te}):e.jsx(as,{open:s,onOpenChange:r,children:e.jsxs(is,{className:O("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:z=>{z.preventDefault()},children:[P,le,e.jsx(Gs,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-row gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:justify-end sm:border-0 sm:bg-transparent sm:px-0 sm:pt-3",children:$()})]})})},ko=".openchamber",Bn=s=>s?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:s}):void 0,Vg=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Kd=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),Yd=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},zn=(s,r)=>{const t=Yd(s),n=Kd(r),o=!t||t==="/"?`/${ko}`:`${t}/${ko}`;return n?`${o}/${n}`:o},Gg=()=>{const[s,r]=l.useState(!1),[t,n]=l.useState(!1),[o,a]=l.useState("new"),[i,c]=l.useState(""),[d,u]=l.useState(""),[m,f]=l.useState("HEAD"),[p,h]=l.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[w,g]=l.useState(!1),[y,x]=l.useState([]),[v,S]=l.useState(!1),[N,j]=l.useState(null),[k,F]=l.useState(!1),[A,M]=l.useState(null),[b,C]=l.useState(!1),D=l.useRef(new Set),[P,R]=l.useState(null),[L,q]=l.useState([]),[te,le]=l.useState(!1),[$,z]=l.useState(!1),{sessions:E,createSession:H,deleteSession:Y,deleteSessions:fe,loadSessions:ne,initializeNewOpenChamberSession:pe,setWorktreeMetadata:je,setSessionDirectory:U,getWorktreeMetadata:ee,isLoading:oe}=he(),{currentDirectory:W,homeDirectory:me,hasPersistedDirectory:ye,isHomeReady:ce}=wt(),{agents:Me}=ut(),{isSessionCreateDialogOpen:Ee,setSessionCreateDialogOpen:Pe}=Fe(),{isMobile:V,isTablet:K,hasTouchInput:T}=Ct(),X=V||K||T,I=l.useMemo(()=>Yd(W),[W]),B=l.useMemo(()=>Vg(i),[i]),G=l.useMemo(()=>o==="existing"?d.trim():B,[d,B,o]),be=l.useMemo(()=>Kd(G),[G]),J=l.useMemo(()=>!I||!be?"":zn(I,be),[I,be]),ge=A===!0,He=l.useMemo(()=>{const ie=p.find(ue=>ue.value===m);return ie?ie.label:m==="HEAD"?"Current (HEAD)":m},[p,m]),We=l.useMemo(()=>(P?.worktree?.status?.isDirty??!1)||L.some(ie=>ie.metadata.status?.isDirty),[P?.worktree?.status?.isDirty,L]),Be=l.useMemo(()=>{const ie=P?.worktree;return ie&&typeof ie.branch=="string"&&ie.branch.trim().length>0?!0:L.length>0&&L.every(({metadata:ue})=>typeof ue.branch=="string"&&ue.branch.trim().length>0)},[P?.worktree,L]),Ze=P?.mode==="worktree",it=Ze,lt=$||!Ze||!Be;l.useEffect(()=>{I&&(D.current.has(I)||Wp(I).then(()=>D.current.add(I)).catch(ie=>{console.warn("Failed to ensure .openchamber directory is ignored:",ie),D.current.delete(I)}))},[I]),l.useEffect(()=>{ne()},[ne,W]),l.useEffect(()=>{!t&&ce&&!ye&&(r(!0),n(!0))},[ye,t,ce]),l.useEffect(()=>{if(!Ee){a("new"),c(""),u(""),f("HEAD"),h([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),g(!1),x([]),j(null),S(!1),F(!1),M(null),C(!1);return}if(!I){a("new"),u(""),h([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),f("HEAD"),x([]),M(null),F(!1);return}let ie=!1;return S(!0),g(!0),F(!0),j(null),(async()=>{try{const ue=await sn(I);if(ie)return;if(M(ue),!ue)a("new"),u(""),h([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),f("HEAD"),x([]),j(null);else{const[Se,Ce]=await Promise.all([po(I),xd(I).catch(()=>null)]);if(ie)return;const Te=[],Ue=Ce?.current?`Current (HEAD: ${Ce.current})`:"Current (HEAD)";if(Te.push({value:"HEAD",label:Ue,group:"special"}),Ce){const st=Ce.all.filter(ot=>!ot.startsWith("remotes/")).sort((ot,Ae)=>ot.localeCompare(Ae)),jt=Ce.current&&!Ce.current.startsWith("remotes/")?Ce.current:st[0]??"";u(ot=>{const Ae=ot.trim();return Ae&&st.includes(Ae)?Ae:jt}),st.forEach(ot=>{Te.push({value:ot,label:ot,group:"local"})}),Ce.all.filter(ot=>ot.startsWith("remotes/")).map(ot=>ot.replace(/^remotes\//,"")).sort((ot,Ae)=>ot.localeCompare(Ae)).forEach(ot=>{Te.push({value:ot,label:ot,group:"remote"})})}h(Te),f(st=>Te.some(jt=>jt.value===st)?st:"HEAD");const bt=Se.map(st=>ho(I,st)),Mt=`${zn(I,"")}/`,pt=bt.filter(st=>st.path.startsWith(Mt));x(pt)}}catch(ue){if(ie)return;const Se=ue instanceof Error?ue.message:"Failed to load worktrees";j(Se)}finally{ie||(S(!1),g(!1),F(!1))}})(),()=>{ie=!0}},[Ee,I]);const ct=l.useCallback(ie=>{R({sessions:ie.sessions,dateLabel:ie.dateLabel,mode:ie.mode??"session",worktree:ie.worktree??null})},[]),mt=l.useCallback(()=>{R(null),q([]),le(!1),z(!1)},[]);l.useEffect(()=>vr.onDeleteRequest(ie=>{ct(ie)}),[ct]),l.useEffect(()=>vr.onDirectoryRequest(()=>{r(!0)}),[]),l.useEffect(()=>vr.onCreateRequest(()=>{a("new"),c(""),u(""),f("HEAD"),j(null),Pe(!0)}),[Pe]),l.useEffect(()=>{if(!P){q([]),le(!1);return}const ie=P.sessions.map(Se=>{const Ce=ee(Se.id);return Ce?{session:Se,metadata:Ce}:null}).filter(Se=>!!Se);if(q(ie),le(!1),ie.length===0)return;let ue=!1;return(async()=>{const Se=await Promise.all(ie.map(async({metadata:Ce})=>{if(Ce.status&&typeof Ce.status.isDirty=="boolean")return Ce.status;try{return await Ra(Ce.path)}catch{return Ce.status}})).catch(Ce=>(console.warn("Failed to inspect worktree status before deletion:",Ce),ie.map(({metadata:Te})=>Te.status)));ue||!Array.isArray(Se)||q(Ce=>Ce.map((Te,Ue)=>({session:Te.session,metadata:{...Te.metadata,status:Se[Ue]??Te.metadata.status}})))})(),()=>{ue=!0}},[P,ee]),l.useEffect(()=>{Be||le(!1)},[Be]);const xt=l.useCallback(ie=>{c(ie),j(null)},[]),vt=l.useCallback(async()=>{if(!(!I||!A))try{const ue=(await po(I)).map(Ue=>ho(I,Ue)),Ce=`${zn(I,"")}/`,Te=ue.filter(Ue=>Ue.path.startsWith(Ce));x(Te)}catch{}},[I,A]),ht=l.useRef(null);l.useEffect(()=>{ht.current?.mode==="worktree"&&!P&&vt(),ht.current=P},[P,vt]);const yt=l.useCallback(()=>{if(!I){const Ce="Select a project directory first.";return j(Ce),se.error(Ce),!1}const ie=G,ue=be;if(!ie){const Ce=o==="existing"?"Select an existing branch for the new worktree.":"Provide a branch name for the new worktree.";return j(Ce),se.error(Ce),!1}if(!ue){const Ce="Provide a branch name that can be used as a folder.";return j(Ce),se.error(Ce),!1}const Se=zn(I,ue);if(y.some(Ce=>Ce.path===Se)){const Ce="A worktree with this folder already exists.";return j(Ce),se.error(Ce),!1}return j(null),!0},[I,o,G,be,y]),Q=async()=>{if(b||oe||!yt())return;C(!0),j(null);let ie=null;try{const ue=G,Se=be,Ce=o==="new",Ue=await wd({projectDirectory:I,worktreeSlug:Se,branch:ue,createBranch:Ce,startPoint:Ce&&m&&m!=="HEAD"?m:void 0});ie=Ue;const bt=await Ra(Ue.path).catch(()=>{}),At=bt?{...Ue,status:bt}:Ue,Mt=await H(void 0,Ue.path);if(!Mt){await el({projectDirectory:I,path:Ue.path,force:!0}).catch(()=>{});const pt="Failed to create session for worktree";j(pt),se.error(pt);return}pe(Mt.id,Me),U(Mt.id,Ue.path),je(Mt.id,At),await vt(),c(""),u(""),se.success("Worktree created")}catch(ue){ie&&await el({projectDirectory:I,path:ie.path,force:!0}).catch(()=>{});const Se=ue instanceof Error?ue.message:"Failed to create worktree";j(Se),se.error(Se)}finally{C(!1)}},De=l.useCallback(ie=>{const ue=E.filter(Se=>ee(Se.id)?.path===ie.path);vr.requestDelete({sessions:ue,mode:"worktree",worktree:ie})},[E,ee]),re=l.useCallback(async()=>{if(P){z(!0);try{const ie=it,ue=ie&&te;if(P.sessions.length===0&&Ze&&P.worktree){const Se=te&&Be;await vd({projectDirectory:I,path:P.worktree.path,branch:P.worktree.branch,force:!0,deleteRemote:Se});const Ce=Se?"Worktree and remote branch removed.":"Worktree removed.";se.success("Worktree removed",{description:Bn(Ce)}),mt(),ne();return}if(P.sessions.length===1){const Se=P.sessions[0];if(!await Y(Se.id,{archiveWorktree:ie,deleteRemoteBranch:ue})){se.error("Failed to delete session"),z(!1);return}const Te=ie?ue?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;se.success("Session deleted",{description:Bn(Te)})}else{const Se=P.sessions.map(Ue=>Ue.id),{deletedIds:Ce,failedIds:Te}=await fe(Se,{archiveWorktree:ie,deleteRemoteBranch:ue});if(Ce.length>0){const Ue=ie?ue?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,At=[Te.length>0?`${Te.length} session${Te.length===1?"":"s"} could not be deleted.`:P.dateLabel?`Removed all sessions from ${P.dateLabel}.`:void 0,Ue].filter(Boolean).join(" ");se.success(`Deleted ${Ce.length} session${Ce.length===1?"":"s"}`,{description:Bn(At||void 0)})}if(Te.length>0&&(se.error(`Failed to delete ${Te.length} session${Te.length===1?"":"s"}`,{description:Bn("Please try again in a moment.")}),Ce.length===0)){z(!1);return}}mt()}finally{z(!1)}}},[P,te,Y,fe,mt,it,Ze,Be,I,ne]),ae=e.jsxs("div",{className:"space-y-4 w-full min-w-0",children:[e.jsxs("div",{className:"space-y-3 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Create worktree"}),e.jsxs("p",{className:"typography-meta text-muted-foreground/80",children:["Branch-specific directory under ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:ko}),"."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ji,{tabs:[{value:"new",label:"New branch"},{value:"existing",label:"Existing branch"}],value:o,onValueChange:ie=>{if(a(ie),j(null),ie==="existing"&&!d){const ue=p.find(Se=>Se.group==="local")?.value??"";ue&&u(ue)}},animate:!1}),o==="new"?e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"worktree-base-branch-select",children:"Base branch"}),e.jsxs(Fs,{value:m,onValueChange:f,disabled:!ge||k||w,children:[e.jsx(Ps,{id:"worktree-base-branch-select",size:"lg",className:"w-full typography-meta text-foreground",children:e.jsx(jo,{placeholder:w?"Loading branches…":"Select a branch"})}),e.jsxs(Rs,{children:[e.jsxs(jr,{children:[e.jsx(Sr,{children:"Default"}),p.filter(ie=>ie.group==="special").map(ie=>e.jsx(Ot,{value:ie.value,children:ie.label},ie.value))]}),p.some(ie=>ie.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(So,{}),e.jsxs(jr,{children:[e.jsx(Sr,{children:"Local branches"}),p.filter(ie=>ie.group==="local").map(ie=>e.jsx(Ot,{value:ie.value,children:ie.label},ie.value))]})]}),p.some(ie=>ie.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(So,{}),e.jsxs(jr,{children:[e.jsx(Sr,{children:"Remote branches"}),p.filter(ie=>ie.group==="remote").map(ie=>e.jsx(Ot,{value:ie.value,children:ie.label},ie.value))]})]})]})]}),e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"worktree-branch-input",children:"New branch name"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(dt,{id:"worktree-branch-input",value:i,onChange:ie=>xt(ie.target.value),placeholder:"feature/new-branch",className:"h-8 flex-1 typography-meta text-foreground placeholder:text-muted-foreground/70",disabled:!ge||k,onKeyDown:ie=>{ie.key==="Enter"&&!b&&Q()}}),e.jsx(ve,{onClick:Q,disabled:b||oe||!ge||!G,className:"h-8",children:b?"Creating…":"Create"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"worktree-existing-branch-select",children:"Existing branch"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Fs,{value:d,onValueChange:ie=>{u(ie),j(null)},disabled:!ge||k||w||!p.some(ie=>ie.group==="local"),children:[e.jsx(Ps,{id:"worktree-existing-branch-select",size:"lg",className:"flex-1 typography-meta text-foreground",children:e.jsx(jo,{placeholder:w?"Loading branches…":"Select a branch"})}),e.jsx(Rs,{children:e.jsxs(jr,{children:[e.jsx(Sr,{children:"Local branches"}),p.filter(ie=>ie.group==="local").map(ie=>e.jsx(Ot,{value:ie.value,children:ie.label},ie.value))]})})]}),e.jsx(ve,{onClick:Q,disabled:b||oe||!ge||!G,className:"h-8",children:b?"Creating…":"Create"})]}),!w&&!p.some(ie=>ie.group==="local")?e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"No local branches found. Fetch or create a branch first."}):null]}),G?e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:o==="existing"?e.jsxs(e.Fragment,{children:["Uses branch"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:G})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:fs(J,me)})]}):e.jsxs(e.Fragment,{children:["Creates branch"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:G})," ","from"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:He})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:fs(J,me)})]})}):null]}),N&&e.jsx("p",{className:"typography-meta text-destructive",children:N}),!ge&&!k&&e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Current directory is not a Git repository."})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border border-border/40 bg-sidebar/60 p-3 overflow-hidden min-w-0",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Existing worktrees"})}),v?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading worktrees…"}):y.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 text-muted-foreground",children:ko}),"."]}):e.jsx("div",{className:"space-y-1.5 min-w-0",children:y.map(ie=>{const ue=ie.relativePath||(ie.path.startsWith(I+"/")?ie.path.slice(I.length+1):ie.path);return e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border/30 bg-sidebar-accent/20 px-3 py-2 min-w-0",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"typography-meta font-medium text-foreground",children:ie.label||ie.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70 break-all",children:ue})]}),e.jsx("button",{type:"button",onClick:()=>De(ie),className:"flex-shrink-0 flex h-7 w-7 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":`Delete worktree ${ie.branch||ie.label}`,children:e.jsx(Ls,{className:"h-4 w-4"})})]},ie.path)})})]})]}),Ie=e.jsx(ve,{variant:"ghost",onClick:()=>Pe(!1),disabled:b,children:"Close"}),_e=P?.worktree??L[0]?.metadata??null,ze=P?P.mode==="worktree"?P.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and ${P.sessions.length===1?"1 linked session":`${P.sessions.length} linked sessions`}.`:`This action permanently removes ${P.sessions.length===1?"1 session":`${P.sessions.length} sessions`}${P.dateLabel?` from ${P.dateLabel}`:""}.`:"",Ge=P?e.jsxs("div",{className:"space-y-2",children:[P.sessions.length>0&&e.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsxs("ul",{className:"space-y-0.5",children:[P.sessions.slice(0,3).map(ie=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:ie.title||"Untitled Session"},ie.id)),P.sessions.length>3&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",P.sessions.length-3," more"]})]})}),Ze?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"}),_e?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:_e.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:_e?fs(_e.path,me):"Worktree path unavailable."}),We&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),Be?e.jsxs("button",{type:"button",onClick:()=>{lt||le(ie=>!ie)},disabled:lt,className:O("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",lt?"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:te?e.jsx(ei,{className:"size-4 text-primary"}):e.jsx(ti,{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:te?"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,rt=e.jsxs(e.Fragment,{children:[e.jsx(ve,{variant:"ghost",onClick:mt,disabled:$,children:"Cancel"}),e.jsx(ve,{variant:"destructive",onClick:re,disabled:$,children:$?"Deleting…":Ze?"Delete worktree":P?.sessions.length===1?"Delete session":"Delete sessions"})]});return e.jsxs(e.Fragment,{children:[X?e.jsx(ps,{open:Ee,onClose:()=>Pe(!1),title:"Worktree Manager",footer:e.jsx("div",{className:"flex justify-end gap-2",children:Ie}),children:e.jsx("div",{className:"space-y-2 pb-2",children:ae})}):e.jsx(as,{open:Ee,onOpenChange:Pe,children:e.jsxs(is,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2 overflow-hidden",children:[e.jsx(ds,{children:e.jsx(us,{children:"Worktree Manager"})}),ae,e.jsx(Gs,{className:"mt-2 gap-2 pt-1 pb-1",children:Ie})]})}),X?e.jsx(ps,{open:!!P,onClose:()=>{$||mt()},title:P?.sessions.length===1?"Delete session":"Delete sessions",footer:e.jsx("div",{className:"flex justify-end gap-2",children:rt}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[ze&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:ze}),Ge]})}):e.jsx(as,{open:!!P,onOpenChange:ie=>{if(!ie){if($)return;mt()}},children:e.jsxs(is,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(ds,{children:[e.jsx(us,{children:P?.sessions.length===1?"Delete session":"Delete sessions"}),ze&&e.jsx(js,{children:ze})]}),Ge,e.jsx(Gs,{className:"mt-2 gap-2 pt-1 pb-1",children:rt})]})}),e.jsx(Wg,{open:s,onOpenChange:r})]})};function qg(){return new Worker(qm,{type:"module"})}const Kg=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function Yg(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 Pl(s){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>s(void 0),0);return()=>window.clearTimeout(r)}const Xg=({children:s})=>{const r=Ym(),t=It(c=>c.activeDirectory),n=It(c=>t?c.directories.get(t)?.lastStatusChange??0:0),o=It(c=>t?c.directories.get(t)?.diffCache.size??0:0),a=Ne.useRef(!1),i=Ne.useRef(new Map);return Ne.useEffect(()=>{if(!r||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=Ca(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Ne.useEffect(()=>{if(!r||!t||!n||o===0)return;const c=It.getState().directories.get(t);if(!c||c.diffCache.size===0||(i.current.get(t)??0)>=c.lastStatusChange)return;i.current.set(t,c.lastStatusChange);let u=!1,m=null;const f=Array.from(c.diffCache.entries());let p=0;const h=w=>{if(u)return;const g=Date.now();for(;p<f.length&&!(w&&w.timeRemaining()<8||!w&&Date.now()-g>8);){const[y,x]=f[p];p+=1,Ir(y);const v=Yg(y,x.original,x.modified),S={name:y,contents:x.original,cacheKey:`old-${v}`},N={name:y,contents:x.modified,cacheKey:`new-${v}`},j=Ca(S,N),k={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(k,j)}p<f.length&&(m=Pl(h))};return h(void 0),p<f.length&&(m=Pl(h)),()=>{u=!0,m?.()}},[r,t,n,o]),e.jsx(e.Fragment,{children:s})},Qg=({children:s})=>{const t=Ro()?.currentTheme?.metadata?.variant==="dark";Od();const n=Ne.useMemo(()=>({theme:{dark:Yr.dark,light:Yr.light},themeType:t?"dark":"light",langs:Kg}),[t]);return e.jsx(Km,{poolOptions:{workerFactory:qg,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(Xg,{children:s})})},Ts=Ne.forwardRef(({className:s,...r},t)=>e.jsx(tt,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:O("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}));Ts.displayName="Textarea";const Jg="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",Zg=Object.assign({"../assets/provider-logos/gocode.svg":Jg}),Ba=new Map;for(const[s,r]of Object.entries(Zg)){const t=s.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&r&&Ba.set(t[1].toLowerCase(),r)}function Xd(s){const r=s?.toLowerCase()??null,t=r?Ba.has(r):!1,n=r?Ba.get(r)??null:null,[o,a]=Ne.useState(t?"local":"remote");Ne.useEffect(()=>{a(t?"local":"remote")},[t,r]);const i=Ne.useCallback(()=>{a(c=>c==="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 Xt=({providerId:s,alt:r,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=Xd(s),c=l.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:r||`${s} logo`,className:O("dark:invert",t),onError:c})},za=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),ex=(s,r)=>{const t=za(s),n=za(r);return`${t}-${n}`.substring(0,60)},Rl=(s,r)=>`${s}/${r}`,tx=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),sx=()=>wt.getState().currentDirectory??null,ia=Tt()(_t(s=>({isLoading:!1,error:null,createMultiRun:async r=>{const t=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:i}=r;if(!t)return s({error:"Group name is required"}),null;if(!n)return s({error:"Prompt is required"}),null;if(o.length<2)return s({error:"Select at least 2 models"}),null;if(o.length>5)return s({error:"Maximum 5 models allowed"}),null;s({isLoading:!0,error:null});try{const c=sx();if(!c)return s({error:"No directory selected",isLoading:!1}),null;if(!await sn(c))return s({error:"Not in a git repository",isLoading:!1}),null;const u=za(t),m=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",f=m!=="HEAD"?m:void 0,p=[],h=new Map;for(const v of o){const S=`${v.providerID}:${v.modelID}`;h.set(S,(h.get(S)||0)+1)}const w=new Map;for(const v of o){const S=`${v.providerID}:${v.modelID}`,N=h.get(S)||1,j=(w.get(S)||0)+1;w.set(S,j);const k=ex(v.providerID,v.modelID),F=N>1?Rl(u,`${k}-${j}`):Rl(u,k);if(!F)return s({error:"Branch name is required for worktree creation",isLoading:!1}),null;const A=tx(F);if(!A)return s({error:`Invalid branch name: ${F}`,isLoading:!1}),null;try{const M=await wd({projectDirectory:c,worktreeSlug:A,branch:F,createBranch:!0,startPoint:f}),b=await Re.withDirectory(M.path,()=>Re.createSession({title:`${v.providerID}/${v.modelID}`}));Je.getState().setWorktreeMetadata(b.id,M),p.push({sessionId:b.id,worktreePath:M.path,providerID:v.providerID,modelID:v.modelID})}catch(M){console.warn("[MultiRun] Failed to create session:",M)}}const g=p.map(v=>v.sessionId),y=p[0]?.sessionId??null;if(g.length===0)return s({error:"Failed to create any sessions",isLoading:!1}),null;const x=i?.map(v=>({type:"file",mime:v.mime,filename:v.filename,url:v.url}));return(async()=>{try{await Promise.allSettled(p.map(async v=>{try{await Re.withDirectory(v.worktreePath,()=>Re.sendMessage({id:v.sessionId,providerID:v.providerID,modelID:v.modelID,text:n,agent:a,files:x}))}catch(S){console.warn("[MultiRun] Failed to start run:",S)}}))}catch(v){console.warn("[MultiRun] Failed to start runs:",v)}})(),s({isLoading:!1}),{sessionIds:g,firstSessionId:y}}catch(c){return s({error:c instanceof Error?c.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{s({error:null})}}),{name:"multirun-store"})),Si=()=>{const{providers:s}=ut(),{favoriteModels:r,recentModels:t}=Fe(),n=l.useMemo(()=>r.map(({providerID:a,modelID:i})=>{const c=s.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===i);return u?{provider:c,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null),[r,s]),o=l.useMemo(()=>t.map(({providerID:a,modelID:i})=>{const c=s.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===i);return u?{provider:c,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:i})=>!r.some(c=>c.providerID===a&&c.modelID===i)),[t,s,r]);return{favoriteModelsList:n,recentModelsList:o}},rx=10*1024*1024,nx=5,Ha=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Qd="h-7",ox=({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:O("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",Qd),children:[e.jsx(Xt,{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(Wt,{className:"h-3.5 w-3.5"})})]})},ax=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),ix=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=ax.format(s);return r.endsWith(".0")?r.slice(0,-2):r},lx=({selectedModels:s,onAdd:r,onRemove:t})=>{const{providers:n,modelsMetadata:o}=ut(),{favoriteModelsList:a,recentModelsList:i}=Si(),[c,d]=l.useState(!1),[u,m]=l.useState(""),[f,p]=l.useState(0),h=l.useRef(null),w=l.useRef(null),g=l.useRef([]),y=l.useMemo(()=>{const b=new Map;for(const C of s){const D=`${C.providerID}:${C.modelID}`;b.set(D,(b.get(D)||0)+1)}return b},[s]),x=l.useCallback(b=>s.filter(D=>D.providerID===b.providerID&&D.modelID===b.modelID).findIndex(D=>D.instanceId===b.instanceId)+1,[s]),v=(b,C)=>{const D=`${b}/${C}`;return o.get(D)},S=b=>{const C=b?.name||b?.id||"",D=String(C);return D.length>40?D.substring(0,37)+"...":D},N=l.useCallback((b,C)=>{if(!u.trim())return!0;const D=u.toLowerCase();return b.toLowerCase().includes(D)||C.toLowerCase().includes(D)},[u]),j=l.useMemo(()=>a.filter(({model:b,providerID:C})=>{const P=n.find(L=>L.id===C)?.name||C,R=S(b);return N(R,P)}),[a,n,N]),k=l.useMemo(()=>i.filter(({model:b,providerID:C})=>{const P=n.find(L=>L.id===C)?.name||C,R=S(b);return N(R,P)}),[i,n,N]),F=l.useMemo(()=>n.map(b=>{const D=(Array.isArray(b.models)?b.models:[]).filter(P=>{const R=S(P);return N(R,b.name||b.id||"")});return{...b,models:D}}).filter(b=>b.models.length>0),[n,N]),A=j.length>0||k.length>0||F.length>0;l.useEffect(()=>{c&&h.current&&h.current.focus()},[c]),l.useEffect(()=>{if(!c)return;const b=C=>{w.current&&!w.current.contains(C.target)&&(d(!1),m(""),p(0))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[c]),l.useEffect(()=>{p(0)},[u]);const M=(b,C,D,P,R,L)=>{const q=`${C}:${D}`,te=y.get(q)||0,le=v(C,D),$=ix(le?.limit?.context);return e.jsxs("button",{ref:z=>{g.current[R]=z},type:"button",onClick:()=>{r({providerID:C,modelID:D,displayName:b.name||D,instanceId:Ha()})},onMouseEnter:()=>p(R),className:O("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",L?"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:S(b)}),$&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:$})]}),te>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",te]})]},`${P}-${q}`)};return e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsxs("div",{className:"relative",ref:w,children:[e.jsxs(ve,{type:"button",variant:"outline",size:"sm",className:Qd,onClick:()=>d(!c),children:[e.jsx(Gt,{className:"h-3.5 w-3.5 mr-1"}),"Add model"]}),c&&(()=>{const b=[];j.forEach(({model:R,providerID:L,modelID:q})=>{b.push({model:R,providerID:L,modelID:q,section:"fav"})}),k.forEach(({model:R,providerID:L,modelID:q})=>{b.push({model:R,providerID:L,modelID:q,section:"recent"})}),F.forEach(R=>{R.models.forEach(L=>{b.push({model:L,providerID:R.id,modelID:L.id,section:"provider"})})});const C=b.length,D=R=>{if(R.key==="ArrowDown"){R.preventDefault(),R.stopPropagation();const L=(f+1)%Math.max(1,C);p(L),setTimeout(()=>{g.current[L]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(R.key==="ArrowUp"){R.preventDefault(),R.stopPropagation();const L=(f-1+Math.max(1,C))%Math.max(1,C);p(L),setTimeout(()=>{g.current[L]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(R.key==="Enter"){R.preventDefault(),R.stopPropagation();const L=b[f];L&&r({providerID:L.providerID,modelID:L.modelID,displayName:L.model.name||L.modelID,instanceId:Ha()})}else R.key==="Escape"&&(R.preventDefault(),R.stopPropagation(),d(!1),m(""),p(0))};let P=0;return e.jsxs("div",{className:"absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden bg-background shadow-lg w-[min(380px,calc(100vw-2rem))] flex flex-col",children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{ref:h,type:"text",placeholder:"Search models",value:u,onChange:R=>m(R.target.value),onKeyDown:D,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(tt,{outerClassName:"max-h-[400px] flex-1",children:e.jsxs("div",{className:"p-1",children:[!A&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),j.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(Js,{className:"h-4 w-4 text-primary"}),"Favorites"]}),j.map(({model:R,providerID:L,modelID:q})=>{const te=P++;return M(R,L,q,"fav",te,f===te)})]}),k.length>0&&e.jsxs(e.Fragment,{children:[j.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"]}),k.map(({model:R,providerID:L,modelID:q})=>{const te=P++;return M(R,L,q,"recent",te,f===te)})]}),(j.length>0||k.length>0)&&F.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),F.map((R,L)=>e.jsxs(l.Fragment,{children:[L>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(Xt,{providerId:R.id,className:"h-4 w-4 flex-shrink-0"}),R.name]}),R.models.map(q=>{const te=P++;return M(q,R.id,q.id,"provider",te,f===te)})]},R.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"})]})})()]}),s.map((b,C)=>{const D=`${b.providerID}:${b.modelID}`,P=y.get(D)||1,R=x(b);return e.jsx(ox,{model:b,instanceIndex:R,totalSameModel:P,onRemove:()=>t(C)},b.instanceId)})]})})},Ll=({initialPrompt:s,onCreated:r,onCancel:t})=>{const[n,o]=l.useState(""),[a,i]=l.useState(()=>s??""),[c,d]=l.useState([]),[u,m]=l.useState([]),[f,p]=l.useState(!1),h=l.useRef(null),w=wt(E=>E.currentDirectory??null),g=Fe(E=>E.isSidebarOpen),[y,x]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),v=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const E=typeof window.opencodeDesktop<"u";x(E)},[]);const S=l.useMemo(()=>y&&v?g?"pl-0":"pl-[8.0rem]":"pl-3",[y,v,g]),[N,j]=l.useState("HEAD"),[k,F]=l.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[A,M]=l.useState(!1),[b,C]=l.useState(null),D=ia(E=>E.createMultiRun),P=ia(E=>E.error),R=ia(E=>E.clearError);l.useEffect(()=>{typeof s=="string"&&s.trim().length>0&&i(E=>E.trim().length>0?E:s)},[s]),l.useEffect(()=>{let E=!1;if(!w){C(null),M(!1),F([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),j("HEAD");return}return M(!0),C(null),(async()=>{try{const H=await sn(w);if(E)return;if(C(H),!H){F([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),j("HEAD");return}const Y=await xd(w).catch(()=>null);if(E)return;const fe=[],ne=Y?.current?`Current (HEAD: ${Y.current})`:"Current (HEAD)";fe.push({value:"HEAD",label:ne,group:"special"}),Y&&(Y.all.filter(U=>!U.startsWith("remotes/")).sort((U,ee)=>U.localeCompare(ee)).forEach(U=>{fe.push({value:U,label:U,group:"local"})}),Y.all.filter(U=>U.startsWith("remotes/")).map(U=>U.replace(/^remotes\//,"")).sort((U,ee)=>U.localeCompare(ee)).forEach(U=>{fe.push({value:U,label:U,group:"remote"})})),F(fe),j(pe=>fe.some(je=>je.value===pe)?pe:"HEAD")}finally{E||M(!1)}})(),()=>{E=!0}},[w]);const L=E=>{c.length>=nx||(d(H=>[...H,E]),R())},q=E=>{d(H=>H.filter((Y,fe)=>fe!==E)),R()},te=async E=>{const H=E.target.files;if(!H)return;let Y=0;for(let fe=0;fe<H.length;fe++){const ne=H[fe];if(ne.size>rx){se.error(`File "${ne.name}" is too large (max 10MB)`);continue}try{const pe=await new Promise((U,ee)=>{const oe=new FileReader;oe.onload=()=>U(oe.result),oe.onerror=ee,oe.readAsDataURL(ne)}),je={id:Ha(),filename:ne.name,mimeType:ne.type||"application/octet-stream",size:ne.size,dataUrl:pe};m(U=>[...U,je]),Y++}catch(pe){console.error("File attach failed",pe),se.error(`Failed to attach "${ne.name}"`)}}Y>0&&se.success(`Attached ${Y} file${Y>1?"s":""}`),h.current&&(h.current.value="")},le=E=>{m(H=>H.filter(Y=>Y.id!==E))},$=async E=>{if(E.preventDefault(),!!a.trim()&&!(c.length<2)){p(!0),R();try{const H=c.map(({instanceId:pe,...je})=>je),Y=u.map(pe=>({mime:pe.mimeType,filename:pe.filename,url:pe.dataUrl})),fe={name:n.trim(),prompt:a.trim(),models:H,worktreeBaseBranch:N,files:Y.length>0?Y:void 0},ne=await D(fe);ne&&(ne.firstSessionId&&he.getState().setCurrentSession(ne.firstSessionId),r?.())}finally{p(!1)}}},z=!!(n.trim()&&a.trim()&&c.length>=2&&b&&!A);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:O("flex h-12 items-center justify-between border-b app-region-drag",S),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:O("flex items-center gap-3",y&&v&&g&&"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(Xe,{delayDuration:500,children:[e.jsx(Qe,{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(Wt,{className:"h-5 w-5"})})}),e.jsx(Ye,{children:e.jsx("p",{children:"Close"})})]})})]}),e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"chat-column py-6",children:e.jsxs("form",{onSubmit:$,className:"space-y-6","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:["Group name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(dt,{id:"group-name",value:n,onChange:E=>o(E.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.jsxs(Fs,{value:N,onValueChange:j,disabled:!b||A,children:[e.jsx(Ps,{id:"multirun-worktree-base-branch",size:"lg",className:"max-w-full typography-meta text-foreground",children:e.jsx(jo,{placeholder:A?"Loading branches…":"Select a branch"})}),e.jsxs(Rs,{fitContent:!0,children:[e.jsxs(jr,{children:[e.jsx(Sr,{children:"Default"}),k.filter(E=>E.group==="special").map(E=>e.jsx(Ot,{value:E.value,className:"w-auto whitespace-nowrap",children:E.label},E.value))]}),k.some(E=>E.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(So,{}),e.jsxs(jr,{children:[e.jsx(Sr,{children:"Local branches"}),k.filter(E=>E.group==="local").map(E=>e.jsx(Ot,{value:E.value,className:"w-auto whitespace-nowrap",children:E.label},E.value))]})]}):null,k.some(E=>E.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(So,{}),e.jsxs(jr,{children:[e.jsx(Sr,{children:"Remote branches"}),k.filter(E=>E.group==="remote").map(E=>e.jsx(Ot,{value:E.value,className:"w-auto whitespace-nowrap",children:E.label},E.value))]})]}):null]})]}),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:N||"HEAD"}),"."]}),b===!1?e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."}):null]})]}),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(Ts,{id:"prompt",value:a,onChange:E=>i(E.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:h,type:"file",multiple:!0,className:"hidden",onChange:te,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(ve,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>h.current?.click(),children:[e.jsx(io,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),u.map(E=>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:[E.mimeType.startsWith("image/")?e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(er,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:E.filename,children:E.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",E.size<1024?`${E.size}B`:E.size<1024*1024?`${(E.size/1024).toFixed(1)}KB`:`${(E.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>le(E.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Wt,{className:"h-3.5 w-3.5"})})]},E.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("span",{className:"ml-1 font-normal text-muted-foreground",children:"(select at least 2, maximum 5)"})]}),e.jsx(lx,{selectedModels:c,onAdd:L,onRemove:q})]}),P&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:P}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(ve,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(ve,{type:"submit",disabled:!z||f,children:f?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(Xm,{className:"h-4 w-4 mr-2"}),"Start (",c.length," models)"]})})]})]})})})]})},cx=(s={})=>{const{edgeThreshold:r=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=s,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:c}=Fe(),d=Ne.useRef(null),u=Ne.useRef(null);return Ne.useEffect(()=>{if(!o||!a)return;const m=w=>{const g=w.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=w=>{if(!d.current)return;const g=w.touches[0];if(!g)return;g.clientX-d.current.x>10&&w.preventDefault()},p=w=>{if(!d.current)return;const g=w.changedTouches[0];if(!g){d.current=null,u.current=null;return}u.current={x:g.clientX,y:g.clientY,time:Date.now()};const{x:y,y:x,time:v}=d.current,{x:S,y:N,time:j}=u.current,k=S-y,F=N-x,A=j-v,M=Math.abs(F)<Math.abs(k),b=A<=n,C=Math.abs(F)<t;k>=t&&M&&b&&C&&!c&&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,c]),null},mn=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;Ne.memo(()=>{const s=Ne.useRef(null),{addAttachedFile:r}=he(),{isMobile:t}=Fe(),n=Pd(),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=he.getState().attachedFiles.length;try{await r(p),he.getState().attachedFiles.length>h&&m++}catch(w){console.error("File attach failed",w),se.error(w instanceof Error?w.message:"Failed to attach file")}}m>0&&se.success(`Attached ${m} file${m>1?"s":""}`)},c=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 w=p.map(g=>`${g?.name||"file"}: ${g?.reason||"skipped"}`).join(`
|
|
61
|
+
`);se.error(`Some files were skipped:
|
|
62
|
+
${w}`)}const h=f.map(w=>{if(!w?.dataUrl)return null;try{const[g,y]=w.dataUrl.split(","),x=w.mimeType||g?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!y)return null;const v=atob(y),S=new Uint8Array(v.length);for(let j=0;j<v.length;j++)S[j]=v.charCodeAt(j);const N=new Blob([S],{type:x});return new File([N],w.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:c,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():s.current?.click()},className:O(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(io,{className:O(a,"text-current")})})]})});const dx=Ne.memo(({file:s,onRemove:r})=>{const t=()=>s.mimeType.startsWith("image/")?e.jsx(cr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("text")||s.mimeType.includes("code")?e.jsx(er,{className:"h-3.5 w-3.5"}):s.mimeType.includes("json")||s.mimeType.includes("xml")?e.jsx(Eo,{className:"h-3.5 w-3.5"}):e.jsx(er,{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(Qm,{className:"h-3 w-3 text-primary"}):e.jsx(qc,{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(Wt,{className:"h-3 w-3"})})]})}),ux=Ne.memo(()=>{const{attachedFiles:s,removeAttachedFile:r}=he();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(dx,{file:t,onRemove:()=>r(t.id)},t.id))]})})}),Jd=Ne.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(cr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(er,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Eo,{className:"h-3.5 w-3.5"}):e.jsx(er,{className:"h-3.5 w-3.5"}):e.jsx(er,{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/")),c=l.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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>c(d),className:"relative flex-none w-16 sm:w-20 md:w-24 aspect-square rounded-xl border border-border/40 bg-muted/10 overflow-hidden snap-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[d.url?e.jsx("img",{src:d.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:f=>{const p=f.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(cr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(Ye,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Zd=Ne.memo(({message:s,sessionId:r,onEdit:t})=>{const n=zs(i=>i.removeFromQueue),o=l.useMemo(()=>{const i=s.content.split(`
|
|
63
|
+
`),c=i[0]||"",d=50;return c.length>d?c.substring(0,d)+"...":c+(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(Jm,{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(Wt,{className:"h-3 w-3"})})]})});Zd.displayName="QueuedMessageChip";const Ol=[],eu=Ne.memo(({onEditMessage:s})=>{const r=he(a=>a.currentSessionId),t=zs(l.useCallback(a=>r?a.queuedMessages[r]??Ol:Ol,[r])),n=zs(a=>a.popToInput),o=l.useCallback(a=>{if(!r)return;const i=n(r,a.id);if(i){if(i.attachments&&i.attachments.length>0){const c=Hs.getState().attachedFiles;Hs.setState({attachedFiles:[...c,...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(Zd,{message:a,sessionId:r,onEdit:o},a.id))]})})});eu.displayName="QueuedMessageChips";const tu=(s,r=200)=>{const[t,n]=Ne.useState(s);return Ne.useEffect(()=>{const o=window.setTimeout(()=>{n(s)},r);return()=>{window.clearTimeout(o)}},[s,r]),t},mx=l.forwardRef(({searchQuery:s,onFileSelect:r,onClose:t},n)=>{const{currentDirectory:o}=wt(),{addServerFile:a}=he(),i=di(C=>C.searchFiles),c=tu(s,180),[d,u]=l.useState([]),[m,f]=l.useState(!1),[p,h]=l.useState(0),[w,g]=l.useState(360),[y,x]=l.useState({}),[v,S]=l.useState({}),N=l.useRef([]),j=l.useRef([]),k=l.useRef([]),F=l.useRef(null),A=l.useCallback((C,D)=>{const P=C.trim().toLowerCase();if(!P)return 0;const R=D.toLowerCase();let L=0,q=-1,te=0;for(let le=0;le<P.length;le+=1){const $=P[le];if(!$||$===" ")continue;const z=R.indexOf($,q+1);if(z===-1)return null;const E=z-q-1;if(E===0?te+=1:te=0,L+=10,L+=Math.max(0,18-z),L-=Math.max(0,E),z===0)L+=12;else{const H=R[z-1];(H==="/"||H==="_"||H==="-"||H==="."||H===" ")&&(L+=10)}L+=te>0?12:0,q=z}return L+=Math.max(0,24-Math.round(R.length/3)),L},[]);l.useEffect(()=>{const C=D=>{const P=D.target;!P||!F.current||F.current.contains(P)||t()};return document.addEventListener("pointerdown",C,!0),()=>{document.removeEventListener("pointerdown",C,!0)}},[t]),l.useEffect(()=>{if(!o){u([]);return}const D=(c??"").trim().toLowerCase();let P=!1;return f(!0),i(o,D,80).then(R=>{if(P)return;const L=D?R.map(q=>{const te=q.relativePath||q.name||q.path,le=A(D,te);return le===null?null:{file:q,score:le,labelLength:te.length}}).filter(Boolean):R.map(q=>({file:q,score:0,labelLength:(q.relativePath||q.name||q.path).length}));L.sort((q,te)=>te.score-q.score||q.labelLength-te.labelLength||q.file.path.localeCompare(te.file.path)),u(L.slice(0,15).map(q=>q.file))}).catch(()=>{P||u([])}).finally(()=>{P||f(!1)}),()=>{P=!0}},[o,c,A,i]),l.useEffect(()=>{h(0),x({}),S({})},[d]),l.useEffect(()=>{N.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]),l.useEffect(()=>{let C=null;const D=()=>{C!==null&&cancelAnimationFrame(C),C=requestAnimationFrame(()=>{const P={},R={};j.current.forEach((L,q)=>{if(!L)return;const le=k.current[q]?.offsetWidth??L.scrollWidth,$=Math.max(0,le-L.clientWidth),z=$>8;if(P[q]=z,z){const E=Math.max(.6,$/110);R[q]=E}}),x(P),S(R)})};return D(),window.addEventListener("resize",D),()=>{C!==null&&cancelAnimationFrame(C),window.removeEventListener("resize",D)}},[d]),l.useEffect(()=>{const C=j.current[p];if(!C)return;const D=()=>{const R=C.clientWidth;R>0&&g(R)};if(D(),typeof ResizeObserver>"u")return;const P=new ResizeObserver(D);return P.observe(C),()=>{P.disconnect()}},[p]);const M=l.useCallback(async C=>{await a(C.path,C.name),r(C)},[a,r]);l.useImperativeHandle(n,()=>({handleKeyDown:C=>{if(C==="Escape"){t();return}const D=d.length;if(D!==0){if(C==="ArrowDown"){h(P=>(P+1)%D);return}if(C==="ArrowUp"){h(P=>(P-1+D)%D);return}if(C==="Enter"||C==="Tab"){const P=(p%D+D)%D,R=d[P];R&&M(R)}}}}),[d,p,t,M]);const b=C=>{switch(C.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(Vs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Vs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(er,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(cr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Eo,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:F,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(tt,{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(Mn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((C,D)=>{const P=C.relativePath||C.name,R=ld(P,{maxLength:45}),L=p===D,q=y[D]??!1,te=v[D]??2.6,le=e.jsxs("div",{ref:$=>{N.current[D]=$},className:O("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",L&&"bg-muted"),onClick:()=>M(C),onMouseEnter:()=>h(D),children:[b(C),e.jsxs("span",{ref:$=>{j.current[D]=$},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:L?{"--file-mention-marquee-width":`${w}px`,"--file-mention-marquee-duration":`${te}s`}:void 0,"aria-label":P,children:[e.jsx("span",{ref:$=>{k.current[D]=$},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:P}),q&&L?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:P}):e.jsx("span",{className:"block truncate",children:R})]})]});return e.jsx(l.Fragment,{children:le},C.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"})]})}),su=l.forwardRef(({searchQuery:s,onCommandSelect:r,onClose:t},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=he(si(y=>{const x=y.currentSessionId;return{hasMessagesInCurrentSession:(x?y.messages.get(x)?.length??0:0)>0,currentSessionId:x}})),i=!!a,[c,d]=l.useState([]),[u,m]=l.useState(!1),[f,p]=l.useState(0),h=l.useRef([]),w=l.useRef(null);l.useEffect(()=>{const y=x=>{const v=x.target;!v||!w.current||w.current.contains(v)||t()};return document.addEventListener("pointerdown",y,!0),()=>{document.removeEventListener("pointerdown",y,!0)}},[t]),l.useEffect(()=>{(async()=>{m(!0);try{const v=(await Re.listCommands()).map(A=>({name:A.name,description:A.description,agent:A.agent,model:A.model,isBuiltIn:!1})),S=[...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}],N=new Map;S.forEach(A=>N.set(A.name,A)),v.forEach(A=>N.set(A.name,A));const j=Array.from(N.values()),k=!o,F=(s?j.filter(A=>A.name.toLowerCase().includes(s.toLowerCase())||A.description&&A.description.toLowerCase().includes(s.toLowerCase())):j).filter(A=>k||A.name!=="init");F.sort((A,M)=>{const b=A.name.toLowerCase().startsWith(s.toLowerCase()),C=M.name.toLowerCase().startsWith(s.toLowerCase());return b&&!C?-1:!b&&C?1:A.name.localeCompare(M.name)}),d(F)}catch{const x=!o,v=[...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=(s?v.filter(N=>N.name.toLowerCase().includes(s.toLowerCase())||N.description&&N.description.toLowerCase().includes(s.toLowerCase())):v).filter(N=>x||N.name!=="init");d(S)}finally{m(!1)}})()},[s,o,i]),l.useEffect(()=>{p(0)},[c]),l.useEffect(()=>{h.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),l.useImperativeHandle(n,()=>({handleKeyDown:y=>{const x=c.length;if(y==="Escape"){t();return}if(x!==0){if(y==="ArrowDown"){p(v=>(v+1)%x);return}if(y==="ArrowUp"){p(v=>(v-1+x)%x);return}if(y==="Enter"||y==="Tab"){const v=(f%x+x)%x,S=c[v];S&&r(S)}}}}),[c,f,t,r]);const g=y=>{switch(y.name){case"init":return e.jsx(er,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(yn,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(tf,{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(ef,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(mr,{className:"h-3.5 w-3.5 text-cyan-500"});default:return y.isBuiltIn?e.jsx(Zm,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(Dr,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:w,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(tt,{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(Mn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[c.map((y,x)=>e.jsxs("div",{ref:v=>{h.current[x]=v},className:O("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",x===f&&"bg-muted"),onClick:()=>r(y),onMouseEnter:()=>p(x),children:[e.jsx("div",{className:"mt-0.5",children:g(y)}),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:["/",y.name]}),y.agent&&e.jsx("span",{className:"typography-meta text-muted-foreground bg-muted px-1.5 py-0.5 rounded",children:y.agent})]}),y.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:y.description})]})]},y.name)),c.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});su.displayName="CommandAutocomplete";const fx=s=>s?s!=="primary":!1,ru=l.forwardRef(({searchQuery:s,onAgentSelect:r,onClose:t},n)=>{const o=l.useRef(null),[a,i]=l.useState(0),[c,d]=l.useState([]),{getVisibleAgents:u}=ut();l.useEffect(()=>{const p=u().filter(g=>fx(g.mode)).map(g=>({name:g.name,description:g.description,mode:g.mode??void 0})),h=s.trim().toLowerCase(),w=h.length?p.filter(g=>g.name.toLowerCase().includes(h)):p;w.sort((g,y)=>g.name.localeCompare(y.name)),d(w),i(0)},[u,s]),l.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]),l.useImperativeHandle(n,()=>({handleKeyDown:f=>{if(f==="Escape"){t();return}if(c.length){if(f==="ArrowDown"){i(p=>(p+1)%c.length);return}if(f==="ArrowUp"){i(p=>(p-1+c.length)%c.length);return}if(f==="Enter"||f==="Tab"){const p=c[(a+c.length)%c.length];p&&r(p.name)}}}}),[c,r,t,a]);const m=(f,p)=>e.jsx("div",{className:O("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(tt,{outerClassName:"flex-1 min-h-0",className:"px-0",children:c.length?e.jsx("div",{children:c.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"})]})});ru.displayName="AgentMentionAutocomplete";function px({className:s,children:r,...t}){return e.jsxs(sf,{"data-slot":"scroll-area",className:O("relative",s),...t,children:[e.jsx(rf,{"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(hx,{}),e.jsx(nf,{})]})}function hx({className:s,orientation:r="vertical",...t}){return e.jsx(of,{"data-slot":"scroll-area-scrollbar",orientation:r,className:O("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(af,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const gx=({onFilesSelected:s,multiSelect:r=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=Ct(),c=i,{currentDirectory:d}=wt(),u=di(T=>T.searchFiles),[m,f]=l.useState(!1),[p,h]=l.useState(!1),[w,g]=l.useState(""),y=tu(w,200),[x,v]=l.useState(new Set),[S,N]=l.useState(new Set),[j,k]=l.useState({}),F=l.useRef(new Set),A=l.useRef(new Set),[M,b]=l.useState([]),[C,D]=l.useState(!1),[P,R]=l.useState(!1),[L,q]=l.useState(!1),[te,le]=l.useState(null),$=n??m,z=o??f,E=l.useCallback(T=>T.slice().sort((X,I)=>X.type!==I.type?X.type==="directory"?-1:1:X.name.localeCompare(I.name)),[]),H=l.useCallback((T,X)=>E(X.filter(I=>!I.name.startsWith(".")).map(I=>{const B=I.name,G=!I.isDirectory&&B.includes(".")?B.split(".").pop()?.toLowerCase():void 0;return{name:B,path:I.path||`${T}/${B}`,type:I.isDirectory?"directory":"file",size:0,extension:G}})),[E]),Y=l.useCallback(async T=>{R(!0),le(null);try{const X=await Re.listLocalDirectory(T),I=H(T,X.map(B=>({name:B.name,path:B.path,isDirectory:B.isDirectory})));F.current=new Set([T]),A.current=new Set,k({[T]:I}),N(new Set)}catch{le("Failed to load directory contents"),F.current=new Set([T]),A.current=new Set,k({[T]:[]}),N(new Set)}finally{R(!1)}},[H]),fe=l.useCallback(async T=>{const X=T.trim();if(X&&!F.current.has(X)&&!A.current.has(X)){A.current=new Set(A.current),A.current.add(X);try{const I=await Re.listLocalDirectory(X),B=H(X,I.map(G=>({name:G.name,path:G.path,isDirectory:G.isDirectory})));F.current=new Set(F.current),F.current.add(X),k(G=>({...G,[X]:B}))}catch{k(I=>I[X]?I:{...I,[X]:[]})}finally{A.current=new Set(A.current),A.current.delete(X)}}},[H]);l.useEffect(()=>{($||p)&&d&&Y(d)},[$,p,d,Y]),l.useEffect(()=>{if(!($||p)||!d){b([]),D(!1);return}const T=y.trim();if(!T){b([]),D(!1);return}let X=!1;return D(!0),u(d,T,150).then(I=>{if(X)return;const B=I.map(G=>({name:G.name,path:G.path,type:"file",extension:G.extension,relativePath:G.relativePath,size:0}));b(B)}).catch(()=>{X||b([])}).finally(()=>{X||D(!1)}),()=>{X=!0}},[$,p,d,y,u]),l.useEffect(()=>{!$&&!p&&(v(new Set),g(""),b([]),D(!1))},[$,p]);const ne=T=>{if(T.type==="directory")return S.has(T.path)?e.jsx(gs,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(gs,{className:"h-3.5 w-3.5 text-primary/60"});switch(T.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(Vs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Vs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Aa,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(cr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Aa,{className:"h-3.5 w-3.5 text-muted-foreground"})}},pe=async T=>{S.has(T)?N(I=>{const B=new Set(I);return B.delete(T),B}):(N(I=>{const B=new Set(I);return B.add(T),B}),await fe(T))},je=T=>{v(r?X=>{const I=new Set(X);return I.has(T)?I.delete(T):I.add(T),I}:new Set([T]))},U=async()=>{const T=new Map;Object.values(j).forEach(B=>{B.forEach(G=>{G.type==="file"&&T.set(G.path,G)})});const X=new Map(M.map(B=>[B.path,B])),I=Array.from(x).map(B=>T.get(B)??X.get(B)).filter(B=>!!B);q(!0);try{await s(I),v(new Set),z(!1),h(!1)}finally{q(!1)}},ee=l.useMemo(()=>d?j[d]??[]:[],[j,d]),oe=w.trim().length>0,W=T=>j[T]??[],me=T=>{if(d&&T.startsWith(d)){const X=T.substring(d.length);return X.startsWith("/")?X.substring(1):X}return T.split("/").pop()||T},ye=(T,X)=>{const I=oe?T.relativePath||me(T.path):T.name,B=oe&&I.includes("/")&&I.length>45,G=B?ld(I,{maxLength:c?42:48}):I,be=e.jsxs("div",{className:O("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",T.type==="file"&&x.has(T.path)&&"bg-primary/10"),style:{paddingLeft:`${X*12}px`},onClick:J=>{J.preventDefault(),J.stopPropagation(),T.type==="file"&&je(T.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ne(T)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":I,children:G})]}),T.type==="file"&&x.has(T.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return B?e.jsxs(Xe,{delayDuration:120,children:[e.jsx(Qe,{asChild:!0,children:be}),e.jsx(Ye,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:I})})]},T.path):l.cloneElement(be,{key:T.path})},ce=(T,X)=>{const I=T.type==="directory",B=I?W(T.path):[],G=S.has(T.path),be=I&&G&&A.current.has(T.path)&&B.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:O("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!I&&x.has(T.path)&&"bg-primary/10"),style:{paddingLeft:`${X*12}px`},onClick:J=>{J.preventDefault(),J.stopPropagation(),I?pe(T.path):je(T.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ne(T)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:T.name}),!I&&x.has(T.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),I&&G&&B.length>0&&e.jsx("div",{children:B.map(J=>ce(J,X+1))}),I&&G&&be&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(X+1)*12}px`},children:"Loading…"})]},T.path)},Me=x.size>0?`${x.size} file${x.size!==1?"s":""} selected`:"No files selected",Ee=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(ve,{size:"sm",onClick:U,disabled:x.size===0||L,className:"h-6 typography-meta",children:L?"Attaching...":"Attach Files"})]}),Pe=c?"flex-1 min-h-[240px]":"h-[300px]",V=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsx("div",{className:"font-medium typography-ui-label text-foreground",children:"Select Project Files"})}),e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(lr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{value:w,onChange:T=>g(T.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:T=>T.stopPropagation()}),w&&e.jsx("button",{onClick:T=>{T.stopPropagation(),g("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(Wt,{className:"h-3 w-3"})})]})}),e.jsxs(px,{className:Pe,children:[P&&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..."})}),te&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:te})}),!P&&!te&&e.jsxs("div",{className:"py-1 px-2",children:[oe?C?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):M.map(T=>ye(T,0)):ee.map(T=>ce(T,0)),!oe&&ee.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),oe&&!C&&M.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),K=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:T=>{T.preventDefault(),T.stopPropagation(),h(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:T=>{T.preventDefault(),T.stopPropagation(),z(!0)},children:t}):null,e.jsx(ps,{open:$,onClose:()=>z(!1),title:"Select Project Files",footer:Ee,children:e.jsx("div",{className:"flex flex-col gap-0",children:V})})]}):c?e.jsxs(e.Fragment,{children:[K,e.jsx(ps,{open:p,onClose:()=>h(!1),title:"Select Project Files",footer:Ee,children:e.jsx("div",{className:"flex flex-col gap-0",children:V})})]}):e.jsxs(Jt,{open:$,onOpenChange:z,children:[e.jsx(Zt,{asChild:!0,children:t}),e.jsxs(es,{className:O("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[V,e.jsx(Us,{}),Ee]})]})},Hn=[{var:"--status-success",class:"agent-success"},{var:"--syntax-keyword",class:"agent-keyword"},{var:"--syntax-type",class:"agent-type"},{var:"--syntax-function",class:"agent-function"},{var:"--syntax-number",class:"agent-number"},{var:"--status-info",class:"agent-info"},{var:"--status-warning",class:"agent-warning"},{var:"--syntax-variable",class:"agent-variable"}];function or(s){if(!s||s==="build")return Hn[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)%(Hn.length-1);return Hn[t]}const xx=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),nu=s=>xx(s),yx=s=>s?typeof s=="string"?s==="ask":nu(s)?Object.values(s).some(r=>r==="ask"):!1:!1,bx=s=>s?typeof s=="string"?s==="deny":nu(s)?Object.values(s).some(r=>r==="deny"):!1:!1,ou=({agentDefaultEditMode:s,webfetchPermission:r,bashPermission:t})=>{const n=yx(t),o=bx(t),a=!n&&!o,i=r==="allow",c=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"&&c&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:c}},Un=s=>s==="primary"||s==="all"||s===void 0||s===null,wx=[{key:"tool_call",icon:Io,label:"Tool calling",isActive:s=>s?.tool_call===!0},{key:"reasoning",icon:Jr,label:"Reasoning",isActive:s=>s?.reasoning===!0}],vx={text:{icon:Kc,label:"Text"},image:{icon:cr,label:"Image"},video:{icon:cf,label:"Video"},audio:{icon:lf,label:"Audio"},pdf:{icon:Eo,label:"PDF"}},jx=s=>s.trim().toLowerCase(),dn=(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=>jx(o)))).map(o=>{const a=vx[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Sx=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),kx=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),ks=s=>{if(typeof s!="number"||Number.isNaN(s))return"—";if(s===0)return"0";const r=Sx.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Wn=s=>typeof s!="number"||!Number.isFinite(s)?"—":kx.format(s),la=s=>wx.filter(r=>r.isActive(s)).map(r=>({key:r.key,icon:r.icon,label:r.label})),$l=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},_l=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)},Bl=({className:s})=>{const{providers:r,currentProviderId:t,currentModelId:n,currentAgentName:o,setProvider:a,setModel:i,setAgent:c,getCurrentProvider:d,getModelMetadata:u,getCurrentAgent:m,getVisibleAgents:f}=ut(),p=f(),{currentSessionId:h,messages:w,saveSessionAgentSelection:g,getSessionAgentSelection:y,saveAgentModelForSession:x,getAgentModelForSession:v,analyzeAndSaveExternalSessionChoices:S,getSessionAgentEditMode:N,setSessionAgentEditMode:j}=he(),k=gt(xe=>xe.hasHydrated),{toggleFavoriteModel:F,isFavoriteModel:A,addRecentModel:M,isModelSelectorOpen:b,setModelSelectorOpen:C}=Fe(),{favoriteModelsList:D,recentModelsList:P}=Si(),{isMobile:R}=Ct(),L=og(),q=Pd(),te=R,[le,$]=l.useState(null),[z,E]=l.useState(null),[H,Y]=l.useState(""),fe=l.useCallback(()=>$(null),[]),ne=l.useCallback(()=>E(null),[]),pe=l.useRef(void 0),[je,U]=l.useState(()=>{const xe=new Set;return t&&xe.add(t),xe}),[ee,oe]=l.useState(!1),W=b,me=C,[ye,ce]=l.useState(!1),Me=l.useId(),[Ee,Pe]=l.useState(""),[V,K]=l.useState(0),T=l.useRef([]);l.useEffect(()=>{le==="model"&&U(()=>{const xe=new Set;return t&&xe.add(t),xe})},[le,t]),l.useEffect(()=>{le!=="agent"&&oe(!1),le!=="model"&&Y("")},[le]);const X=l.useRef(W);l.useEffect(()=>{const xe=X.current;X.current=W,W||(ce(!1),Pe(""),K(0),xe&&!te&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[W,te]),l.useEffect(()=>{K(0)},[Ee]);const I=m?.(),B=I?.permission?.edit;let G="ask";(B==="allow"||B==="ask"||B==="deny"||B==="full")&&(G=B);const be=I?I.tools?.edit!==!1:!1;(!I||!be)&&(G="deny");const J=I?.permission?.webfetch,ge=I?.permission?.bash,He=l.useMemo(()=>ou({agentDefaultEditMode:G,webfetchPermission:J,bashPermission:ge}),[G,J,ge]),{cascadeDefaultMode:We,modeAvailability:Be,autoApproveAvailable:Ze}=He,it=!!(h&&o),lt=it&&h&&o?N(h,o,We):We,ct={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},mt=l.useCallback(xe=>!Be[xe],[Be]),xt=l.useMemo(()=>!it||mt(lt)&<!==We?We:lt,[We,mt,it,lt]),vt=[{mode:"ask",label:ct.ask,disabled:mt("ask")},{mode:"allow",label:ct.allow,disabled:mt("allow")},{mode:"full",label:ct.full,disabled:mt("full")}],ht=l.useMemo(()=>mn(xt),[xt]),yt=!it||!Ze;l.useEffect(()=>{yt&&(oe(!1),ce(!1))},[yt]);const Q=R?"mobile":q?"vscode":"default",De=Q==="mobile"?"h-9":Q==="vscode"?"h-6":"h-8",re=Q==="mobile"?"h-5 w-5":"h-4 w-4",ae=Q==="mobile"?"h-5 w-5":"h-4 w-4",Ie=te?"typography-micro":"typography-meta",_e=Q==="mobile"?"gap-x-2":Q==="vscode"?"gap-x-1":"gap-x-3",ze=ct[xt],Ge=l.useCallback((xe,_=re)=>{const Z=O(_,"flex-shrink-0"),we=mn(xe),$e={color:we?we.text:"var(--foreground)"};return xe==="full"?e.jsx(Qs,{className:Z,style:$e}):xe==="allow"?e.jsx(Xn,{className:Z,style:$e}):xe==="deny"?e.jsx(Kr,{className:Z,style:$e}):e.jsx(Gr,{className:Z,style:$e})},[re]),rt=l.useCallback(xe=>{yt||!h||!o||mt(xe)||(j(h,o,xe,We),me(!1),oe(!1),ce(!1))},[We,yt,h,o,j,me,ce,mt]),ie=d(),ue=Array.isArray(ie?.models)?ie.models:[],Se=t&&n?u(t,n):void 0,Ce=la(Se),Te=dn(Se,"input"),Ue=dn(Se,"output"),bt=[{label:"Input",value:Wn(Se?.cost?.input)},{label:"Output",value:Wn(Se?.cost?.output)},{label:"Cache read",value:Wn(Se?.cost?.cache_read)},{label:"Cache write",value:Wn(Se?.cost?.cache_write)}],At=[{label:"Context",value:ks(Se?.limit?.context)},{label:"Output",value:ks(Se?.limit?.output)}],Mt=l.useRef(void 0),pt=h?w.get(h)?.length??-1:-1,st=l.useRef(null),jt=l.useCallback((xe,_,Z)=>{if(!xe||!_)return"model-missing";const we=r.find(de=>de.id===xe);return we?(Array.isArray(we.models)?we.models:[]).find(de=>de.id===_)?(a(xe),i(_),h&&Z&&x(h,Z,xe,_),"applied"):"model-missing":"provider-missing"},[r,a,i,h,x]);l.useEffect(()=>{if(!h){st.current=null;return}if(!k||r.length===0||p.length===0)return;(!st.current||st.current.sessionId!==h)&&(st.current={sessionId:h,resolved:!1,inFlight:!1});const xe=st.current;if(!xe||xe.resolved||xe.inFlight)return;let _=!1;const Z=()=>{if(_)return;const de=st.current;de&&de.sessionId===h&&(de.resolved=!0,de.inFlight=!1)},we=()=>{const de=y(h);if(de){o!==de&&c(de);const Le=v(h,de);if(Le){const ke=jt(Le.providerId,Le.modelId,de);if(ke==="applied")return"resolved";if(ke==="provider-missing")return"waiting"}else return"resolved"}for(const Le of p){const ke=v(h,Le.name);if(!ke)continue;o!==Le.name&&c(Le.name),g(h,Le.name);const Ve=jt(ke.providerId,ke.modelId,Le.name);if(Ve==="applied")return"resolved";if(Ve==="provider-missing")return"waiting"}return"continue"},Oe=()=>{if(p.length===0)return;const de=p.filter(ke=>Un(ke.mode)),Le=p.find(ke=>ke.name==="build")||de[0]||p[0];Le&&(g(h,Le.name),o!==Le.name&&c(Le.name),Le.model?.providerID&&Le.model?.modelID&&jt(Le.model.providerID,Le.model.modelID,Le.name))};return(async()=>{try{const de=we();if(de==="resolved"){Z();return}if(de==="waiting"||pt===-1)return;if(pt>0){xe.inFlight=!0;try{const Le=await S(h,p);if(_)return;if(Le.size>0){let ke=null,Ve=-1/0;for(const[et,nt]of Le)nt.timestamp>Ve&&(Ve=nt.timestamp,ke=et);if(ke){g(h,ke),o!==ke&&c(ke);const et=Le.get(ke);if(et){const nt=jt(et.providerId,et.modelId,ke);if(nt==="applied"){Z();return}if(nt==="provider-missing")return}else{Z();return}}}}catch(Le){_||console.error("[ModelControls] Error resolving session from messages:",Le)}finally{const Le=st.current;!_&&Le&&Le.sessionId===h&&(Le.inFlight=!1)}}Oe(),Z()}catch(de){_||console.error("[ModelControls] Error in session switch:",de)}})(),()=>{_=!0}},[h,pt,p,o,y,v,c,jt,S,g,k,r]),l.useEffect(()=>{if(!k||!h||r.length===0||p.length===0)return;const _=y(h)||o;if(!_)return;const Z=v(h,_);if(!Z)return;const we=r.find(Le=>Le.id===Z.providerId);if(!we||!(Array.isArray(we.models)?we.models.some(Le=>Le.id===Z.modelId):!1))return;const $e=t===Z.providerId,de=n===Z.modelId;$e&&de||(_!==o&&c(_),jt(Z.providerId,Z.modelId,_))},[k,h,o,t,n,r,p,y,v,jt,c]),l.useEffect(()=>{if(!k)return;(async()=>{try{if(o!==Mt.current&&(Mt.current=o,o&&h)){await new Promise(we=>setTimeout(we,50));const _=v(h,o);if(_){const we=jt(_.providerId,_.modelId,o);if(we==="applied"||we==="provider-missing")return}const Z=p.find(we=>we.name===o);if(Z?.model?.providerID&&Z?.model?.modelID&&jt(Z.model.providerID,Z.model.modelID,o)==="provider-missing")return}}catch(_){console.error("[ModelControls] Agent change error:",_)}})()},[o,h,v,jt,p,k]);const Ft=xe=>{try{c(xe),me(!1),h&&g(h,xe),te&&fe()}catch(_){console.error("[ModelControls] Handle agent change error:",_)}},ot=(xe,_)=>{try{const Z=jt(xe,_,o||void 0);if(Z!=="applied"){Z==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",xe):Z==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:xe,modelId:_});return}M(xe,_),me(!1),te&&fe(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(Z){console.error("[ModelControls] Handle model change error:",Z)}},Ae=xe=>{const _=typeof xe?.name=="string"?xe.name:typeof xe?.id=="string"?xe.id:"";return _.length>40?_.substring(0,37)+"...":_},qe=()=>r.find(_=>_.id===t)?.name||t,Ke=()=>{if(!t||!n||ue.length===0)return"Not selected";const xe=ue.find(_=>_.id===n);return Ae(xe)},ft=()=>{if(!o){const _=p.filter(Oe=>Un(Oe.mode)),we=_.find(Oe=>Oe.name==="build")||_[0];return we?St(we.name):"Select Agent"}const xe=p.find(_=>_.name===o);return St(xe?xe.name:o)},St=xe=>xe.charAt(0).toUpperCase()+xe.slice(1),Pt=(xe,_,Z)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:_,"aria-label":_,role:"img",children:e.jsx(xe,{className:"h-3.5 w-3.5"})},Z),cs=l.useCallback(xe=>{U(_=>{const Z=new Set(_);return Z.has(xe)?Z.delete(xe):Z.add(xe),Z})},[]),Os=l.useCallback(xe=>{pe.current&&clearTimeout(pe.current),pe.current=setTimeout(()=>{E(xe)},500)},[]),Ss=l.useCallback(()=>{pe.current&&clearTimeout(pe.current)},[]);l.useEffect(()=>()=>{pe.current&&clearTimeout(pe.current)},[]);const nn=()=>!te||z!=="model"?null:e.jsx(ps,{open:!0,onClose:ne,title:Se?.name||Ke(),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:qe()})]}),Ce.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:Ce.map(({key:xe,icon:_,label:Z})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Pt(_,Z,`cap-${xe}`),e.jsx("span",{className:"typography-meta text-foreground",children:Z})]},xe))})]}),(Te.length>0||Ue.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:[Te.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Input"}),e.jsx("div",{className:"flex gap-1",children:Te.map(({key:xe,icon:_,label:Z})=>Pt(_,`${Z} input`,`input-${xe}`))})]}),Ue.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:Ue.map(({key:xe,icon:_,label:Z})=>Pt(_,`${Z} output`,`output-${xe}`))})]})]})]}),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:ks(Se?.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:ks(Se?.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:$l(Se?.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:_l(Se?.release_date)})]})]})]})]})}),Oo=()=>{if(!te||z!=="agent"||!I)return null;const xe=Object.entries(I.tools||{}).filter(([,de])=>de).map(([de])=>de).sort(),_=!!(I.prompt&&I.prompt.trim().length>0),Z=I.model?.providerID&&I.model?.modelID,we=I.temperature!==void 0||I.topP!==void 0,Oe=de=>Ge(de==="full"||de==="allow"||de==="deny"?de:"ask","h-3.5 w-3.5"),$e=de=>de==="full"?"Full":de==="allow"?"Allow":de==="deny"?"Deny":"Ask";return e.jsx(ps,{open:!0,onClose:ne,title:St(I.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[I.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:I.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:I.mode==="primary"?"Primary":I.mode==="subagent"?"Subagent":I.mode==="all"?"All":"—"})]}),(Z||we)&&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"}),Z&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[I.model.providerID," / ",I.model.modelID]}),we&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[I.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:I.temperature})]}),I.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:I.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:"Tools"}),xe.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:xe.map(de=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:de},de))}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),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:[Oe(I.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:$e(I.permission?.edit)})]})]}),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:[Oe(typeof I.permission?.bash=="string"?I.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:$e(typeof I.permission?.bash=="string"?I.permission.bash:void 0)})]})]}),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:[Oe(I.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:$e(I.permission?.webfetch)})]})]})]})]}),_&&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(Xn,{className:"h-4 w-4 text-foreground"})]})})]})})},$o=()=>{if(!te)return null;const xe=H.trim().toLowerCase(),_=r.map(Z=>{const we=Array.isArray(Z.models)?Z.models:[],Oe=xe.length===0?!0:Z.name.toLowerCase().includes(xe)||Z.id.toLowerCase().includes(xe),$e=xe.length===0?we:we.filter(de=>{const Le=Ae(de).toLowerCase(),ke=typeof de.id=="string"?de.id.toLowerCase():"";return Le.includes(xe)||ke.includes(xe)});return{provider:Z,providerModels:$e,matchesProvider:Oe}}).filter(({matchesProvider:Z,providerModels:we})=>Z||we.length>0);return e.jsx(ps,{open:le==="model",onClose:fe,title:"Select model",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"relative",children:[e.jsx(lr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{value:H,onChange:Z=>Y(Z.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),H&&e.jsx("button",{type:"button",onClick:()=>Y(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Kr,{className:"h-4 w-4"})})]})}),_.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."}),!H&&D.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(Js,{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:D.map(({model:Z,providerID:we,modelID:Oe})=>{const $e=we===t&&Oe===n,de=u(we,Oe);return e.jsxs("button",{type:"button",onClick:()=>ot(we,Oe),className:O("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(Xt,{providerId:we,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ae(Z)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(de?.limit?.context||de?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[de?.limit?.context?`${ks(de?.limit?.context)} ctx`:"",de?.limit?.context&&de?.limit?.output?" • ":"",de?.limit?.output?`${ks(de?.limit?.output)} out`:""]})})]},`fav-mobile-${we}-${Oe}`)})})]}),!H&&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(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:P.map(({model:Z,providerID:we,modelID:Oe})=>{const $e=we===t&&Oe===n,de=u(we,Oe);return e.jsxs("button",{type:"button",onClick:()=>ot(we,Oe),className:O("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(Xt,{providerId:we,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ae(Z)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(de?.limit?.context||de?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[de?.limit?.context?`${ks(de?.limit?.context)} ctx`:"",de?.limit?.context&&de?.limit?.output?" • ":"",de?.limit?.output?`${ks(de?.limit?.output)} out`:""]})})]},`recent-mobile-${we}-${Oe}`)})})]}),_.map(({provider:Z,providerModels:we})=>{if(we.length===0&&!xe.length)return null;const Oe=Z.id===t,$e=je.has(Z.id)||xe.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:()=>cs(Z.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(Xt,{providerId:Z.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Z.name}),Oe&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),$e?e.jsx(Nt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(As,{className:"h-3 w-3 text-muted-foreground"})]}),$e&&we.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:we.map(de=>{const Le=Oe&&de.id===n,ke=u(Z.id,de.id),Ve=la(ke).slice(0,3),et=dn(ke,"input");return e.jsxs("div",{className:O("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",!Le&&"hover:bg-muted",Le?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>ot(Z.id,de.id),className:O("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:Ae(de)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(ke?.limit?.context||ke?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[ke?.limit?.context?e.jsxs("span",{children:[ks(ke?.limit?.context)," ctx"]}):null,ke?.limit?.context&&ke?.limit?.output?e.jsx("span",{children:"•"}):null,ke?.limit?.output?e.jsxs("span",{children:[ks(ke?.limit?.output)," out"]}):null]}),(Ve.length>0||et.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Ve,...et].map(({key:nt,icon:ts,label:Rt})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Rt,"aria-label":Rt,children:e.jsx(ts,{className:"h-3 w-3"})},`meta-${Z.id}-${de.id}-${nt}`))})]})]}),e.jsx("button",{type:"button",onClick:nt=>{nt.preventDefault(),nt.stopPropagation(),F(Z.id,de.id)},className:O("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",A(Z.id,de.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":A(Z.id,de.id)?"Unfavorite":"Favorite",title:A(Z.id,de.id)?"Remove from favorites":"Add to favorites",children:A(Z.id,de.id)?e.jsx(Js,{className:"h-4 w-4"}):e.jsx(Hr,{className:"h-4 w-4"})})]},de.id)})})]},Z.id)})]})})},pr=()=>{if(!te)return null;const xe=p.filter(_=>Un(_.mode));return e.jsx(ps,{open:le==="agent",onClose:fe,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[xe.map(_=>{const Z=_.name===o,we=or(_.name);return e.jsxs("button",{type:"button",className:O("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",we.class,Z?"active":"border-border/40"),onClick:()=>Ft(_.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:O("h-2 w-2 rounded-full",we.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:Z?{color:`var(${we.var})`}:void 0,children:St(_.name)})]}),_.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:_.description})]},_.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:yt,onClick:()=>{yt||oe(_=>!_)},className:O("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",yt?"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:ht?ht.text:"var(--foreground)",mixBlendMode:"normal"},children:ze})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:O("flex items-center justify-center p-1",!ht&&"text-muted-foreground"),style:ht?{color:ht.text}:void 0,children:Ge(xt,re)}),e.jsx(Nt,{className:O("h-4 w-4 text-muted-foreground transition-transform",ee?"rotate-180":"")})]})]}),ee&&!yt&&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:vt.map(_=>{const Z=_.mode===xt,we=mn(_.mode);return e.jsxs("button",{type:"button",disabled:_.disabled,onClick:()=>rt(_.mode),className:O("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",_.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",Z?"bg-primary/10":void 0),style:Z&&we?{backgroundColor:we.background??void 0}:void 0,children:[Ge(_.mode,re),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:we?we.text:"var(--foreground)"},children:_.label})})]},_.mode)})})})]})]})})},hr=()=>e.jsx(Ye,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Se?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:Se.name||Ke()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:qe()})]}),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:Ce.length>0?Ce.map(({key:xe,icon:_,label:Z})=>Pt(_,Z,`cap-${xe}`)):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:Te.length>0?Te.map(({key:xe,icon:_,label:Z})=>Pt(_,`${Z} input`,`input-${xe}`)):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:Ue.length>0?Ue.map(({key:xe,icon:_,label:Z})=>Pt(_,`${Z} output`,`output-${xe}`)):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)"}),bt.map(xe=>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:xe.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:xe.value})]},xe.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),At.map(xe=>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:xe.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:xe.value})]},xe.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:$l(Se.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:_l(Se.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),Dn=(xe,_,Z,we,Oe,$e)=>{const de=u(_,Z),Le=la(de).map(Lt=>({...Lt,id:`cap-${Lt.key}`})),ke=[...dn(de,"input"),...dn(de,"output")],Ve=Array.from(new Map(ke.map(Lt=>[Lt.key,Lt])).values()).map(Lt=>({...Lt,id:`mod-${Lt.key}`})),et=[...Le,...Ve],nt=ks(de?.limit?.context),ts=t===_&&n===Z,Rt=A(_,Z);return e.jsxs("div",{ref:Lt=>{T.current[Oe]=Lt},className:O("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:()=>ot(_,Z),onMouseEnter:()=>K(Oe),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:Ae(xe)}),de?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:nt}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[et.length>0&&e.jsx("div",{className:O("items-center gap-0.5",$e?"flex":"hidden group-hover:flex"),children:et.map(({id:Lt,icon:Vu,label:Ri})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":Ri,role:"img",title:Ri,children:e.jsx(Vu,{className:"h-2.5 w-2.5"})},Lt))}),ts&&e.jsx(Dt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:Lt=>{Lt.preventDefault(),Lt.stopPropagation(),F(_,Z)},className:O("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Rt?"text-yellow-500":"text-muted-foreground"),"aria-label":Rt?"Unfavorite":"Favorite",title:Rt?"Remove from favorites":"Add to favorites",children:Rt?e.jsx(Js,{className:"h-3.5 w-3.5"}):e.jsx(Hr,{className:"h-3.5 w-3.5"})})]})]},`${we}-${_}-${Z}`)},Pr=(xe,_,Z)=>{if(!Z.trim())return!0;const we=Z.toLowerCase();return xe.toLowerCase().includes(we)||_.toLowerCase().includes(we)},_o=()=>{const xe=D.filter(({model:ke,providerID:Ve})=>{const nt=r.find(Rt=>Rt.id===Ve)?.name||Ve,ts=Ae(ke);return Pr(ts,nt,Ee)}),_=P.filter(({model:ke,providerID:Ve})=>{const nt=r.find(Rt=>Rt.id===Ve)?.name||Ve,ts=Ae(ke);return Pr(ts,nt,Ee)}),Z=r.map(ke=>{const et=(Array.isArray(ke.models)?ke.models:[]).filter(nt=>{const ts=Ae(nt);return Pr(ts,ke.name||ke.id||"",Ee)});return{...ke,models:et}}).filter(ke=>ke.models.length>0),we=xe.length>0||_.length>0||Z.length>0,Oe=[];xe.forEach(({model:ke,providerID:Ve,modelID:et})=>{Oe.push({model:ke,providerID:Ve,modelID:et,section:"fav"})}),_.forEach(({model:ke,providerID:Ve,modelID:et})=>{Oe.push({model:ke,providerID:Ve,modelID:et,section:"recent"})}),Z.forEach(ke=>{ke.models.forEach(Ve=>{Oe.push({model:Ve,providerID:ke.id,modelID:Ve.id,section:"provider"})})});const $e=Oe.length,de=ke=>{if(ke.key==="ArrowDown")ke.preventDefault(),ke.stopPropagation(),K(Ve=>(Ve+1)%Math.max(1,$e)),setTimeout(()=>{const Ve=(V+1)%Math.max(1,$e);T.current[Ve]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(ke.key==="ArrowUp")ke.preventDefault(),ke.stopPropagation(),K(Ve=>(Ve-1+Math.max(1,$e))%Math.max(1,$e)),setTimeout(()=>{const Ve=(V-1+Math.max(1,$e))%Math.max(1,$e);T.current[Ve]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(ke.key==="Enter"){ke.preventDefault(),ke.stopPropagation();const Ve=Oe[V];Ve&&ot(Ve.providerID,Ve.modelID)}else ke.key==="Escape"&&(ke.preventDefault(),ke.stopPropagation(),me(!1))};let Le=0;return e.jsxs(Xe,{delayDuration:1e3,children:[te?e.jsxs("button",{type:"button",onClick:()=>$("model"),onTouchStart:()=>Os("model"),onTouchEnd:Ss,onTouchCancel:Ss,className:O("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",De),children:[t?e.jsx(Xt,{providerId:t,className:O(ae,"flex-shrink-0")}):e.jsx(Qs,{className:O(ae,"text-muted-foreground")}),e.jsx("span",{className:O("model-controls__model-label typography-micro font-medium truncate min-w-0",!R&&"max-w-[220px]"),children:Ke()})]}):e.jsxs(Jt,{open:W,onOpenChange:me,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:O("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",De),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(Xt,{providerId:t,className:O(ae,"flex-shrink-0")}),e.jsx(Qs,{className:O(ae,"text-primary/60 hidden")})]}):e.jsx(Qs,{className:O(ae,"text-muted-foreground")}),e.jsx("span",{className:O("model-controls__model-label",Ie,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:Ke()},`${t}-${n}`)]})})}),e.jsxs(es,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{type:"text",placeholder:"Search models",value:Ee,onChange:ke=>Pe(ke.target.value),onKeyDown:de,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(tt,{outerClassName:"max-h-[400px] flex-1",children:e.jsxs("div",{className:"p-1",children:[!we&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),xe.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Js,{className:"h-4 w-4 text-primary"}),"Favorites"]}),xe.map(({model:ke,providerID:Ve,modelID:et})=>{const nt=Le++;return Dn(ke,Ve,et,"fav",nt,V===nt)})]}),_.length>0&&e.jsxs(e.Fragment,{children:[xe.length>0&&e.jsx(Us,{}),e.jsxs(Wr,{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"]}),_.map(({model:ke,providerID:Ve,modelID:et})=>{const nt=Le++;return Dn(ke,Ve,et,"recent",nt,V===nt)})]}),(xe.length>0||_.length>0)&&Z.length>0&&e.jsx(Us,{}),Z.map((ke,Ve)=>e.jsxs(l.Fragment,{children:[Ve>0&&e.jsx(Us,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Xt,{providerId:ke.id,className:"h-4 w-4 flex-shrink-0"}),ke.name]}),ke.models.map(et=>{const nt=Le++;return Dn(et,ke.id,et.id,"provider",nt,V===nt)})]},ke.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"})]})]}),hr()]})},Bo=()=>{if(!I)return e.jsx(Ye,{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 xe=Object.entries(I.tools||{}).filter(([,de])=>de).map(([de])=>de).sort(),_=!!(I.prompt&&I.prompt.trim().length>0),Z=I.model?.providerID&&I.model?.modelID,we=I.temperature!==void 0||I.topP!==void 0,Oe=de=>Ge(de==="full"||de==="allow"||de==="deny"?de:"ask","h-3.5 w-3.5"),$e=de=>de==="full"?"Full":de==="allow"?"Allow":de==="deny"?"Deny":"Ask";return e.jsx(Ye,{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:St(I.name)}),I.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:I.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:I.mode==="primary"?"Primary":I.mode==="subagent"?"Subagent":I.mode==="all"?"All":"—"})]}),(Z||we)&&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"}),Z?e.jsxs("span",{className:"typography-meta text-foreground",children:[I.model.providerID," / ",I.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),we&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[I.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:I.temperature})]}),I.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:I.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:"Tools"}),xe.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:xe.map(de=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:de},de))}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),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:[Oe(I.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:$e(I.permission?.edit)})]})]}),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:[Oe(typeof I.permission?.bash=="string"?I.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:$e(typeof I.permission?.bash=="string"?I.permission.bash:void 0)})]})]}),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:[Oe(I.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:$e(I.permission?.webfetch)})]})]})]}),_&&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(Xn,{className:"h-4 w-4 text-foreground"})]})]})})},An=()=>te?e.jsxs("button",{type:"button",onClick:()=>$("agent"),onTouchStart:()=>Os("agent"),onTouchEnd:Ss,onTouchCancel:Ss,className:O("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",De,"cursor-pointer hover:opacity-70",te&&"ml-1"),children:[e.jsx(bn,{className:O(ae,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${or(o).var})`}:void 0}),e.jsx("span",{className:O("model-controls__agent-label",Ie,"font-medium truncate min-w-0"),style:o?{color:`var(${or(o).var})`}:void 0,children:ft()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(Xe,{delayDuration:1e3,children:[e.jsxs(Jt,{children:[e.jsx(Qe,{asChild:!0,children:e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:O("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",De),children:[e.jsx(bn,{className:O(ae,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${or(o).var})`}:void 0}),e.jsx("span",{className:O("model-controls__agent-label",Ie,"font-medium min-w-0 truncate",L?"max-w-[220px]":void 0),style:o?{color:`var(${or(o).var})`}:void 0,children:ft()})]})})}),e.jsxs(es,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[p.filter(xe=>Un(xe.mode)).map(xe=>e.jsx(kt,{className:"typography-meta",onSelect:()=>Ft(xe.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:O("h-1 w-1 rounded-full agent-dot",or(xe.name).class)}),e.jsx("span",{className:"font-medium",children:St(xe.name)})]}),xe.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:xe.description})]})},xe.name)),e.jsx(Us,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:yt,onClick:()=>{yt||ce(xe=>!xe)},className:O("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",yt?"cursor-not-allowed opacity-60":void 0),"aria-expanded":ye,"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:ht?ht.text:"var(--foreground)"},children:ze})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:O("flex items-center justify-center p-1",!ht&&"text-muted-foreground"),style:ht?{color:ht.text}:void 0,children:Ge(xt)}),e.jsx(Nt,{className:O("h-3.5 w-3.5 transition-transform text-muted-foreground",ye?"rotate-180":"")})]})]}),ye&&!yt&&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:vt.map(xe=>{const _=xe.mode===xt,Z=mn(xe.mode);return e.jsxs("button",{type:"button",disabled:xe.disabled,onClick:()=>rt(xe.mode),className:O("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",xe.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",_?"bg-primary/10":void 0),style:_&&Z?{backgroundColor:Z.background??void 0}:void 0,children:[Ge(xe.mode,re),e.jsx("span",{className:"typography-meta font-medium",style:{color:Z?Z.text:"var(--foreground)"},children:xe.label})]},xe.mode)})})]})]})]}),Bo()]})}),zo=O("@container/model-controls flex items-center min-w-0",_e,R&&"w-full",s);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:zo,children:[e.jsx("div",{className:O("flex items-center min-w-0 flex-1 justify-end",R&&"overflow-hidden"),children:_o()}),e.jsx("div",{className:O("flex items-center min-w-0",_e,R&&"flex-shrink-0"),children:An()})]}),$o(),pr(),nn(),Oo()]})},Nx=s=>s?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(s):!0,zl=(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 c=i.index,d=c+i[0].length,u=c>0?s[c-1]:null;if(!Nx(u))continue;const m={name:o.name,source:{value:i[0],start:c,end:d}};n||(n=m)}}return n?{sanitizedText:s,mention:n}:{sanitizedText:s,mention:null}},au=s=>({id:s.id,content:s.content,status:s.status||"pending",priority:s.priority||"medium"}),Ua=Tt()(_t((s,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){s({isLoading:!0});try{const o=(await Re.getSessionTodos(t)).map(au);s(a=>{const i=new Map(a.sessionTodos);return i.set(t,o),{sessionTodos:i,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"})),Cx=(s,r)=>{const t=r.map(au);Ua.getState().updateTodos(s,t)},Hl=[{variant:"shine",component:({children:s,className:r,...t})=>e.jsx($r.span,{...t,className:O("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)=>Ne.createElement($r.span,{...t,key:n+String(o),className:O("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:O("invisible",r),children:s}),e.jsx("span",{...t,className:O("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:O("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($r.span,{...t,className:O("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,c)=>e.jsx($r.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:i},String(c)))}),e.jsx("div",{className:O("absolute inset-0"),children:a.map((i,c)=>e.jsx($r.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:i},String(c)))})]})}},{variant:"shake",component:({children:s,className:r,...t})=>e.jsx("span",{...t,className:O("text-primary-muted hover:animate-text-shake",r),children:s})},{variant:"hover-decoration",component:({children:s,className:r,...t})=>e.jsx("div",{className:O("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:O("text-primary-muted",r),children:s})})}];function ca({variant:s="shine",className:r,...t}){const a=Hl.find(i=>i.variant===s)?.component||Hl[0].component;return e.jsx(Vc,{children:e.jsx(a,{...t,className:r})})}const Ul=1500,Mx=2e3;function Dx({statusText:s,isGenericStatus:r,isWaitingForPermission:t,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:i}){const[c,d]=Ne.useState("idle"),[u,m]=Ne.useState(null),[f,p]=Ne.useState(!1),h=Ne.useRef(0),w=Ne.useRef(null),g=Ne.useRef(null),y=Ne.useRef(null),x=Ne.useRef(null),v=Ne.useRef(!1),S=Ne.useRef(!1),N=Ne.useRef(!1),j=Ne.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),y.current&&(clearTimeout(y.current),y.current=null)},[]),k=Ne.useCallback((P,R)=>{j(),w.current=null,m(P),p(R),d("showing"),h.current=Date.now(),v.current=!0},[j]),F=Ne.useCallback(()=>{if(g.current)return;const P=Date.now()-h.current,R=Math.max(0,Ul-P);g.current=setTimeout(()=>{g.current=null;const L=w.current;L&&k(L.text,L.permission)},R)},[k]),A=Ne.useCallback(P=>{if(j(),w.current=null,!v.current){d("idle"),m(null),i?.(!1);return}if(P==="done"&&o&&x.current===o){d("idle"),m(null),v.current=!1,i?.(!1);return}P==="done"&&o&&(x.current=o),d(P),m(null),i?.(!0),y.current=setTimeout(()=>{y.current=null,d("idle"),v.current=!1,i?.(!1)},Mx)},[j,o,i]);if(Ne.useEffect(()=>{if(n&&!N.current){N.current=!0,A("aborted");return}if(N.current=!!n,a&&!S.current){S.current=!0,A("done");return}if(!a&&S.current&&(S.current=!1),!(c==="done"||c==="aborted")&&s){const R=Date.now()-h.current;if(c==="idle"||!u)k(s,!!t);else if(s!==u||!!t!==f){if(r)return;R>=Ul?k(s,!!t):(w.current={text:s,permission:!!t},F())}}},[s,t,n,a,c,u,f,k,A,F,r]),Ne.useEffect(()=>()=>j(),[j]),Ne.useEffect(()=>{const P=()=>{typeof document>"u"||document.visibilityState==="visible"&&(c==="done"||c==="aborted")&&(j(),d("idle"),m(null),v.current=!1)};return document.addEventListener("visibilitychange",P),()=>document.removeEventListener("visibilitychange",P)},[c,j]),c==="idle"&&!u)return null;let M,b=!0;c==="done"?(M="Done",b=!1):c==="aborted"?(M="Aborted",b=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const C=b?`${M}...`:M,D=c!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${D?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":M,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:c==="done"?e.jsx(ca,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):c==="aborted"?e.jsx(ca,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(ca,{variant:"shine",className:"typography-ui-header",children:C})})})}const Wl={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Ax=({todo:s})=>{const r=Wl[s.status]||Wl.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:O("flex-1 typography-ui-label",r.textClassName),children:s.content})})},Vl=[],Ex=({isWorking:s,statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:i,isComplete:c,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=l.useState(!1),h=he(R=>R.currentSessionId),w=Ua(R=>h?R.sessionTodos.get(h)??Vl:Vl),g=Ua(R=>R.loadTodos),{isMobile:y}=Fe(),x=y||Et();l.useEffect(()=>{h&&g(h)},[h,g]);const v=l.useMemo(()=>{const R={in_progress:0,pending:1,completed:2,cancelled:3};return[...w].filter(L=>L.status!=="cancelled").sort((L,q)=>R[L.status]-R[q.status])},[w]),S=l.useMemo(()=>v.find(R=>R.status==="in_progress")||v.find(R=>R.status==="pending")||null,[v]),N=l.useMemo(()=>{const R=w.filter(q=>q.status!=="cancelled").length;return{completed:w.filter(q=>q.status==="completed").length,total:R}},[w]),j=v.length>0,k=!m&&(o||!a),[F,A]=l.useState(!1),M=s||c||o||F||j||m,b=l.useRef(null);if(l.useEffect(()=>{if(!f)return;const R=L=>{b.current&&!b.current.contains(L.target)&&p(!1)};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[f]),!M)return null;const C=()=>p(R=>!R),D=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(Kr,{size:18,"aria-hidden":"true"})}):null,P=j?e.jsxs("button",{type:"button",onClick:C,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!x&&S?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:S.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[N.completed,"/",N.total]}),f?e.jsx(Ao,{className:"h-3.5 w-3.5"}):e.jsx(Nt,{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(Kr,{size:16,"aria-hidden":"true"}),"Aborted"]})}):k?e.jsx(Dx,{statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,completionId:i??null,isComplete:c,onResultVisibilityChange:A},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:b,children:[D,P,f&&j&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:O("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px]","rounded-xl border border-border bg-background shadow-md","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"Tasks"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[N.completed,"/",N.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:v.map(R=>e.jsx(Ax,{todo:R},R.id))})]})]})]})})},Wa=s=>!s||typeof s!="object"?!1:!!s.synthetic,Gl=s=>!Array.isArray(s)||s.length===0?!1:s.every(r=>Wa(r)),Ix=s=>!Array.isArray(s)||s.length===0?[]:s.some(t=>!Wa(t))?s.filter(t=>!Wa(t)):s,Tx={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Fx(s){const r=he(t=>!s||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(s)??"idle");return l.useMemo(()=>{if(r==="idle")return Tx;const t=r==="busy",n=r==="cooldown";return{phase:r,isWorking:t||n,isBusy:t,isCooldown:n}},[r])}function ki(){const s=he(r=>r.currentSessionId);return Fx(s)}const Px={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},ql=s=>s.role==="assistant",Rx=s=>s.type==="reasoning",iu=s=>s.type==="text",Kl=s=>{if(iu(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},Yl=s=>(iu(s)||Rx(s),s.time),Lx=s=>{if(s.tool)return s.tool;const r=s;return typeof r.name=="string"?r.name:"tool"};function lu(){const{currentSessionId:s,messages:r,permissions:t,sessionAbortFlags:n}=he(si(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=ki(),c=l.useMemo(()=>s?r.get(s)??[]:[],[s,r]),d=l.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=c.filter(M=>ql(M.info)&&!Gl(M.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const w=[...h].sort((M,b)=>{const C=typeof M.info.time?.created=="number"?M.info.time.created:null,D=typeof b.info.time?.created=="number"?b.info.time.created:null;return C!==null&&D!==null&&C!==D?C-D:M.info.id.localeCompare(b.info.id)}),g=w[w.length-1];let y,x;const v=new Set(["edit","write"]);for(let M=(g.parts??[]).length-1;M>=0;M-=1){const b=g.parts?.[M];if(b)switch(b.type){case"reasoning":{const C=b.time??Yl(b);(!C||typeof C.end>"u")&&!y&&(y="reasoning");break}case"tool":{const C=b.state?.status;if((C==="running"||C==="pending")&&!y){const D=Lx(b);v.has(D)?y="editing":(y="tool",x=D)}break}case"text":{const C=Kl(b)??"";if(typeof C=="string"&&C.trim().length>0){const D=Yl(b);(!D||typeof D.end>"u")&&!y&&(y="text")}break}}}const S={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"},N=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],j=M=>S[M]??`using ${M}`,k=()=>N[Math.floor(Math.random()*N.length)],F=y===void 0,A=y==="editing"?"editing file":y==="tool"&&x?j(x):y==="reasoning"?"thinking":y==="text"?"composing":k();return{activePartType:y,activeToolName:x,statusText:A,isGenericStatus:F}},[c]),u=l.useMemo(()=>{const h=s,w=h?n?.get(h)??null:null,g=!!(w&&!w.acknowledged);return{wasAborted:g,abortActive:g}},[s,n]),m=l.useMemo(()=>{if(u.wasAborted)return{...Px,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,w=o==="busy",g=i;let y="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?y="tooling":y=g?"cooldown":"streaming"),{activity:y,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:w,isCooldown:g,lifecyclePhase:w?"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=l.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const w=c.filter(x=>ql(x.info)&&!Gl(x.parts));if(w.length===0)return{isActive:h,characterCount:0};const g=w[w.length-1];let y=0;return(g.parts??[]).forEach(x=>{if(x.type!=="text")return;const v=Kl(x)??"";typeof v=="string"&&v.trim().length>0&&(y+=v.length)}),{isActive:h,characterCount:y}},[c,a,d.activePartType]),p=l.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 Ox=8,Xl=[],$x=s=>s==="primary"||s==="all"||s===void 0||s===null,Vn=({onOpenSettings:s,scrollToBottom:r})=>{const[t,n]=l.useState(""),[o,a]=l.useState(!1),[i,c]=l.useState(!1),[d,u]=l.useState(""),[m,f]=l.useState(!1),[p,h]=l.useState(""),[w,g]=l.useState(!1),[y,x]=l.useState(""),[v,S]=l.useState(null),N=l.useRef(null),j=l.useRef(null),k=l.useRef(null),F=l.useRef(null),A=l.useRef(null),M=he(_=>_.sendMessage),b=he(_=>_.currentSessionId),C=he(_=>_.newSessionDraft?.open),D=he(_=>_.abortCurrentOperation),P=he(_=>_.acknowledgeSessionAbort),R=he(_=>_.abortPromptSessionId),L=he(_=>_.abortPromptExpiresAt),q=he(_=>_.clearAbortPrompt),te=he(_=>_.sessionAbortFlags),le=he(_=>_.attachedFiles),$=he(_=>_.addAttachedFile),z=he(_=>_.addServerFile),E=he(_=>_.clearAttachedFiles),H=he(_=>_.saveSessionAgentSelection),Y=he(_=>_.consumePendingInputText),fe=he(_=>_.pendingInputText),{currentProviderId:ne,currentModelId:pe,currentAgentName:je,setAgent:U,getVisibleAgents:ee}=ut(),oe=ee(),{isMobile:W,inputBarOffset:me,isKeyboardOpen:ye,setTimelineDialogOpen:ce}=Fe(),{working:Me}=lu(),[Ee,Pe]=l.useState(!1),V=l.useRef(null),K=l.useRef(!1),T=l.useRef(!1),X=zs(_=>_.queueModeEnabled),I=zs(l.useCallback(_=>b?_.queuedMessages[b]??Xl:Xl,[b])),B=zs(_=>_.addToQueue),G=zs(_=>_.clearQueue),{phase:be}=ki(),J=l.useRef(be),ge=l.useRef(!1),He=l.useCallback(_=>{if(!W||_.pointerType!=="touch")return;const Z=N.current;if(!Z||document.activeElement===Z)return;_.preventDefault(),_.stopPropagation();const we=document.scrollingElement;we&&we.scrollTop!==0&&(we.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{Z.focus({preventScroll:!0})}catch{Z.focus()}const Oe=Z.value.length;try{Z.setSelectionRange(Oe,Oe)}catch{}},[W]);l.useEffect(()=>{if(fe!==null){const _=Y();_&&(n(_),setTimeout(()=>{N.current?.focus()},0))}},[fe,Y]);const We=l.useMemo(()=>{if(je)return oe.find(_=>_.name===je)},[oe,je]),Be=l.useMemo(()=>{const _=We?.permission?.edit;let Z="ask";(_==="allow"||_==="ask"||_==="deny"||_==="full")&&(Z=_);const we=We?We.tools?.edit!==!1:!1;return(!We||!we)&&(Z="deny"),Z},[We]),Ze=he(l.useCallback(_=>!b||!je?void 0:_.sessionAgentEditModes.get(b)?.get(je),[b,je])),it=We?.permission?.webfetch,lt=We?.permission?.bash,ct=l.useMemo(()=>ou({agentDefaultEditMode:Be,webfetchPermission:it,bashPermission:lt}),[Be,it,lt]),mt=!!(b&&je),xt=l.useMemo(()=>mt&&Ze&&ct.modeAvailability[Ze]?Ze:ct.cascadeDefaultMode,[ct,mt,Ze]),vt=l.useMemo(()=>mn(xt),[xt]),ht=l.useCallback(_=>Et()?`color-mix(in srgb, ${_} 55%, transparent)`:_,[]),yt=l.useMemo(()=>{const _=Et()?1:2;if(!vt)return{borderWidth:_};const Z=vt.border??vt.text;return{borderColor:ht(Z),borderWidth:_}},[vt,ht]),Q=t.trim()||le.length>0,De=I.length>0,re=Q||De,ae=Me.isWorking,Ie=l.useMemo(()=>b?R===b&&!!L:!1,[R,L,b]),_e=l.useCallback(()=>{if(!Q||!b)return;const _=t.replace(/^\n+|\n+$/g,""),Z=le.map(we=>({...we}));B(b,{content:_,attachments:Z.length>0?Z:void 0}),n(""),Z.length>0&&E(),W||N.current?.focus()},[Q,b,t,le,B,E,W]),ze=async _=>{if(_?.preventDefault(),!re||!b&&!C)return;if(r?.({instant:!0,force:!0}),!ne||!pe){console.warn("Cannot send message: provider or model not selected");return}let Z="",we=[],Oe;const $e=[];for(let ke=0;ke<I.length;ke++){const Ve=I[ke],{sanitizedText:et,mention:nt}=zl(Ve.content,oe);!Oe&&nt?.name&&(Oe=nt.name),ke===0?(Z=et,we=Ve.attachments??[]):$e.push({text:et,attachments:Ve.attachments})}if(Q){const ke=t.replace(/^\n+|\n+$/g,""),{sanitizedText:Ve,mention:et}=zl(ke,oe),nt=le.map(ts=>({...ts}));!Oe&&et?.name&&(Oe=et.name),I.length===0?(Z=Ve,we=nt):$e.push({text:Ve,attachments:nt.length>0?nt:void 0})}if(!Z&&$e.length===0)return;b&&De&&G(b),n(""),le.length>0&&E(),W&&N.current?.blur();const de=Z.trimStart();if(de.startsWith("/")){const ke=de.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(ke==="undo"&&b){await he.getState().handleSlashUndo(b),r?.({instant:!0,force:!0});return}else if(ke==="redo"&&b){await he.getState().handleSlashRedo(b),r?.({instant:!0,force:!0});return}else if(ke==="timeline"&&b){ce(!0),n("");return}else ke==="summarize"&&r?.({instant:!0,force:!0})}const Le=[...we,...$e.flatMap(ke=>ke.attachments??[])];await M(Z,ne,pe,je,we,Oe,$e.length>0?$e:void 0).catch(ke=>{const Ve=ke instanceof Error?ke.message:typeof ke=="string"?ke:String(ke??""),et=Ve.toLowerCase();console.error("Message send failed:",Ve||ke),!(et.includes("timeout")||et.includes("timed out")||et.includes("may still be processing")||et.includes("being processed")||et.includes("failed to fetch")||et.includes("networkerror")||et.includes("network error")||et.includes("gateway timeout")||et==="failed to send message")&&(Le.length>0&&Hs.setState({attachedFiles:Le}),se.error(Ve||"Message failed to send. Attachments restored."))}),W||N.current?.focus()},Ge=l.useRef(ze);Ge.current=ze,l.useEffect(()=>{const _=J.current==="busy"||J.current==="cooldown",Z=be==="idle",we=b&&te.has(b)&&(()=>{const Oe=te.get(b);return Oe?Date.now()-Oe.timestamp<2e3:!1})();_&&Z&&I.length>0&&!ge.current&&!we&&(ge.current=!0,setTimeout(()=>{b&&ne&&pe&&Ge.current(),ge.current=!1},100)),J.current=be},[be,I.length,b,ne,pe,te]);const rt=_=>{if(m&&F.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),F.current.handleKeyDown(_.key);return}if(w&&A.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),A.current.handleKeyDown(_.key);return}if(i&&k.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),k.current.handleKeyDown(_.key);return}if(_.key==="Tab"&&!m&&!i){_.preventDefault(),Se();return}if(_.key==="Enter"&&!_.shiftKey&&!W){_.preventDefault();const Z=_.ctrlKey||_.metaKey,we=Q&&b&&be!=="idle";X?Z||!we?ze():_e():Z&&we?_e():ze()}},ie=l.useCallback(()=>{V.current&&(clearTimeout(V.current),V.current=null),Pe(!0),V.current=setTimeout(()=>{Pe(!1),V.current=null},1800)},[]),ue=l.useCallback(()=>{q(),ie(),D()},[D,q,ie]),Se=()=>{const _=oe.filter($e=>$x($e.mode));if(_.length<=1)return;const we=(_.findIndex($e=>$e.name===je)+1)%_.length,Oe=_[we];U(Oe.name),b&&H(b,Oe.name)},Ce=l.useCallback(()=>{const _=N.current;if(!_)return;_.style.height="auto";const Z=_.ownerDocument?.defaultView,we=Z?Z.getComputedStyle(_):null,Oe=we?parseFloat(we.lineHeight):NaN,$e=we?parseFloat(we.paddingTop):NaN,de=we?parseFloat(we.paddingBottom):NaN,Le=22,Ve=Number.isNaN($e)||Number.isNaN(de)?16:$e+de,nt=(Number.isNaN(Oe)?Le:Oe)*Ox+Ve,ts=_.scrollHeight||_.offsetHeight,Rt=Math.min(ts,nt);_.style.height=`${Rt}px`,_.style.maxHeight=`${nt}px`,S(Lt=>Lt&&Lt.height===Rt&&Lt.maxHeight===nt?Lt:{height:Rt,maxHeight:nt})},[]);l.useLayoutEffect(()=>{Ce()},[Ce,t,W]);const Te=l.useCallback((_,Z)=>{if(_.startsWith("/")){const de=_.indexOf(" "),Le=_.indexOf(`
|
|
64
|
+
`),ke=Math.min(de===-1?_.length:de,Le===-1?_.length:Le);if(Z<=ke&&de===-1){const Ve=_.substring(1,ke);h(Ve),f(!0),c(!1),g(!1)}else f(!1);return}f(!1);const we=_.substring(0,Z),Oe=we.lastIndexOf("#");if(Oe!==-1){const de=Oe>0?we[Oe-1]:null,Le=we.substring(Oe+1),ke=Le.includes(" ")||Le.includes(`
|
|
65
|
+
`);if((!de||/\s/.test(de))&&!ke){x(Le),g(!0),c(!1);return}}g(!1),x("");const $e=we.lastIndexOf("@");if($e!==-1){const de=we.substring($e+1);!de.includes(" ")&&!de.includes(`
|
|
66
|
+
`)?(u(de),c(!0)):c(!1)}else c(!1)},[x,h,u,g,f,c]),Ue=l.useCallback(_=>{if(!_)return;const Z=N.current;if(!Z){const Le=t+_;n(Le),Te(Le,Le.length),requestAnimationFrame(()=>Ce());return}const we=Z.selectionStart??t.length,Oe=Z.selectionEnd??t.length,$e=`${t.substring(0,we)}${_}${t.substring(Oe)}`;n($e);const de=we+_.length;requestAnimationFrame(()=>{const Le=N.current;Le&&(Le.selectionStart=de,Le.selectionEnd=de),Ce()}),Te($e,de)},[Ce,t,Te]),bt=_=>{const Z=_.target.value,we=_.target.selectionStart??Z.length;n(Z),Ce(),Te(Z,we)},At=l.useCallback(async _=>{const Z=new Map;Array.from(_.clipboardData.files||[]).forEach(de=>{de.type.startsWith("image/")&&Z.set(`${de.name}-${de.size}`,de)}),Array.from(_.clipboardData.items||[]).forEach(de=>{if(de.kind==="file"&&de.type.startsWith("image/")){const Le=de.getAsFile();Le&&Z.set(`${Le.name}-${Le.size}`,Le)}});const we=Array.from(Z.values());if(we.length===0||!b&&!C)return;_.preventDefault();const Oe=_.clipboardData.getData("text");Oe&&Ue(Oe);let $e=0;for(const de of we){const Le=he.getState().attachedFiles.length;try{await $(de),he.getState().attachedFiles.length>Le&&($e+=1)}catch(ke){console.error("Clipboard image attach failed",ke),se.error(ke instanceof Error?ke.message:"Failed to attach image from clipboard")}}$e>0&&se.success(`Attached ${$e} image${$e>1?"s":""} from clipboard`)},[$,b,C,Ue]),Mt=_=>{const Z=N.current?.selectionStart||0,Oe=t.substring(0,Z).lastIndexOf("@");if(Oe!==-1){const $e=t.substring(0,Oe)+_.name+t.substring(Z);n($e)}c(!1),u(""),N.current?.focus()},pt=_=>{const we=N.current?.selectionStart??t.length,$e=t.substring(0,we).lastIndexOf("#");if($e!==-1){const de=t.substring(0,$e)+`#${_} `+t.substring(we);n(de);const Le=$e+_.length+2;requestAnimationFrame(()=>{N.current&&(N.current.selectionStart=Le,N.current.selectionEnd=Le),Ce(),Te(de,Le)})}g(!1),x(""),N.current?.focus()},st=_=>{n(`/${_.name} `);const Z=N.current;Z&&(Z._commandMetadata=_),f(!1),h(""),setTimeout(()=>{N.current&&(N.current.focus(),N.current.setSelectionRange(N.current.value.length,N.current.value.length))},0)};l.useEffect(()=>{b&&N.current&&!W&&N.current.focus()},[b,W]),l.useEffect(()=>{R&&R!==b&&q()},[R,b,q]);const jt=_=>{_.preventDefault(),_.stopPropagation(),(b||C)&&!o&&a(!0)},Ft=_=>{_.preventDefault(),_.stopPropagation(),_.currentTarget===_.target&&a(!1)},ot=async _=>{if(_.preventDefault(),_.stopPropagation(),a(!1),!b&&!C)return;const Z=Array.from(_.dataTransfer.files);let we=0;for(const Oe of Z){const $e=he.getState().attachedFiles.length;try{await $(Oe),he.getState().attachedFiles.length>$e&&(we+=1)}catch(de){console.error("File attach failed",de),se.error(de instanceof Error?de.message:"Failed to attach file")}}we>0&&se.success(`Attached ${we} file${we>1?"s":""}`)},Ae=l.useCallback(async _=>{let Z=0;for(const we of _){const Oe=he.getState().attachedFiles.length;try{await z(we.path,we.name),he.getState().attachedFiles.length>Oe&&(Z+=1)}catch($e){console.error("Server file attach failed",$e),se.error($e instanceof Error?$e.message:"Failed to attach file")}}Z>0&&se.success(`Attached ${Z} file${Z>1?"s":""}`)},[z]),qe=l.useRef(null),[Ke,ft]=l.useState(!1),St=l.useCallback(async _=>{let Z=0;const we=Array.isArray(_)?_:Array.from(_);for(const Oe of we){const $e=he.getState().attachedFiles.length;try{await $(Oe),he.getState().attachedFiles.length>$e&&(Z+=1)}catch(de){console.error("File attach failed",de),se.error(de instanceof Error?de.message:"Failed to attach file")}}Z>0&&se.success(`Attached ${Z} file${Z>1?"s":""}`)},[$]),Pt=l.useCallback(async()=>{try{const Z=await(await fetch("/api/vscode/pick-files")).json(),we=Array.isArray(Z?.files)?Z.files:[],Oe=Array.isArray(Z?.skipped)?Z.skipped:[];if(Oe.length>0){const de=Oe.map(Le=>`${Le?.name||"file"}: ${Le?.reason||"skipped"}`).join(`
|
|
67
|
+
`);se.error(`Some files were skipped:
|
|
68
|
+
${de}`)}const $e=we.map(de=>{if(!de?.dataUrl)return null;try{const[Le,ke]=de.dataUrl.split(","),Ve=de.mimeType||Le?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!ke)return null;const et=atob(ke),nt=new Uint8Array(et.length);for(let Rt=0;Rt<et.length;Rt++)nt[Rt]=et.charCodeAt(Rt);const ts=new Blob([nt],{type:Ve});return new File([ts],de.name||"file",{type:Ve})}catch(Le){return console.error("Failed to decode VS Code picked file",Le),null}}).filter(Boolean);$e.length>0&&await St($e)}catch(_){console.error("VS Code file pick failed",_),se.error(_ instanceof Error?_.message:"Failed to pick files in VS Code")}},[St]),cs=l.useCallback(()=>{if(Et()){Pt();return}qe.current?.click()},[Pt]),Os=l.useCallback(async _=>{const Z=_.target.files;Z&&(await St(Z),_.target.value="")},[St]),Ss="gap-x-1.5 gap-y-0",nn=Et(),Oo=W?"px-1.5 py-1.5":nn?"px-1.5 py-1":"px-2.5 py-1.5",$o=W?"h-9 w-9":nn?"h-[22px] w-[22px]":"h-7 w-7",pr=W?"h-5 w-5":nn?"h-4 w-4":"h-[18px] w-[18px]",hr=O($o,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),Pr=!W&&Ie&&ae?e.jsx("button",{type:"button",onClick:ue,className:O(hr,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(Kr,{className:O(pr)})}):e.jsx("button",{type:W?"button":"submit",disabled:!re||!b&&!C,onPointerDownCapture:_=>{!W||_.pointerType!=="touch"||!re||!b&&!C||(T.current=!0,_.preventDefault(),_.stopPropagation(),ze())},onClick:_=>{if(W){if(T.current){T.current=!1;return}_.preventDefault(),ze()}},className:O(hr,re&&(b||C)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(df,{className:O(pr)})}),_o=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:qe,type:"file",multiple:!0,className:"hidden",onChange:Os,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(gx,{onFilesSelected:Ae,multiSelect:!0,presentation:W?"modal":"dropdown",open:Ke,onOpenChange:ft,children:W?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Jt,{children:[e.jsx(Zt,{asChild:!0,children:e.jsx("button",{type:"button",className:hr,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(uf,{className:O(pr,"text-current")})})}),e.jsxs(es,{align:"start",children:[e.jsxs(kt,{onSelect:()=>{requestAnimationFrame(()=>cs())},children:[e.jsx(io,{}),"Attach files"]}),e.jsxs(kt,{onSelect:()=>{requestAnimationFrame(()=>{ft(!0)})},children:[e.jsx(mf,{}),"Attach from project"]})]})]})]})]}),Bo=s?e.jsx("button",{type:"button",onClick:s,className:hr,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(bn,{className:O(pr,"text-current")})}):null,An=e.jsxs(e.Fragment,{children:[_o,Bo]}),zo=Me.statusText;l.useEffect(()=>{const _=!!Me.wasAborted;!K.current&&_&&!Ee&&(ie(),b&&P(b)),K.current=_},[P,b,Ee,ie,Me.wasAborted]),l.useEffect(()=>()=>{V.current&&(clearTimeout(V.current),V.current=null)},[]);const xe=W&&ae;return e.jsxs("form",{onSubmit:ze,className:"pt-0 pb-2 md:pb-4 bottom-safe-area","data-keyboard-avoid":"true",style:W&&me>0&&!ye?{marginBottom:`${me}px`}:void 0,children:[e.jsx(Ex,{isWorking:Me.isWorking,statusText:zo,isGenericStatus:Me.isGenericStatus,isWaitingForPermission:Me.isWaitingForPermission,wasAborted:Me.wasAborted,abortActive:Me.abortActive,completionId:Me.lastCompletionId,isComplete:Me.isComplete,showAbort:xe,onAbort:ue,showAbortStatus:Ee}),e.jsxs("div",{ref:j,className:O("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:jt,onDragLeave:Ft,onDrop:ot,children:[o&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-xl",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-flex justify-center",children:e.jsx("button",{type:"button",className:hr,onClick:()=>cs(),title:"Attach files","aria-label":"Attach files",children:e.jsx(io,{className:O(pr,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(ux,{}),e.jsx(eu,{onEditMessage:_=>{n(_),setTimeout(()=>{N.current?.focus()},0)}}),e.jsxs("div",{className:O("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:yt,children:[m&&e.jsx(su,{ref:F,searchQuery:p,onCommandSelect:st,onClose:()=>f(!1)}),w&&e.jsx(ru,{ref:A,searchQuery:y,onAgentSelect:pt,onClose:()=>g(!1)}),i&&e.jsx(mx,{ref:k,searchQuery:d,onFileSelect:Mt,onClose:()=>c(!1)}),e.jsx(Ts,{ref:N,"data-chat-input":"true",value:t,onChange:bt,onKeyDown:rt,onPaste:At,onPointerDownCapture:He,placeholder:b||C?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!b&&!C,className:O("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",W?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:v?`${v.height}px`:void 0,maxHeight:v?`${v.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:O("rounded-b-xl bg-transparent",Oo,W?"flex items-center gap-x-1.5":O("flex items-center justify-between",Ss)),"data-chat-input-footer":"true",children:W?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:An}),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(Bl,{className:O("w-full flex items-center justify-end min-w-0")})}),Pr]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:O("flex items-center flex-shrink-0",Ss),children:An}),e.jsxs("div",{className:O("flex items-center flex-1 justify-end",Ss,"md:gap-x-3"),children:[e.jsx(Bl,{className:O("flex-1 min-w-0 justify-end")}),Pr]})]})})]})]})]})};function da({className:s,...r}){return e.jsx("div",{"data-slot":"skeleton",className:O("bg-accent animate-pulse rounded-xl",s),...r})}const Ql=(s,r,t,n,o=4)=>{const a=[];for(let i=0;i<o;i++)for(let c=0;c<o;c++){const d=c/o,u=(c+1)/o,m=i/o,f=(i+1)/o,p=(v,S,N)=>v+(S-v)*N,h=(v,S,N,j,k,F)=>{const A=p(v,S,k),M=p(j,N,k);return p(A,M,F)},w={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)},y={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${w.x} ${w.y} L${g.x} ${g.y} L${y.x} ${y.y} L${x.x} ${x.y} Z`,row:i,col:c})}return a},Ni=({className:s="",width:r=70,height:t=70,isAnimated:n=!1})=>{const o=Ro();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",c=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,h=50,w={x:50,y:h-m},g={x:50-m*f,y:h-m*p},y={x:50+m*f,y:h-m*p},x={x:50,y:h},v={x:50-m*f,y:h+m*p},S={x:50+m*f,y:h+m*p},N={x:50,y:h+m},k=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(w.y+g.y+x.y+y.y)/4})`,F=Ql(g,x,N,v),A=Ql(x,y,S,N),M=Ne.useMemo(()=>{const b=[];for(let C=0;C<32;C++)b.push(.1+Math.random()*.5);return b},[]);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${v.x} ${v.y} L${N.x} ${N.y} Z`,fill:c,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),F.map((b,C)=>e.jsx("path",{d:b.path,fill:u,opacity:M[C]},`left-${C}`)),e.jsx("path",{d:`M${x.x} ${x.y} L${y.x} ${y.y} L${S.x} ${S.y} L${N.x} ${N.y} Z`,fill:c,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),A.map((b,C)=>e.jsx("path",{d:b.path,fill:u,opacity:M[C+16]},`right-${C}`)),e.jsx("path",{d:`M${w.x} ${w.y} L${g.x} ${g.y} L${x.x} ${x.y} L${y.x} ${y.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:`${k} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function _x({children:s,className:r,interval:t=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:i=!0,mode:c="popLayout"}){const[d,u]=Ne.useState(0),m=Ne.Children.toArray(s);Ne.useEffect(()=>{if(!i)return;const p=t*1e3,h=setInterval(()=>{u(w=>{const g=(w+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:O("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(ff,{mode:c,initial:!1,children:e.jsx($r.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const Bx=["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"],zx=()=>{const s=Ro();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(Ni,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(_x,{className:"text-body-md",interval:4,transition:{duration:.5},children:Bx.map(n=>e.jsxs("span",{style:{color:t},children:['"',n,'…"']},n))})]})},ua=l.memo(zx),Hx={'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"}},Ux={'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 ar{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return ar.instance||(ar.instance=new ar),ar.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 cu(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 rs=({children:s,className:r})=>{const[t,n]=l.useState(!1);return l.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:O("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:s})},Wx=({isUser:s,providerID:r,agentName:t,modelName:n,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:c}=Xd(r);return e.jsx(rs,{children:e.jsx("div",{className:O("pl-3","mb-2"),children:e.jsx("div",{className:O("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(bs,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:c&&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(Jr,{className:"h-4 w-4",style:{color:`var(${or(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:O("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:O("flex items-center gap-1 px-1.5 py-0 rounded","agent-badge typography-meta",or(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},Vx=l.memo(Wx),Jl=(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},Zl=()=>{if(!Et()||typeof window>"u")return bl;const s=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(s?.light&&s?.dark){const r=Jl({...s.light},`vscode-shiki-light:${String(s.light?.name??"theme")}`),t=Jl({...s.dark},`vscode-shiki-dark:${String(s.dark?.name??"theme")}`);return[r,t]}return bl},du=()=>{const[s,r]=l.useState(Zl);return l.useEffect(()=>{if(!Et()||typeof window>"u")return;const t=n=>{r(Zl())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),s},uu=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 c=i.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:r,rows:t}},mu=({headers:s,rows:r})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
|
|
69
|
+
`)?`"${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(`
|
|
70
|
+
`)},Gx=({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(`
|
|
71
|
+
`)},qx=({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,c)=>t(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
|
|
72
|
+
`)},Kx=(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)},Yx=({tableRef:s})=>{const[r,t]=l.useState(!1),[n,o]=l.useState(!1),a=l.useRef(null);l.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const i=async c=>{const d=s.current?.querySelector("table");if(d)try{const u=uu(d),m=c==="csv"?mu(u):Gx(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(Dt,{className:"size-3.5"}):e.jsx(qs,{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"})]})]})},Xx=({tableRef:s})=>{const[r,t]=l.useState(!1),n=l.useRef(null);l.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 c=uu(i),d=a==="csv"?mu(c):qx(c);Kx(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),t(!1)}catch(c){console.error("Failed to download table:",c)}};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(qr,{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"})]})]})},Qx=({children:s,className:r})=>{const t=l.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(Yx,{tableRef:t}),e.jsx(Xx,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:O("w-full border-collapse border border-border",r),"data-streamdown":"table",children:s})})]})},Jx=({children:s,className:r,style:t,...n})=>{const[o,a]=l.useState(!1),i=l.useRef(null),c=l.useMemo(()=>{if(!t)return t;const m={...t},f=w=>{if(typeof w!="string")return{value:void 0,vars:{}};const[g,...y]=w.split(";").map(v=>v.trim()).filter(Boolean),x={};for(const v of y){const S=v.indexOf(":");if(S===-1)continue;const N=v.slice(0,S).trim(),j=v.slice(S+1).trim();!N.startsWith("--")||j.length===0||(x[N]=j)}return{value:g,vars:x}},p=f(t.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[w,g]of Object.entries(p.vars))m[w]=g;const h=f(t.color);h.value&&(m.color=h.value,m["--shiki-light"]=h.value);for(const[w,g]of Object.entries(h.vars))m[w]=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:O(r),style:c,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(Dt,{className:"size-3.5"}):e.jsx(qs,{className:"size-3.5"})})})]})},fu={pre:Jx,table:Qx},Zx=({content:s,part:r,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const c=du(),d=l.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:O("break-words",o),children:e.jsx(Xc,{mode:a?"streaming":"static",shikiTheme:c,className:u,controls:{code:!1,table:!1},components:fu,children:s})});return n?e.jsx(rs,{children:m},d):m},Nr=({content:s,className:r,variant:t="assistant"})=>{const n=du(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:O("break-words",r),children:e.jsx(Xc,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:fu,children:s})})},ey={thinking:{label:"Thinking",Icon:Jr},justification:{label:"Justification",Icon:Za}},pu=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
|
|
73
|
+
`).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
|
|
74
|
+
`).trim(),ty=s=>{if(!s)return"";const r=s.trim(),t=r.indexOf(`
|
|
75
|
+
`),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},Ci=({text:s,variant:r,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>ty(s),[s]),{label:c,Icon:d}=ey[r];return l.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:O("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:O("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:O("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(Nt,{className:"h-3.5 w-3.5"}):e.jsx(As,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:c})]}),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:O("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(tt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:s})})]})},hu=({part:s,onContentChange:r,messageId:t})=>{const n=s,o=n.text||n.content||"",a=l.useMemo(()=>pu(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Ci,{text:a,variant:"thinking",onContentChange:r,blockId:s.id||`${t}-reasoning`}):null},sy=s=>pu(s),ry=({part:s,messageId:r,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=s,c=i.text,d=typeof c=="string"?c:i.content||i.value||"",u=l.useMemo(()=>a?sy(d):d,[d,a]),m=t==="streaming",f=t==="cooldown",p=l.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(Ci,{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(Zx,{content:u,part:s,messageId:r,isAnimated:n,isStreaming:!1})},s.id||`${r}-text`)},ny=s=>`https://opencode.ai/docs/agents/#${encodeURIComponent(s)}`,oy=({part:s,messageId:r,agentMention:t})=>{const n=s,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,c]=l.useState(!1),[d,u]=l.useState(!1),m=l.useRef(null);l.useEffect(()=>{const h=m.current;if(!h||i)return;const w=()=>{u(h.scrollHeight>h.clientHeight)};w();const g=new ResizeObserver(w);return g.observe(h),()=>g.disconnect()},[a,i]);const f=l.useCallback(()=>{(d||i)&&c(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),w=a.slice(0,h),g=a.slice(h+t.token.length);return e.jsxs(e.Fragment,{children:[w,e.jsx("a",{href:ny(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:y=>y.stopPropagation(),children:t.token}),g]})};return e.jsx("div",{className:O("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`)},ay=l.memo(oy),iy=s=>{let r=s.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},gu=s=>s?s.includes("<file_diagnostics>")||s.includes("This file has errors")||s.includes("please fix"):!1,ly=s=>s?s.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",ec=(s,r)=>!s||typeof s!="object"?String(s):ng(s,r||""),ma=(s,r,t)=>{let n=iy(s);if((r==="edit"||r==="multiedit")&&gu(n)&&(n=ly(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},cy=(s,r)=>{try{const t=s.trim().split(`
|
|
76
|
+
`).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,c]=a,d=Math.floor(i.length/2),u=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:O("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:Zs.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}},dy=(s,r,t)=>{try{const n=s.trim().split(`
|
|
77
|
+
`).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,c,d,u]=i,m=u!==void 0?d:"",f=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].push({lineNum:m,content:f})}}),e.jsxs("div",{className:O("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Zs.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:O("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:O("flex items-start gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[c.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",c.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:c.content||" "})]})]},d))})]},a))]})}catch{return null}},uy=(s,r,t)=>{try{const n=s.trim().split(`
|
|
78
|
+
`).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const c=i.lastIndexOf("/"),d=c>0?i.substring(0,c):"/",u=c>=0?i.substring(c+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:O("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Zs.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:O("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:O("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(c=>e.jsxs("div",{className:O("flex items-center gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:c})]},c))})]},i))]})}catch{return null}},my=(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:O("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Zs.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(Dt,{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(Dt,{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}},fy=(s,r,t)=>{try{return e.jsx("div",{className:O("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:Zs.tool.popup,children:e.jsx(Nr,{content:s,variant:"tool"})})}catch{return null}},xu=s=>{const r=s.split(`
|
|
79
|
+
`);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+ @@/),c=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:c,newStart:d,lines:u}),o=f;continue}o++}return n},Va=(s,r,t)=>tg(r,s,t),yu=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(pf,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(Qc,{className:r}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(Aa,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(mr,{className:r}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(gs,{className:r}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(hf,{className:r}):t==="glob"?e.jsx(gf,{className:r}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(Ea,{className:r}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(Ea,{className:r}):t==="todowrite"||t==="todoread"?e.jsx(xf,{className:r}):t==="skill"?e.jsx(Jc,{className:r}):t.startsWith("git")?e.jsx(Vt,{className:r}):e.jsx(Io,{className:r})},py=(s,r,t=Date.now())=>{const o=(r?r-s:t-s)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},hy=({start:s,end:r,active:t})=>{const[n,o]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:py(s,r,n)})},gy=s=>{if(!s?.diff||typeof s.diff!="string")return null;const r=s.diff.split(`
|
|
80
|
+
`);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}},Ga=(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},xy=(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 Ga(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 Ga(d,n,t)}if(s.tool==="bash"&&i?.command&&typeof i.command=="string"){const d=i.command.split(`
|
|
81
|
+
`)[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 c=i?.description||a?.description||"title"in r&&r.title||"";return typeof c=="string"?c:""},qa=({children:s,maxHeightClass:r="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(tt,{outerClassName:O("w-full min-w-0 flex-none overflow-hidden",r,n),className:O("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})}),yy=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"},by=s=>s.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),wy=({entries:s,isExpanded:r,hasPrevTool:t,hasNextTool:n,output:o})=>{const a=l.useMemo(()=>s.filter(p=>p.state?.status==="completed"),[s]),i=typeof o=="string"?by(o):"",c=i.length>0,[d,u]=l.useState(!1);if(a.length===0&&!c)return null;const m=r?a:a.slice(-6),f=Math.max(0,a.length-m.length);return e.jsxs("div",{className:O("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:[a.length>0?e.jsx(qa,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[f>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",f," more…"]}):null,m.map((p,h)=>{const w=typeof p.tool=="string"&&p.tool.trim().length>0?p.tool:"tool",g=yy(p),y=pi(w).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:yu(w)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:y}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:g})]},p.id??`${w}-${h}`)})]})}):null,c?e.jsxs("div",{className:O("space-y-1",a.length>0&&"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:p=>p.stopPropagation(),onClick:p=>{p.stopPropagation(),u(h=>!h)},children:[d?e.jsx(Nt,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(As,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),d?e.jsx(qa,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Nr,{content:i,variant:"tool"})})}):null]}):null]})},vy=({diff:s,syntaxTheme:r,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:xu(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:O("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(Bs,{style:r,language:Ir(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))}),jy=({content:s,syntaxTheme:r,filePath:t,displayPath:n})=>{const o=s.split(`
|
|
82
|
+
`),a=Ir(t??"")||Va(s,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),c=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} (${c})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Bs,{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))})]})},Sy=({content:s,filePath:r,displayPath:t})=>{const n=rg(r),o=r.toLowerCase().endsWith(".svg"),a=l.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"}})})]})},ky=({part:s,state:r,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const c=r,d=c.metadata,u=c.input,m=c.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",h=typeof d?.diff=="string"?d.diff:null,w=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,y=s.tool==="write"&&!!g,x=w?Td(w):!1,v=y?w?Ga(w,o,n):"New file":null,S=l.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&s.tool==="bash"?ec(u,s.tool):typeof u.content=="string"?u.content??"":ec(u,s.tool),[u,s.tool]),N=S.trim().length>0,j=(F,A)=>e.jsx(qa,{maxHeightClass:A?.maxHeightClass,className:A?.className,disableHorizontal:A?.disableHorizontal,outerClassName:A?.outerClassName,children:F}),k=()=>{if(s.tool==="todowrite"||s.tool==="todoread"){if(r.status==="completed"&&f){const F=my(p,{unstyled:!0});return j(F??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 F=cy(p,{unstyled:!0});return j(F??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 F=dy(p,n,{unstyled:!0});return j(F??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 F=uy(p,n,{unstyled:!0});return j(F??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 j(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Nr,{content:p,variant:"tool"})}));if((s.tool==="web-search"||s.tool==="websearch"||s.tool==="search_web")&&f){const F=fy(p,t,{unstyled:!0});return j(F??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 j(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Nr,{content:p,variant:"tool"})}));if(s.tool==="skill"&&f)return j(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Nr,{content:p,variant:"tool"})}));if((s.tool==="edit"||s.tool==="multiedit")&&(!f&&h||p.trim().length===0||gu(p))&&h)return j(e.jsx(vy,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&p.trim()){if(s.tool==="read"){const F=ma(p,s.tool,d),A=F.split(`
|
|
83
|
+
`),M=typeof u?.offset=="number"?u.offset:0,b=typeof u?.limit=="number"?u.limit:void 0,C=D=>D.trim().startsWith("(");return j(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:A.map((D,P)=>{const R=C(D),L=M+P+1,q=!R&&(b===void 0||P<b);return e.jsxs("div",{className:O("typography-code font-mono flex w-full min-w-0",R&&"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:q?L:""}),e.jsx("div",{className:"flex-1 min-w-0",children:R?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:D}):e.jsx(Bs,{style:t,language:Va(F,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:D})})]},P)})}),{className:"p-1"})}return j(e.jsx(Bs,{style:t,language:Va(ma(p,s.tool,d),s.tool,u),PreTag:"div",customStyle:{...Qn.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:ma(p,s.tool,d)}),{className:"p-1"})}return j(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:O("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"?k():e.jsxs(e.Fragment,{children:[y&&x?e.jsx("div",{className:"my-1",children:j(e.jsx(Sy,{content:g,filePath:w,displayPath:v??"New file"}))}):y?e.jsx("div",{className:"my-1",children:j(e.jsx(jy,{content:g,syntaxTheme:t,filePath:w,displayPath:v??"New file"}))}):N?e.jsx("div",{className:"my-1",children:j(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:S}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,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:"}),k()]}),r.status==="error"&&"error"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]})]})})},ro=({part:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=s.state,u=wt(R=>R.currentDirectory),m=s.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",p=d.status==="running"||d.status==="pending",h=d.status==="error",w=l.useRef(r);l.useEffect(()=>{!f&&!m||w.current!==r&&(w.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const g=d,y=g.metadata,x=g.input,v=g.time,S=l.useRef({}),N=l.useRef(s.id);if(N.current!==s.id&&(N.current=s.id,S.current={}),m){if(typeof v?.start=="number"){const R=S.current.start;(typeof R!="number"||v.start<R)&&(S.current.start=v.start)}typeof v?.end=="number"&&(S.current.end=v.end)}const j=m?S.current.start??v?.start:v?.start,k=m?S.current.end??v?.end:v?.end,F=l.useMemo(()=>{if(!m)return[];const R=y?.summary;return Array.isArray(R)?R.filter(L=>typeof L=="object"&&L!==null):[]},[m,y]),A=l.useRef(F.length);l.useEffect(()=>{m&&A.current!==F.length&&(A.current=F.length,a?.("structural"))},[m,a,F.length]);const M=s.tool==="edit"||s.tool==="multiedit"?gy(y):null,b=xy(s,d,o,u),C=pi(s.tool).displayName,D=l.useContext(hi),P=R=>{if(m||!D?.editor){t(s.id);return}let L;if((s.tool==="edit"||s.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(s.tool))&&(L=x?.filePath||x?.file_path||x?.path||y?.filePath||y?.file_path||y?.path),typeof L=="string"){R.stopPropagation();let q=L;L.startsWith("/")||(q=u.endsWith("/")?u+L:u+"/"+L),D.editor.openFile(q)}else t(s.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:O("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:P,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:R=>{R.stopPropagation(),t(s.id)},children:[e.jsx("div",{className:O("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&h?{color:"var(--status-error)"}:{},children:yu(s.tool)}),e.jsx("div",{className:O("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(Nt,{className:"h-3.5 w-3.5"}):e.jsx(As,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:C})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[b&&e.jsx("span",{className:O("truncate",o&&"max-w-[120px]"),children:b}),M&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",M.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",M.removed]})]}),typeof j=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(hy,{start:j,end:typeof k=="number"?k:void 0,active:!!(m&&p&&typeof k!="number")})})]})]}),m&&(F.length>0||p||f)?e.jsx(wy,{entries:F,isExpanded:r,hasPrevTool:i,hasNextTool:c,output:typeof g.output=="string"?g.output:void 0}):null,!m&&r?e.jsx(ky,{part:s,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:c}):null]})},Ny=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
|
|
84
|
+
`).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
|
|
85
|
+
`).trim(),Cy=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=l.useMemo(()=>Ny(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Ci,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},My=l.memo(Cy),Dy=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(", ")},tc=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}),Ay=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},Ey=({parts:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:c,isWorking:d,previewedPartIds:u,diffStats:m})=>{const f=l.useRef(r),[p,h]=l.useState(0);l.useEffect(()=>{if(f.current===r)return;const x=f.current===!1;f.current=r,c?.("structural"),r&&x&&h(v=>v+1)},[r,c]);const w=l.useMemo(()=>tc(d?s.filter(x=>x.part.id&&u.has(x.id)):s),[s,d,u]),g=Dy(w),y=Ay(w);return w.length===0?null:e.jsx(rs,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:O("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:O("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(wn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:O("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(Nt,{className:"h-3.5 w-3.5"}):e.jsx(As,{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:O("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:w.map((x,v)=>{const S=x.part.id||`group-part-${v}`,N=y[S],j=`${S}-exp${p}`;switch(x.kind){case"tool":return e.jsx(rs,{children:e.jsx(ro,{part:x.part,isExpanded:a.has(S),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:N?.hasPrev??!1,hasNextTool:N?.hasNext??!1})},j);case"reasoning":return e.jsx(rs,{children:e.jsx(hu,{part:x.part,messageId:x.messageId,onContentChange:c})},j);case"justification":return e.jsx(rs,{children:e.jsx(My,{part:x.part,messageId:x.messageId,onContentChange:c})},j);default:return null}})})]})})},Iy=l.memo(Ey),Ty=({isMigrating:s,children:r,className:t})=>e.jsx("div",{className:O("w-full overflow-hidden",s&&"pointer-events-none",t),style:s?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:r}),fa=l.memo(Ty),bu=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},wu=s=>{if(s.type!=="text")return!1;const r=bu(s);return!r||r.trim().length===0},Fy=(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"))},Py=(s,r)=>{const t=l.useRef(null),n=l.useRef(null),[o,a]=l.useState(!1),i=l.useRef(s);i.current=s;const c=l.useRef(r);c.current=r;const d=l.useRef(!1),u=r.size>0;return l.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(c.current);f.length>0&&m.markPartsPreviewed(f)},300)},1e3)))},[u,s]),l.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]),l.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},Ry=new Set(["task"]),Or=s=>typeof s=="string"&&Ry.has(s.toLowerCase()),Ly=({messageId:s,parts:r,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:c,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=l.useState(!1),h=l.useRef(null),w=l.useMemo(()=>r.filter(A=>A.type!=="text"?!1:!wu(A)),[r]),g=d?.token;let y=!1;const x=!!a,v=!!i,S=!!(n??t),N=!!o,j=l.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),k=l.useCallback(()=>{!S||!x||!N||typeof window>"u"||(j(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[x,j,N,S]);l.useEffect(()=>{N||(p(!1),j())},[j,N]);const F=l.useCallback(A=>{!a||!N||(A.stopPropagation(),A.preventDefault(),a(),S&&k())},[N,S,a,k]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&x&&N?k:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:w.map((A,M)=>{let b;return d&&g&&!y&&bu(A).includes(g)&&(b=d,y=!0),e.jsx(rs,{children:e.jsx(ay,{part:A,messageId:s,isMobile:t,agentMention:b})},`user-text-${M}`)})}),e.jsx(Jd,{files:r,onShowPopup:c}),x&&N||u||m?e.jsxs("div",{className:O("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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{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:A=>A.stopPropagation(),onClick:A=>{A.stopPropagation(),u()},children:e.jsx(yn,{className:"h-3.5 w-3.5"})})}),e.jsx(Ye,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{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:A=>A.stopPropagation(),onClick:A=>{A.stopPropagation(),m()},children:e.jsx(Vt,{className:"h-3.5 w-3.5"})})}),e.jsx(Ye,{sideOffset:6,children:"Fork from here"})]}),x&&N&&e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{type:"button",variant:"ghost",size:"icon","data-visible":f||v?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:A=>A.stopPropagation(),onClick:F,onFocus:()=>p(!0),onBlur:()=>{v||p(!1)},children:v?e.jsx(Dt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(qs,{className:"h-3.5 w-3.5"})})}),e.jsx(Ye,{sideOffset:6,children:"Copy message"})]})]}):null]})},Oy=({messageId:s,parts:r,isMessageCompleted:t,messageFinish:n,syntaxTheme:o,isMobile:a,hasTouchInput:i,expandedTools:c,onToggleTool:d,onShowPopup:u,streamPhase:m,allowAnimation:f,onContentChange:p,hasTextContent:h=!1,onCopyMessage:w,copiedMessage:g=!1,onAuxiliaryContentComplete:y,showReasoningTraces:x=!1,turnGroupingContext:v,errorMessage:S})=>{const[N,j]=l.useState(!1),k=l.useRef(null),F=!!w,A=!!g,M=!!(i??a),b=!t,C=l.useMemo(()=>r.filter(ue=>!wu(ue)).filter(ue=>ue.type!=="compaction"),[r]),D=l.useMemo(()=>C.filter(ue=>ue.type==="tool"),[C]),P=l.useMemo(()=>C.filter(ue=>ue.type==="text"),[C]),R=he(ue=>ue.createSessionFromAssistantMessage),L=Fe(ue=>ue.openMultiRunLauncherWithPrompt),q=v?.isLastAssistantInTurn??!1,te=n==="stop",le=D.length>0,$=l.useMemo(()=>D.some(ue=>{const Ce=(ue.state??{})?.status;return Ce==="pending"||Ce==="running"||Ce==="started"}),[D]),z=l.useCallback(ue=>{const Se=ue.state??{},Ce=Se?.status;if(Ce==="pending"||Ce==="running"||Ce==="started")return!1;const Te=Se?.time??{},Ue=typeof Te?.end=="number"?Te.end:void 0,bt=typeof Te?.start=="number"?Te.start:void 0;return!(typeof Ue!="number"||typeof bt=="number"&&Ue<bt)},[]),E=l.useMemo(()=>D.length===0?!0:$?!1:D.every(ue=>z(ue)),[D,$,z]),H=l.useMemo(()=>P.length===0?!0:P.every(ue=>typeof ue.time?.end=="number"),[P]),Y=l.useMemo(()=>C.filter(ue=>ue.type==="reasoning"),[C]),fe=l.useMemo(()=>Y.length===0?!0:Y.every(ue=>typeof ue.time?.end=="number"),[Y]),ne=typeof n!="string",pe=Y.length>0&&le&&($||ne||!E),je=l.useMemo(()=>le?P.length===0?ne||$||!E:!0:P.length>0?pe:!1,[P.length,ne,$,le,pe,E]),U=b||je&&(!H||!E||$||ne)||pe,ee=b||le&&($||ne||!E),oe=b||pe,W=le||Y.length>0,me=P.length===0,ye=W&&me&&!ee&&!oe&&E&&fe,ce=l.useRef(!1),Me=l.useRef(!1);l.useEffect(()=>{Me.current=!1},[s]),l.useEffect(()=>{if(!ye){ce.current=!1;return}ce.current||(ce.current=!0,y?.())},[ye,y]),l.useEffect(()=>{if(b){Me.current=!1;return}if(le){Me.current=!1;return}Y.length!==0&&(oe||!fe||Me.current||(Me.current=!0,p?.("structural")))},[b,le,p,fe,Y.length,oe]);const Ee=!!h&&!b,Pe=l.useCallback(()=>{k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null)},[]),V=l.useCallback(()=>{!M||!F||!Ee||typeof window>"u"||(Pe(),j(!0),k.current=window.setTimeout(()=>{j(!1),k.current=null},1800))},[F,Pe,Ee,M]);l.useEffect(()=>{Ee||(j(!1),Pe())},[Pe,Ee]);const K=l.useCallback(ue=>{!w||!Ee||(ue.stopPropagation(),ue.preventDefault(),w(),M&&V())},[Ee,M,w,V]),T=l.useCallback(ue=>{ue.stopPropagation(),ue.preventDefault(),R&&R(s)},[R,s]),X=l.useCallback(ue=>{ue.stopPropagation(),ue.preventDefault();const Se=mi(P);if(!Se.trim())return;const Ce=`${yh}
|
|
86
|
+
|
|
87
|
+
${Se}`;L(Ce)},[P,L]);l.useEffect(()=>()=>{Pe()},[Pe]);const I=l.useMemo(()=>{const ue={},Se=D.filter(Ce=>Or(Ce.tool)||ee?!1:z(Ce));return Se.forEach((Ce,Te)=>{ue[Ce.id]={hasPrev:Te>0,hasNext:Te<Se.length-1}}),ue},[D,ee,z]),B=l.useMemo(()=>v?.activityParts??[],[v]),G=l.useMemo(()=>v?B.filter(ue=>ue.messageId===s):[],[B,s,v]),be=l.useMemo(()=>v?v.activityGroupSegments.filter(ue=>ue.anchorMessageId===s):[],[s,v]),J=l.useMemo(()=>{const ue=new Map;return G.forEach(Se=>{ue.set(Se.part,Se)}),ue},[G]),ge=l.useMemo(()=>v?(x?B:B.filter(Se=>Se.kind==="tool")).filter(Se=>{if(Se.kind!=="tool")return!0;const Ce=Se.part.tool;return!Or(Ce)}):[],[B,x,v]),[He,We]=l.useState(!1);l.useEffect(()=>{if(!v)return;const ue=v.activityGroupSegments.some(Se=>Se.afterToolPartId!==null);(ge.length>1||ue&&ge.length>0)&&We(!0)},[v,ge.length]);const Be=!!(v&&He),Ze=l.useMemo(()=>{if(!v)return[];if(!Be)return[];if(!v.isWorking)return[];const ue=[];return G.forEach(Se=>{if(v.previewedPartIds.has(Se.id)||!x&&Se.kind!=="tool")return;const Ce=Se.part;if(Se.kind==="tool"){const Te=Ce;if(Or(Te.tool)||ee||!z(Te))return}else if(Se.kind==="reasoning"){if(!x||oe||typeof Ce.time?.end!="number")return}else if(Se.kind==="justification"&&(!x||U||typeof Ce.time?.end!="number"))return;ue.push(Se)}),ue},[G,z,U,oe,ee,x,Be,v]),it=l.useMemo(()=>{const ue=new Set;return Ze.forEach(Se=>{ue.add(Se.id)}),ue},[Ze]),{isAnimating:lt}=Py(v,it),ct=!!(v&&Be&&ge.length>0&&be.length>0),mt=l.useMemo(()=>D.filter(ue=>Or(ue.tool)),[D]),xt=l.useMemo(()=>{const ue=[],Se=Te=>{!v||!ct||be.filter(Ue=>(Ue.afterToolPartId??null)===Te).forEach(Ue=>{const bt=x?Ue.parts:Ue.parts.filter(At=>At.kind==="tool");bt.length!==0&&ue.push(e.jsx(Iy,{parts:bt,isExpanded:v.isGroupExpanded,onToggle:v.toggleGroup,syntaxTheme:o,isMobile:a,expandedTools:c,onToggleTool:d,onShowPopup:u,onContentChange:p,isWorking:v.isWorking,previewedPartIds:v.previewedPartIds,diffStats:v.diffStats},`progressive-group-${Ue.id}`))})};Se(null),mt.forEach(Te=>{ue.push(e.jsx(rs,{children:e.jsx(ro,{part:Te,isExpanded:c.has(Te.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Te.id}`)),Se(Te.id)});const Ce=[];return C.forEach((Te,Ue)=>{const bt=J.get(Te);if(!bt||!v)return;let At=null,Mt=null;if(!Be){if(bt.kind==="tool"){const st=Te;if(Or(st.tool))return;const Ft=st.state?.time,ot=z(st);if(!(!ee&&ot))return;const qe=I[st.id];Mt=e.jsx(rs,{children:e.jsx(ro,{part:st,isExpanded:c.has(st.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:qe?.hasPrev??!1,hasNextTool:qe?.hasNext??!1})},`tool-${st.id}`),At=ot&&typeof Ft?.end=="number"?Ft.end:null}Mt&&Ce.push({part:Te,index:Ue,endTime:At,element:Mt});return}if(!v.isWorking||v.isGroupExpanded||v.previewedPartIds.has(bt.id)||!x&&bt.kind!=="tool")return;const pt=it.has(bt.id);switch(bt.kind){case"tool":{const st=Te;if(Or(st.tool))break;const Ft=st.state?.time,ot=z(st);if(!(!ee&&ot))break;const qe=I[st.id],Ke=e.jsx(rs,{children:e.jsx(ro,{part:st,isExpanded:c.has(st.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:qe?.hasPrev??!1,hasNextTool:qe?.hasNext??!1})},`tool-${st.id}`);Mt=pt?e.jsx(fa,{isMigrating:lt,children:Ke},`migrating-tool-${st.id}`):Ke,At=ot&&typeof Ft?.end=="number"?Ft.end:null;break}case"reasoning":{if(!x)break;const st=Te.time,jt=typeof st?.end=="number";if(!(jt&&!oe))break;const ot=e.jsx(rs,{children:e.jsx(hu,{part:Te,messageId:s,onContentChange:p})},`reasoning-${Ue}`);Mt=pt?e.jsx(fa,{isMigrating:lt,children:ot},`migrating-reasoning-${Ue}`):ot,At=jt?st?.end??null:null;break}case"justification":{if(!x)break;const st=Te.time,jt=typeof st?.end=="number";if(!(jt&&!U))break;const ot=e.jsx(rs,{children:e.jsx(ry,{part:Te,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:p,renderAsReasoning:!0})},`assistant-text-${Ue}`);Mt=pt?e.jsx(fa,{isMigrating:lt,children:ot},`migrating-text-${Ue}`):ot,At=jt?st?.end??null:null;break}}Mt&&Ce.push({part:Te,index:Ue,endTime:At,element:Mt})}),Ce.sort((Te,Ue)=>Te.endTime===null&&Ue.endTime===null?Te.index-Ue.index:Te.endTime===null?1:Ue.endTime===null?-1:Te.endTime-Ue.endTime),Ce.forEach(({element:Te})=>{ue.push(Te)}),ue},[J,be,c,lt,a,z,s,p,u,d,it,U,oe,ee,Be,x,o,I,v,C,mt,ct]),vt=v?.turnId,ht=he(ue=>ue.currentSessionId),yt=at(ue=>{if(!vt||!ht)return;const Se=ue.messages.get(ht);if(!Se)return;const Ce=Se.find(bt=>bt.info?.id===vt);if(!Ce)return;const Ue=Ce.info.summary?.body;return typeof Ue=="string"&&Ue.trim().length>0?Ue:void 0}),Q=typeof v?.summaryBody=="string"&&v.summaryBody.trim().length>0?v.summaryBody:yt,De=l.useRef(void 0);Q&&Q.trim().length>0&&(De.current=Q);const re=l.useRef(vt);re.current!==vt&&(re.current=vt,De.current=void 0);const ae=De.current,Ie=v?.isLastAssistantInTurn&&ae&&ae.trim().length>0,_e=!!S,ze=q&&h&&(te||!!S),[Ge,rt]=l.useState(!1),ie=e.jsxs(e.Fragment,{children:[e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{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:ue=>ue.stopPropagation(),onClick:T,children:e.jsx(yf,{className:"h-4 w-4"})})}),e.jsx(Ye,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{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:ue=>ue.stopPropagation(),onClick:X,children:e.jsx(Gd,{className:"h-4 w-4"})})}),e.jsx(Ye,{sideOffset:6,children:"Start new multi-run from this answer"})]}),w&&e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{type:"button",variant:"ghost",size:"icon","data-visible":N||A?"true":void 0,className:O("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",!Ee&&"opacity-50"),disabled:!Ee,"aria-label":"Copy message text","aria-hidden":!Ee,onPointerDown:ue=>ue.stopPropagation(),onClick:K,onFocus:()=>{Ee&&j(!0)},onBlur:()=>{A||j(!1)},children:A?e.jsx(Dt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(qs,{className:"h-3.5 w-3.5"})})}),e.jsx(Ye,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:O("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:M&&F&&Ee?V: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:[xt,_e&&e.jsx(rs,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Nr,{content:S??""})})},"assistant-error"),Ie&&e.jsx(rs,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>rt(!0),onMouseLeave:()=>rt(!1),children:[e.jsx(Nr,{content:ae}),ze&&e.jsx("div",{className:O("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",Ge&&"opacity-100 pointer-events-auto"),children:ie})]})},"summary-body")]}),e.jsx(Jd,{files:r,onShowPopup:u}),!Ie&&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:ie})]})})},$y=({isUser:s,...r})=>s?e.jsx(Ly,{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(Oy,{...r}),sc=l.memo($y),pa=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}},_y=l.lazy(()=>Kt(()=>import("./ToolOutputDialog-zILn8Ed6.js"),__vite__mapDeps([2,0,1,3,4]))),By=new Set(["task","edit","multiedit","write","bash"]),rc=s=>typeof s=="string"&&By.has(s.toLowerCase());function ha(s){const r=l.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 Ys=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},zy=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:c,hasTouchInput:d}=Ct(),{currentTheme:u}=Fr(),m=l.useRef(null),f=he(si(Ae=>({lifecyclePhase:Ae.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const qe=s.info.sessionID??Ae.currentSessionId??null;return qe?(Ae.streamingMessageIds.get(qe)??null)===s.info.id:!1})(),currentSessionId:Ae.currentSessionId,getCurrentAgent:Ae.getCurrentAgent,getSessionAgentSelection:Ae.getSessionAgentSelection,getAgentModelForSession:Ae.getAgentModelForSession,getSessionModelSelection:Ae.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:h,currentSessionId:w,getCurrentAgent:g,getSessionAgentSelection:y,getAgentModelForSession:x,getSessionModelSelection:v}=f,S=ut(Ae=>Ae.providers),N=Fe(Ae=>Ae.showReasoningTraces),j=Fe(Ae=>Ae.toolCallExpansion);l.useEffect(()=>{w&&ar.getInstance().recordSessionStart(w)},[w]);const[k,F]=l.useState(null),[A,M]=l.useState(!1),[b,C]=l.useState(new Set),[D,P]=l.useState({open:!1,title:"",content:""});l.useEffect(()=>{C(new Set)},[s.info.id,j]);const L=l.useMemo(()=>pa(s.info),[s.info]).isUser,q=l.useMemo(()=>L?s.parts.map(Ae=>Ae.type==="compaction"?{type:"text",text:"/summarize"}:Ae):s.parts,[L,s.parts]),te=l.useMemo(()=>{if(L||!r)return null;const Ae=Ys(r.info,"clientRole"),qe=Ys(r.info,"role");if((typeof Ae=="string"?Ae:typeof qe=="string"?qe:void 0)!=="user")return null;const ft=Ys(r.info,"mode"),St=Ys(r.info,"providerID"),Pt=Ys(r.info,"modelID"),cs=typeof ft=="string"&&ft.trim().length>0?ft:void 0,Os=typeof St=="string"&&St.trim().length>0?St:void 0,Ss=typeof Pt=="string"&&Pt.trim().length>0?Pt:void 0;return!cs&&!Os&&!Ss?null:{agentName:cs,providerId:Os,modelId:Ss}},[L,r]),le=l.useMemo(()=>{if(L)return;const Ae=Ys(s.info,"mode");if(typeof Ae=="string"&&Ae.trim().length>0)return Ae;if(te?.agentName)return te.agentName;const qe=s.info.sessionID;if(!qe)return;const Ke=g(qe);return Ke||(y(qe)??void 0)},[L,s.info,te,g,y]),$=s.info.sessionID,z=L?null:Ys(s.info,"providerID"),E=L?null:Ys(s.info,"modelID"),H=l.useMemo(()=>{if(L||!$)return null;if(te?.providerId&&te?.modelId)return{providerId:te.providerId,modelId:te.modelId};if(le){const qe=x($,le);if(qe?.providerId&&qe?.modelId)return qe}const Ae=v($);return Ae?.providerId&&Ae?.modelId?Ae:null},[L,$,le,te,x,v]),Y=l.useMemo(()=>L?null:typeof z=="string"&&z.trim().length>0?z:H?.providerId??null,[L,z,H]),fe=l.useMemo(()=>L?null:typeof E=="string"&&E.trim().length>0?E:H?.modelId??null,[L,E,H]),ne=l.useMemo(()=>{if(!L&&Y&&fe&&S.length>0){const Ae=S.find(qe=>qe.id===Y);if(Ae?.models&&Array.isArray(Ae.models)){const ft=Ae.models.find(St=>St.id===fe)?.name;return typeof ft=="string"?ft:void 0}}},[L,Y,fe,S]),pe=ha(le),je=ha(Y??void 0),U=ha(ne),ee=pe??void 0,oe=je??null,W=U??void 0,me=l.useMemo(()=>{const Ae=s.info.time;return typeof Ae?.completed=="number"?Ae.completed:null},[s.info.time]),ye=l.useMemo(()=>L?!0:!!(me&&me>0),[L,me]),ce=l.useMemo(()=>{const Ae=s.info.finish;return typeof Ae=="string"?Ae:void 0},[s.info]),Me=l.useMemo(()=>Fy(q,{includeReasoning:N}),[q,N]),Ee=l.useMemo(()=>L||ye?Me:[],[L,ye,Me]),Pe=l.useMemo(()=>L?[]:Me.filter(Ae=>Ae.type==="text"),[L,Me]),V=l.useMemo(()=>L?[]:Me.filter(qe=>qe.type==="tool"),[L,Me]),K=l.useMemo(()=>{if(j==="collapsed"||j==="activity")return b;const Ae=new Set;for(const Ke of V){const ft=Ke.tool;Ke.id&&rc(ft)&&Ae.add(Ke.id)}if(i?.isFirstAssistantInTurn)for(const Ke of i.activityParts){if(Ke.kind!=="tool")continue;const ft=Ke.part;ft.id&&rc(ft.tool)&&Ae.add(ft.id)}const qe=new Set(Ae);for(const Ke of b)qe.has(Ke)?qe.delete(Ke):qe.add(Ke);return qe},[b,j,V,i]),T=l.useMemo(()=>{if(!L)return;const Ae=s.parts.find(St=>St.type==="agent");if(!Ae)return;const qe=Ae,Ke=typeof qe.name=="string"?qe.name:void 0;if(!Ke)return;const ft=qe.source&&typeof qe.source.value=="string"&&qe.source.value.trim().length>0?qe.source.value:`#${Ke}`;return{name:Ke,token:ft}},[L,s.parts]),X=typeof ce!="string",I=l.useMemo(()=>L?!1:Pe.length===0||V.length===0?X:!0,[Pe.length,V.length,X,L]),B=u?.metadata.variant,G=l.useMemo(()=>B?B==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[B]),be=l.useMemo(()=>u?cu(u):G?Hx:Ux,[u,G]),J=l.useMemo(()=>L?!1:ar.getInstance().shouldAnimateMessage(s.info,w||s.info.sessionID),[s.info,w,L]),ge=l.useRef(!1),He=l.useMemo(()=>r?pa(r.info):null,[r]),We=l.useMemo(()=>t?pa(t.info):null,[t]),Be=l.useMemo(()=>L||!We?!1:!We.isUser&&We.role==="assistant",[L,We]),Ze=l.useMemo(()=>ye?"completed":p||(h?"streaming":"completed"),[ye,p,h]),it=l.useMemo(()=>{if(L)return!0;const Ae=i?.headerMessageId;if(Ae){if(s.info.id===Ae){if(Ze==="completed")return!0;const Ke=Ze==="streaming"||Ze==="cooldown",ft=ge.current;return Ke&&!ft&&(ge.current=!0),ft||Ke}return!1}return He?He.isUser:!0},[L,He,i,Ze,s.info]),lt=l.useCallback(Ae=>{navigator.clipboard.writeText(Ae),F(Ae),setTimeout(()=>F(null),2e3)},[]),ct=i?.turnId,mt=at(Ae=>{if(!ct)return;const qe=s.info.sessionID;if(!qe)return;const Ke=Ae.messages.get(qe);if(!Ke)return;const ft=Ke.find(cs=>cs.info?.id===ct);if(!ft)return;const Pt=ft.info.summary?.body;return typeof Pt=="string"&&Pt.trim().length>0?Pt:void 0}),xt=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:mt,vt=l.useRef(void 0);xt&&xt.trim().length>0&&(vt.current=xt);const ht=l.useRef(ct);ht.current!==ct&&(ht.current=ct,vt.current=void 0);const yt=vt.current,Q=l.useMemo(()=>{if(L)return;const Ae=s.info?.error;if(!Ae)return;const qe=typeof Ae.data?.message=="string"?Ae.data.message:void 0,Ke=typeof Ae.message=="string"?Ae.message:void 0,ft=typeof Ae.name=="string"?Ae.name:void 0,St=qe||Ke||ft;if(St)return`Opencode failed to send message with error:
|
|
88
|
+
\`${St}\``},[L,s.info]),De=l.useMemo(()=>L?Ee.filter(Ke=>Ke.type==="text").map(Ke=>(Ke.text||Ke.content||"").trim()).filter(Ke=>Ke.length>0).join(`
|
|
89
|
+
`).replace(/\n\s*\n+/g,`
|
|
90
|
+
`):Q&&Q.trim().length>0?Q:yt&&yt.trim().length>0?yt:mi(Ee),[Q,yt,Ee,L]),re=De.length>0,ae=l.useCallback(()=>{navigator.clipboard.writeText(De),M(!0),setTimeout(()=>M(!1),2e3)},[De]),Ie=he(Ae=>Ae.revertToMessage),_e=he(Ae=>Ae.forkFromMessage),ze=l.useCallback(()=>{!$||!s.info.id||Ie($,s.info.id)},[$,s.info.id,Ie]),Ge=l.useCallback(()=>{!$||!s.info.id||_e($,s.info.id)},[$,s.info.id,_e]),rt=l.useCallback(Ae=>{C(qe=>{const Ke=new Set(qe);return Ke.has(Ae)?Ke.delete(Ae):Ke.add(Ae),Ke})},[]),ie=o??null,ue=l.useRef(!1),Se=l.useRef(!1),Ce=l.useRef(!1),Te=l.useRef(!1),Ue=l.useRef(!1);l.useEffect(()=>{Se.current=!1,Ce.current=!1,Te.current=!1,Ue.current=!1,ue.current=!1},[s.info.id]);const bt=l.useCallback(()=>{L||ue.current||(ue.current=!0,n?.("structural"))},[L,n]),At=l.useCallback(Ae=>{Ae.image&&P(Ae)},[]),Mt=l.useCallback(Ae=>{P(qe=>({...qe,open:Ae}))},[]),pt=!!Ys(s.info,"animationSettled"),st=Ze==="streaming",jt=l.useMemo(()=>L?!1:Me.some(Ae=>Ae.type==="reasoning"),[L,Me]),Ft=J&&!pt&&!st,ot=!L&&J&&Pe.length>0&&!I;return l.useEffect(()=>{if(ie?.onStreamingCandidate){if(!ot){Ce.current&&(jt&&ie?.onReasoningBlock?ie.onReasoningBlock():ie?.onReservationCancelled&&ie.onReservationCancelled(),Ce.current=!1);return}Ue.current||(Ue.current=!0,ie.onStreamingCandidate(),Ce.current=!0)}},[ie,ot,jt]),l.useEffect(()=>{ie?.onAnimationStart&&Ft&&(Te.current||(ie.onAnimationStart(),Te.current=!0))},[ie,Ft]),l.useEffect(()=>{if(L)return;const Ae=ie?.onAnimatedHeightChange;if(!Ae||!(Ft||ot))return;const Ke=m.current;if(!Ke)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Ae(Ke.getBoundingClientRect().height);return}let ft=null;const St=cs=>{if(typeof window>"u"){Ae(cs);return}ft!==null&&window.cancelAnimationFrame(ft),ft=window.requestAnimationFrame(()=>{Ae(cs)})},Pt=new ResizeObserver(cs=>{const Os=cs[0];Os&&St(Os.contentRect.height)});return Pt.observe(Ke),St(Ke.getBoundingClientRect().height),()=>{ft!==null&&(window.cancelAnimationFrame(ft),ft=null),Pt.disconnect()}},[Ft,L,ie,ot]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:O("group w-full",it?"pt-2":"pt-0",L?"pb-2":Be?"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:L?e.jsx(rs,{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(sc,{messageId:s.info.id,parts:Me,isUser:L,isMessageCompleted:ye,messageFinish:ce,syntaxTheme:be,isMobile:c,hasTouchInput:d,copiedCode:k,onCopyCode:lt,expandedTools:b,onToggleTool:rt,onShowPopup:At,streamPhase:Ze,allowAnimation:Ft,onContentChange:n,shouldShowHeader:!1,hasTextContent:re,onCopyMessage:ae,copiedMessage:A,showReasoningTraces:N,onAuxiliaryContentComplete:bt,agentMention:T,onRevert:ze,onFork:L?Ge:void 0,errorMessage:Q})})})}):e.jsxs("div",{children:[it&&e.jsx(Vx,{isUser:L,providerID:oe,agentName:ee,modelName:W,isDarkTheme:G}),e.jsx(sc,{messageId:s.info.id,parts:Me,isUser:L,isMessageCompleted:ye,messageFinish:ce,syntaxTheme:be,isMobile:c,hasTouchInput:d,copiedCode:k,onCopyCode:lt,expandedTools:K,onToggleTool:rt,onShowPopup:At,streamPhase:Ze,allowAnimation:Ft,onContentChange:n,shouldShowHeader:it,hasTextContent:re,onCopyMessage:ae,copiedMessage:A,onAuxiliaryContentComplete:bt,showReasoningTraces:N,agentMention:T,turnGroupingContext:i,errorMessage:Q})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(_y,{popup:D,onOpenChange:Mt,syntaxTheme:be,isMobile:c})})]})},Hy=l.memo(zy),Uy=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:xu(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:O("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(Bs,{style:r,language:Ir(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))}),Wy=({content:s,syntaxTheme:r,filePath:t})=>{const n=s.split(`
|
|
91
|
+
`),o=Ir(t??"")||"text",a=t?.split("/").pop()||"New file",i=Math.max(n.length,1),c=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} (${c})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Bs,{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))})]})},Vy=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(Qs,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(Qc,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(mr,{className:r}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(Ea,{className:r}):e.jsx(Io,{className:r})},Gy=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},qy=({permission:s,onResponse:r})=>{const[t,n]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=he(),{currentTheme:c}=Fr(),d=l.useMemo(()=>cu(c),[c]),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.type||"Unknown Tool",f=m.toLowerCase(),p=(x,v="")=>{const S=s.metadata[x];return typeof S=="string"?S:typeof S=="number"?String(S):v},h=x=>{const v=s.metadata[x];return typeof v=="number"?v:void 0},w=x=>!!s.metadata[x],g=Gy(m),y=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const S=p("command")||p("cmd")||p("script"),N=p("description"),j=p("cwd")||p("working_directory")||p("directory")||p("path"),k=h("timeout"),F=s.title===S;return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:N}),j&&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:j})]}),k&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",k,"ms"]}),S&&!F&&e.jsx("div",{children:e.jsx(Bs,{language:"bash",style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:S})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("changes")||p("diff"),j=w("replace_all")||w("replaceAll");return e.jsxs(e.Fragment,{children:[j&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),N&&e.jsx(tt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Uy,{diff:N,syntaxTheme:d,filePath:S})})]})}if(f==="write"||f==="create"||f==="file_write"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("content")||p("text")||p("data");return N?e.jsx(tt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Wy,{content:N,syntaxTheme:d,filePath:S})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const S=p("url")||p("uri")||p("endpoint"),N=p("method")||"GET",j=s.metadata.headers&&typeof s.metadata.headers=="object"?s.metadata.headers:void 0,k=p("body")||p("data")||p("payload"),F=h("timeout"),A=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[S&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Request:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded",children:N}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:S})]})]}),j&&Object.keys(j).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(tt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(Bs,{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(j,null,2)})})]}),k&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(tt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(Bs,{language:typeof k=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof k=="object"?JSON.stringify(k,null,2):String(k)})})]}),(F||A)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[F&&e.jsxs("span",{children:["Timeout: ",F,"ms"]}),F&&A&&e.jsx("span",{children:" • "}),A&&e.jsxs("span",{children:["Response format: ",A]})]})]})}const x=p("command")||p("content")||p("action")||p("operation"),v=p("description");return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),x&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(tt,{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&&!v&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(tt,{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(Gr,{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:[Vy(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:g})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[(()=>{let x="",v="text",S=!1;f==="bash"||f==="shell"||f==="shell_command"?(x=p("command")||p("cmd")||p("script"),v="bash",S=!0):f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"||f==="write"||f==="create"||f==="file_write"?(x=p("path")||p("file_path")||p("filename")||p("filePath"),S=!1):(f==="webfetch"||f==="fetch")&&(x=p("url")||p("uri")||p("endpoint"),S=!1);const N=s.title===x;return N&&x&&S?e.jsx("div",{className:"mb-3",children:e.jsx(Bs,{language:v,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:x})}):N&&x&&!S?e.jsx("div",{className:"mb-3",children:e.jsx("code",{className:"typography-ui-label px-2 py-1 bg-muted/30 rounded block break-all",children:x})}):s.title?e.jsx("div",{className:O("typography-ui-label text-foreground mb-3",(S||x)&&"font-mono"),children:s.title}):null})(),y()]}),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:O("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(Dt,{className:"h-3 w-3"}),"Allow Once"]}),e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:O("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:O("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(Wt,{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"})})]})]})})})},Ky=new Set(["task"]),nc=s=>typeof s=="string"&&Ky.has(s.toLowerCase()),Yy=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},Xy=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}}},Qy=s=>{const r=Xy(s);let t;const o=s.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let x=0,v=0,S=0;o.forEach(N=>{if(!N)return;const j=typeof N.additions=="number"?N.additions:0,k=typeof N.deletions=="number"?N.deletions:0;(j!==0||k!==0)&&(S+=1),x+=j,v+=k}),S>0&&(t={additions:x,deletions:v,files:S})}let a=!1,i=!1;s.assistantMessages.forEach(x=>{x.parts.forEach(v=>{v.type==="tool"?a=!0:v.type==="reasoning"&&(i=!0)})});const c=[];let d=0;s.assistantMessages.forEach(x=>{const v=x.info.id;x.info.finish,x.parts.forEach(S=>{const N=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-activity-${d++}`;if(S.type==="tool"){const k=S.state?.time,F=typeof k?.end=="number"?k.end:void 0;c.push({id:N,turnId:s.turnId,messageId:v,kind:"tool",part:S,endedAt:F});return}if(S.type==="reasoning"){const j=S.text??S.content;if(typeof j!="string"||j.trim().length===0)return;const k=S.time,F=typeof k?.end=="number"?k.end:void 0;c.push({id:N,turnId:s.turnId,messageId:v,kind:"reasoning",part:S,endedAt:F});return}})});const u=[],m=new WeakMap;c.forEach(x=>{m.set(x.part,x)});const f=new Map,p=[],h=new Map;let w=null;s.assistantMessages.forEach(x=>{const v=x.info.id;x.parts.forEach(S=>{if(S.type==="tool"){const k=S.tool;if(nc(k)){const F=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-task-${p.length+1}`;f.has(F)||(f.set(F,v),p.push(F)),w=F;return}}const N=m.get(S);if(!N)return;if(N.kind==="tool"){const k=N.part.tool;if(nc(k))return}const j=h.get(w)??[];j.push(N),h.set(w,j)})});const g=x=>{if(x.length===0)return;const v=new Map;x.forEach(j=>{v.set(j.messageId,(v.get(j.messageId)??0)+1)});let S,N=0;for(const j of s.assistantMessages){const k=v.get(j.info.id)??0;if(k>0&&!S&&(S=j.info.id),N+=k,N>=2)return j.info.id}return S};return[null,...p].forEach(x=>{const v=h.get(x)??[];if(v.length===0)return;const S=x===null?g(v):f.get(x);S&&u.push({id:`${s.turnId}:${S}:${x??"start"}`,anchorMessageId:S,afterToolPartId:x,parts:v})}),{activityParts:c,activityGroupSegments:u,hasTools:a,hasReasoning:i,summaryBody:r,diffStats:t}},Jy=s=>{const{isWorking:r}=ki(),t=l.useMemo(()=>Yy(s),[s]),n=l.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=l.useMemo(()=>{const g=new Map;return t.forEach(y=>{g.set(y.userMessage.info.id,y),y.assistantMessages.forEach(x=>{g.set(x.info.id,y)})}),g},[t]),a=l.useMemo(()=>{const g=new Map;return t.forEach(y=>{g.set(y.turnId,Qy(y))}),g},[t]),[i,c]=l.useState(()=>new Map),d=Fe(g=>g.toolCallExpansion),u=d==="activity"||d==="detailed";l.useEffect(()=>{c(new Map)},[d]);const m=l.useCallback(g=>{const y=i.get(g);return y||{isExpanded:u,previewedPartIds:new Set}},[i,u]),f=l.useCallback(g=>{c(y=>{const x=new Map(y),v=x.get(g)??{isExpanded:u,previewedPartIds:new Set};return x.set(g,{...v,isExpanded:!v.isExpanded}),x})},[u]),p=l.useCallback((g,y)=>{y.length!==0&&c(x=>{const v=new Map(x),S=v.get(g)??{isExpanded:u,previewedPartIds:new Set},N=new Set(S.previewedPartIds);return y.forEach(j=>{j&&j.trim().length>0&&N.add(j)}),v.set(g,{...S,previewedPartIds:N}),v})},[u]),h=l.useCallback(g=>o.get(g),[o]),w=l.useCallback(g=>{const y=o.get(g);if(!y||!y.assistantMessages.some(q=>q.info.id===g))return;const v=a.get(y.turnId),S=v?.activityParts??[],N=v?.activityGroupSegments??[],j=!!v?.hasTools,k=!!v?.hasReasoning,F=v?.summaryBody,A=v?.diffStats,M=y.assistantMessages[0]?.info.id,b=g===M,C=y.assistantMessages[y.assistantMessages.length-1]?.info.id,D=g===C,P=M,R=m(y.turnId),L=r&&n===y.turnId;return{turnId:y.turnId,isFirstAssistantInTurn:b,isLastAssistantInTurn:D,summaryBody:F,activityParts:S,activityGroupSegments:N,headerMessageId:P,hasTools:j,hasReasoning:k,diffStats:A,isWorking:L,isGroupExpanded:R.isExpanded,previewedPartIds:R.previewedPartIds,toggleGroup:()=>f(y.turnId),markPartsPreviewed:q=>p(y.turnId,q)}},[m,n,p,o,r,f,a]);return{turns:t,getTurnForMessage:h,getContextForMessage:w}},Zy=({messages:s,permissions:r,onMessageContentChange:t,getAnimationHandlers:n,hasMoreAbove:o,isLoadingOlder:a,onLoadOlder:i,scrollToBottom:c,pendingAnchorId:d})=>{l.useEffect(()=>{r.length!==0&&t("permission")},[r,t]);const u=l.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:Ix(p.parts)}))},[s]),{getContextForMessage:m}=Jy(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(Hy,{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:c,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(qy,{permission:f},f.id))})]})},eb=l.memo(Zy);function tb(...s){return r=>{s.forEach(t=>{typeof t=="function"?t(r):t&&typeof t=="object"&&(t.current=r)})}}const vu=l.forwardRef(({orientation:s="vertical",offset:r=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:c,children:d,...u},m)=>{const f=l.useRef(null),p=l.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const w=l.useMemo(()=>{const v={...i};return v["--scroll-shadow-size"]=`${t}px`,v},[t,i]),g=l.useCallback((v,S,N,j,k)=>{const F=`${j}${k.charAt(0).toUpperCase()}${k.slice(1)}Scroll`;S&&N?(v.dataset[F]="true",v.removeAttribute(`data-${j}-scroll`),v.removeAttribute(`data-${k}-scroll`)):(v.dataset[`${j}Scroll`]=String(S),v.dataset[`${k}Scroll`]=String(N),v.removeAttribute(`data-${j}-${k}-scroll`))},[]),y=l.useCallback(v=>{["top","bottom","top-bottom","left","right","left-right"].forEach(S=>{v.removeAttribute(`data-${S}-scroll`)})},[]),x=l.useCallback(()=>{const v=f.current;if(!v)return;if(!n){y(v);return}const S=s==="vertical"?v.scrollTop>r:v.scrollLeft>r;let N=s==="vertical"?v.scrollTop+v.clientHeight+r<v.scrollHeight:v.scrollLeft+v.clientWidth+r<v.scrollWidth;o&&s==="vertical"&&(N=!1),g(v,S,N,s==="vertical"?"top":"left",s==="vertical"?"bottom":"right");const j=S&&N?"both":S?s==="vertical"?"top":"left":N?s==="vertical"?"bottom":"right":"none";j!==p.current&&(p.current=j,a?.(j))},[y,o,n,r,a,s,g]);return l.useEffect(()=>{const v=f.current;if(!v)return;const S=()=>x(),N=typeof ResizeObserver<"u"?new ResizeObserver(()=>x()):null,j=typeof MutationObserver<"u"?new MutationObserver(()=>x()):null;return x(),v.addEventListener("scroll",S,{passive:!0}),N?.observe(v),j?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{v.removeEventListener("scroll",S),N?.disconnect(),j?.disconnect()}},[x]),e.jsx("div",{...u,ref:tb(f,m),className:c,"data-orientation":s,"data-scroll-shadow":h??!0,style:w,children:d})});vu.displayName="ScrollShadow";const sb=160,rb=({containerRef:s})=>{const[r,t]=l.useState(!0),n=l.useRef(!0),o=l.useRef(!1),a=l.useRef(null),i=l.useRef(null),c=l.useRef(0),d=l.useRef(0),u=l.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),m=l.useCallback(S=>{const N=s.current;if(!N){u();return}i.current===null&&(i.current=S);const j=Math.min(1,(S-i.current)/sb),k=1-Math.pow(1-j,3),F=c.current,A=d.current,M=F+(A-F)*k;if(N.scrollTop=M,j<1){a.current=window.requestAnimationFrame(m);return}N.scrollTop=A,u(),n.current&&(n.current=!1,t(!1))},[u,s,t]),f=l.useCallback((S,N)=>{const j=s.current;if(!j)return;const k=Math.max(0,S),F=N?.instant??!1;if(o.current=!1,typeof window>"u"||F){u(),j.scrollTop=k;const M=k<=1;n.current!==M&&(n.current=M,t(M));return}if(u(),Math.abs(k-j.scrollTop)<=.5){j.scrollTop=k;const M=k<=1;n.current!==M&&(n.current=M,t(M));return}c.current=j.scrollTop,d.current=k,i.current=null,a.current=window.requestAnimationFrame(m)},[u,s,m,t]),p=l.useCallback(()=>{o.current=!0},[]),h=l.useCallback(()=>{o.current=!0},[]),w=l.useCallback(()=>o.current,[]),g=l.useCallback(()=>s.current?.scrollTop??0,[s]),y=l.useCallback(()=>s.current?.scrollHeight??0,[s]),x=l.useCallback(()=>s.current?.clientHeight??0,[s]),v=l.useCallback(()=>{const S=s.current;if(!S)return;o.current&&a.current!==null&&u();const N=S.scrollTop<=1;n.current!==N&&(n.current=N,t(N))},[u,s]);return l.useEffect(()=>{const S=s.current;if(S)return S.addEventListener("wheel",h,{passive:!0}),S.addEventListener("touchstart",h,{passive:!0}),()=>{S.removeEventListener("wheel",h),S.removeEventListener("touchstart",h)}},[s,h]),l.useEffect(()=>()=>{u()},[u]),l.useMemo(()=>({handleScroll:v,scrollToPosition:f,forceManualMode:p,isAtTop:r,isManualOverrideActive:w,getScrollTop:g,getScrollHeight:y,getClientHeight:x}),[v,f,p,r,w,g,y,x])},oc=typeof window<"u"?l.useLayoutEffect:l.useEffect,ac=50,ic=40,nb=.2,ob=.1,ab=150,Ns=s=>{const r=s.info;return typeof r?.id=="string"?r.id:null},ib=s=>{const r=s.info;if(r?.userMessageMarker===!0)return!0;const t=r?.clientRole,n=r?.role;return t==="user"||n==="user"},lb=({currentSessionId:s,sessionMessages:r,updateViewportAnchor:t,updateActiveTurnAnchor:n,getActiveTurnAnchor:o,isSyncing:a,isMobile:i,sessionActivityPhase:c})=>{const d=l.useRef(null),u=rb({containerRef:d}),[m,f]=l.useState(null),[p,h]=l.useState(0),[w,g]=l.useState(!1),[y,x]=l.useState(null),v=l.useRef(null),S=l.useRef(null),N=l.useRef(r.length),j=l.useRef(r.length>0?Ns(r[0]):null),k=l.useRef(r.length>0?Ns(r[r.length-1]):null),F=l.useRef(0),A=l.useRef(0),M=l.useRef(void 0),b=l.useRef(null),C=l.useRef(!1),D=l.useRef(!1),P=l.useRef(null),R=s?c?.get(s)??"idle":"idle",L=l.useCallback(U=>{const ee=Math.max(0,U);F.current!==ee&&(F.current=ee,h(ee))},[]),q=l.useCallback(()=>{const U=d.current;U&&(A.current=U.clientHeight)},[]),te=l.useCallback(()=>{if(!m)return null;const U=d.current;return U?U.querySelector(`[data-message-id="${m}"]`):null},[m]),le=l.useCallback(()=>{const U=d.current,ee=F.current;if(!U||ee<=0)return!0;const oe=U.scrollHeight-ee;return U.scrollTop+U.clientHeight<oe},[]),$=l.useCallback((U,ee)=>{const oe=U.offsetHeight,W=U.offsetTop;if(oe>ee*nb){const ye=ee*ob;return W+oe-ye}else return W-ac},[]),z=l.useCallback(()=>{const U=d.current;if(!U||!b.current)return;const ee=te();if(!ee)return;const oe=U.clientHeight,W=U.scrollHeight,ye=$(ee,oe)+oe,ce=F.current,Me=W-ce;if(!C.current&&Me<ye){const Ee=ye-Me;Ee>ce&&(L(Ee),s&&b.current&&n(s,b.current,Ee))}},[$,s,te,n,L]),E=l.useCallback(()=>{const U=d.current;if(!U){g(!1);return}if(y){g(!1);return}if(!(U.scrollHeight>U.clientHeight)){g(!1);return}const oe=U.scrollHeight-U.scrollTop-U.clientHeight,W=F.current;if(W>0){const me=U.scrollHeight-W,ye=U.scrollTop+U.clientHeight;g(ye<me)}else g(oe>ic)},[y]),H=l.useCallback(U=>{const ee=d.current;if(!ee)return;const oe=ee.scrollHeight-ee.scrollTop-ee.clientHeight;if(D.current&&R==="idle"&&!a&&!U?.force&&oe>ic)return;U?.force&&(D.current=!1);const me=ee.scrollHeight-ee.clientHeight;u.scrollToPosition(Math.max(0,me),U)},[R,a,u]),Y=l.useCallback(U=>{if(v.current===U)return;v.current=U,x(U);const ee=d.current;if(!ee){x(null);return}const oe=ee.scrollHeight,W=F.current,me=oe-W,ye=A.current>0?A.current:ee.clientHeight,Me=me-ac,Ee=Me+ye;let Pe=0;me<Ee&&(Pe=Ee-me),Pe!==W&&L(Pe),s&&n(s,U,Pe),C.current=!0,window.requestAnimationFrame(()=>{u.scrollToPosition(Me,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[s,u,n,L]),fe=l.useCallback(U=>{const ee=d.current;if(!ee||!s)return;U?.isTrusted&&(D.current=!0),u.handleScroll(),E(),R==="idle"&&F.current>0&&le()&&(L(0),b.current=null,f(null),n(s,null,0));const{scrollTop:oe,scrollHeight:W,clientHeight:me}=ee,ye=(oe+me/2)/Math.max(W,1),ce=Math.floor(ye*r.length);t(s,ce)},[s,R,le,u,r.length,n,E,L,t]);l.useEffect(()=>{const U=d.current;if(U)return U.addEventListener("scroll",fe,{passive:!0}),()=>{U.removeEventListener("scroll",fe)}},[fe]),oc(()=>{if(typeof window>"u")return;q();const U=()=>{M.current!==void 0&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{q()},ab)};return window.addEventListener("resize",U),()=>{window.removeEventListener("resize",U),M.current!==void 0&&window.clearTimeout(M.current)}},[q]),l.useEffect(()=>{if(s&&s!==S.current){S.current=s,ar.getInstance().recordSessionStart(s),N.current=r.length,j.current=r.length>0?Ns(r[0]):null,k.current=r.length>0?Ns(r[r.length-1]):null;const U=o(s);R!=="idle"&&U&&U.anchorId?(b.current=U.anchorId,v.current=U.anchorId,C.current=!0,f(U.anchorId),F.current=U.spacerHeight,h(U.spacerHeight),window.requestAnimationFrame(()=>{const oe=d.current;if(!oe)return;const W=oe.querySelector(`[data-message-id="${U.anchorId}"]`);if(W){const me=oe.clientHeight,ye=$(W,me);u.scrollToPosition(ye,{instant:!0})}})):(v.current=null,b.current=null,C.current=!1,f(null),F.current=0,h(0),window.requestAnimationFrame(()=>{H({instant:!0,force:!0})})),x(null),g(!1),D.current=!1,P.current=null}},[R,s,H,r.length,o]),oc(()=>{if(a){N.current=r.length,j.current=r.length>0?Ns(r[0]):null,k.current=r.length>0?Ns(r[r.length-1]):null;return}if(S.current!==s)return;const U=N.current,ee=r.length;if(ee>U&&U>0){const oe=j.current,W=Ns(r[0]),me=Ns(r[ee-1]),ye=k.current,ce=oe!==null&&W!==oe,Me=ye!==null&&me!==ye,Ee=ce&&!Me,Pe=Me&&!ce;if(Ee){b.current=null,C.current=!1,f(null),L(0),N.current=ee,j.current=W,k.current=me;return}if(Pe){const K=r.slice(U,ee).find(ib);if(K){const T=Ns(K);T&&(b.current=T,f(T),Y(T))}else z()}}N.current=ee,j.current=r.length>0?Ns(r[0]):null,k.current=r.length>0?Ns(r[r.length-1]):null},[s,a,z,Y,r]),l.useEffect(()=>{const U=d.current;if(!U||typeof ResizeObserver>"u")return;const ee=new ResizeObserver(()=>{z(),E()});return ee.observe(U),()=>{ee.disconnect()}},[z,E]),l.useEffect(()=>{if(typeof window>"u"){E();return}const U=window.requestAnimationFrame(()=>{E()});return()=>{window.cancelAnimationFrame(U)}},[s,r.length,E]),l.useEffect(()=>{m&&(z(),E())},[m,z,E]),l.useEffect(()=>{const U=P.current;P.current=R,U!==null&&U!=="idle"&&R==="idle"&&F.current>0&&le()&&b.current!==null&&(L(0),b.current=null,C.current=!1,f(null),s&&n(s,null,0))},[R,s,le,n,L]),l.useEffect(()=>{E()},[p,E]);const ne=l.useRef(new Map),pe=l.useCallback(()=>{z(),E()},[z,E]),je=l.useCallback(U=>{const ee=ne.current.get(U);if(ee)return ee;const oe={onChunk:()=>{z()},onComplete:()=>{z()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{z()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return ne.current.set(U,oe),oe},[z]);return{scrollRef:d,handleMessageContentChange:pe,getAnimationHandlers:je,showScrollButton:w,scrollToBottom:H,spacerHeight:p,pendingAnchorId:y,hasActiveAnchor:m!==null}};function cb(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 db=({open:s,onOpenChange:r,onScrollToMessage:t})=>{const n=he(g=>g.currentSessionId),o=at(g=>n?g.messages.get(n)||[]:[]),a=he(g=>g.revertToMessage),i=he(g=>g.forkFromMessage),c=he(g=>g.loadSessions),[d,u]=l.useState(null),[m,f]=l.useState(""),p=l.useMemo(()=>o.filter(y=>y.info.role==="user").reverse(),[o]),h=l.useMemo(()=>{if(!m.trim())return p;const g=m.toLowerCase();return p.filter(y=>lc(y.parts).toLowerCase().includes(g))},[p,m]),w=async g=>{if(n){u(g);try{await i(n,g),await c(),r(!1)}finally{u(null)}}};return n?e.jsx(as,{open:s,onOpenChange:r,children:e.jsxs(is,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(ds,{children:[e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(tr,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(js,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(dt,{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 y=lc(g.parts),x=g.info.time.created,v=cb(x),S=p.length-p.indexOf(g);return e.jsxs("div",{className:"group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",onClick:()=>{t?.(g.info.id),r(!1)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:[S,"."]}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:[y||"[No text content]",y&&y.length>=80&&"…"]}),e.jsxs("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground whitespace-nowrap group-hover:hidden",children:v}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:async N=>{N.stopPropagation(),await a(n,g.info.id),r(!1)},children:e.jsx(yn,{className:"h-4 w-4"})})}),e.jsx(Ye,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",onClick:N=>{N.stopPropagation(),w(g.info.id)},disabled:d===g.info.id,children:d===g.info.id?e.jsx(Qt,{className:"h-4 w-4 animate-spin"}):e.jsx(Vt,{className:"h-4 w-4"})})}),e.jsx(Ye,{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(yn,{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(Vt,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function lc(s){const r=s.find(t=>t.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const ub=()=>{const{currentSessionId:s,messages:r,permissions:t,streamingMessageIds:n,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:c,updateActiveTurnAnchor:d,getActiveTurnAnchor:u,sessionMemoryState:m,openNewSessionDraft:f,isSyncing:p,messageStreamStates:h,trimToViewportWindow:w,sessionActivityPhase:g,newSessionDraft:y}=he(),{isTimelineDialogOpen:x,setTimelineDialogOpen:v}=Fe(),S=l.useMemo(()=>s?n.get(s)??null:null,[s,n]),{isMobile:N}=Ct(),j=!!y?.open;l.useEffect(()=>{!s&&!j&&f()},[s,j,f]);const k=l.useMemo(()=>s?r.get(s)||[]:[],[s,r]),F=l.useMemo(()=>s?t.get(s)||[]:[],[s,t]),{scrollRef:A,handleMessageContentChange:M,getAnimationHandlers:b,showScrollButton:C,scrollToBottom:D,spacerHeight:P,pendingAnchorId:R,hasActiveAnchor:L}=lb({currentSessionId:s,sessionMessages:k,updateViewportAnchor:c,updateActiveTurnAnchor:d,getActiveTurnAnchor:u,isSyncing:p,isMobile:N,sessionActivityPhase:g}),te=!!l.useMemo(()=>s?m.get(s)??null:null,[s,m])?.hasMoreAbove,[le,$]=l.useState(!1);l.useEffect(()=>{$(!1)},[s]);const z=l.useRef(null);l.useLayoutEffect(()=>{if(!(!s||s===z.current)&&(z.current=s,!L)){const Y=A.current;Y&&(Y.scrollTop=Y.scrollHeight-Y.clientHeight)}},[s,A,L]);const E=l.useCallback(async()=>{if(!s||le)return;const Y=A.current,fe=Y?.scrollHeight??null,ne=Y?.scrollTop??null;$(!0);try{if(await i(s,"up"),Y&&fe!==null&&ne!==null){const pe=Y.scrollHeight-fe;Y.scrollTop=ne+pe}}finally{$(!1)}},[s,le,i,A]),H=l.useCallback(Y=>{const fe=A.current;if(!fe)return;const ne=fe.querySelector(`[data-message-id="${Y}"]`);if(ne){const pe=fe.getBoundingClientRect(),ee=ne.getBoundingClientRect().top-pe.top+fe.scrollTop-50;fe.scrollTo({top:ee,behavior:"smooth"})}},[A]);return l.useEffect(()=>{if(!s||(r.has(s)?r.get(s)??[]:[]).length>0)return;(async()=>{try{await a(s)}finally{typeof window>"u"?D():window.requestAnimationFrame(()=>{D()})}})()},[s,a,r,D]),!s&&!j?e.jsx("div",{className:"flex flex-col h-full bg-background",style:N?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(ua,{})}):!s&&j?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:N?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(ua,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Vn,{scrollToBottom:D})})]}):s?o&&k.length===0&&!S&&!r.has(s)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:N?{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(fe=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(da,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(da,{className:"h-4 w-24"}),e.jsx(da,{className:"h-20 w-full"})]})]},fe))})}),e.jsx(Vn,{scrollToBottom:D})]}):k.length===0&&!S?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:N?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(ua,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Vn,{scrollToBottom:D})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:N?{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(vu,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:A,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!R,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(eb,{messages:k,permissions:F,onMessageContentChange:M,getAnimationHandlers:b,hasMoreAbove:te,isLoadingOlder:le,onLoadOlder:E,scrollToBottom:D,pendingAnchorId:R}),P>0&&L&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:P},"aria-hidden":"true"})]})}),e.jsx(fi,{containerRef:A})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[C&&k.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>D({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(Zr,{className:"h-4 w-4"})})}),e.jsx(Vn,{scrollToBottom:D})]}),e.jsx(db,{open:x,onOpenChange:v,onScrollToMessage:H})]}):null};class mb extends l.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(vi,{className:"w-full max-w-md",children:[e.jsx($d,{className:"text-center",children:e.jsxs(_d,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(bf,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(Bd,{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(ve,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(xs,{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 Ka=()=>{const s=he(r=>r.currentSessionId);return e.jsx(mb,{sessionId:s||void 0,children:e.jsx(ub,{})})},cc=12,fb=[{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"}],pb=({isActive:s,burstKey:r=0,className:t,durationMs:n=900,bursts:o=fb,onComplete:a})=>{const i=Ne.useRef(!1);Ne.useEffect(()=>{!s&&i.current&&a?.(),s&&(i.current=!0)},[s,a]);const c=Ne.useMemo(()=>Array.from({length:cc},(d,u)=>{const m=Math.PI*2*u/cc;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return s?e.jsx("div",{className:O("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:c.map((m,f)=>{const p=m.x*d.radius,h=m.y*d.radius,w={"--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:w},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},hb=({durationMs:s=3400}={})=>{const[r,t]=Ne.useState({isActive:!1,cycle:0}),n=Ne.useRef(null),o=Ne.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Ne.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),i=Ne.useCallback(()=>{o(),t(c=>({isActive:!0,cycle:c.cycle+1})),n.current=window.setTimeout(()=>{t(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},s)},[o,s]);return Ne.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:i,dismissFireworks:a}},ju=l.createContext(void 0),dc=({children:s})=>{const{isActive:r,burstKey:t,triggerFireworks:n,dismissFireworks:o}=hb(),a=l.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(ju.Provider,{value:a,children:[s,e.jsx(pb,{isActive:r,burstKey:t})]})},gb=()=>{const s=l.useContext(ju);if(!s)throw new Error("useFireworksCelebration must be used within FireworksProvider");return s},Lo=Tt()(_t(ws((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 Vp();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 Yp("");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 Gp(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 qp(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 Kp(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:vs(()=>ls()),partialize:s=>({selectedProfileId:s.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Lo);const xb=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),yb=({currentBranch:s,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:o,onCreate:a,disabled:i=!1})=>{const[c,d]=l.useState(!1),[u,m]=l.useState(""),[f,p]=l.useState(!1),[h,w]=l.useState(""),[g,y]=l.useState(!1),x=l.useRef(null),v=l.useMemo(()=>xb(h),[h]),S=l.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(b=>b.toLowerCase().includes(M)):r},[u,r]),N=l.useMemo(()=>{const M=u.toLowerCase();return M?t.filter(b=>b.toLowerCase().includes(M)):t},[u,t]),j=M=>{if(M===s){d(!1);return}o(M),d(!1),m("")},k=()=>{p(!0),setTimeout(()=>x.current?.focus(),50)},F=async()=>{if(!(!v||g)){y(!0);try{await a(v),w(""),p(!1),d(!1)}finally{y(!1)}}},A=()=>{w(""),p(!1)};return l.useEffect(()=>{c||(m(""),p(!1),w(""))},[c]),e.jsxs(Jt,{open:c,onOpenChange:d,children:[e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(Zt,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:i,children:[e.jsx(Vt,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:s||"Detached HEAD"}),e.jsx(Nt,{className:"size-4 opacity-60"})]})})}),e.jsxs(Ye,{sideOffset:8,children:["Switch branch (",r.length," local · ",t.length," remote)"]})]}),e.jsx(es,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Hd,{className:"h-full min-h-0",children:[e.jsx(Ud,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(Wd,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Vd,{children:"No branches found."}),e.jsx(Vr,{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:M=>w(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),F()):M.key==="Escape"&&(M.preventDefault(),A())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:F,disabled:!v||g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:g?e.jsx(Qt,{className:"size-4 animate-spin"}):e.jsx(Gt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:A,disabled:g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Wt,{className:"size-4"})})]}):e.jsxs($t,{onSelect:k,children:[e.jsx(Gt,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(vo,{}),e.jsxs(Vr,{heading:"Local branches",children:[S.map(M=>e.jsxs($t,{onSelect:()=>j(M),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:M}),(n?.[M]?.ahead||n?.[M]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[M].ahead||0," ahead ·"," ",n[M].behind||0," behind"]})]}),s===M&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${M}`)),S.length===0&&e.jsx($t,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(vo,{}),e.jsxs(Vr,{heading:"Remote branches",children:[N.map(M=>e.jsx($t,{onSelect:()=>j(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),N.length===0&&e.jsx($t,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},bb=({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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[s==="fetch"?e.jsx(Qt,{className:"size-4 animate-spin"}):e.jsx(Mn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(Ye,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:t,disabled:a,children:[s==="pull"?e.jsx(Qt,{className:"size-4 animate-spin"}):e.jsx(Zr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(Ye,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[s==="push"?e.jsx(Qt,{className:"size-4 animate-spin"}):e.jsx(Nn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(Ye,{sideOffset:8,children:"Push changes"})]})]})},wb={branch:Vt,briefcase:oi,house:ni,graduation:ri,code:Vs,heart:Zc,user:bs},vb={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 Su(s){return s&&vb[s]||"var(--primary)"}const uc=({icon:s,className:r,colorToken:t})=>{const n=wb[s??"branch"]??bs;return e.jsx(n,{className:r,style:{color:Su(t)}})},jb=({activeProfile:s,identities:r,onSelect:t,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(Jt,{children:[e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(Zt,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:Su(s?.color)},disabled:o,children:[n?e.jsx(Qt,{className:"size-4 animate-spin"}):e.jsx(uc,{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(Nt,{className:"size-4 opacity-60"})]})})}),e.jsxs(Ye,{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(es,{align:"end",className:"w-64",children:r.length===0?e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):r.map(a=>e.jsx(kt,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(uc,{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))})]})},Sb=({status:s,localBranches:r,remoteBranches:t,branchInfo:n,syncAction:o,onFetch:a,onPull:i,onPush:c,onCheckoutBranch:d,onCreateBranch:u,activeIdentityProfile:m,availableIdentities:f,onSelectIdentity:p,isApplyingIdentity:h,isWorktreeMode:w})=>s?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[!w&&e.jsx(yb,{currentBranch:s.current,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:d,onCreate:u}),(!!s.tracking||s.ahead>0||s.behind>0)&&e.jsxs(Xe,{delayDuration:800,children:[e.jsx(Qe,{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(Nn,{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(Zr,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.behind})]})]})}),e.jsx(Ye,{sideOffset:8,children:s.tracking?`Upstream: ${s.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(bb,{syncAction:o,onFetch:a,onPull:i,onPush:c,disabled:!s}),e.jsx("div",{className:"flex-1"}),e.jsx(jb,{activeProfile:m,identities:f,onSelect:p,isApplying:h})]}):null,kb=({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(Ja,{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(ve,{variant:"outline",onClick:r,disabled:t,children:[t?e.jsx(Qt,{className:"size-4 animate-spin"}):e.jsx(Zr,{className:"size-4"}),"Pull ",s," commit",s===1?"":"s"]})]}),ku={"?":{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"}},Nb=ku.M;function Cb(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 Mb(s){const r=Cb(s);return ku[r]??Nb}const Db=l.memo(function({file:r,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:i,stats:c}){const d=Ne.useMemo(()=>Mb(r),[r]),u=d.description,m=c?.insertions??0,f=c?.deletions??0,p=Ne.useCallback(g=>{g.key===" "?(g.preventDefault(),n()):g.key==="Enter"&&(g.preventDefault(),o())},[n,o]),h=Ne.useCallback(g=>{g.preventDefault(),g.stopPropagation(),n()},[n]),w=Ne.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(ei,{className:"size-4 text-primary"}):e.jsx(ti,{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(Xe,{delayDuration:200,children:[e.jsx(Qe,{asChild:!0,children:e.jsx("button",{type:"button",onClick:w,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(Qt,{className:"size-3.5 animate-spin"}):e.jsx(Mn,{className:"size-3.5"})})}),e.jsx(Ye,{sideOffset:8,children:"Revert changes"})]})]})})}),Ab=({changeEntries:s,selectedPaths:r,diffStats:t,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:i,onViewDiff:c,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(ve,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(ve,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:i,disabled:u===0,children:"None"})]})]})]}),e.jsx(tt,{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(Db,{file:f,checked:r.has(f.path),stats:t?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>c(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})},Nu=wf,Eb=({className:s,...r})=>e.jsx(jf,{className:O("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}),Cu=({className:s,...r})=>e.jsx(vf,{className:O("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",s),...r});function Mr({className:s,variant:r,...t}){return e.jsx(ve,{variant:r,size:"sm",className:O("h-7 px-2 py-0",s),...t})}const ga=38,mc=200,Ib=({value:s,onChange:r,placeholder:t="Commit message",disabled:n=!1})=>{const o=l.useRef(null);return l.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${ga}px`;const i=Math.min(Math.max(a.scrollHeight,ga),mc);a.style.height=`${i}px`},[s]),e.jsx(Ts,{ref:o,value:s,onChange:a=>r(a.target.value),placeholder:t,rows:1,disabled:n,className:O("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:ga,maxHeight:mc}})},Tb=({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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(Zr,{className:"size-4"})})}),e.jsx(Ye,{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))})]})},Fb=({selectedCount:s,commitMessage:r,onCommitMessageChange:t,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:i,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f})=>{const p=s>0,h=r.trim()&&p&&m===null;return e.jsxs(Nu,{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(Cu,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(Tb,{highlights:n,onInsert:o,onClear:a}),e.jsx(Ib,{value:r,onChange:t,placeholder:"Commit message",disabled:m!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:i,disabled:c||m!==null||s===0||f,"aria-label":"Generate commit message",children:c?e.jsx(Qt,{className:"size-4 animate-spin"}):e.jsx(Sf,{className:"size-4 text-primary"})})}),e.jsx(Ye,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Mr,{variant:"outline",onClick:d,disabled:!h||c,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Qt,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"size-4"}),"Commit"]})}),e.jsx(Mr,{variant:"default",onClick:u,disabled:!h||c,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Qt,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function fc(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 Pb(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 Rb=({entry:s,isExpanded:r,onToggle:t,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:O("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:fc(s.date),children:fc(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(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:i=>{i.stopPropagation(),a(s.hash)},children:e.jsx(qs,{className:"size-3"})})}),e.jsx(Ye,{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(Qt,{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:O("font-semibold w-3 text-center",Pb(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))})})]}),Lb=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],Ob=({log:s,isLogLoading:r,logMaxCount:t,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:i,loadingCommitHashes:c,onCopyHash:d})=>{const[u,m]=l.useState(!0);return s?e.jsxs(Nu,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Eb,{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(Fs,{value:String(t),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Ps,{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(jo,{placeholder:"Commits"})}),e.jsx(Rs,{children:Lb.map(f=>e.jsx(Ot,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(Ao,{className:"size-4 text-muted-foreground"}):e.jsx(Nt,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(Cu,{children:e.jsx(tt,{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(Rb,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:i.get(f.hash)??[],isLoadingFiles:c.has(f.hash),onCopyHash:d},f.hash))})})})]}):null};let un=null;const $b=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=he(),{currentDirectory:n}=wt(),o=s?t.get(s)??void 0:void 0,i=r.find(c=>c.id===s)?.directory;return o?.path??i??n??void 0},_b=()=>{const{git:s}=Tr(),r=$b(),{currentSessionId:t,worktreeMetadata:n}=he(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=Lo(),u=Id(r??null),m=Ed(r??null),f=Kh(r??null),p=Yh(r??null),h=Xh(r??null),w=It(re=>re.isLoadingStatus),g=It(re=>re.isLoadingLog),{setActiveDirectory:y,fetchAll:x,fetchStatus:v,fetchBranches:S,fetchLog:N,fetchIdentity:j,setLogMaxCount:k}=It(),F=l.useMemo(()=>!un||un.directory!==r?null:un,[r]),[A,M]=l.useState(F?.commitMessage??""),[b,C]=l.useState(null),[D,P]=l.useState(null),[R,L]=l.useState(25),[q,te]=l.useState(!1),{triggerFireworks:le}=gb(),[$,z]=l.useState(()=>new Set(F?.selectedPaths??[])),[E,H]=l.useState(!1),[Y,fe]=l.useState(new Set),[ne,pe]=l.useState(!1),[je,U]=l.useState([]),ee=l.useCallback(()=>{U([])},[]),[oe,W]=l.useState(new Set),[me,ye]=l.useState(new Map),[ce,Me]=l.useState(new Set),Ee=l.useCallback(re=>{navigator.clipboard.writeText(re).then(()=>{se.success("Commit hash copied")}).catch(()=>{se.error("Failed to copy")})},[]),Pe=l.useCallback(re=>{W(ae=>{const Ie=new Set(ae);return Ie.has(re)?Ie.delete(re):Ie.add(re),Ie})},[]);l.useEffect(()=>{if(!r||!s)return;const re=Array.from(oe).filter(ae=>!me.has(ae)&&!ce.has(ae));re.length!==0&&(Me(ae=>{const Ie=new Set(ae);return re.forEach(_e=>Ie.add(_e)),Ie}),re.forEach(ae=>{s.getCommitFiles(r,ae).then(Ie=>{ye(_e=>new Map(_e).set(ae,Ie.files))}).catch(Ie=>{console.error("Failed to fetch commit files:",Ie),ye(_e=>new Map(_e).set(ae,[]))}).finally(()=>{Me(Ie=>{const _e=new Set(Ie);return _e.delete(ae),_e})})}))},[oe,r,s,me,ce]),l.useEffect(()=>()=>{if(!r){un=null;return}un={directory:r,selectedPaths:Array.from($),commitMessage:A}},[A,r,$]),l.useEffect(()=>{c(),d()},[c,d]),l.useEffect(()=>{r&&(y(r),It.getState().directories.get(r)?.status||x(r,s,{force:!0}))},[r,y,x,s]);const V=l.useCallback(async(re=!0)=>{if(r)try{await Promise.all([v(r,s),S(r,s)])}catch(ae){if(re){const Ie=ae instanceof Error?ae.message:"Failed to refresh repository state";se.error(Ie)}}},[r,s,v,S]),K=l.useCallback(async()=>{r&&await N(r,s,R)},[r,s,N,R]),T=l.useCallback(async()=>{r&&await j(r,s)},[r,s,j]),X=l.useMemo(()=>{if(!m)return[];const re=m.files??[],ae=new Map;return re.forEach(Ie=>{ae.set(Ie.path,Ie)}),Array.from(ae.values()).sort((Ie,_e)=>Ie.path.localeCompare(_e.path))},[m]);l.useEffect(()=>{if(!m||X.length===0){z(new Set),H(!1);return}z(re=>{const ae=new Set,Ie=re??new Set;return X.forEach(_e=>{Ie.has(_e.path)?ae.add(_e.path):E||ae.add(_e.path)}),ae})},[m,X,E]);const I=async re=>{if(r){C(re);try{if(re==="fetch")await s.gitFetch(r),se.success("Fetched latest updates");else if(re==="pull"){const ae=await s.gitPull(r);se.success(`Pulled ${ae.files.length} file${ae.files.length===1?"":"s"}`)}else re==="push"&&(await s.gitPush(r),se.success("Pushed to remote"));await V(!1),await K()}catch(ae){const Ie=ae instanceof Error?ae.message:`Failed to ${re==="pull"?"pull":re}`;se.error(Ie)}finally{C(null)}}},B=async(re={})=>{if(!r)return;if(!A.trim()){se.error("Please enter a commit message");return}const ae=Array.from($).sort();if(ae.length===0){se.error("Select at least one file to commit");return}const Ie=re.pushAfter?"commitAndPush":"commit";P(Ie);try{await s.createGitCommit(r,A.trim(),{files:ae}),se.success("Commit created successfully"),M(""),z(new Set),H(!1),ee(),await V(),re.pushAfter?(await s.gitPush(r),se.success("Pushed to remote"),le(),await V(!1)):await V(!1),await K()}catch(_e){const ze=_e instanceof Error?_e.message:"Failed to create commit";se.error(ze)}finally{P(null)}},G=l.useCallback(async()=>{if(r){if($.size===0){se.error("Select at least one file to describe");return}pe(!0);try{const{message:re}=await s.generateCommitMessage(r,Array.from($)),ae=re.subject?.trim()??"",Ie=Array.isArray(re.highlights)?re.highlights:[];ae&&M(ae),U(Ie),se.success("Commit message generated")}catch(re){const ae=re instanceof Error?re.message:"Failed to generate commit message";se.error(ae)}finally{pe(!1)}}},[r,$,s]),be=async re=>{if(!r||!m)return;const ae=m.current??null;try{await s.createBranch(r,re,ae??"HEAD"),se.success(`Created branch ${re}`);let Ie=!1;try{await s.checkoutBranch(r,re),await s.gitPush(r,{remote:"origin",branch:re,options:["--set-upstream"]}),Ie=!0}catch(_e){const ze=_e instanceof Error?_e.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: ",ze]})})}finally{if(ae)try{await s.checkoutBranch(r,ae)}catch(_e){console.warn("Failed to restore original branch after creation:",_e)}}await V(),await K(),Ie&&se.success(`Upstream set for ${re}`)}catch(Ie){const _e=Ie instanceof Error?Ie.message:"Failed to create branch";throw se.error(_e),Ie}},J=async re=>{if(!r)return;const ae=re.replace(/^remotes\//,"");if(m?.current!==ae)try{await s.checkoutBranch(r,ae),se.success(`Checked out ${ae}`),await V(),await K()}catch(Ie){const _e=Ie instanceof Error?Ie.message:`Failed to checkout ${ae}`;se.error(_e)}},ge=async re=>{if(r){te(!0);try{await s.setGitIdentity(r,re.id),se.success(`Applied "${re.name}" to repository`),await T()}catch(ae){const Ie=ae instanceof Error?ae.message:"Failed to apply git identity";se.error(Ie)}finally{te(!1)}}},He=l.useMemo(()=>f?.all?f.all.filter(re=>!re.startsWith("remotes/")).sort():[],[f]),We=l.useMemo(()=>f?.all?f.all.filter(re=>re.startsWith("remotes/")).map(re=>re.replace(/^remotes\//,"")).sort():[],[f]),Be=l.useMemo(()=>{const re=new Map;i&&re.set(i.id,i);for(const ae of a)re.set(ae.id,ae);return Array.from(re.values())},[a,i]),Ze=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const re=a.find(ae=>ae.userName===h.userName&&ae.userEmail===h.userEmail);return re||(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]),it=X.length,lt=$.size,ct=w||b!==null||D!==null,mt=it>0,xt=re=>{z(ae=>{const Ie=new Set(ae);return Ie.has(re)?Ie.delete(re):Ie.add(re),Ie}),H(!0)},vt=()=>{const re=new Set(X.map(ae=>ae.path));z(re),H(!0)},ht=()=>{z(new Set),H(!0)},yt=l.useCallback(async re=>{if(r){fe(ae=>{const Ie=new Set(ae);return Ie.add(re),Ie});try{await s.revertGitFile(r,re),se.success(`Reverted ${re}`),await V(!1)}catch(ae){const Ie=ae instanceof Error?ae.message:"Failed to revert changes";se.error(Ie)}finally{fe(ae=>{const Ie=new Set(ae);return Ie.delete(re),Ie})}}},[r,V,s]),Q=l.useCallback(()=>{if(je.length===0)return;const re=je.map(ae=>ae.trim()).filter(Boolean);if(re.length===0){ee();return}M(ae=>{const Ie=ae.trim(),_e=Ie.length>0?`
|
|
92
|
+
|
|
93
|
+
`:"";return`${Ie}${_e}${re.join(`
|
|
94
|
+
`)}`.trim()})},[je,ee]),De=l.useCallback(re=>{L(re),r&&(k(r,re),N(r,s,re))},[r,k,N,s]);return r?w&&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(Qt,{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(Vt,{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(Sb,{status:m,localBranches:He,remoteBranches:We,branchInfo:f?.branches,syncAction:b,onFetch:()=>I("fetch"),onPull:()=>I("pull"),onPush:()=>I("push"),onCheckoutBranch:J,onCreateBranch:be,activeIdentityProfile:Ze,availableIdentities:Be,onSelectIdentity:ge,isApplyingIdentity:q,isWorktreeMode:!!o}),e.jsx(tt,{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:[mt?e.jsx(Ab,{changeEntries:X,selectedPaths:$,diffStats:m?.diffStats,revertingPaths:Y,onToggleFile:xt,onSelectAll:vt,onClearSelection:ht,onViewDiff:re=>Fe.getState().navigateToDiff(re),onRevertFile:yt}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(kb,{behind:m?.behind??0,onPull:()=>I("pull"),isPulling:b==="pull"})}),X.length>0&&e.jsx(Fb,{selectedCount:lt,commitMessage:A,onCommitMessageChange:M,generatedHighlights:je,onInsertHighlights:Q,onClearHighlights:ee,onGenerateMessage:G,isGeneratingMessage:ne,onCommit:()=>B({pushAfter:!1}),onCommitAndPush:()=>B({pushAfter:!0}),commitAction:D,isBusy:ct})]}),e.jsx(Ob,{log:p,isLogLoading:g,logMaxCount:R,onLogMaxCountChange:De,expandedCommitHashes:oe,onToggleCommit:Pe,commitFilesMap:me,loadingCommitHashes:ce,onCopyHash:Ee})]})})]}):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."})})},Bb=1e6;function br(s){let r=s.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const Gn=s=>({directory:s,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),pc=Tt((s,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=br(t);return r().sessions.get(n)},setTerminalSession:(t,n)=>{const o=br(t);s(a=>{const i=new Map(a.sessions),c=i.get(o),u=!c||c.terminalSessionId!==n.sessionId?Gn(o):c??Gn(o);return i.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=br(t);s(a=>{const i=new Map(a.sessions),c=i.get(o)??Gn(o);return i.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=br(t);s(a=>{const i=new Map(a.sessions),c=i.get(o)??Gn(o),d=a.nextChunkId,u={id:d,data:n},m=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>Bb&&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,{...c,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:i,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=br(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=br(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=br(t);s(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{s({sessions:new Map,nextChunkId:1})}})),Mu=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),zb=[{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'}],Hb=[{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'}],Du=s=>Object.fromEntries(s.map(r=>[r.id,r])),hc=Du(zb),wr=Du(Hb),Ub="ibm-plex-sans",no="ibm-plex-mono";function Wb(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 Vb(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 xa=null;function Gb(){return xa||(xa=Cf.load()),xa}function qb(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 Ya=l.forwardRef(({sessionKey:s,chunks:r,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:c,enableTouchScroll:d},u)=>{const m=l.useRef(null),f=l.useRef(null),p=l.useRef(null),h=l.useRef(null),w=l.useRef(t),g=l.useRef(n),y=l.useRef(null),x=l.useRef(""),v=l.useRef(null),S=l.useRef(!1),N=l.useRef(null),j=l.useRef(null),k=l.useRef(null),F=l.useRef(0),A=l.useRef(null),[,M]=l.useReducer($=>$+1,0),[b,C]=l.useReducer($=>$+1,0);w.current=t,g.current=n;const D=l.useCallback(($,z)=>{const E=A.current,H=m.current;if(!E||!H)return;const Y=H.getBoundingClientRect(),fe=Y.left+Y.width/2,ne=Y.top+Y.height-12,pe=typeof $=="number"?$:fe,je=typeof z=="number"?z:ne,U=8,ee=Math.max(U,Math.min(Y.width-U,pe-Y.left)),oe=Math.max(U,Math.min(Y.height-U,je-Y.top));E.style.left=`${ee}px`,E.style.top=`${oe}px`,E.style.bottom="";try{E.focus({preventScroll:!0})}catch{try{E.focus()}catch{}}},[]),P=l.useCallback(()=>{x.current="",v.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(v.current),v.current=null,S.current=!1,N.current=null},[]),R=l.useCallback(()=>{const $=h.current,z=p.current,E=m.current;if(!$||!z||!E)return;const H=E.getBoundingClientRect();if(!(H.width<24||H.height<24))try{$.fit();const Y={cols:z.cols,rows:z.rows},fe=y.current;(!fe||fe.cols!==Y.cols||fe.rows!==Y.rows)&&(y.current=Y,g.current(Y.cols,Y.rows))}catch{}},[]),L=l.useCallback(()=>{if(S.current)return;const $=p.current;if(!$){P();return}if(!x.current)return;const z=x.current;x.current="",S.current=!0,$.write(z,()=>{S.current=!1,x.current&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,L()}):L())})},[P]),q=l.useCallback(()=>{v.current===null&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,L()}):L())},[L]),te=l.useCallback($=>{$&&(x.current+=$,q())},[q]),le=l.useCallback(()=>{if(j.current?.(),j.current=null,k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),!d){F.current=0;return}const $=m.current;if(!$)return;const z=p.current;if(!z)return;F.current=0;const E=2.2,H=2.8,Y=25,fe=.25,ne=8,pe=.05,je=.015,U={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},ee=()=>typeof performance<"u"?performance.now():Date.now(),oe=Math.max(12,Math.round(i*1.35));let W=0;const me=X=>{if(!X)return!1;const I=z.getViewportY(),B=W+X,G=Math.trunc(B/oe);return W=B-G*oe,G!==0&&z.scrollLines(G),z.getViewportY()!==I},ye=()=>{U.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(U.rafId),U.rafId=null},ce={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const X=Object.assign(U,{pointerId:null,startX:null,startY:null,moved:!1}),I=6,B=ge=>{if(ge.pointerType==="touch"){ye(),X.pointerId=ge.pointerId,X.startX=ge.clientX,X.startY=ge.clientY,X.moved=!1,X.lastY=ge.clientY,X.lastTime=ee(),X.velocity=0;try{$.setPointerCapture(ge.pointerId)}catch{}}},G=ge=>{if(ge.pointerType!=="touch"||X.pointerId!==ge.pointerId)return;if(X.startX!==null&&X.startY!==null&&!X.moved){const xt=ge.clientX-X.startX,vt=ge.clientY-X.startY;Math.hypot(xt,vt)>=I&&(X.moved=!0)}if(X.lastY===null){X.lastY=ge.clientY,X.lastTime=ee();return}const He=X.lastY,We=X.lastTime??ee(),Be=ee();X.lastY=ge.clientY,X.lastTime=Be;const Ze=He-ge.clientY;if(Math.abs(Ze)<1)return;const it=Math.max(Be-We,8),lt=E+Math.min(H,Math.abs(Ze)/Y),ct=Ze*lt,mt=ct/it;X.velocity=X.velocity*(1-fe)+mt*fe,X.velocity>ne?X.velocity=ne:X.velocity<-ne&&(X.velocity=-ne),X.moved&&(ge.cancelable&&ge.preventDefault(),ge.stopPropagation()),me(ct)},be=ge=>{if(ge.pointerType!=="touch"||X.pointerId!==ge.pointerId)return;const He=!X.moved;X.pointerId=null,X.startX=null,X.startY=null,X.moved=!1,X.lastY=null,X.lastTime=null;try{$.releasePointerCapture(ge.pointerId)}catch{}if(He){D(ge.clientX,ge.clientY);return}if(typeof window>"u")return;if(Math.abs(X.velocity)<pe){X.velocity=0;return}let We=ee();const Be=()=>{const Ze=ee(),it=Math.max(Ze-We,8);We=Ze;const lt=me(X.velocity*it)??!1,ct=Math.sign(X.velocity),mt=Math.max(0,Math.abs(X.velocity)-je*it);if(X.velocity=mt*ct,!lt||mt<=pe){ye(),X.velocity=0;return}X.rafId=window.requestAnimationFrame(Be)};X.rafId=window.requestAnimationFrame(Be)};$.addEventListener("pointerdown",B,ce),$.addEventListener("pointermove",G,ce),$.addEventListener("pointerup",be,ce),$.addEventListener("pointercancel",be,ce);const J=$.style.touchAction;$.style.touchAction="manipulation",j.current=()=>{ye(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),F.current=0,$.removeEventListener("pointerdown",B,ce),$.removeEventListener("pointermove",G,ce),$.removeEventListener("pointerup",be,ce),$.removeEventListener("pointercancel",be,ce),$.style.touchAction=J};return}const Ee=6,Pe=X=>{X.touches.length===1&&(ye(),U.lastY=X.touches[0].clientY,U.lastTime=ee(),U.velocity=0,U.startX=X.touches[0].clientX,U.startY=X.touches[0].clientY,U.didMove=!1)},V=X=>{if(X.touches.length!==1){U.lastY=null,U.lastTime=null,U.velocity=0,U.startX=null,U.startY=null,U.didMove=!1,ye();return}const I=X.touches[0].clientX,B=X.touches[0].clientY;if(U.startX!==null&&U.startY!==null&&!U.didMove){const it=I-U.startX,lt=B-U.startY;Math.hypot(it,lt)>=Ee&&(U.didMove=!0)}if(U.lastY===null){U.lastY=B,U.lastTime=ee();return}const G=U.lastY,be=U.lastTime??ee(),J=ee();U.lastY=B,U.lastTime=J;const ge=G-B;if(Math.abs(ge)<1)return;const He=Math.max(J-be,8),We=E+Math.min(H,Math.abs(ge)/Y),Be=ge*We,Ze=Be/He;U.velocity=U.velocity*(1-fe)+Ze*fe,U.velocity>ne?U.velocity=ne:U.velocity<-ne&&(U.velocity=-ne),U.didMove&&(X.preventDefault(),X.stopPropagation()),me(Be)},K=X=>{const I=!U.didMove;U.lastY=null,U.lastTime=null;const B=U.velocity;if(U.startX=null,U.startY=null,U.didMove=!1,I){const J=X.changedTouches?.[0];D(J?.clientX,J?.clientY);return}if(typeof window>"u")return;if(Math.abs(B)<pe){U.velocity=0;return}let G=ee();const be=()=>{const J=ee(),ge=Math.max(J-G,8);G=J;const He=me(U.velocity*ge)??!1,We=Math.sign(U.velocity),Be=Math.max(0,Math.abs(U.velocity)-je*ge);if(U.velocity=Be*We,!He||Be<=pe){ye(),U.velocity=0;return}U.rafId=window.requestAnimationFrame(be)};U.rafId=window.requestAnimationFrame(be)};$.addEventListener("touchstart",Pe,ce),$.addEventListener("touchmove",V,ce),$.addEventListener("touchend",K,ce),$.addEventListener("touchcancel",K,ce);const T=$.style.touchAction;$.style.touchAction="manipulation",j.current=()=>{ye(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),F.current=0,$.removeEventListener("touchstart",Pe,ce),$.removeEventListener("touchmove",V,ce),$.removeEventListener("touchend",K,ce),$.removeEventListener("touchcancel",K,ce),$.style.touchAction=T}},[d,D,i]);return l.useEffect(()=>{let $=!1,z=null,E=null,H=[];const Y=m.current;return Y?(Y.tabIndex=0,(async()=>{try{const ne=await Gb();if($)return;const pe=Vb(a,i,o,ne),je=new kf(pe),U=new Nf;z=je,p.current=je,h.current=U,je.loadAddon(U),je.open(Y),C();const ee=qb(Y);ee?(ee.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=ee,M()):f.current=null,R(),le(),je.focus(),H=[je.onData(oe=>{w.current(oe)})],E=new ResizeObserver(()=>{R()}),E.observe(Y),typeof window<"u"&&window.setTimeout(()=>{R()},0)}catch{}})(),()=>{$=!0,j.current?.(),j.current=null,H.forEach(ne=>ne.dispose()),E?.disconnect(),z?.dispose(),p.current=null,h.current=null,f.current=null,y.current=null,P()}):void 0},[R,a,i,le,o,P]),l.useEffect(()=>{const $=p.current;$&&($.reset(),P(),y.current=null,R(),$.focus())},[s,b,R,P]),l.useEffect(()=>(le(),()=>{j.current?.(),j.current=null}),[le,s]),l.useEffect(()=>{const $=p.current;if(!$)return;if(r.length===0){N.current!==null&&($.reset(),P(),R());return}const z=N.current;let E;if(z===null)E=r;else{const H=r.findIndex(Y=>Y.id===z);E=H>=0?r.slice(H+1):r}E.length>0&&te(E.map(H=>H.data).join("")),N.current=r[r.length-1].id},[r,b,te,R,P]),l.useImperativeHandle(u,()=>({focus:()=>{if(d){D();return}p.current?.focus()},clear:()=>{const $=p.current;$&&($.reset(),P(),R())},fit:()=>{R()}}),[d,D,R,P]),e.jsxs("div",{ref:m,className:O("relative h-full w-full",c),style:{backgroundColor:o.background},onClick:$=>{d?D($.clientX,$.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:A,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:$=>{const z=String($.currentTarget.value||"");if(!z)return;const E=z.replace(/\r\n|\r|\n/g,"\r");w.current(E),$.currentTarget.value=""},onKeyDown:$=>{$.key==="Backspace"&&($.currentTarget.value||w.current(""))}}):null,f.current&&!d?e.jsx(fi,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});Ya.displayName="TerminalViewport";const gc=13,Kb={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},qn={ctrl:"5",cmd:"3"},Yb={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},Xb=(s,r)=>{if(r)switch(s){case"arrow-up":return`\x1B[1;${qn[r]}A`;case"arrow-down":return`\x1B[1;${qn[r]}B`;case"arrow-right":return`\x1B[1;${qn[r]}C`;case"arrow-left":return`\x1B[1;${qn[r]}D`}return Kb[s]??null},Qb=()=>{const{terminal:s}=Tr(),{currentTheme:r}=Fr(),{monoFont:t}=Mu(),{isMobile:n,hasTouchInput:o}=Ct(),{currentSessionId:a,sessions:i,worktreeMetadata:c}=he(),d=a?c.get(a)??void 0:void 0,u=l.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const I=i.find(G=>G.id===a),B=typeof I?.directory=="string"?I.directory:null;return B&&B.length>0?B:null},[a,i,d]),{currentDirectory:m,homeDirectory:f}=wt(),p=u||m||null,h=l.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),w=pc(),g=w.sessions,y=w.setTerminalSession,x=w.setConnecting,v=w.appendToBuffer,S=w.clearTerminalSession,N=w.removeTerminalSession,j=w.clearBuffer,k=l.useMemo(()=>{if(p)return g.get(p)},[g,p]),F=k?.terminalSessionId??null,A=k?.bufferChunks??[],M=k?.bufferLength??0,b=k?.isConnecting??!1,C=F,[D,P]=l.useState(null),[R,L]=l.useState(!1),[q,te]=l.useState(null),[le,$]=l.useState(!1),z=l.useRef(null),E=l.useRef(null),H=l.useRef(C),Y=l.useRef(p),fe=l.useRef(null),pe=Fe(I=>I.activeMainTab)==="terminal";l.useEffect(()=>{H.current=C},[C]),l.useEffect(()=>{Y.current=p},[p]),l.useEffect(()=>{!n&&q!==null&&te(null)},[n,q,te]),l.useEffect(()=>{!C&&q!==null&&te(null)},[C,q,te]);const je=l.useCallback(()=>{z.current?.(),z.current=null,E.current=null},[]);l.useEffect(()=>()=>{je(),H.current=null},[je]);const U=l.useCallback(I=>{if(E.current===I)return;je();const B=s.connect(I,{onEvent:G=>{const be=Y.current;if(be)switch(G.type){case"connected":{(G.runtime||G.ptyBackend)&&console.log(`[Terminal] connected runtime=${G.runtime??"unknown"} pty=${G.ptyBackend??"unknown"}`),x(be,!1),P(null),L(!1),fe.current?.focus();break}case"reconnecting":{const J=G.attempt??0,ge=G.maxAttempts??3;P(`Reconnecting (${J}/${ge})...`),L(!1);break}case"data":{G.data&&v(be,G.data);break}case"exit":{const J=typeof G.exitCode=="number"?G.exitCode:null,ge=typeof G.signal=="number"?G.signal:null;v(be,`\r
|
|
95
|
+
[Process exited${J!==null?` with code ${J}`:""}${ge!==null?` (signal ${ge})`:""}]\r
|
|
96
|
+
`),S(be),x(be,!1),P("Terminal session ended"),L(!1),je();break}}},onError:(G,be)=>{const J=Y.current;if(!J)return;const ge=be?`Connection failed: ${G.message}`:G.message||"Terminal stream connection error";P(ge),L(!!be),be&&(x(J,!1),je(),N(J))}},Yb);z.current=()=>{B.close(),E.current=null},E.current=I},[v,S,je,N,x,s,P]);l.useEffect(()=>{let I=!1;if(!p){P(a?"No working directory available for terminal.":"Select a session to open the terminal."),je();return}return(async()=>{const G=p;if(!Y.current||Y.current!==G)return;let J=pc.getState().getTerminalSession(G)?.terminalSessionId??null;if(!J){P(null),L(!1),x(G,!0);try{const ge=await s.createSession({cwd:G});if(I){try{await s.close(ge.sessionId)}catch{}return}y(G,ge),J=ge.sessionId}catch(ge){I||(P(ge instanceof Error?ge.message:"Failed to start terminal session"),L(!0),x(G,!1));return}}!J||I||(H.current=J,U(J))})(),()=>{I=!0,H.current=null,je()}},[a,p,C,N,x,y,U,je,s]);const ee=l.useCallback(async()=>{if(!p||le)return;$(!0),P(null),L(!1),je();const I=H.current;try{if(s.restartSession&&I){const B=await s.restartSession(I,{cwd:p});y(p,B),H.current=B.sessionId,U(B.sessionId)}else{if(I)try{await s.close(I)}catch{}N(p)}}catch(B){P(B instanceof Error?B.message:"Failed to restart terminal"),L(!0)}finally{$(!1)}},[p,le,je,s,y,U,N]),oe=l.useCallback(async()=>{if(p&&!le){$(!0),P(null),L(!1),je();try{s.forceKill&&await s.forceKill({cwd:p})}catch{}N(p),j(p),fe.current?.clear(),await new Promise(I=>setTimeout(I,100));try{x(p,!0);const I=await s.createSession({cwd:p});y(p,I),H.current=I.sessionId,U(I.sessionId)}catch(I){P(I instanceof Error?I.message:"Failed to create terminal"),L(!0),x(p,!1)}finally{$(!1)}}},[p,le,je,s,N,j,x,y,U]),W=l.useCallback(()=>{if(!p)return;j(p),fe.current?.clear(),fe.current?.focus();const I=H.current;I&&s.sendInput(I,"\f").catch(B=>{P(B instanceof Error?B.message:"Failed to refresh prompt")})},[j,p,P,s]),me=l.useCallback(I=>{if(!I)return;let B=I,G=!1;if(q&&I.length>0){const J=I[0];if(J.length===1&&/[a-zA-Z]/.test(J)){const ge=J.toUpperCase();(q==="ctrl"||q==="cmd")&&(B=String.fromCharCode(ge.charCodeAt(0)&31),G=!0)}G||(G=!0)}const be=H.current;be&&(s.sendInput(be,B).catch(J=>{P(J instanceof Error?J.message:"Failed to send input")}),G&&(te(null),fe.current?.focus()))},[q,te,s]),ye=l.useCallback((I,B)=>{const G=H.current;G&&s.resize({sessionId:G,cols:I,rows:B}).catch(()=>{})},[s]),ce=l.useCallback(I=>{te(B=>B===I?null:I),fe.current?.focus()},[te]),Me=l.useCallback(I=>{const B=Xb(I,q);B&&(me(B),te(null),fe.current?.focus())},[q,me,te]);l.useEffect(()=>{if(!n||!q||!C)return;const I=B=>{if(B.repeat)return;const G=B.key;if(!G||G==="Control"||G==="Meta"||G==="Alt"||G==="Shift")return;const be=G.length===1?G.toLowerCase():G,J=B.code??"",ge=J.startsWith("Key")&&J.length===4?J.slice(3).toUpperCase():null,He=G.length===1&&/[a-zA-Z]/.test(G)?G.toUpperCase():ge,We={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(be in We){B.preventDefault(),B.stopPropagation(),Me(We[be]);return}if(q==="ctrl"&&He&&He.length===1&&He>="A"&&He<="Z"){const Be=String.fromCharCode(He.charCodeAt(0)&31);B.preventDefault(),B.stopPropagation(),me(Be),te(null),fe.current?.focus()}};return window.addEventListener("keydown",I),()=>{window.removeEventListener("keydown",I)}},[q,Me,me,n,te,C]);const Ee=l.useMemo(()=>{const I=wr[no].stack;if(typeof window>"u")return(wr[t]??wr[no]).stack;const G=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return G&&G.trim().length>0?G.trim():(wr[t]??wr[no]).stack??I},[t]),Pe=l.useMemo(()=>Wb(r),[r]),V=l.useMemo(()=>`${p??"no-dir"}::${C??"pending"}`,[p,C]);l.useEffect(()=>{if(!pe)return;const I=fe.current;if(!I)return;const B=()=>{I.fit()};if(typeof window<"u"){const G=window.requestAnimationFrame(()=>{B(),I.focus()}),be=[220,400].map(J=>window.setTimeout(B,J));return()=>{window.cancelAnimationFrame(G),be.forEach(J=>window.clearTimeout(J))}}B()},[pe,V,C]);const K=D?.includes("Reconnecting"),T=D?K?e.jsx(Mf,{size:20,className:"text-amber-400"}):e.jsx(Wt,{size:20,className:"text-destructive"}):C&&!b&&!le?e.jsx(Xn,{size:20,className:"text-emerald-400"}):b||le?e.jsx($i,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx($i,{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:ee,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const X=!C||b||le;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:[T,e.jsxs(ve,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:W,disabled:!M,title:"Clear output",type:"button",children:[e.jsx(Ls,{size:16}),"Clear"]}),e.jsxs(ve,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:ee,disabled:le,title:"Restart terminal session",type:"button",children:[e.jsx(xs,{size:16,className:O((b||le)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>Me("esc"),disabled:X,children:"Esc"}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Me("tab"),disabled:X,children:[e.jsx(Oi,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:q==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ce("ctrl"),disabled:X,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:q==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ce("cmd"),disabled:X,children:[e.jsx(Dr,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Me("arrow-up"),disabled:X,children:[e.jsx(Nn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Me("arrow-left"),disabled:X,children:[e.jsx(ed,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Me("arrow-down"),disabled:X,children:[e.jsx(Zr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Me("arrow-right"),disabled:X,children:[e.jsx(Oi,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Me("enter"),disabled:X,children:[e.jsx(yn,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Pe.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:pe?n?e.jsx(Ya,{ref:I=>{fe.current=I},sessionKey:V,chunks:A,onInput:me,onResize:ye,theme:Pe,fontFamily:Ee,fontSize:gc,enableTouchScroll:o},V):e.jsx(tt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Ya,{ref:I=>{fe.current=I},sessionKey:V,chunks:A,onInput:me,onResize:ye,theme:Pe,fontFamily:Ee,fontSize:gc,enableTouchScroll:o},V)}):null}),D&&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:D}),R&&e.jsx(ve,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:oe,disabled:le,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},Au=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Za},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Jr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:Dr},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:Jc},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:wn},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Vt},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:Cr}],Jb={},Zb={},ew={};Au.forEach(s=>{Jb[s.id]=s.label,Zb[s.id]=s.description,ew[s.id]=s});const tw=({onItemSelect:s})=>{const[r,t]=l.useState(null),[n,o]=l.useState(""),{selectedAgentName:a,agents:i,setSelectedAgent:c,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=tn(),{setSidebarOpen:p}=Fe(),{isMobile:h}=Ct(),[w,g]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=l.useMemo(()=>Et(),[]);l.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{f()},[f]);const x=w?"bg-transparent":y?"bg-background":"bg-sidebar",v=()=>{const D="new-agent";let P=D,R=1;for(;i.some(L=>L.name===P);)P=`${D}-${R}`,R++;d({name:P,scope:"user"}),c(P),s?.(),h&&p(!1)},S=async D=>{if(_r(D)){se.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${D.name}"?`)&&(await m(D.name)?se.success(`Agent "${D.name}" deleted successfully`):se.error("Failed to delete agent"))},N=async D=>{_r(D)&&window.confirm(`Are you sure you want to reset agent "${D.name}" to its default configuration?`)&&(await m(D.name)?se.success(`Agent "${D.name}" reset to default`):se.error("Failed to reset agent"))},j=D=>{const P=D.name;let R=1,L=`${P}-copy`;for(;i.some($=>$.name===L);)R++,L=`${P}-copy-${R}`;const q=D,te=typeof D.model=="string"?D.model:D.model?.providerID&&D.model?.modelID?`${D.model.providerID}/${D.model.modelID}`:void 0,le=D;d({name:L,scope:q.scope||"user",description:D.description,model:te,temperature:D.temperature,top_p:D.topP,prompt:D.prompt,mode:D.mode,tools:D.tools,permission:D.permission,disable:le.disable}),c(L),h&&p(!1)},k=D=>{o(D.name),t(D)},F=async()=>{if(!r)return;const D=n.trim().replace(/\s+/g,"-");if(!D){se.error("Agent name is required");return}if(D===r.name){t(null);return}if(i.some(q=>q.name===D)){se.error("An agent with this name already exists");return}const P=typeof r.model=="string"?r.model:r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:void 0,R=r;await u({name:D,description:r.description,model:P,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,tools:r.tools,permission:r.permission,disable:R.disable,scope:R.scope})?await m(r.name)?(se.success(`Agent renamed to "${D}"`),c(D)):se.error("Failed to remove old agent after rename"):se.error("Failed to rename agent"),t(null)},A=D=>{switch(D){case"primary":return e.jsx(bn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(sd,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(td,{className:"h-3 w-3 text-primary"});default:return null}},M=i.filter(D=>!cd(D)),b=M.filter(_r),C=M.filter(D=>!_r(D));return e.jsxs("div",{className:O("flex h-full flex-col",x),children:[e.jsx("div",{className:O("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",M.length]}),e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(Gt,{className:"size-4"})})]})}),e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:M.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(lo,{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:[b.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"}),b.map(D=>e.jsx(xc,{agent:D,isSelected:a===D.name,onSelect:()=>{c(D.name),s?.(),h&&p(!1)},onReset:()=>N(D),onDuplicate:()=>j(D),getAgentModeIcon:A},D.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 Agents"}),C.map(D=>e.jsx(xc,{agent:D,isSelected:a===D.name,onSelect:()=>{c(D.name),s?.(),h&&p(!1)},onRename:()=>k(D),onDelete:()=>S(D),onDuplicate:()=>j(D),getAgentModeIcon:A},D.name))]})]})}),e.jsx(as,{open:r!==null,onOpenChange:D=>!D&&t(null),children:e.jsxs(is,{children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Rename Agent"}),e.jsxs(js,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(dt,{value:n,onChange:D=>o(D.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:D=>{D.key==="Enter"&&F()}}),e.jsxs(Gs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Mr,{onClick:F,children:"Rename"})]})]})})]})},xc=({agent:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i,getAgentModeIcon:c})=>{const d=s;return e.jsx("div",{className:O("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}),c(s.mode),(d.scope||_r(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:_r(s)?"system":d.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Jt,{children:[e.jsx(Zt,{asChild:!0,children:e.jsx(ve,{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(Cn,{className:"h-3.5 w-3.5"})})}),e.jsxs(es,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(kt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(ai,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(kt,{onClick:u=>{u.stopPropagation(),i()},children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(kt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(xs,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(kt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Cs({className:s,variant:r,...t}){return e.jsx(ve,{variant:r,size:"sm",className:O("h-6 px-2 text-xs",s),...t})}const sw=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),rw=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=sw.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Mi=({providerId:s,modelId:r,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=ut(),i=Fe(E=>E.isMobile),{toggleFavoriteModel:c,isFavoriteModel:d,addRecentModel:u}=Fe(),{favoriteModelsList:m,recentModelsList:f}=Si(),{isMobile:p}=Ct(),h=i||p,[w,g]=l.useState(!1),[y,x]=l.useState(new Set),[v,S]=l.useState(!1),[N,j]=l.useState(""),[k,F]=l.useState(0),A=l.useRef([]),M=()=>g(!1),b=E=>{x(H=>{const Y=new Set(H);return Y.has(E)?Y.delete(E):Y.add(E),Y})};l.useEffect(()=>{v||(j(""),F(0))},[v]),l.useEffect(()=>{F(0)},[N]);const C=E=>{const H=E?.name||E?.id||"",Y=String(H);return Y.length>40?Y.substring(0,37)+"...":Y},D=(E,H)=>{const Y=`${E}/${H}`;return a.get(Y)},P=(E,H)=>{t(E,H),E&&H&&u(E,H),S(!1)},R=(E,H)=>{if(!N.trim())return!0;const Y=N.toLowerCase();return E.toLowerCase().includes(Y)||H.toLowerCase().includes(Y)},L=(E,H,Y,fe,ne,pe)=>{const je=D(H,Y),U=rw(je?.limit?.context),ee=s===H&&r===Y,oe=d(H,Y);return e.jsxs("div",{ref:W=>{A.current[ne]=W},className:O("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",pe?"bg-accent":"hover:bg-accent/50"),onClick:()=>P(H,Y),onMouseEnter:()=>F(ne),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:C(E)}),U?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:U}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[ee&&e.jsx(Dt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:W=>{W.preventDefault(),W.stopPropagation(),c(H,Y)},className:O("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",oe?"text-yellow-500":"text-muted-foreground"),"aria-label":oe?"Unfavorite":"Favorite",title:oe?"Remove from favorites":"Add to favorites",children:oe?e.jsx(Js,{className:"h-3.5 w-3.5"}):e.jsx(Hr,{className:"h-3.5 w-3.5"})})]})]},`${fe}-${H}-${Y}`)},q=m.filter(({model:E,providerID:H})=>{const fe=o.find(pe=>pe.id===H)?.name||H,ne=C(E);return R(ne,fe)}),te=f.filter(({model:E,providerID:H})=>{const fe=o.find(pe=>pe.id===H)?.name||H,ne=C(E);return R(ne,fe)}),le=o.map(E=>{const Y=(Array.isArray(E.models)?E.models:[]).filter(fe=>{const ne=C(fe);return R(ne,E.name||E.id||"")});return{...E,models:Y}}).filter(E=>E.models.length>0),$=q.length>0||te.length>0||le.length>0,z=()=>h?e.jsx(ps,{open:w,onClose:M,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:H,modelID:Y})=>{const fe=H===s&&Y===r;return e.jsxs("div",{className:O("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",fe?"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:()=>{P(H,Y),M()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{providerId:H,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:C(E)})]})}),e.jsx("button",{onClick:ne=>{ne.preventDefault(),ne.stopPropagation(),c(H,Y)},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(Js,{className:"h-4 w-4"})})]},`fav-mobile-${H}-${Y}`)})})]}),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:H,modelID:Y})=>{const fe=H===s&&Y===r;return e.jsxs("div",{className:O("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",fe?"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:()=>{P(H,Y),M()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{providerId:H,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:C(E)})]})}),e.jsx("button",{onClick:ne=>{ne.preventDefault(),ne.stopPropagation(),c(H,Y)},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(Hr,{className:"h-4 w-4"})})]},`recent-mobile-${H}-${Y}`)})})]}),o.map(E=>{const H=Array.isArray(E.models)?E.models:[];if(H.length===0)return null;const Y=E.id===s,fe=y.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:()=>b(E.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{providerId:E.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:E.name}),Y&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),fe?e.jsx(Nt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(As,{className:"h-3 w-3 text-muted-foreground"})]}),fe&&e.jsx("div",{className:"border-t border-border/20",children:H.map(ne=>{const pe=E.id===s&&ne.id===r;return e.jsxs("div",{className:O("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",pe?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{P(E.id,ne.id),M()},children:e.jsx("span",{className:"font-medium truncate",children:C(ne)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:je=>{je.preventDefault(),je.stopPropagation(),c(E.id,ne.id)},className:O("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(E.id,ne.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(E.id,ne.id)?"Unfavorite":"Favorite",children:d(E.id,ne.id)?e.jsx(Js,{className:"h-4 w-4"}):e.jsx(Hr,{className:"h-4 w-4"})}),pe&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},ne.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:()=>{P("",""),M()},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:O("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(Xt,{providerId:s,className:"h-3.5 w-3.5"}):e.jsx(Qs,{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(Nt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Jt,{open:v,onOpenChange:S,children:[e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:O("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(Xt,{providerId:s,className:"h-3 w-3 flex-shrink-0"}),e.jsx(Qs,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Qs,{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(Nt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(es,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const E=[];q.forEach(({model:ne,providerID:pe,modelID:je})=>{E.push({model:ne,providerID:pe,modelID:je,section:"fav"})}),te.forEach(({model:ne,providerID:pe,modelID:je})=>{E.push({model:ne,providerID:pe,modelID:je,section:"recent"})}),le.forEach(ne=>{ne.models.forEach(pe=>{E.push({model:pe,providerID:ne.id,modelID:pe.id,section:"provider"})})});const H=E.length,Y=ne=>{if(ne.key==="ArrowDown"){ne.preventDefault(),ne.stopPropagation();const pe=(k+1)%Math.max(1,H);F(pe),setTimeout(()=>{A.current[pe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(ne.key==="ArrowUp"){ne.preventDefault(),ne.stopPropagation();const pe=(k-1+Math.max(1,H))%Math.max(1,H);F(pe),setTimeout(()=>{A.current[pe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(ne.key==="Enter"){ne.preventDefault(),ne.stopPropagation();const pe=E[k];pe&&P(pe.providerID,pe.modelID)}else ne.key==="Escape"&&(ne.preventDefault(),ne.stopPropagation(),S(!1))};let fe=0;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{type:"text",placeholder:"Search models",value:N,onChange:ne=>j(ne.target.value),onKeyDown:Y,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(tt,{outerClassName:"max-h-[400px] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:O("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>P("",""),children:[e.jsx(Wt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!s&&!r&&e.jsx(Dt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Us,{}),!$&&N&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),q.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Js,{className:"h-4 w-4 text-primary"}),"Favorites"]}),q.map(({model:ne,providerID:pe,modelID:je})=>{const U=fe++;return L(ne,pe,je,"fav",U,k===U)})]}),te.length>0&&e.jsxs(e.Fragment,{children:[q.length>0&&e.jsx(Us,{}),e.jsxs(Wr,{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"]}),te.map(({model:ne,providerID:pe,modelID:je})=>{const U=fe++;return L(ne,pe,je,"recent",U,k===U)})]}),(q.length>0||te.length>0)&&le.length>0&&e.jsx(Us,{}),le.map((ne,pe)=>e.jsxs(l.Fragment,{children:[pe>0&&e.jsx(Us,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Xt,{providerId:ne.id,className:"h-4 w-4 flex-shrink-0"}),ne.name]}),ne.models.map(je=>{const U=fe++;return L(je,ne.id,je.id,"provider",U,k===U)})]},ne.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()]})},nw=()=>{const{tools:s}=Tr(),[r,t]=l.useState([]),[n,o]=l.useState(!0),[a,i]=l.useState(null);return l.useEffect(()=>{let c=!1;return(async()=>{o(!0),i(null);try{const u=await s.getAvailableTools();if(c)return;t(u)}catch(u){if(c)return;const m=u instanceof Error?u.message:"Failed to fetch tools";console.error("Failed to fetch available tools:",m),i(m),t([])}finally{c||o(!1)}})(),()=>{c=!0}},[s]),{tools:r,isLoading:n,error:a}},ow=()=>{const{selectedAgentName:s,getAgentByName:r,createAgent:t,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:i}=tn();ut();const{tools:c}=nw(),d=s?r(s):null,u=!!(a&&a.name===s&&!d),[m,f]=l.useState(""),[p,h]=l.useState("user"),[w,g]=l.useState(""),[y,x]=l.useState("subagent"),[v,S]=l.useState(""),[N,j]=l.useState(void 0),[k,F]=l.useState(void 0),[A,M]=l.useState(""),[b,C]=l.useState({}),[D,P]=l.useState("allow"),[R,L]=l.useState("allow"),[q,te]=l.useState("allow"),[le,$]=l.useState("allow"),[z,E]=l.useState("ask"),[H,Y]=l.useState("ask"),[fe,ne]=l.useState(!1);l.useEffect(()=>{if(u&&a){f(a.name||""),h(a.scope||"user"),g(a.description||""),x(a.mode||"subagent"),S(a.model||""),j(a.temperature),F(a.top_p),M(a.prompt||"");const ee=a.tools||{};C(ee);const oe=(ce,Me,Ee)=>ce==="allow"||ce==="ask"||ce==="deny"?ce:Me?"deny":Ee,W=a.permission||{},me=ce=>{if(ce==="allow"||ce==="ask"||ce==="deny")return ce;if(ce&&typeof ce=="object"&&!Array.isArray(ce)){const Me=ce["*"];if(Me==="allow"||Me==="ask"||Me==="deny")return Me}},ye=ee.edit===!1||ee.write===!1||ee.patch===!1;P(oe(me(W.edit),ye,"allow")),te(oe(me(W.bash),ee.bash===!1,"allow")),L(oe(me(W.webfetch),ee.webfetch===!1,"allow")),$(oe(me(W.skill),ee.skill===!1,"allow")),E(oe(me(W.doom_loop),!1,"ask")),Y(oe(me(W.external_directory),!1,"ask"))}else if(d){g(d.description||""),x(d.mode||"subagent"),d.model?.providerID&&d.model?.modelID?S(`${d.model.providerID}/${d.model.modelID}`):S(""),j(d.temperature),F(d.topP),M(d.prompt||"");const ee=d.tools||{};C(ee);const oe=(ce,Me,Ee)=>ce==="allow"||ce==="ask"||ce==="deny"?ce:Me?"deny":Ee,W=d.permission||{},me=ce=>{if(ce==="allow"||ce==="ask"||ce==="deny")return ce;if(ce&&typeof ce=="object"&&!Array.isArray(ce)){const Me=ce["*"];if(Me==="allow"||Me==="ask"||Me==="deny")return Me}},ye=ee.edit===!1||ee.write===!1||ee.patch===!1;P(oe(me(W.edit),ye,"allow")),te(oe(me(W.bash),ee.bash===!1,"allow")),L(oe(me(W.webfetch),ee.webfetch===!1,"allow")),$(oe(me(W.skill),ee.skill===!1,"allow")),E(oe(me(W.doom_loop),!1,"ask")),Y(oe(me(W.external_directory),!1,"ask"))}},[d,u,s,o,a]);const pe=async()=>{const ee=u?m.trim().replace(/\s+/g,"-"):s?.trim();if(!ee){se.error("Agent name is required");return}if(u&&o.some(oe=>oe.name===ee)){se.error("An agent with this name already exists");return}ne(!0);try{const oe=v.trim(),W={name:ee,description:w.trim()||void 0,mode:y,model:oe===""?null:oe,temperature:N,top_p:k,prompt:A.trim()||void 0,tools:Object.keys(b).length>0?b:void 0,permission:{edit:D,webfetch:R,bash:q,skill:le,doom_loop:z,external_directory:H},scope:u?p:void 0};let me;u?(me=await t(W),me&&i(null)):me=await n(ee,W),me?se.success(u?"Agent created successfully":"Agent updated successfully"):se.error(u?"Failed to create agent":"Failed to update agent")}catch(oe){console.error("Error saving agent:",oe),se.error("An error occurred while saving")}finally{ne(!1)}},je=ee=>{C(oe=>({...oe,[ee]:!oe[ee]}))},U=ee=>{const oe={};c.forEach(W=>{oe[W]=ee}),C(oe)};return s?e.jsx(tt,{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:u?"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"})]}),u&&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(dt,{value:m,onChange:ee=>f(ee.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Fs,{value:p,onValueChange:ee=>h(ee),children:[e.jsxs(Ps,{className:"!h-9 w-auto gap-1.5",children:[p==="user"?e.jsx(bs,{className:"h-4 w-4"}):e.jsx(dr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:p})]}),e.jsxs(Rs,{align:"end",children:[e.jsx(Ot,{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(bs,{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(Ot,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Ts,{value:w,onChange:ee=>g(ee.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(Cs,{variant:y==="primary"?"default":"outline",onClick:()=>x("primary"),className:O("gap-2",y==="primary"?void 0:"text-foreground"),children:[e.jsx(bn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Cs,{variant:y==="subagent"?"default":"outline",onClick:()=>x("subagent"),className:O("gap-2",y==="subagent"?void 0:"text-foreground"),children:[e.jsx(td,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Cs,{variant:y==="all"?"default":"outline",onClick:()=>x("all"),className:O("gap-2",y==="all"?void 0:"text-foreground"),children:[e.jsx(sd,{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(Mi,{providerId:v?v.split("/")[0]:"",modelId:v?v.split("/")[1]:"",onChange:(ee,oe)=>{S(ee&&oe?`${ee}/${oe}`:"")}})]}),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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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 oe=Math.max(0,(N!==void 0?N:.7)-.1);j(parseFloat(oe.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(_i,{className:"h-3.5 w-3.5"})}),e.jsx(dt,{type:"text",inputMode:"decimal",value:N!==void 0?N:"",onChange:ee=>{const oe=ee.target.value;if(oe===""){j(void 0);return}const W=parseFloat(oe);!isNaN(W)&&W>=0&&W<=2&&j(W)},onBlur:ee=>{const oe=ee.target.value;if(oe!==""){const W=parseFloat(oe);if(!isNaN(W)){const me=Math.max(0,Math.min(2,W));j(parseFloat(me.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const oe=Math.min(2,(N!==void 0?N:.7)+.1);j(parseFloat(oe.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(Gt,{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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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 oe=Math.max(0,(k!==void 0?k:.9)-.1);F(parseFloat(oe.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(_i,{className:"h-3.5 w-3.5"})}),e.jsx(dt,{type:"text",inputMode:"decimal",value:k!==void 0?k:"",onChange:ee=>{const oe=ee.target.value;if(oe===""){F(void 0);return}const W=parseFloat(oe);!isNaN(W)&&W>=0&&W<=1&&F(W)},onBlur:ee=>{const oe=ee.target.value;if(oe!==""){const W=parseFloat(oe);if(!isNaN(W)){const me=Math.max(0,Math.min(1,W));F(parseFloat(me.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const oe=Math.min(1,(k!==void 0?k:.9)+.1);F(parseFloat(oe.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(Gt,{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(Ts,{value:A,onChange:ee=>M(ee.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),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:"Available Tools"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select tools this agent can access"})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>U(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>U(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:c.map(ee=>e.jsx("button",{type:"button",onClick:()=>je(ee),className:O("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",b[ee]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:ee},ee))})]}),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:"Configure permission levels for different operations"})]}),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:"Edit Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:D==="allow"?"default":"outline",onClick:()=>P("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:D==="ask"?"default":"outline",onClick:()=>P("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:D==="deny"?"default":"outline",onClick:()=>P("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:"Controls file editing permissions."}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Ye,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Allows file editing without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompts for confirmation before editing"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Blocks all file editing operations"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Bash Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:q==="allow"?"default":"outline",onClick:()=>te("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:q==="ask"?"default":"outline",onClick:()=>te("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:q==="deny"?"default":"outline",onClick:()=>te("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:"Permission for running bash commands"}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Ye,{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 bash commands without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before execution"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all bash command execution"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"WebFetch Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:R==="allow"?"default":"outline",onClick:()=>L("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:R==="ask"?"default":"outline",onClick:()=>L("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:R==="deny"?"default":"outline",onClick:()=>L("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:"Permission for fetching web content"}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Ye,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Fetch web content without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before fetching"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all web content access"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Skill Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:le==="allow"?"default":"outline",onClick:()=>$("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:le==="ask"?"default":"outline",onClick:()=>$("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:le==="deny"?"default":"outline",onClick:()=>$("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:"Permission for loading skills"}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Ye,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Load skills without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before loading skills"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all skill loading"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Doom Loop Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:z==="allow"?"default":"outline",onClick:()=>E("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:z==="ask"?"default":"outline",onClick:()=>E("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:z==="deny"?"default":"outline",onClick:()=>E("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:"Permission for repeated identical tool calls"}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Ye,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Continue without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt when a doom loop is detected"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block repeated tool calls"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"External Directory Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:H==="allow"?"default":"outline",onClick:()=>Y("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:H==="ask"?"default":"outline",onClick:()=>Y("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:H==="deny"?"default":"outline",onClick:()=>Y("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:"Permission for file access outside project"}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Ye,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Access external paths without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt before accessing external paths"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block external directory access"]})]})})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(ve,{size:"sm",variant:"default",onClick:pe,disabled:fe,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(To,{className:"h-3 w-3"}),fe?"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(lo,{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"})]})})},aw=({onItemSelect:s})=>{const[r,t]=l.useState(null),[n,o]=l.useState(""),{selectedCommandName:a,commands:i,setSelectedCommand:c,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=rn(),{setSidebarOpen:p}=Fe(),{isMobile:h}=Ct(),[w,g]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=l.useMemo(()=>Et(),[]);l.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{f()},[f]);const x=w?"bg-transparent":y?"bg-background":"bg-sidebar",v=()=>{const b="new-command";let C=b,D=1;for(;i.some(P=>P.name===C);)C=`${b}-${D}`,D++;d({name:C,scope:"user"}),c(C),s?.(),h&&p(!1)},S=async b=>{if(Br(b)){se.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${b.name}"?`)&&(await m(b.name)?se.success(`Command "${b.name}" deleted successfully`):se.error("Failed to delete command"))},N=async b=>{Br(b)&&window.confirm(`Are you sure you want to reset command "${b.name}" to its default configuration?`)&&(await m(b.name)?se.success(`Command "${b.name}" reset to default`):se.error("Failed to reset command"))},j=b=>{const C=b.name;let D=1,P=`${C}-copy`;for(;i.some(R=>R.name===P);)D++,P=`${C}-copy-${D}`;d({name:P,scope:b.scope||"user",description:b.description,template:b.template,agent:b.agent,model:b.model,subtask:b.subtask}),c(P),h&&p(!1)},k=b=>{o(b.name),t(b)},F=async()=>{if(!r)return;const b=n.trim().replace(/\s+/g,"-");if(!b){se.error("Command name is required");return}if(b===r.name){t(null);return}if(i.some(D=>D.name===b)){se.error("A command with this name already exists");return}await u({name:b,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(se.success(`Command renamed to "${b}"`),c(b)):se.error("Failed to remove old command after rename"):se.error("Failed to rename command"),t(null)},A=i.filter(Br),M=i.filter(b=>!Br(b));return e.jsxs("div",{className:O("flex h-full flex-col",x),children:[e.jsx("div",{className:O("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(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(Gt,{className:"size-4"})})]})}),e.jsx(tt,{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(mr,{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:[A.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"}),[...A].sort((b,C)=>b.name.localeCompare(C.name)).map(b=>e.jsx(yc,{command:b,isSelected:a===b.name,onSelect:()=>{c(b.name),s?.(),h&&p(!1)},onReset:()=>N(b),onDuplicate:()=>j(b)},b.name))]}),M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Commands"}),[...M].sort((b,C)=>b.name.localeCompare(C.name)).map(b=>e.jsx(yc,{command:b,isSelected:a===b.name,onSelect:()=>{c(b.name),s?.(),h&&p(!1)},onRename:()=>k(b),onDelete:()=>S(b),onDuplicate:()=>j(b)},b.name))]})]})}),e.jsx(as,{open:r!==null,onOpenChange:b=>!b&&t(null),children:e.jsxs(is,{children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Rename Command"}),e.jsxs(js,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(dt,{value:n,onChange:b=>o(b.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:b=>{b.key==="Enter"&&F()}}),e.jsxs(Gs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Mr,{onClick:F,children:"Rename"})]})]})})]})},yc=({command:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i})=>e.jsx("div",{className:O("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||Br(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:Br(s)?"system":s.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Jt,{children:[e.jsx(Zt,{asChild:!0,children:e.jsx(ve,{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(Cn,{className:"h-3.5 w-3.5"})})}),e.jsxs(es,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(kt,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(ai,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(kt,{onClick:c=>{c.stopPropagation(),i()},children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(kt,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(xs,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(kt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),Eu=({agentName:s,onChange:r,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=tn(),a=o(),i=Fe(w=>w.isMobile),{isMobile:c}=Ct(),d=i||c,[u,m]=l.useState(!1);l.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=w=>{r(w)},h=()=>d?e.jsx(ps,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(w=>{const g=w.name===s;return e.jsxs("button",{type:"button",className:O("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(w.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:w.name}),w.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:w.description})]}),g&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},w.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:O("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(lo,{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(Nt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Jt,{children:[e.jsx(Zt,{asChild:!0,children:e.jsxs("div",{className:O("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(lo,{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(Nt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(es,{className:"max-w-[300px]",children:[a.map(w=>e.jsx(kt,{className:"typography-meta",onSelect:()=>p(w.name),children:e.jsx("span",{className:"font-medium",children:w.name})},w.name)),e.jsx(kt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},iw=()=>{const{selectedCommandName:s,getCommandByName:r,createCommand:t,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:i}=rn(),c=s?r(s):null,d=!!(a&&a.name===s&&!c),[u,m]=l.useState(""),[f,p]=l.useState("user"),[h,w]=l.useState(""),[g,y]=l.useState(""),[x,v]=l.useState(""),[S,N]=l.useState(""),[j,k]=l.useState(!1),[F,A]=l.useState(!1);l.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),w(a.description||""),y(a.agent||""),v(a.model||""),N(a.template||""),k(a.subtask||!1)):c&&(w(c.description||""),y(c.agent||""),v(c.model||""),N(c.template||""),k(c.subtask||!1))},[c,d,s,o,a]);const M=async()=>{const b=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!b){se.error("Command name is required");return}if(!S.trim()){se.error("Command template is required");return}if(d&&o.some(C=>C.name===b)){se.error("A command with this name already exists");return}A(!0);try{const C=g.trim(),D=x.trim(),P=S.trim(),R={name:b,description:h.trim()||void 0,agent:C===""?null:C,model:D===""?null:D,template:P,subtask:j,scope:d?f:void 0};let L;d?(L=await t(R),L&&i(null)):L=await n(b,R),L?se.success(d?"Command created successfully":"Command updated successfully"):se.error(d?"Failed to create command":"Failed to update command")}catch(C){console.error("Error saving command:",C),se.error("An error occurred while saving")}finally{A(!1)}};return s?e.jsx(tt,{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(dt,{value:u,onChange:b=>m(b.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Fs,{value:f,onValueChange:b=>p(b),children:[e.jsxs(Ps,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(bs,{className:"h-4 w-4"}):e.jsx(dr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Rs,{align:"end",children:[e.jsx(Ot,{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(bs,{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(Ot,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Ts,{value:h,onChange:b=>w(b.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(Eu,{agentName:g,onChange:b=>y(b)}),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(Mi,{providerId:x?x.split("/")[0]:"",modelId:x?x.split("/")[1]:"",onChange:(b,C)=>{v(b&&C?`${b}/${C}`:"")}}),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:j,onChange:b=>k(b.target.checked),className:"sr-only"}),e.jsx("div",{className:O("w-5 h-5 rounded border-2 flex items-center justify-center",j?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:j&&e.jsx(Dt,{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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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(Ts,{value:S,onChange:b=>N(b.target.value),placeholder:`Your command template here...
|
|
97
|
+
|
|
98
|
+
Use $ARGUMENTS to reference user input.
|
|
99
|
+
Use !\`shell command\` to inject shell output.
|
|
100
|
+
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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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(ve,{size:"sm",variant:"default",onClick:M,disabled:F,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(To,{className:"h-3 w-3"}),F?"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(mr,{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"})]})})},nr=()=>{try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},oo="useSkillsStore",ir=Tt()(_t(ws((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=nr(),i=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills${i}`);if(!c.ok)throw new Error(`Failed to list skills: ${c.status}`);const u=(await c.json()).skills||[];return s({skills:u,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load skills:",n),s({skills:t,isLoading:!1}),!1},getSkillDetail:async t=>{try{const n=nr(),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=>{Es("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=nr(),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)}),c=await i.json().catch(()=>null);if(!i.ok){const u=c?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&ys("skills",{source:oo}),d}catch{return!1}finally{os()}},updateSkill:async(t,n)=>{Es("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=nr(),i=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(t)}${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&ys("skills",{source:oo}),u}catch{return!1}finally{os()}},deleteSkill:async t=>{Es("Deleting skill...");try{const n=nr(),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 c=await r().loadSkills();return c&&ys("skills",{source:oo}),r().selectedSkillName===t&&s({selectedSkillName:null}),c}catch{return!1}finally{os()}},getSkillByName:t=>{const{skills:n}=r();return n.find(o=>o.name===t)},readSupportingFile:async(t,n)=>{try{const o=nr(),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=nr(),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=nr(),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:vs(()=>ls()),partialize:s=>({selectedSkillName:s.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=ir);let bc=null;bc||(bc=Po(s=>{if(s.source!==oo&&vn(s,"skills")){const{loadSkills:r}=ir.getState();r()}}));const lw=({onItemSelect:s})=>{const[r,t]=l.useState(null),[n,o]=l.useState(""),{selectedSkillName:a,skills:i,setSelectedSkill:c,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=ir(),{setSidebarOpen:h}=Fe(),{isMobile:w}=Ct(),[g,y]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=l.useMemo(()=>Et(),[]);l.useEffect(()=>{typeof window>"u"||y(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{f()},[f]);const v=g?"bg-transparent":x?"bg-background":"bg-sidebar",S=()=>{const b="new-skill";let C=b,D=1;for(;i.some(P=>P.name===C);)C=`${b}-${D}`,D++;d({name:C,scope:"user",description:""}),c(C),s?.(),w&&h(!1)},N=async b=>{window.confirm(`Are you sure you want to delete skill "${b.name}"?`)&&(await m(b.name)?se.success(`Skill "${b.name}" deleted successfully`):se.error("Failed to delete skill"))},j=async b=>{const C=b.name;let D=1,P=`${C}-copy`;for(;i.some(L=>L.name===P);)D++,P=`${C}-copy-${D}`;const R=await p(b.name);if(!R){se.error("Failed to load skill details for duplication");return}d({name:P,scope:b.scope||"user",description:(R.sources.md.fields.includes("description"),""),instructions:""}),c(P),w&&h(!1)},k=b=>{o(b.name),t(b)},F=async()=>{if(!r)return;const b=n.trim().replace(/\s+/g,"-").toLowerCase();if(!b){se.error("Skill name is required");return}if(b===r.name){t(null);return}if(i.some(P=>P.name===b)){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:b,description:"Renamed skill",scope:r.scope})?await m(r.name)?(se.success(`Skill renamed to "${b}"`),c(b)):se.error("Failed to remove old skill after rename"):se.error("Failed to rename skill"),t(null)},A=i.filter(b=>b.scope==="project"),M=i.filter(b=>b.scope==="user");return e.jsxs("div",{className:O("flex h-full flex-col",v),children:[e.jsx("div",{className:O("border-b px-3",w?"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(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:S,children:e.jsx(Gt,{className:"size-4"})})]})}),e.jsx(tt,{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(rd,{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:[A.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"}),A.map(b=>e.jsx(wc,{skill:b,isSelected:a===b.name,onSelect:()=>{c(b.name),s?.(),w&&h(!1)},onRename:()=>k(b),onDelete:()=>N(b),onDuplicate:()=>j(b)},b.name))]}),M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"User Skills"}),M.map(b=>e.jsx(wc,{skill:b,isSelected:a===b.name,onSelect:()=>{c(b.name),s?.(),w&&h(!1)},onRename:()=>k(b),onDelete:()=>N(b),onDuplicate:()=>j(b)},b.name))]})]})}),e.jsx(as,{open:r!==null,onOpenChange:b=>!b&&t(null),children:e.jsxs(is,{children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Rename Skill"}),e.jsxs(js,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(dt,{value:n,onChange:b=>o(b.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:b=>{b.key==="Enter"&&F()}}),e.jsxs(Gs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Mr,{onClick:F,children:"Rename"})]})]})})]})},wc=({skill:s,isSelected:r,onSelect:t,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:O("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(Jt,{children:[e.jsx(Zt,{asChild:!0,children:e.jsx(ve,{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(Cn,{className:"h-3.5 w-3.5"})})}),e.jsxs(es,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(kt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(ai,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(kt,{onClick:i=>{i.stopPropagation(),a()},children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(kt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),ya=()=>{try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},Di=Tt()(_t((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=ya(),c=t?.refresh?"&refresh=true":"",d=i?`?directory=${encodeURIComponent(i)}${c}`:c?"?refresh=true":"",u=await fetch(`/api/config/skills/catalog${d}`,{method:"GET",headers:{Accept:"application/json"}}),m=await u.json().catch(()=>null);if(!u.ok||!m?.ok){o=m?.error||{kind:"unknown",message:`Failed to load catalog (${u.status})`};const g=200*(a+1);await new Promise(y=>setTimeout(y,g));continue}const f=m.sources||[],p=m.itemsBySource||{},h=r().selectedSourceId,w=h&&f.some(g=>g.id===h)?h:f[0]?.id??null;return s({sources:f,itemsBySource:p,selectedSourceId:w}),!0}catch(i){o={kind:"unknown",message:i instanceof Error?i.message:String(i)};const c=200*(a+1);await new Promise(d=>setTimeout(d,c))}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=ya(),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 c=i?.error||{kind:"unknown",message:"Failed to scan repository"};return s({lastScanError:c}),{ok:!1,error:c}}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=ya(),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 c={kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:c}),{ok:!1,error:c}}if(!a.ok||!i.ok){const c=i.error||{kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:c}),{ok:!1,error:c}}return ir.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"})),cw=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,dw=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},uw=async()=>{try{if(Ht())return await en();const s=Er()?.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}},mw=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=Di(),[a,i]=l.useState(""),[c,d]=l.useState(""),[u,m]=l.useState(""),[f,p]=l.useState([]),[h,w]=l.useState(null),[g,y]=l.useState(!1),[x,v]=l.useState([]),[S,N]=l.useState(null);l.useEffect(()=>{s&&(i(""),d(""),m(""),w(null),y(!1),v([]),N(null),(async()=>{const A=await uw(),M=Array.isArray(A?.skillCatalogs)?A?.skillCatalogs:[];p(M||[])})())},[s]);const j=l.useMemo(()=>{const A=c.trim(),M=u.trim();return f.some(b=>{const C=(b.source||"").trim(),D=(b.subpath||"").trim();return C===A&&D===M})},[f,c,u]),k=async()=>{const A=c.trim();if(!A){se.error("Repository source is required");return}a.trim()||i(dw(A)),y(!1),w(null);const M=await t({source:A,subpath:u.trim()||void 0,gitIdentityId:S||void 0});if(!M.ok){if(M.error?.kind==="authRequired"){if(Et()){se.error("Private repositories are not supported in VS Code yet");return}const C=M.error.identities||[];v(C),!S&&C.length>0&&N(C[0].id),se.error("Authentication required. Select a Git identity and scan again.");return}se.error(M.error?.message||"Failed to scan repository");return}const b=M.items?.length||0;if(w(b),b===0){se.error("No skills found in this repository"),y(!1);return}v([]),y(!0),se.success(`Found ${b} skill(s)`)},F=async()=>{const A=a.trim(),M=c.trim(),b=u.trim();if(!A){se.error("Catalog name is required");return}if(!M){se.error("Repository source is required");return}if(!g){se.error("Scan the repository before adding this catalog");return}if(j){se.error("This catalog already exists");return}const C={id:cw(),label:A,source:M,...b?{subpath:b}:{},...S?{gitIdentityId:S}:{}},D=[...f,C];try{await ns({skillCatalogs:D}),p(D),se.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(P){se.error(P instanceof Error?P.message:"Failed to save catalog")}};return e.jsx(as,{open:s,onOpenChange:r,children:e.jsxs(is,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Add skills catalog"}),e.jsxs(js,{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(dt,{value:a,onChange:A=>i(A.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(dt,{value:c,onChange:A=>{d(A.target.value),y(!1),w(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(dt,{value:u,onChange:A=>{m(A.target.value),y(!1),w(null)},placeholder:"e.g. skills"})]}),x.length>0&&!Et()?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(Fs,{value:S||"",onValueChange:A=>N(A),children:[e.jsx(Ps,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:x.find(A=>A.id===S)?.name||"Choose identity"})}),e.jsx(Rs,{align:"start",children:x.map(A=>e.jsx(Ot,{value:A.id,className:"pr-2 [&>span:first-child]:hidden",children:A.name},A.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,j?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Gs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(ve,{variant:"outline",onClick:()=>{k()},disabled:o||!c.trim(),className:"gap-2",children:[e.jsx(Yc,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(ve,{variant:"default",onClick:()=>{F()},disabled:!g||j||!a.trim()||!c.trim(),children:"Add catalog"})]})]})})},fw=({open:s,onOpenChange:r,conflicts:t,onConfirm:n})=>{const[o,a]=l.useState({});l.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)},c=t.length>0&&t.every(d=>o[d.skillName]);return e.jsx(as,{open:s,onOpenChange:r,children:e.jsxs(is,{className:"max-w-2xl",children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Skills already exist"}),e.jsx(js,{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(ve,{variant:"outline",size:"sm",onClick:()=>i("skip"),children:"Skip all"}),e.jsx(ve,{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(Fs,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Ps,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(Rs,{align:"end",children:[e.jsx(Ot,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Ot,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Gs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Mr,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},pw=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=Di(),[a,i]=l.useState("user"),[c,d]=l.useState(!1),[u,m]=l.useState([]),[f,p]=l.useState(null);l.useEffect(()=>{s&&(i("user"),d(!1),m([]),p(null))},[s]);const h=async w=>{const g=await n({source:w.source,subpath:w.subpath,gitIdentityId:t?.gitIdentityId,scope:w.scope,selections:[{skillDir:w.skillDir}],conflictPolicy:"prompt",conflictDecisions:w.conflictDecisions});if(g.ok){se.success("Skill installed successfully"),r(!1);return}if(g.error?.kind==="conflicts"){p({source:w.source,subpath:w.subpath,scope:w.scope,skillDir:w.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(as,{open:s,onOpenChange:r,children:e.jsxs(is,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Install skill"}),e.jsxs(js,{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(w=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:w},w))})]}):null}),e.jsxs(Gs,{className:"flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-center",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Fs,{value:a,onValueChange:w=>i(w),children:[e.jsx(Ps,{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(bs,{className:"h-4 w-4"}):e.jsx(dr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Rs,{align:"start",children:[e.jsx(Ot,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Ot,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]})})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(ve,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(ve,{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(fw,{open:c,onOpenChange:d,conflicts:u,onConfirm:w=>{f&&(h({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:w}),d(!1))}})]}):null},hw=async()=>{try{if(Ht())return await en();const s=Er()?.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}},gw=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:i,isLoadingCatalog:c,lastCatalogError:d}=Di(),[u,m]=l.useState(""),[f,p]=l.useState(!1),[h,w]=l.useState(!1),[g,y]=l.useState(null),[x,v]=l.useState(!1);l.useEffect(()=>{i()},[i]);const S=l.useMemo(()=>o?n[o]||[]:[],[n,o]),N=l.useMemo(()=>{const A=u.trim().toLowerCase();return A?S.filter(M=>{const b=M.skillName.toLowerCase(),C=(M.description||"").toLowerCase(),D=(M.frontmatterName||"").toLowerCase();return b.includes(A)||C.includes(A)||D.includes(A)}):S},[S,u]),j=l.useMemo(()=>t.find(A=>A.id===o)||null,[t,o]),k=!!(o&&o.startsWith("custom:")),F=async()=>{if(!(!o||!k)&&window.confirm("Remove this catalog?")){v(!0);try{const A=await hw(),b=(Array.isArray(A?.skillCatalogs)?A?.skillCatalogs:[]).filter(C=>C.id!==o);await ns({skillCatalogs:b}),await i({refresh:!0})}finally{v(!1)}}};return e.jsx(tt,{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(ji,{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(Fs,{value:o||"",onValueChange:A=>a(A),children:[e.jsx(Ps,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:j?.label||"Select source"})}),e.jsx(Rs,{align:"start",children:t.map(A=>e.jsx(Ot,{value:A.id,className:"pr-2 [&>span:first-child]:hidden",children:A.label},A.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ve,{type:"button",variant:"outline",onClick:()=>{i({refresh:!0})},disabled:c,className:"gap-2",children:[e.jsx(Mn,{className:"h-4 w-4"}),"Refresh"]}),k?e.jsxs(ve,{type:"button",variant:"outline",onClick:()=>{F()},disabled:x,className:"gap-2",children:[e.jsx(Ls,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(ve,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(Gt,{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(dt,{value:u,onChange:A=>m(A.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:c?"Loading…":`${N.length} skill(s)`})]}),d?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Catalog error"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:d.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:N.length===0?e.jsxs("div",{className:"py-10 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"No skills found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Try a different search or refresh the catalog"})]}):N.map(A=>{const M=A.installed?.isInstalled,b=A.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:A.skillName}),M?e.jsxs("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:["installed (",b||"unknown",")"]}):null,A.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"})]}),A.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:A.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),A.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:A.warnings.join(" · ")}):null]}),e.jsx(ve,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!A.installable,onClick:()=>{y(A),w(!0)},children:"Install"})]})},`${A.sourceId}:${A.skillDir}`)})}),e.jsx(mw,{open:f,onOpenChange:p}),e.jsx(pw,{open:h,onOpenChange:w,item:g})]})})},xw=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:i,setSkillDraft:c,setSelectedSkill:d}=ir(),u=s?r(s):null,m=!!(i&&i.name===s&&!u),f=!!(s&&!u&&!i),[p,h]=l.useState("manual");l.useEffect(()=>{!m&&p!=="manual"&&h("manual")},[m,p]),l.useEffect(()=>{f&&d(null)},[f,d]);const w=m?e.jsx(ji,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[g,y]=l.useState(""),[x,v]=l.useState("user"),[S,N]=l.useState(""),[j,k]=l.useState(""),[F,A]=l.useState([]),[M,b]=l.useState([]),[C,D]=l.useState(!1),[P,R]=l.useState(!1),[L,q]=l.useState(""),[te,le]=l.useState(""),[$,z]=l.useState(!1),[E,H]=l.useState(""),[Y,fe]=l.useState(""),[ne,pe]=l.useState(null),[je,U]=l.useState(!1),[ee,oe]=l.useState(""),W=m?g.trim()!==""||S.trim()!==""||j.trim()!==""||M.length>0:S!==L||j!==te,me=ne?Y!==ee:E.trim()!=="";l.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&i)y(i.name||""),v(i.scope||"user"),N(i.description||""),k(i.instructions||""),q(""),le(""),A([]),b(i.pendingFiles||[]);else if(s&&u){R(!0);try{const K=await t(s);if(K){const T=K.sources.md;N(T.description||""),k(T.instructions||""),q(T.description||""),le(T.instructions||""),A(T.supportingFiles||[])}}catch(K){console.error("Failed to load skill details:",K)}finally{R(!1)}}})()},[u,m,s,a,i,t,p]);const ye=async()=>{const V=m?g.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!V){se.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(V)||V.length>64){se.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!S.trim()){se.error("Description is required");return}if(m&&a.some(K=>K.name===V)){se.error("A skill with this name already exists");return}D(!0);try{const K={name:V,description:S.trim(),instructions:j.trim()||void 0,scope:m?x:void 0,supportingFiles:m&&M.length>0?M:void 0};let T;m?(T=await n(K),T&&(c(null),b([]),d(V))):(T=await o(V,K),T&&(q(S.trim()),le(j.trim()))),T?se.success(m?"Skill created successfully":"Skill updated successfully"):se.error(m?"Failed to create skill":"Failed to update skill")}catch(K){console.error("Error saving skill:",K),se.error("An error occurred while saving")}finally{D(!1)}},ce=()=>{pe(null),H(""),fe(""),oe(""),z(!0)},Me=async V=>{if(pe(V),H(V),m){const T=M.find(X=>X.path===V)?.content||"";fe(T),oe(T),z(!0);return}if(s){U(!0),z(!0);try{const{readSupportingFile:K}=ir.getState(),T=await K(s,V);fe(T||""),oe(T||"")}catch{se.error("Failed to load file content"),fe(""),oe("")}finally{U(!1)}}},Ee=async()=>{if(!E.trim()){se.error("File name is required");return}const V=E.trim(),K=ne!==null;if(m){if(K)b(I=>I.map(B=>B.path===ne?{path:V,content:Y}:B)),se.success(`File "${V}" updated`);else{if(M.some(I=>I.path===V)){se.error("A file with this name already exists");return}b(I=>[...I,{path:V,content:Y}]),se.success(`File "${V}" added`)}z(!1),pe(null);return}if(!s){se.error("No skill selected");return}const{writeSupportingFile:T}=ir.getState();if(await T(s,V,Y)){se.success(K?`File "${V}" updated`:`File "${V}" created`),z(!1),pe(null);const I=await t(s);I&&A(I.sources.md.supportingFiles||[])}else se.error(K?"Failed to update file":"Failed to create file")},Pe=async V=>{if(m){b(K=>K.filter(T=>T.path!==V)),se.success(`File "${V}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${V}"?`)){const{deleteSupportingFile:K}=ir.getState();if(await K(s,V)){se.success(`File "${V}" deleted`);const X=await t(s);X&&A(X.sources.md.supportingFiles||[])}else se.error("Failed to delete file")}};return m&&p==="external"?e.jsx(gw,{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(rd,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a skill from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})}):P?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Loading skill details..."})})}):e.jsx(tt,{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?w: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(dt,{value:g,onChange:V=>y(V.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(Fs,{value:x,onValueChange:V=>v(V),children:[e.jsxs(Ps,{className:"!h-9 w-auto gap-1.5",children:[x==="user"?e.jsx(bs,{className:"h-4 w-4"}):e.jsx(dr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:x})]}),e.jsxs(Rs,{align:"end",children:[e.jsx(Ot,{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(bs,{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(Ot,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Lowercase letters, numbers, and hyphens only. Cannot start or end with hyphen."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Description ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Ts,{value:S,onChange:V=>N(V.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(Ts,{value:j,onChange:V=>k(V.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(ve,{variant:"outline",size:"sm",onClick:ce,className:"gap-1.5",children:[e.jsx(Gt,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const V=m?M:F;return V.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:V.map(K=>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(K.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(er,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:K.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(ve,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:T=>{T.stopPropagation(),Pe(K.path)},children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]},K.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(ve,{size:"sm",variant:"default",onClick:ye,disabled:C||!W,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(To,{className:"h-3 w-3"}),C?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(as,{open:$,onOpenChange:V=>{z(V),V||pe(null)},children:e.jsxs(is,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(ds,{className:"flex-shrink-0",children:[e.jsx(us,{children:ne?"Edit Supporting File":"Add Supporting File"}),e.jsx(js,{children:ne?"Modify the file content":"Create a new file in the skill directory"})]}),je?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(dt,{value:E,onChange:V=>H(V.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:ne!==null}),!ne&&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(Ts,{value:Y,onChange:V=>fe(V.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Gs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>{z(!1),pe(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Mr,{onClick:Ee,disabled:je||!me,children:ne?"Save Changes":"Create File"})]})]})})]})})},yw="__add_provider__",bw=({onItemSelect:s})=>{const r=ut(u=>u.providers),t=ut(u=>u.selectedProviderId),n=ut(u=>u.setSelectedProvider),{isMobile:o}=Ct(),[a,i]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=l.useMemo(()=>Et(),[]);l.useEffect(()=>{typeof window>"u"||i(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":c?"bg-background":"bg-sidebar";return e.jsxs("div",{className:O("flex h-full flex-col",d),children:[e.jsx("div",{className:O("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(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(yw),s?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(Gt,{className:"size-4"})})]})}),e.jsx(tt,{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(wn,{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:O("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(Xt,{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)})})]})},ww=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),vc=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=ww.format(s);return r.endsWith(".0")?r.slice(0,-2):r},jc="__add_provider__",Xr=s=>typeof s=="object"&&s!==null,Sc=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()},vw=s=>{if(!Xr(s))return{};const r={};for(const[t,n]of Object.entries(s))Array.isArray(n)&&(r[t]=n.filter(o=>Xr(o)));return r},jw=s=>{if(typeof s=="string")return{id:s};if(!Xr(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}},Sw=s=>{let r=[];Array.isArray(s)?r=s:Xr(s)&&(Array.isArray(s.all)?r=s.all:Array.isArray(s.providers)&&(r=s.providers));const t=r.map(o=>jw(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},kw=()=>{const s=ut(W=>W.providers),r=ut(W=>W.selectedProviderId),t=ut(W=>W.setSelectedProvider),n=ut(W=>W.loadProviders),o=ut(W=>W.getModelMetadata),[a,i]=l.useState({}),[c,d]=l.useState(!1),[u,m]=l.useState({}),[f,p]=l.useState(null),[h,w]=l.useState(""),[g,y]=l.useState(null),[x,v]=l.useState({}),[S,N]=l.useState({}),[j,k]=l.useState([]),[F,A]=l.useState(!1),[M,b]=l.useState(null),[C,D]=l.useState(""),[P,R]=l.useState(""),[L,q]=l.useState(!1);l.useEffect(()=>{!r&&s.length>0&&t(s[0].id)},[s,r,t]),l.useEffect(()=>{let W=!0;return(async()=>{d(!0);try{const ye=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!ye.ok)throw new Error(`Auth methods request failed (${ye.status})`);const ce=await ye.json().catch(()=>({}));if(!W)return;i(vw(ce))}catch(ye){if(!W)return;console.error("Failed to load provider auth methods:",ye),se.error("Failed to load provider authentication methods")}finally{W&&d(!1)}})(),()=>{W=!1}},[]),l.useEffect(()=>{let W=!0;return(async()=>{A(!0),b(null);try{const ye=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!ye.ok)throw new Error(`Provider list request failed (${ye.status})`);const ce=await ye.json().catch(()=>({}));if(!W)return;k(Sw(ce))}catch(ye){if(!W)return;console.error("Failed to load available providers:",ye),b("Unable to load provider list")}finally{W&&A(!1)}})(),()=>{W=!1}},[]);const te=l.useMemo(()=>new Set(s.map(W=>W.id)),[s]),le=l.useMemo(()=>j.filter(W=>!te.has(W.id)),[j,te]);l.useEffect(()=>{if(r===jc){if(!C&&le.length>0){D(le[0].id);return}C&&!le.some(W=>W.id===C)&&D(le[0]?.id??"")}},[r,C,le]);const $=s.find(W=>W.id===r),z=async W=>{const me=u[W]?.trim()??"";if(!me){se.error("API key is required");return}const ye=`api:${W}`;p(ye);try{const ce=await fetch(`/api/auth/${encodeURIComponent(W)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:me})}),Me=await ce.json().catch(()=>null);if(!ce.ok){const Ee=Me?.error||"Failed to save API key";throw new Error(Ee)}se.success("API key saved"),m(Ee=>({...Ee,[W]:""})),await pn(),await n(),t(W)}catch(ce){console.error("Failed to save API key:",ce),se.error("Failed to save API key")}finally{p(null)}},E=async(W,me)=>{const ye=`oauth:${W}:${me}`;p(ye);try{const ce=await fetch(`/api/provider/${encodeURIComponent(W)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:me})}),Me=await ce.json().catch(()=>null);if(!ce.ok){const I=Me?.error||"Failed to start OAuth flow";throw new Error(I)}const Ee=Xr(Me)?Me:{},Pe=Xr(Ee.data)?Ee.data:Ee,V=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,K=typeof Pe.instructions=="string"&&Pe.instructions||typeof Pe.message=="string"&&Pe.message||void 0,T=typeof Pe.user_code=="string"&&Pe.user_code||typeof Pe.code=="string"&&Pe.code||typeof Pe.userCode=="string"&&Pe.userCode||void 0;if(!V&&!K&&!T)throw new Error("No OAuth details returned");const X=`${W}:${me}`;N(I=>({...I,[X]:{url:V,instructions:K,userCode:T}})),V&&window.open(V,"_blank","noopener,noreferrer"),y({providerId:W,methodIndex:me}),se.message("Complete the OAuth flow in your browser")}catch(ce){console.error("Failed to start OAuth flow:",ce),se.error("Failed to start OAuth flow")}finally{p(null)}},H=async(W,me)=>{const ye=`${W}:${me}`,ce=x[ye]?.trim(),Me=`oauth-complete:${W}:${me}`;p(Me);try{const Ee={method:me};ce&&(Ee.code=ce);const Pe=await fetch(`/api/provider/${encodeURIComponent(W)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ee)}),V=await Pe.json().catch(()=>null);if(!Pe.ok){const K=V?.error||"Failed to complete OAuth flow";throw new Error(K)}se.success("OAuth connection completed"),v(K=>({...K,[ye]:""})),y(null),await pn(),await n(),t(W)}catch(Ee){console.error("Failed to complete OAuth flow:",Ee),se.error("Failed to complete OAuth flow")}finally{p(null)}},Y=async W=>{try{await navigator.clipboard.writeText(W),se.success("OAuth link copied")}catch(me){console.error("Failed to copy OAuth link:",me),se.error("Failed to copy OAuth link")}},fe=async W=>{try{await navigator.clipboard.writeText(W),se.success("Device code copied")}catch(me){console.error("Failed to copy device code:",me),se.error("Failed to copy device code")}},ne=async W=>{const me=`disconnect:${W}`;p(me);try{const ye=await fetch(`/api/provider/${encodeURIComponent(W)}/auth`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),ce=await ye.json().catch(()=>null);if(!ye.ok){const Me=ce?.error||"Failed to disconnect provider";throw new Error(Me)}se.success("Provider disconnected"),await pn(),await n()}catch(ye){console.error("Failed to disconnect provider:",ye),se.error("Failed to disconnect provider")}finally{p(null)}},pe=r===jc;if(!pe&&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(wn,{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(pe)return e.jsx(tt,{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."})]}),F?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):M?e.jsx("p",{className:"typography-meta text-muted-foreground",children:M}):le.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(Jt,{open:L,onOpenChange:W=>{q(W),W||R("")},children:[e.jsx(Zt,{asChild:!0,children:e.jsxs("button",{type:"button",className:O("flex w-fit items-center justify-between gap-2 rounded-lg border border-input bg-transparent px-3 py-2 typography-ui-label","hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[e.jsx("span",{className:C?"text-foreground":"text-muted-foreground",children:C?le.find(W=>W.id===C)?.name||C:"Select provider"}),e.jsx(Nt,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(es,{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(lr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:P,onChange:W=>R(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(tt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const W=le.filter(me=>{const ye=P.toLowerCase();return(me.name||me.id).toLowerCase().includes(ye)||me.id.toLowerCase().includes(ye)});return W.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):W.map(me=>e.jsxs(kt,{onSelect:()=>{D(me.id),q(!1),R("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:me.name||me.id}),C===me.id&&e.jsx(Dt,{className:"h-4 w-4 text-primary"})]},me.id))})()})]})]})]}),C&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),c?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{type:"password",value:u[C]??"",onChange:W=>m(me=>({...me,[C]:W.target.value})),placeholder:"sk-..."}),e.jsx(ve,{size:"sm",onClick:()=>z(C),disabled:f===`api:${C}`,className:"h-8",children:f===`api:${C}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by OpenChamber."})]}),(()=>{const me=(a[C]??[]).filter(ye=>Sc(ye)==="oauth");return me.length===0?null:e.jsx("div",{className:"space-y-3",children:me.map((ye,ce)=>{const Me=ye.label||ye.name||`OAuth method ${ce+1}`,Ee=`${C}:${ce}`,Pe=g?.providerId===C&&g?.methodIndex===ce;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:Me}),(ye.description||ye.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(ye.description||ye.help)})]}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>E(C,ce),disabled:f===`oauth:${C}:${ce}`,className:"h-8",children:"Connect"})]}),S[Ee]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:S[Ee]?.instructions}),S[Ee]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:S[Ee]?.userCode,readOnly:!0}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>fe(S[Ee]?.userCode??""),className:"h-8",children:"Copy code"})]}),S[Ee]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:S[Ee]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ve,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:S[Ee]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>Y(S[Ee]?.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(dt,{value:x[Ee]??"",onChange:V=>v(K=>({...K,[Ee]:V.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(ve,{size:"sm",onClick:()=>H(C,ce),disabled:f===`oauth-complete:${C}:${ce}`,className:"h-8",children:f===`oauth-complete:${C}:${ce}`?"Saving…":"Complete"})]})]},`${C}-${Me}`)})})})()]})]})]})});if(!$)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(wn,{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 je=Array.isArray($.models)?$.models:[],ee=(a[$.id]??[]).filter(W=>Sc(W)==="oauth"),oe=je.filter(W=>{const me=typeof W?.name=="string"?W.name:"",ye=typeof W?.id=="string"?W.id:"",ce=h.trim().toLowerCase();return ce?me.toLowerCase().includes(ce)||ye.toLowerCase().includes(ce):!0});return e.jsx(tt,{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(Xt,{providerId:$.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:$.name||$.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",$.id]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),c?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{type:"password",value:u[$.id]??"",onChange:W=>m(me=>({...me,[$.id]:W.target.value})),placeholder:"sk-..."}),e.jsx(ve,{size:"sm",onClick:()=>z($.id),disabled:f===`api:${$.id}`,className:"h-8",children:f===`api:${$.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(ve,{size:"sm",variant:"outline",onClick:()=>ne($.id),disabled:f===`disconnect:${$.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:f===`disconnect:${$.id}`?"Disconnecting…":"Disconnect provider"})}),ee.length>0&&e.jsx("div",{className:"space-y-3",children:ee.map((W,me)=>{const ye=W.label||W.name||`OAuth method ${me+1}`,ce=`${$.id}:${me}`,Me=g?.providerId===$.id&&g?.methodIndex===me;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:ye}),(W.description||W.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(W.description||W.help)})]}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>E($.id,me),disabled:f===`oauth:${$.id}:${me}`,className:"h-8",children:"Connect"})]}),S[ce]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:S[ce]?.instructions}),S[ce]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:S[ce]?.userCode,readOnly:!0}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>fe(S[ce]?.userCode??""),className:"h-8",children:"Copy code"})]}),S[ce]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:S[ce]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ve,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:S[ce]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>Y(S[ce]?.url??""),className:"h-8",children:"Copy link"})]})]}),Me&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:x[ce]??"",onChange:Ee=>v(Pe=>({...Pe,[ce]:Ee.target.value})),placeholder:"Paste authorization code"}),e.jsx(ve,{size:"sm",onClick:()=>H($.id,me),disabled:f===`oauth-complete:${$.id}:${me}`,className:"h-8",children:f===`oauth-complete:${$.id}:${me}`?"Saving…":"Complete"})]})]},`${$.id}-${ye}`)})})]})]}),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(dt,{value:h,onChange:W=>w(W.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:oe.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):oe.map(W=>{const me=typeof W?.id=="string"?W.id:"",ye=typeof W?.name=="string"?W.name:me,ce=me?o($.id,me):void 0,Me=vc(ce?.limit?.context),Ee=vc(ce?.limit?.output),Pe=[];return ce?.tool_call&&Pe.push({key:"tools",icon:Io,label:"Tool calling"}),ce?.reasoning&&Pe.push({key:"reasoning",icon:Jr,label:"Reasoning"}),ce?.attachment&&Pe.push({key:"image",icon:cr,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:ye}),(Me||Ee)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[Me?`${Me} ctx`:"",Me&&Ee?" · ":"",Ee?`${Ee} out`:""]}),Pe.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:Pe.map(({key:V,icon:K,label:T})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:T,"aria-label":T,children:e.jsx(K,{className:"h-3 w-3"})},V))})]},me)})})]})]})})},Nw={branch:Vt,briefcase:oi,house:ni,graduation:ri,code:Vs,heart:Zc},Cw={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Mw=({onItemSelect:s})=>{const{selectedProfileId:r,profiles:t,globalIdentity:n,setSelectedProfile:o,deleteProfile:a,loadProfiles:i,loadGlobalIdentity:c}=Lo(),{setSidebarOpen:d}=Fe(),{isMobile:u}=Ct(),[m,f]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),p=l.useMemo(()=>Et(),[]);l.useEffect(()=>{typeof window>"u"||f(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{i(),c()},[i,c]);const h=m?"bg-transparent":p?"bg-background":"bg-sidebar",w=()=>{o("new"),s?.(),u&&d(!1)},g=async y=>{window.confirm(`Are you sure you want to delete profile "${y.name}"?`)&&(await a(y.id)?se.success(`Profile "${y.name}" deleted successfully`):se.error("Failed to delete profile"))};return e.jsxs("div",{className:O("flex h-full flex-col",h),children:[e.jsx("div",{className:O("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(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(Gt,{className:"size-4"})})]})}),e.jsxs(tt,{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(kc,{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(Vt,{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(y=>e.jsx(kc,{profile:y,isSelected:r===y.id,onSelect:()=>{o(y.id),s?.(),u&&d(!1)},onDelete:()=>g(y)},y.id))})]})]})},kc=({profile:s,isSelected:r,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=Nw[s.icon||"branch"]||Vt,i=Cw[s.color||""];return e.jsx("div",{className:O("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(Jt,{children:[e.jsx(Zt,{asChild:!0,children:e.jsx(ve,{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(Cn,{className:"h-3.5 w-3.5"})})}),e.jsx(es,{align:"end",className:"w-fit min-w-20",children:e.jsxs(kt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})},Nc=[{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)"}],Dw=[{key:"branch",Icon:Vt,label:"Branch"},{key:"briefcase",Icon:oi,label:"Work"},{key:"house",Icon:ni,label:"Personal"},{key:"graduation",Icon:ri,label:"School"},{key:"code",Icon:Vs,label:"Code"}],Aw=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=Lo(),a=l.useMemo(()=>s&&s!=="new"?r(s):null,[s,r]),i=s==="new",c=s==="global",[d,u]=l.useState(""),[m,f]=l.useState(""),[p,h]=l.useState(""),[w,g]=l.useState(""),[y,x]=l.useState("keyword"),[v,S]=l.useState("branch"),[N,j]=l.useState(!1);l.useEffect(()=>{i?(u(""),f(""),h(""),g(""),x("keyword"),S("branch")):a&&(u(a.name),f(a.userName),h(a.userEmail),g(a.sshKey||""),x(a.color||"keyword"),S(a.icon||"branch"))},[a,i,s]);const k=async()=>{if(!m.trim()||!p.trim()){se.error("User name and email are required");return}j(!0);try{const M={name:d.trim()||m.trim(),userName:m.trim(),userEmail:p.trim(),sshKey:w.trim()||null,color:y,icon:v};let b;if(i)b=await t(M);else if(s)b=await n(s,M);else return;b?se.success(i?"Profile created successfully":"Profile updated successfully"):se.error(i?"Failed to create profile":"Failed to update profile")}catch(M){console.error("Error saving profile:",M),se.error("An error occurred while saving")}finally{j(!1)}},F=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(M){console.error("Error deleting profile:",M),se.error("An error occurred while deleting")}},A=l.useMemo(()=>Nc.find(b=>b.key===y)?.cssVar||"var(--syntax-keyword)",[y]);return s?e.jsx(tt,{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":c?"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":c?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!c&&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(dt,{value:d,onChange:M=>u(M.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:Nc.map(M=>e.jsx("button",{onClick:()=>x(M.key),className:O("w-8 h-8 rounded-lg border-2 transition-all",y===M.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:M.cssVar},title:M.label},M.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:Dw.map(M=>{const b=M.Icon;return e.jsx("button",{onClick:()=>S(M.key),className:O("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",v===M.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:M.label,children:e.jsx(b,{className:"w-4 h-4",style:{color:A}})},M.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 ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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(dt,{value:m,onChange:M=>f(M.target.value),placeholder:"John Doe",required:!c,readOnly:c,disabled:c}),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 ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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(dt,{type:"email",value:p,onChange:M=>h(M.target.value),placeholder:"john@example.com",required:!c,readOnly:c,disabled:c}),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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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(dt,{value:w,onChange:M=>g(M.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),!c&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!i&&e.jsxs(ve,{size:"sm",variant:"destructive",onClick:F,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Ls,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:O("flex gap-2",i&&"ml-auto"),children:e.jsxs(ve,{size:"sm",variant:"default",onClick:k,disabled:N,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(To,{className:"h-3 w-3"}),N?"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(bs,{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 ba(s,r,t){return Math.min(t,Math.max(r,s))}const No=Ne.forwardRef(({value:s,onValueChange:r,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:i,onBlur:c,onKeyDown:d,disabled:u,...m},f)=>{const p=Ne.useRef(null);Ne.useImperativeHandle(f,()=>p.current);const[h,w]=Ne.useState(()=>String(s));Ne.useEffect(()=>{document.activeElement!==p.current&&w(String(s))},[s]);const g=Ne.useCallback(()=>{p.current?.focus()},[]),y=Ne.useCallback(b=>{const C=ba(b,t,n);r(C),w(String(C))},[n,t,r]),x=Ne.useCallback(()=>{const b=Number(h);return Number.isFinite(b)?b:s},[h,s]),v=Ne.useCallback(()=>{y(x()+o),g()},[y,x,g,o]),S=Ne.useCallback(()=>{y(x()-o),g()},[y,x,g,o]),N=b=>{const C=b.target.value;w(C);const D=Number(C);Number.isFinite(D)&&r(ba(D,t,n))},j=b=>{const C=Number(h);if(!Number.isFinite(C))w(String(s));else{const D=ba(C,t,n);D!==C&&r(D),w(String(D))}c?.(b)},k=b=>{if(b.key==="ArrowUp"){b.preventDefault(),v();return}if(b.key==="ArrowDown"){b.preventDefault(),S();return}d?.(b)},F=x(),A=u||F<=t,M=u||F>=n;return e.jsxs("div",{className:O("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:N,onBlur:j,onKeyDown:k,disabled:u,className:O("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:M,onClick:v,className:O("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(Ao,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:A,onClick:S,className:O("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(Nt,{className:"h-3.5 w-3.5"})})]})]})});No.displayName="NumberInput";const Ew=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Cc=[{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"}],Mc=[{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."}],Ai=({visibleSettings:s})=>{const{isMobile:r}=Ct(),t=Fe(S=>S.showReasoningTraces),n=Fe(S=>S.setShowReasoningTraces),o=Fe(S=>S.toolCallExpansion),a=Fe(S=>S.setToolCallExpansion),i=Fe(S=>S.fontSize),c=Fe(S=>S.setFontSize),d=Fe(S=>S.padding),u=Fe(S=>S.setPadding),m=Fe(S=>S.inputBarOffset),f=Fe(S=>S.setInputBarOffset),p=Fe(S=>S.diffLayoutPreference),h=Fe(S=>S.setDiffLayoutPreference),w=zs(S=>S.queueModeEnabled),g=zs(S=>S.setQueueMode),{themeMode:y,setThemeMode:x}=Fr(),v=S=>s?s.includes(S):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[v("theme")&&!Et()&&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:Ew.map(S=>e.jsx(Cs,{variant:y===S.value?"default":"outline",className:O(y===S.value?void 0:"text-foreground"),onClick:()=>x(S.value),children:S.label},S.value))})]}),v("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:S=>c(Number(S.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(No,{value:i,onValueChange:c,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Cs,{type:"button",variant:"ghost",onClick:()=>c(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(xs,{className:"h-3.5 w-3.5"})})]})]}),v("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:S=>u(Number(S.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(Cs,{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(xs,{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:S=>u(Number(S.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(No,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Cs,{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(xs,{className:"h-3.5 w-3.5"})})]})]}),v("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:S=>f(Number(S.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(Cs,{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(xs,{className:"h-3.5 w-3.5"})})]})]}),v("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:Cc.find(S=>S.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Cc.map(S=>e.jsx(Cs,{variant:o===S.value?"default":"outline",className:O(o===S.value?void 0:"text-foreground"),onClick:()=>a(S.value),children:S.label},S.value))})]}),v("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:Mc.map(S=>e.jsx(Cs,{variant:p===S.id?"default":"outline",className:O(p===S.id?void 0:"text-foreground"),onClick:()=>h(S.id),children:S.label},S.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Mc.find(S=>S.id===p)?.description})]})]}),v("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:S=>n(S.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),v("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:w,onChange:S=>g(S.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:w?`Enter queues messages, ${ss()}+Enter sends immediately.`:`Enter sends immediately, ${ss()}+Enter queues messages.`})]})]})},Dc="https://github.com/btriapitsyn/openchamber",Iw=800,Iu=()=>{const[s,r]=l.useState(!1),[t,n]=l.useState(!1),o=Fo(),{isMobile:a}=Ct(),i=o.info?.currentVersion||"unknown",c=l.useRef(!1);l.useEffect(()=>{if(o.checking)n(!0),c.current=!0;else if(t){const u=setTimeout(()=>{n(!1),c.current&&!o.available&&!o.error&&(se.success("You are on the latest version"),c.current=!1)},Iw);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(xs,{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:O("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(qr,{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:Dc,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ia,{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(nd,{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(Ta,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx($a,{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(Yn,{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:O("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(qr,{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:O("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:Dc,target:"_blank",rel:"noopener noreferrer",className:O("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Ia,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:O("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx($a,{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})]})},Tw=1440*60*1e3,Tu=5,Ac=1440*60*1e3,wa=s=>s.time?.updated??s.time?.created??0,Ec=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=Tu,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*Tw,i=[...s].sort((d,u)=>wa(u)-wa(d)),c=new Set(i.slice(0,n).map(d=>d.id));return i.filter(d=>{if(!d?.id||c.has(d.id)||d.id===r||d.share)return!1;const u=wa(d);return u?u<a:!1}).map(d=>d.id)},Fu=s=>{const r=s?.autoRun!==!1,t=he(g=>g.sessions),n=he(g=>g.currentSessionId),o=he(g=>g.isLoading),a=he(g=>g.deleteSessions),i=Fe(g=>g.autoDeleteEnabled),c=Fe(g=>g.autoDeleteAfterDays),d=Fe(g=>g.autoDeleteLastRunAt),u=Fe(g=>g.setAutoDeleteLastRunAt),[m,f]=l.useState(!1),p=l.useRef(!1),h=l.useMemo(()=>c<=0?[]:Ec({sessions:t,currentSessionId:n,cutoffDays:c}),[c,n,t]),w=l.useCallback(async({force:g=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!i||c<=0)&&!g)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const y=Date.now();if(!g&&d&&y-d<Ac)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const x=Ec({sessions:t,currentSessionId:n,cutoffDays:c,now:y});if(x.length===0)return u(y),{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())}},[c,i,d,n,a,o,t,u]);return l.useEffect(()=>{if(!r||!i||c<=0||o||t.length===0)return;const g=Date.now();d&&g-d<Ac||w()},[c,i,d,r,o,t.length,w]),{candidates:h,isRunning:m,runCleanup:w,keepRecentCount:Tu}},va=1,ja=365,Pu=()=>{const{isMobile:s}=Ct(),r=Fe(p=>p.autoDeleteEnabled),t=Fe(p=>p.autoDeleteAfterDays),n=Fe(p=>p.setAutoDeleteEnabled),o=Fe(p=>p.setAutoDeleteAfterDays),[a,i]=l.useState(String(t));l.useEffect(()=>{i(String(t))},[t]);const{candidates:c,isRunning:d,runCleanup:u}=Fu({autoRun:!1}),m=c.length,f=l.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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{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 w=Number(h);if(!Number.isFinite(w))return;const g=Math.min(ja,Math.max(va,Math.round(w)));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(ja,Math.max(va,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(No,{value:t,onValueChange:o,min:va,max:ja,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(Cs,{type:"button",variant:"outline",onClick:f,disabled:d,children:d?"Cleaning up...":"Run cleanup now"})]}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Eligible for deletion right now: ",m]})]})},Ru=()=>{const s=ut(g=>g.setProvider),r=ut(g=>g.setModel),t=ut(g=>g.setAgent),n=ut(g=>g.setSettingsDefaultModel),o=ut(g=>g.setSettingsDefaultAgent),a=ut(g=>g.providers),[i,c]=l.useState(),[d,u]=l.useState(),[m,f]=l.useState(!0),p=l.useMemo(()=>{if(!i)return{providerId:"",modelId:""};const g=i.split("/");return g.length!==2?{providerId:"",modelId:""}:{providerId:g[0]||"",modelId:g[1]||""}},[i]);l.useEffect(()=>{(async()=>{try{let y=null;if(Ht())y=await en();else{const x=Er()?.settings;if(x)try{const S=(await x.load())?.settings;S&&(y={defaultModel:typeof S.defaultModel=="string"?S.defaultModel:void 0,defaultAgent:typeof S.defaultAgent=="string"?S.defaultAgent:void 0})}catch{}if(!y){const v=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});v.ok&&(y=await v.json())}}y&&(c(y.defaultModel),u(y.defaultAgent))}catch(y){console.warn("Failed to load defaults settings:",y)}finally{f(!1)}})()},[]);const h=l.useCallback(async(g,y)=>{const x=g&&y?`${g}/${y}`:void 0;c(x),n(x),g&&y&&a.find(S=>S.id===g)&&(s(g),r(y));try{await ns({defaultModel:x??""})}catch(v){console.warn("Failed to save default model:",v)}},[a,s,r,n]),w=l.useCallback(async g=>{const y=g||void 0;u(y),o(y),g&&t(g);try{await ns({defaultAgent:y??""})}catch(x){console.warn("Failed to save default agent:",x)}},[t,o]);return m?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:"Default model & agent"}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Ye,{sideOffset:8,className:"max-w-xs",children:["Set the default model and agent for new sessions.",e.jsx("br",{}),"When not set, uses agent's preferred model or opencode/big-pickle as fallback."]})]})]})}),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(Mi,{providerId:p.providerId,modelId:p.modelId,onChange:h})]}),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(Eu,{agentName:d||"",onChange:w})]})]}),(i||d)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",i&&e.jsx("span",{className:"text-foreground",children:i}),i&&d&&" / ",d&&e.jsx("span",{className:"text-foreground",children:d})]})]})},Fw=({section:s})=>{const{isMobile:r}=Ct(),t=r&&ii();if(!s)return e.jsxs(tt,{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(Ai,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Ru,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Pu,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Iu,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(Pw,{});case"chat":return e.jsx(Rw,{});case"sessions":return e.jsx(Lw,{});default:return null}};return e.jsx(tt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},Pw=()=>e.jsx(Ai,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),Rw=()=>e.jsx(Ai,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),Lw=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ru,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Pu,{})})]}),Ow=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]}],$w=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=Ct(),n=t&&ii(),[o,a]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),i=l.useMemo(()=>Et(),[]);l.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const c=o?"bg-transparent":i?"bg-background":"bg-sidebar";return e.jsxs("div",{className:O("flex h-full flex-col",c),children:[e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:Ow.map(d=>{const u=s===d.id;return e.jsx("div",{className:O("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(Iu,{})})]})},_w=(()=>{const s=Au.filter(n=>n.id!=="sessions"),r=s.find(n=>n.id==="settings"),t=s.filter(n=>n.id!=="settings");return r?[r,...t]:s})(),Sa=200,ka=500,Bw=264,zw=700,Xa=({onClose:s,forceMobile:r})=>{const t=Ct(),n=r??t.isMobile,[o,a]=l.useState("settings"),[i,c]=l.useState("visual"),[d,u]=l.useState(!1),[m,f]=l.useState(()=>typeof window<"u"?Math.min(ka,Math.max(Sa,Math.floor(window.innerWidth*.2))):Bw),[p,h]=l.useState(!1),[w,g]=l.useState(!1),[y,x]=l.useState(0),v=l.useRef(null),S=l.useRef(0),N=l.useRef(m),[j,k]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),F=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),A=l.useMemo(()=>Et(),[]);l.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{const z=v.current;if(!z)return;const E=new ResizeObserver(H=>{for(const Y of H)x(Y.contentRect.width)});return E.observe(z),x(z.clientWidth),()=>E.disconnect()},[]);const M=y===0||y>=zw;l.useEffect(()=>{if(typeof window>"u")return;const z=()=>{if(!p){const E=Math.min(ka,Math.max(Sa,Math.floor(window.innerWidth*.2)));f(E)}};return window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[p]),l.useEffect(()=>{if(!w)return;const z=H=>{const Y=H.clientX-S.current,fe=Math.min(ka,Math.max(Sa,N.current+Y));f(fe),h(!0)},E=()=>g(!1);return window.addEventListener("pointermove",z),window.addEventListener("pointerup",E,{once:!0}),()=>{window.removeEventListener("pointermove",z),window.removeEventListener("pointerup",E)}},[w]);const b=z=>{g(!0),S.current=z.clientX,N.current=m,z.preventDefault()},C=l.useCallback(async z=>{if(!z.target.closest("button, a, input, select, textarea")&&z.button===0&&j)try{const{getCurrentWindow:E}=await Kt(async()=>{const{getCurrentWindow:Y}=await import("./vendor-.bun-COPXsM7o.js").then(fe=>fe.ca);return{getCurrentWindow:Y}},__vite__mapDeps([0,1]));await E().startDragging()}catch(E){console.error("Failed to start window dragging:",E)}},[j]),D=l.useCallback(async z=>{if(z.button===0&&j)try{const{getCurrentWindow:E}=await Kt(async()=>{const{getCurrentWindow:Y}=await import("./vendor-.bun-COPXsM7o.js").then(fe=>fe.ca);return{getCurrentWindow:Y}},__vite__mapDeps([0,1]));await E().startDragging()}catch(E){console.error("Failed to start window dragging:",E)}},[j]),P=l.useCallback(z=>{a(z),u(!1)},[]),R=l.useCallback(()=>{n&&u(!0)},[n]),L=()=>{switch(o){case"settings":return e.jsx($w,{selectedSection:i,onSelectSection:z=>{c(z),R()}});case"agents":return e.jsx(tw,{onItemSelect:R});case"commands":return e.jsx(aw,{onItemSelect:R});case"skills":return e.jsx(lw,{onItemSelect:R});case"providers":return e.jsx(bw,{onItemSelect:R});case"git-identities":return e.jsx(Mw,{onItemSelect:R});default:return null}},q=()=>{switch(o){case"agents":return e.jsx(ow,{});case"commands":return e.jsx(iw,{});case"skills":return e.jsx(xw,{});case"providers":return e.jsx(kw,{});case"git-identities":return e.jsx(Aw,{});case"settings":return e.jsx(Fw,{section:i});default:return null}},te=ss(),le=l.useMemo(()=>j&&F?"pl-[5.75rem]":"",[j,F]),$=j&&F;return e.jsxs("div",{ref:v,className:O("flex h-full flex-col overflow-hidden",j?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:C,className:O("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&le,j?"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(Df,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:O("flex items-center",n?"gap-1":"h-full"),children:[!n&&$&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),_w.map(({id:z,label:E,icon:H})=>{const Y=o===z,fe=H;return n?e.jsxs(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsx("button",{onClick:()=>P(z),className:O("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",Y?"text-foreground":"text-muted-foreground"),"aria-pressed":Y,"aria-label":E,children:e.jsx(fe,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(Ye,{children:e.jsx("p",{children:E})})]},z):e.jsxs(l.Fragment,{children:[e.jsxs("button",{onClick:()=>P(z),onMouseDown:Y?D:void 0,className:O("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",Y?"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",Y?"text-foreground":"text-muted-foreground"),"aria-pressed":Y,"aria-label":E,children:[e.jsx(fe,{className:"h-4 w-4",weight:"regular"}),M&&e.jsx("span",{children:E})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},z)})]}),s&&e.jsx("div",{className:O("flex items-center",n?"":"pr-3"),children:e.jsxs(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close settings",className:O("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(Wt,{className:"h-5 w-5"})})}),e.jsx(Ye,{children:e.jsxs("p",{children:["Close Settings (",te,"+,)"]})})]})})]}),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(Ut,{children:q()})}):e.jsx("div",{className:O("flex-1 overflow-hidden",A?"bg-background":"bg-sidebar"),children:e.jsx(Ut,{children:L()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:O("relative overflow-hidden border-r",j?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":A?"bg-background":"bg-sidebar",w?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:O("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",w?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:b,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(Ut,{children:L()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(Ut,{children:q()})})]})})]})},Hw=()=>{const{isSidebarOpen:s,activeMainTab:r,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i,isMultiRunLauncherOpen:c,setMultiRunLauncherOpen:d,multiRunLauncherPrefillPrompt:u}=Fe(),{isMobile:m}=Ct(),[f,p]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{typeof window>"u"||p(typeof window.opencodeDesktop<"u")},[]),cx({enabled:!0});const h=Fo(x=>x.checkForUpdates);l.useEffect(()=>{const x=setTimeout(()=>{h()},3e3);return()=>clearTimeout(x)},[h]),l.useEffect(()=>{Fe.getState().isMobile!==m&&t(m)},[m,t]),l.useEffect(()=>{if(typeof window>"u")return;let x;const v=()=>{x!==void 0&&window.clearTimeout(x),x=window.setTimeout(()=>{Fe.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",v),()=>{window.removeEventListener("resize",v),x!==void 0&&window.clearTimeout(x)}},[]),l.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const x=document.documentElement;let v=0,S=!1,N=0,j=null;const k=Fe.getState().setKeyboardOpen,F=()=>{j&&(j.style.setProperty("--oc-keyboard-avoid-offset","0px"),j.removeAttribute("data-keyboard-avoid-active"),j=null)},A=R=>{if(!R)return null;const L=R.closest("[data-keyboard-avoid]");if(L)return L;if(R.classList.contains("overlay-scrollbar-container")){const q=R.parentElement;if(q instanceof HTMLElement)return q}return R},M=()=>{v=0,S=!0,x.style.setProperty("--oc-keyboard-inset","0px"),k(!1)},b=()=>{const R=window.visualViewport,L=R?Math.round(R.height):window.innerHeight,q=R?Math.max(0,Math.round(R.offsetTop)):0;x.style.setProperty("--oc-visual-viewport-offset-top",`${q}px`);const te=document.activeElement,le=te?.tagName,z=le==="INPUT"||le==="TEXTAREA"||le==="SELECT"||!!te?.isContentEditable,E=Math.round(x.clientHeight||window.innerHeight),H=L+q,Y=Math.max(0,E-H),ne=Y>=(z?120:180)?Y:0;if(S)ne===0&&(S=!1),v=0;else if(v===0)ne>0&&z&&(v=ne);else{const je=!z&&L>N+6;ne===0?(v=0,k(!1)):je?M():(ne>0&&z||ne>v)&&(v=ne,k(!0))}x.style.setProperty("--oc-keyboard-inset",`${v}px`),N=L;const pe=z?A(te):null;if(!m||!pe||!te)F();else{pe!==j&&(F(),j=pe);const je=q+L,ee=te.getBoundingClientRect().bottom-je,oe=8,W=Math.max(v,ne),me=ee>oe&&W>0?Math.min(ee,W):0,ye=j;ye&&(ye.style.setProperty("--oc-keyboard-avoid-offset",`${me}px`),ye.setAttribute("data-keyboard-avoid-active","true"))}if(m&&z){const je=document.scrollingElement;je&&je.scrollTop!==0&&(je.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};b();const C=window.visualViewport;C?.addEventListener("resize",b),C?.addEventListener("scroll",b),window.addEventListener("resize",b),window.addEventListener("orientationchange",b);const D=R=>{const L=R.target;if(!L)return;const q=L.tagName;(q==="INPUT"||q==="TEXTAREA"||q==="SELECT"||L.isContentEditable)&&(S=!1),b()};document.addEventListener("focusin",D,!0);const P=R=>{const L=R.target;if(!L)return;const q=L.tagName;if(q==="INPUT"||q==="TEXTAREA"||q==="SELECT"||L.isContentEditable){const le=R.relatedTarget,$=le?.tagName;if($==="INPUT"||$==="TEXTAREA"||$==="SELECT"||le?.isContentEditable)return;M()}};return document.addEventListener("focusout",P,!0),()=>{C?.removeEventListener("resize",b),C?.removeEventListener("scroll",b),window.removeEventListener("resize",b),window.removeEventListener("orientationchange",b),document.removeEventListener("focusin",D,!0),document.removeEventListener("focusout",P,!0),F()}},[m]);const w=l.useMemo(()=>{switch(r){case"git":return e.jsx(_b,{});case"diff":return e.jsx(Ag,{});case"terminal":return e.jsx(Qb,{});default:return null}},[r]),g=r==="chat",y=a&&!m;return e.jsx(Qg,{children:e.jsxs("div",{className:O("main-content-safe-area h-[100dvh]",m?"flex flex-col":"flex",f?"bg-transparent":"bg-background"),children:[e.jsx($g,{}),e.jsx(zg,{}),e.jsx(Gg,{}),m?e.jsxs(e.Fragment,{children:[!(a||c)&&e.jsx(Sl,{}),e.jsx("div",{className:O("flex flex-1 overflow-hidden bg-background",(a||c)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:O("absolute inset-0",!g&&"invisible"),children:e.jsx(Ut,{children:e.jsx(Ka,{})})}),w&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ut,{children:w})})]})}),e.jsx(ps,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(_a,{mobileVariant:!0})}),c&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(Ut,{children:e.jsx(Ll,{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(Ut,{children:e.jsx(Xa,{onClose:()=>i(!1)})})})]}):e.jsxs(e.Fragment,{children:[!y&&e.jsx(Lg,{isOpen:s,isMobile:m,children:e.jsx(_a,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:O("absolute inset-0 flex flex-col",(y||c)&&"invisible"),children:[e.jsx(Sl,{}),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:O("absolute inset-0",!g&&"invisible"),children:e.jsx(Ut,{children:e.jsx(Ka,{})})}),w&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ut,{children:w})})]})})]}),c&&e.jsx("div",{className:O("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(Ut,{children:e.jsx(Ll,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})})]}),y&&e.jsx("div",{className:O("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(Ut,{children:e.jsx(Xa,{onClose:()=>i(!1)})})})]}),!y&&e.jsx(Ig,{})]})})},Uw=550,Ww=()=>{const[s,r]=l.useState("chat"),[t,n]=l.useState(0),o=l.useRef(null),a=he(k=>k.currentSessionId),i=he(k=>k.sessions),c=he(k=>!!k.newSessionDraft?.open),d=he(k=>k.openNewSessionDraft),[u,m]=l.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),f=ut(k=>k.isInitialized),p=ut(k=>k.initializeApp),h=he(k=>k.loadSessions),w=he(k=>k.loadMessages),g=he(k=>k.messages),[y,x]=l.useState(()=>f),[v,S]=l.useState(!1);l.useEffect(()=>{a&&r("chat")},[a]),l.useEffect(()=>{!a&&!c&&d()},[a,c,d]);const N=l.useCallback(()=>{r("sessions")},[]);l.useEffect(()=>{const k=F=>{const M=F.detail?.status;(M==="connected"||M==="connecting"||M==="error"||M==="disconnected")&&m(M)};return window.addEventListener("openchamber:connection-status",k),()=>window.removeEventListener("openchamber:connection-status",k)},[]),l.useEffect(()=>{const k=F=>{const M=F.detail?.view;M==="settings"?r("settings"):M==="chat"?r("chat"):M==="sessions"&&r("sessions")};return window.addEventListener("openchamber:navigate",k),()=>window.removeEventListener("openchamber:navigate",k)},[]),l.useEffect(()=>{(async()=>{if(!(v||y||u!=="connected")){S(!0);try{f||await p(),await h(),x(!0)}catch{}finally{S(!1)}}})()},[u,f,y,p,v,h]),l.useEffect(()=>{(async()=>{if(!y||u!=="connected"||s!=="chat"||c||!a)return;if(!(g.has(a)&&(g.get(a)?.length||0)>0))try{await w(a)}catch{}})()},[u,a,s,y,w,g,c]),l.useEffect(()=>{const k=o.current;if(!k)return;const F=new ResizeObserver(A=>{for(const M of A)n(M.contentRect.width)});return F.observe(k),n(k.clientWidth),()=>F.disconnect()},[]);const j=t>0&&t<Uw;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(Ic,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(_a,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>r("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):s==="settings"?e.jsx(Xa,{onClose:()=>r("sessions"),forceMobile:j}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Ic,{title:c&&!a?"New session":i.find(k=>k.id===a)?.title||"Chat",showBack:!0,onBack:N,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ut,{children:e.jsx(Ka,{})})})]})})},Ic=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,showContextUsage:a})=>{const{getCurrentModel:i}=ut(),c=he(h=>h.getContextUsage),d=i(),u=d?.limit&&typeof d.limit=="object"?d.limit:null,m=typeof u?.context=="number"?u.context:0,f=typeof u?.output=="number"?u.output:0,p=c(m,f);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(ed,{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(Gt,{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(Cr,{className:"h-5 w-5"})}),a&&p&&p.totalTokens>0&&e.jsx(Oa,{totalTokens:p.totalTokens,percentage:p.percentage,contextLimit:p.contextLimit,outputLimit:p.outputLimit??0,size:"compact"})]})},Tc=({...s})=>{const{theme:r="system"}=Af();return e.jsx(Ef,{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})},Vw=(s=5e3)=>{const[r,t]=Ne.useState(null);return Ne.useEffect(()=>{if(!Ht())return;let n=!1,o=null;const a=async()=>{const i=await Xf();n||(t(i),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},Gw=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=he(),c=Vw(4e3),d=l.useMemo(()=>{let f=0;return t.forEach(p=>{f+=p.length}),f},[t]),u=l.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(vi,{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(If,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),s&&e.jsx(ve,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:s,children:e.jsx(Wt,{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," / ",Yt.MAX_SESSIONS]})]})]}),c&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:c.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[c.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:c.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[Yt.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:[Yt.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:[Yt.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(tt,{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(Tf,{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>Yt.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(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs(ve,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Ls,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(Ye,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"})}),e.jsx(Ye,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{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(Ye,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},qw="openchamber-message-cursors",Qr="cursors",Kw=1,Lu="openchamber.messageCursors",Ei=()=>typeof window<"u",Ii=()=>Ei()&&typeof indexedDB<"u",Ou=()=>Ii()?new Promise((s,r)=>{const t=indexedDB.open(qw,Kw);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Qr)||n.createObjectStore(Qr)},t.onerror=()=>{r(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{s(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),$u=()=>{if(!Ei())return{};try{const s=window.localStorage.getItem(Lu);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},Yw=s=>{if(Ei())try{window.localStorage.setItem(Lu,JSON.stringify(s))}catch{}},Xw=async(s,r,t)=>{if(!s||!r)return;if(Ii())try{const o=await Ou();await new Promise((a,i)=>{const c=o.transaction(Qr,"readwrite");c.objectStore(Qr).put({messageId:r,completedAt:t},s),c.oncomplete=()=>a(),c.onerror=()=>i(c.error??new Error("Cursor write failed")),c.onabort=()=>i(c.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=$u();n[s]={messageId:r,completedAt:t},Yw(n)},Qw=async s=>{if(!s)return null;if(Ii())try{const t=await Ou(),n=await new Promise((o,a)=>{const i=t.transaction(Qr,"readonly"),d=i.objectStore(Qr).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 $u()[s]??null},Jw=50,Zw=750,Fc=new WeakMap,Pc=s=>{if(!s||!Array.isArray(s))return 0;const r=Fc.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 Fc.set(s,t),t},ev=10,Rc=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<ev?null:n},Lc=(s,r)=>{const t=Rc(s),n=Rc(r);return!t||!n||t.length!==n.length?!0:t>n},Qa=new Map,Oc=(s,r)=>{const t=`${s}:${r}`,n=Qa.get(t);if(n&&n.sessionId===s)return n.message;const i=(he.getState().messages.get(s)||[]).find(c=>c.info.id===r)||null;return Qa.set(t,{sessionId:s,message:i}),i},tv=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:c,getWorktreeMetadata:d,loadMessages:u,loadSessions:m}=he(),{checkConnection:f}=ut(),p=wt(K=>K.currentDirectory),h=l.useMemo(()=>{if(!a)return;try{const T=d?.(a);if(T?.path)return T.path}catch(T){console.warn("Failed to inspect worktree metadata for session directory:",T)}const K=c.find(T=>T.id===a);if(K&&typeof K.directory=="string"&&K.directory.trim().length>0)return K.directory.trim()},[a,d,c]),w=l.useMemo(()=>{if(h&&h.length>0)return h;if(typeof p=="string"&&p.trim().length>0)return p.trim()},[h,p]),g=Fe(K=>K.setEventStreamStatus),y=l.useRef(null),x=l.useCallback((K,T)=>{const X=T??null,I=y.current;if(!(I&&I.status===K&&I.hint===X)){if(y.current={status:K,hint:X},Bt()){const G={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[K]??"[INFO]",be=X?`${G} SSE ${K}: ${X}`:`${G} SSE ${K}`;console.info(be)}g(K,X)}},[g]),v=l.useCallback((K,T)=>{if(!K)return Promise.resolve();const X=Date.now();if(D.current)return D.current;if(X-P.current<Zw)return Promise.resolve();const I=u(K).catch(B=>{console.warn(`[useEventStream] Failed to resync messages (${T}):`,B)}).finally(()=>{D.current=null,P.current=Date.now()});return D.current=I,I},[u]),S=l.useCallback(async K=>{Bt()&&console.info("[useEventStream] Bootstrapping state:",K);try{await Promise.all([m(),a?v(a,K):Promise.resolve()])}catch(T){console.warn("[useEventStream] Bootstrap failed:",K,T)}},[a,m,v]),N=l.useCallback((K,T,X)=>{Bt()&&console.debug(`[MessageTracker] ${K}: ${T}`,X)},[]),j=l.useCallback(K=>{Bt()&&console.debug(`[MessageTracker] ${K}: reported`)},[]),k=l.useRef(null),F=l.useRef(null),A=l.useRef(0);l.useRef(new Set);const M=l.useRef(new Map),b=l.useRef(null),C=l.useRef(!1),D=l.useRef(null),P=l.useRef(0),R=l.useCallback(()=>{if(typeof document>"u")return"visible";const K=document.visibilityState;return K==="hidden"&&document.hasFocus()?"visible":K},[]),L=l.useRef(R()),q=l.useRef(typeof navigator>"u"?!0:navigator.onLine),te=l.useRef(!1),le=l.useRef(null),$=l.useRef(null),z=l.useRef(Date.now()),E=l.useRef(!1),H=l.useCallback(K=>{const T=Date.now();T-z.current>25e3&&(S(K),z.current=T)},[S]);l.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(E.current=!0)},[]);const Y=l.useRef(new Map),fe=l.useRef(new Map),ne=l.useRef(0),pe=l.useRef(null),je=l.useRef(a);l.useEffect(()=>{je.current=a},[a]);const U=l.useCallback(K=>{if(!K)return;const T=Date.now(),X=M.current,I=X.get(K);I&&T-I<3e3||(X.set(K,T),setTimeout(async()=>{try{const B=await Re.getSession(K);if(B){const G={};typeof B.title=="string"&&B.title.length>0&&(G.title=B.title),B.summary!==void 0&&(G.summary=B.summary),Object.keys(G).length>0&&i(K,G)}}catch(B){console.warn("Failed to refresh session metadata:",B)}},100))},[i]),ee=l.useCallback(()=>{b.current||(b.current=setTimeout(()=>{b.current=null;try{m()}catch(K){console.warn("Failed to refresh sessions after stream completion:",K)}},500))},[m]),oe=l.useCallback((K,T)=>{if(he.getState().sessionActivityPhase?.get(K)===T){fe.current=new Map(he.getState().sessionActivityPhase??new Map);return}const I=Y.current.get(K);I&&(clearTimeout(I),Y.current.delete(K));const B=new Map(he.getState().sessionActivityPhase??new Map);if(B.set(K,T),fe.current=B,he.setState({sessionActivityPhase:B}),T==="cooldown"){const G=setTimeout(()=>{if(Y.current.delete(K),he.getState().sessionActivityPhase?.get(K)==="cooldown"){const J=new Map(he.getState().sessionActivityPhase??new Map);J.set(K,"idle"),fe.current=J,he.setState({sessionActivityPhase:J})}},2e3);Y.current.set(K,G)}},[]),W=l.useCallback(async()=>{const K=Date.now();if(pe.current)return pe.current;if(K-ne.current<1500)return;ne.current=K;const T=G=>{if(typeof G!="string")return null;const be=G.trim();if(!be)return null;const J=be.replace(/\\/g,"/");return J.length>1?J.replace(/\/+$/,""):J},X=G=>{try{const ge=d?.(G),He=T(ge?.path??null);if(He)return He}catch{}const be=c.find(ge=>ge.id===G);return T(be?.directory??null)},I=G=>{Object.entries(G).forEach(([be,J])=>{if(!be||!J)return;const ge=J.type==="busy"||J.type==="retry"?"busy":"idle";oe(be,ge)})},B=(async()=>{try{const G=await Re.getGlobalSessionStatus();if(G&&Object.keys(G).length>0){I(G);return}const be=new Set;c.forEach(Be=>{const Ze=X(Be.id);Ze&&be.add(Ze)});const J=T(w??null);J&&be.add(J);const ge=Array.from(be);if(ge.length===0){const Be=await Re.getSessionStatus();Be&&I(Be);return}const He=await Promise.allSettled(ge.map(Be=>Re.getSessionStatusForDirectory(Be))),We={};He.forEach(Be=>{Be.status!=="fulfilled"||!Be.value||Object.assign(We,Be.value)}),I(We)}catch{}})().finally(()=>{pe.current=null});return pe.current=B,B},[w,d,c,oe]),me=l.useCallback(K=>{if(z.current=Date.now(),Bt()&&console.debug("[useEventStream] Received event:",K.type,K.properties),!K.properties)return;const T=K.properties;if(!new Set(["session.abort","session.error"]).has(K.type)){const I=(typeof T.session=="object"&&T.session!==null?T.session:null)||(typeof T.sessionInfo=="object"&&T.sessionInfo!==null?T.sessionInfo:null);if(I){const B=I,G=typeof B.id=="string"&&B.id.length>0?B.id:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:typeof T.id=="string"&&T.id.length>0?T.id:void 0;if(G){const be=typeof B.title=="string"?B.title:typeof T.title=="string"?T.title:void 0,J=typeof B.summary=="object"&&B.summary!==null?B.summary:typeof T.summary=="object"&&T.summary!==null?T.summary:void 0;if(be!==void 0||J!==void 0){const ge={};be!==void 0&&(ge.title=be),J!==void 0&&(ge.summary=J),i(G,ge)}}}}switch(K.type){case"server.connected":f();break;case"global.disposed":case"server.instance.disposed":{S("server_disposed_event");break}case"openchamber:session-activity":{const I=typeof T.sessionId=="string"?T.sessionId:null,B=typeof T.phase=="string"?T.phase:null;I&&(B==="idle"||B==="busy"||B==="cooldown")&&(oe(I,B),ee());break}case"session.status":if(E.current)break;{const I=typeof T.sessionID=="string"?T.sessionID:null,B=typeof T.status=="object"&&T.status!==null?T.status:null,G=typeof B?.type=="string"?B.type:null;I&&G&&(oe(I,G==="busy"||G==="retry"?"busy":"idle"),ee())}break;case"message.part.updated":{const I=typeof T.part=="object"&&T.part!==null?T.part:null;if(!I)break;const B=I,G=typeof T.info=="object"&&T.info!==null?T.info:T,be=typeof G.sessionID=="string"?G.sessionID:null,J=typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof be=="string"&&be.length>0?be:typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:null,ge=typeof G.id=="string"?G.id:null,He=typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:typeof ge=="string"&&ge.length>0?ge:typeof T.messageID=="string"&&T.messageID.length>0?T.messageID:null;if(!J||!He){Bt()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:B.sessionID??be??T.sessionID,messageID:B.messageID??ge??T.messageID});break}const We=J,Be=He,Ze=he.getState().sessionMemoryState.get(We)?.trimmedHeadMaxId;if(Ze&&!Lc(Be,Ze)){Bt()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:We,messageId:Be,trimmedHeadMaxId:Ze});break}let it="assistant";if(G&&typeof G.role=="string")it=G.role;else{const ct=Oc(We,Be);if(ct){const mt=ct.info.role;typeof mt=="string"&&(it=mt)}}if(N(Be,"part_received",{role:it}),it==="user"&&B.synthetic===!0){N(Be,"skipped_synthetic_user_part");break}const lt={...I,type:I.type||"text"};N(Be,"addStreamingPart_called"),s(We,Be,lt,it);break}case"message.updated":{const I=typeof T.info=="object"&&T.info!==null?T.info:T,B=I,G=typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:null,be=typeof B.id=="string"&&B.id.length>0?B.id:typeof T.messageID=="string"&&T.messageID.length>0?T.messageID:null;if(!G||!be){Bt()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:B.sessionID??T.sessionID,messageID:B.id??T.messageID});break}const J=G,ge=be,He=he.getState().sessionMemoryState.get(J)?.trimmedHeadMaxId;if(He&&!Lc(ge,He)){Bt()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:J,messageId:ge,trimmedHeadMaxId:He});break}if(E.current&&Bt())try{const _e=T.parts||B.parts||[],Ge=(Array.isArray(_e)?_e.filter(rt=>rt?.type==="text"):[]).map(rt=>{const ie=rt;return typeof ie?.text=="string"?ie.text:typeof ie?.content=="string"?ie.content:""}).join(`
|
|
101
|
+
`);console.info("[STREAM-TRACE] message.updated",{messageId:ge,role:B.role,status:B.status,textLen:Ge.length,textPreview:Ge.slice(0,120),partsCount:Array.isArray(_e)?_e.length:0})}catch{}if(N(ge,"message_updated",{role:B.role}),B.role==="user"){const _e=T.parts||B.parts,ze=Array.isArray(_e)?_e:[],Ge={...I,userMessageMarker:!0,clientRole:"user"};if(t(J,ge,Ge),ze.length>0)for(let rt=0;rt<ze.length;rt++){const ie=ze[rt];if(ie.synthetic===!0)continue;const ue={...ie,type:ie?.type||"text",sessionID:ie?.sessionID||J,messageID:ie?.messageID||ge};s(J,ge,ue,"user")}N(ge,"user_message_created_from_event",{partsCount:ze.length});break}const We=Oc(J,ge),Be=Pc(We?.parts||[]),Ze=We?.info?.finish==="stop",it=T.parts||B.parts,lt=Array.isArray(it)?it:[],ct=lt.length>0,xt=typeof(B.time||{})?.completed=="number";if(!ct&&!xt)break;const vt=I.finish,ht=typeof vt=="string"?vt:null,yt=ht==="stop";if(B.role==="assistant"&&ct){const _e=Pc(lt);if(Be>0&&_e+Jw<Be&&!yt){N(ge,"skipped_shrinking_update",{incomingLen:_e,existingLen:Be});break}if(E.current){const Ge=Be>0&&_e<Be,rt=lt.some(ue=>{if(!ue||ue.type!=="text")return!1;const Se=ue;return typeof Se.text=="string"&&Se.text.length>0});if(Ge&&!(yt&&rt)){N(ge,"desktop_shrinking_update_suppressed",{incomingLen:_e,existingLen:Be});break}}}if(t(J,ge,I),ct&&B.role!=="user"){const Ge=(he.getState().messages.get(J)||[]).find(ue=>ue.info.id===ge),rt=!Ge||Ge.parts.length===0;N(ge,rt?"server_parts_injected":"server_parts_refreshed",{count:lt.length});const ie=E.current&&B.role==="assistant"?lt.filter(ue=>ue?.type!=="text"):lt;for(let ue=0;ue<ie.length;ue++){const Se=ie[ue],Ce={...Se,type:Se?.type||"text",sessionID:Se?.sessionID||J,messageID:Se?.messageID||ge};s(J,ge,Ce,B.role),N(ge,`server_part_${ue}`)}}const Q=I.time,De=Q?.completed,re=typeof De=="number"&&Number.isFinite(De),ae=ht==="stop"||Ze;if(I.role==="assistant"&&(re||ae)&&I.role==="assistant"){const ze=he.getState().messages.get(J)||[];let Ge=null,rt="";for(let Te=0;Te<ze.length;Te++){const Ue=ze[Te];Ue.info.role==="assistant"&&Ue.info.id>rt&&(rt=Ue.info.id,Ge=Ue.info.id)}if(ge!==Ge)break;if(!ae&&E.current){N(ge,"desktop_completion_without_stop");break}const ie=re?De:Date.now();re||t(J,ge,{...I,time:{...Q??{},completed:ie}}),N(ge,"completed",{timeCompleted:ie}),j(ge),Xw(J,ge,ie),r(J,ge),E.current||ht==="stop"&&he.getState().sessionActivityPhase?.get(J)==="busy"&&oe(J,"cooldown");const ue=I.sessionID,Se=typeof ue=="string"&&ue.length>0?ue:J;U(Se),I.summary&&typeof Se=="string"&&n(Se,null)}break}case"session.updated":{const I=typeof T.info=="object"&&T.info!==null?T.info:typeof T.sessionInfo=="object"&&T.sessionInfo!==null?T.sessionInfo:typeof T.session=="object"&&T.session!==null?T.session:T,B=typeof I.id=="string"&&I.id.length>0?I.id:typeof I.sessionID=="string"&&I.sessionID.length>0?I.sessionID:typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:typeof T.id=="string"&&T.id.length>0?T.id:void 0;if(B){const G=typeof I.time=="object"&&I.time!==null?I.time:typeof T.time=="object"&&T.time!==null?T.time:null,be=G&&typeof G.compacting=="number"?G.compacting:null;n(B,be)}break}case"session.abort":{const I=typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:null,B=typeof T.messageID=="string"&&T.messageID.length>0?T.messageID:null;I&&B&&r(I,B);break}case"permission.updated":a===T.sessionID&&o(T);break;case"permission.replied":break;case"todo.updated":{const I=typeof T.sessionID=="string"?T.sessionID:null,B=Array.isArray(T.todos)?T.todos:[];I&&B.length>0&&Cx(I,B);break}}},[a,s,r,t,o,f,U,ee,n,i,N,j,oe,S]),ye=l.useCallback(()=>{const K=R();return L.current=K,K==="visible"&&q.current},[R]),ce=l.useCallback(()=>{Bt()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:E.current,hasUnsubscribe:!!k.current,currentSessionId:je.current,effectiveDirectory:w,onlineStatus:q.current,visibilityState:L.current,lastEventTimestamp:z.current,reconnectAttempts:A.current})},[w]),Me=l.useCallback(async()=>!0,[]),Ee=l.useCallback(()=>{if(C.current){Bt()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(C.current=!0,F.current&&(clearTimeout(F.current),F.current=null),k.current){const K=k.current;k.current=null;try{K()}catch(T){console.warn("[useEventStream] Error during unsubscribe:",T)}}C.current=!1},[]),Pe=l.useCallback(async K=>{if(ce(),!ye()){te.current=!0,q.current?x("paused","Paused while hidden"):x("offline","Waiting for network");return}E.current&&(await Me()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),K?.resetAttempts&&(A.current=0),Ee(),z.current=Date.now(),x("connecting",null),Bt()&&console.info("[useEventStream] Starting event stream...");const T=I=>{console.warn("Event stream error:",I)},X=()=>{const I=te.current;if(A.current=0,te.current=!1,z.current=Date.now(),x("connected",null),f(),Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(G=>G==="busy")&&W(),I)S("sse_reconnected");else{const G=je.current;G&&setTimeout(()=>{v(G,"sse_reconnected").then(()=>U(G)).catch(be=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",be)})},0)}};if(Bt()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:w,isCleaningUp:C.current}),C.current){Bt()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const I=Re.subscribeToEvents(me,T,X,w),B=()=>{try{I()}catch(G){console.warn("[useEventStream] Error during unsubscribe:",G)}};C.current?B():k.current=B}catch(I){console.error("[useEventStream] Error during subscription:",I),T(I)}},[ye,Ee,x,f,v,U,me,w,W,Me,ce,S]),V=l.useCallback(K=>{if(!ye()){te.current=!0,Ee(),q.current?x("paused","Paused while hidden"):x("offline","Waiting for network");return}const T=A.current+1;A.current=T;const X=K??`Retrying (${T})`;x("reconnecting",X);const I=T<=3?Math.min(1e3*Math.pow(2,T-1),8e3):Math.min(2e3*Math.pow(2,T-3),32e3),B=Math.floor(Math.random()*250),G=I+B;F.current&&clearTimeout(F.current),F.current=setTimeout(()=>{Pe({resetAttempts:!1})},G)},[ye,Ee,x,Pe]);l.useEffect(()=>{const K=Y.current;typeof window<"u"&&(window.__messageTracker=N);let T=null;E.current&&typeof window<"u"&&(T=He=>{const We=typeof He.detail?.sessionId=="string"?He.detail.sessionId:null,Be=typeof He.detail?.phase=="string"?He.detail.phase:null;We&&(Be==="idle"||Be==="busy"||Be==="cooldown")&&(oe(We,Be),ee())},window.addEventListener("openchamber:session-activity",T));const X=()=>{le.current&&(clearTimeout(le.current),le.current=null)},I=()=>{le.current||(le.current=setTimeout(()=>{const He=R();L.current=He,He!=="visible"?(Ee(),te.current=!0,x("paused","Paused while hidden")):X()},5e3))},B=()=>{if(L.current=R(),L.current==="visible"){if(X(),H("visibility_restore"),te.current||!k.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const He=je.current;He&&(v(He,"visibility_restore").catch(()=>{}),U(He)),m(),W(),x("connecting","Resuming stream"),Pe({resetAttempts:!0})}}else x("paused","Paused while hidden"),I()},G=()=>{if(L.current=R(),L.current==="visible"&&(X(),H("window_focus"),te.current||!k.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const He=je.current;He&&(U(He),v(He,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(We=>console.warn("[useEventStream] Failed to refresh messages:",We))),m(),W(),x("connecting","Resuming stream"),Pe({resetAttempts:!0})}},be=()=>{q.current=!0,H("network_restored"),(te.current||!k.current)&&(x("connecting","Network restored"),Pe({resetAttempts:!0}))},J=()=>{q.current=!1,te.current=!0,x("offline","Waiting for network"),Ee()};typeof document<"u"&&document.addEventListener("visibilitychange",B),typeof window<"u"&&(window.addEventListener("online",be),window.addEventListener("offline",J),window.addEventListener("focus",G));const ge=setTimeout(()=>{Pe({resetAttempts:!0})},100);return $.current&&clearInterval($.current),$.current=setInterval(()=>{if(!ye())return;const He=Date.now();Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(Be=>Be==="busy")&&W(),He-z.current>25e3&&Promise.resolve().then(async()=>{try{await Re.checkHealth()?z.current=Date.now():V("Refreshing stalled stream")}catch(Be){console.warn("Health check after stale stream failed:",Be),V("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(ge),T&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",T),typeof document<"u"&&document.removeEventListener("visibilitychange",B),typeof window<"u"&&(window.removeEventListener("online",be),window.removeEventListener("offline",J),window.removeEventListener("focus",G)),X(),$.current&&(clearInterval($.current),$.current=null),K.forEach(He=>clearTimeout(He)),K.clear(),Qa.clear(),te.current=!1,L.current=R(),q.current=typeof navigator>"u"?!0:navigator.onLine,Ee(),b.current&&(clearTimeout(b.current),b.current=null),x("idle",null)}},[w,N,R,Ee,x,Pe,V,u,U,ee,oe,W,ye,m,H,v])},sv=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=he(),{toggleCommandPalette:a,toggleHelpDialog:i,toggleSidebar:c,setSessionSwitcherOpen:d,setSessionCreateDialogOpen:u,setActiveMainTab:m,setSettingsDialogOpen:f,setModelSelectorOpen:p}=Fe(),{themeMode:h,setThemeMode:w}=Fr(),{working:g}=lu(),y=l.useRef(null),x=l.useRef(null),v=l.useRef(!1),S=l.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null),y.current=null,n()},[n]);l.useEffect(()=>{const N=j=>{if(hs(j)&&j.key==="k"&&(j.preventDefault(),a()),hs(j)&&j.shiftKey&&j.key.toLowerCase()==="l"){const F=Er()?.diagnostics;if(!F||(j.preventDefault(),v.current))return;v.current=!0,F.downloadLogs().then(({fileName:A,content:M})=>{const b=A||"openchamber.log",C=new Blob([M],{type:"text/plain;charset=utf-8"}),D=URL.createObjectURL(C),P=document.createElement("a");P.href=D,P.download=b,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(D)}).finally(()=>{v.current=!1});return}if(hs(j)&&j.key==="."&&(j.preventDefault(),i()),hs(j)&&j.key.toLowerCase()==="n"){if(j.preventDefault(),j.shiftKey){u(!0);return}m("chat"),d(!1),s()}if(hs(j)&&j.key==="/"){j.preventDefault();const k=["light","dark","system"],A=(k.indexOf(h)+1)%k.length;w(k[A])}if(hs(j)&&!j.shiftKey&&j.key.toLowerCase()==="t"){j.preventDefault();const{isTimelineDialogOpen:k,setTimelineDialogOpen:F}=Fe.getState();F(!k);return}if(hs(j)&&!j.shiftKey&&j.key===","){j.preventDefault();const{isSettingsDialogOpen:k}=Fe.getState();f(!k);return}if(hs(j)&&!j.shiftKey&&j.key.toLowerCase()==="l"){j.preventDefault();const{isMobile:k,isSessionSwitcherOpen:F}=Fe.getState();k?d(!F):c();return}if(hs(j)&&!j.shiftKey&&j.key.toLowerCase()==="i"){j.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(hs(j)&&j.shiftKey&&j.key.toLowerCase()==="m"){const{isSettingsDialogOpen:k,isCommandPaletteOpen:F,isHelpDialogOpen:A,isSessionSwitcherOpen:M,isSessionCreateDialogOpen:b,isAboutDialogOpen:C,activeMainTab:D,isModelSelectorOpen:P}=Fe.getState();if(k||F||A||M||b||C||!(D==="chat"))return;j.preventDefault(),p(!P);return}if(j.key==="Escape"){const{isSettingsDialogOpen:k,isCommandPaletteOpen:F,isHelpDialogOpen:A,isSessionSwitcherOpen:M,isSessionCreateDialogOpen:b,isAboutDialogOpen:C,activeMainTab:D}=Fe.getState();if(k){j.preventDefault(),f(!1),S();return}if(F||A||M||b||C||!(D==="chat")){S();return}const L=o;if(!(g.canAbort&&!!L)){S();return}const te=Date.now(),le=y.current;if(le&&te<le){j.preventDefault(),S(),r();return}j.preventDefault();const $=t(3e3)??te+3e3;y.current=$,x.current&&clearTimeout(x.current);const z=Math.max($-te,0);x.current=setTimeout(()=>{y.current&&Date.now()>=y.current&&S()},z||0);return}};return window.addEventListener("keydown",N),()=>{window.removeEventListener("keydown",N)}},[s,r,a,i,c,d,u,m,f,p,w,h,g,t,S,o]),l.useEffect(()=>()=>{S()},[S])},$c="openchamber:menu-action",rv=s=>{const{openNewSessionDraft:r}=he(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setSessionCreateDialogOpen:i,setActiveMainTab:c,setSettingsDialogOpen:d,setAboutDialogOpen:u}=Fe(),{setDirectory:m}=wt(),{setThemeMode:f}=Fr(),p=l.useRef(!1),h=l.useCallback(()=>{Ht()&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(w=>{w.success&&w.path?m(w.path,{showOverlay:!0}):w.error&&w.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:w.error})}).catch(w=>{console.error("Desktop: Error selecting directory:",w),se.error("Failed to select directory")}):vr.requestDirectoryDialog()},[m]);l.useEffect(()=>{const w=g=>{switch(g.detail){case"about":u(!0);break;case"settings":d(!0);break;case"command-palette":t();break;case"new-session":c("chat"),a(!1),r();break;case"worktree-creator":i(!0);break;case"change-workspace":h();break;case"open-git-tab":{const{activeMainTab:x}=Fe.getState();c(x==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:x}=Fe.getState();c(x==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:x}=Fe.getState();c(x==="terminal"?"chat":"terminal");break}case"theme-light":f("light");break;case"theme-dark":f("dark");break;case"theme-system":f("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":s?.();break;case"help-dialog":n();break;case"download-logs":{const v=Er()?.diagnostics;if(!v||p.current)break;p.current=!0,v.downloadLogs().then(({fileName:S,content:N})=>{const j=S||"openchamber.log",k=new Blob([N],{type:"text/plain;charset=utf-8"}),F=URL.createObjectURL(k),A=document.createElement("a");A.href=F,A.download=j,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(F),se.success("Logs saved",{description:`Downloaded to ~/Downloads/${j}`})}).catch(()=>{se.error("Failed to download logs")}).finally(()=>{p.current=!1});break}}};return window.addEventListener($c,w),()=>window.removeEventListener($c,w)},[r,t,n,o,a,i,c,d,u,f,s,h])},nv=s=>s.role==="assistant",_c=s=>{const r=s.info;if(!nv(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},ao=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},Bc=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>gn(n)).join(" ").replace(/\s+/g," ").trim(),ov=(s,r)=>{if(!s||!ao(s.info))return-1;const t=Bc(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,c)=>{if(!ao(i.info))return;const d=Bc(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=c,a=p);return}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=c,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(i=>{if(!ao(i.info))return!1;const c=typeof i.info?.time?.created=="number"?i.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},av=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=he(),n=l.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=l.useRef(void 0),a=l.useRef(0),i=l.useCallback(async()=>{if(!s||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=r.get(s)||[],u=await Re.getSessionMessages(s),m=await Qw(s);if(!u)return;const f=d[d.length-1];if(f){const p=u.findIndex(g=>g.info.id===f.info.id),w=p===-1?ov(f,u):p;if(w!==-1)if(w<u.length-1){const g=u.slice(w+1);console.log(`[SYNC] Found ${g.length} new messages to append`);const y=[...d,...g],{syncMessages:x}=he.getState();x(s,y)}else{const g=u[w],y=d[d.length-1],x=_c(g),v=_c(y);if(x&&!v){console.log("[SYNC] Last message completed on server");const S=[...d.slice(0,-1),g],{syncMessages:N}=he.getState();N(s,S)}}else if(ao(f.info)){const g=u.slice(-Yt.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:y}=he.getState();y(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 w=u.slice(p+1).slice(-Yt.VIEWPORT_MESSAGES);if(w.length>0){console.log(`[SYNC] Restoring ${w.length} messages after cursor`);const{syncMessages:g}=he.getState();g(s,w)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const h=u.slice(-Yt.VIEWPORT_MESSAGES),{syncMessages:w}=he.getState();w(s,h)}}else if(u.length>0){const p=u.slice(-Yt.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:h}=he.getState();h(s,p)}}catch(d){console.debug("Background sync failed:",d)}}},[s,r,n]);l.useEffect(()=>{const c=()=>{console.log("[FOCUS] Window focused - checking for updates"),i()};return window.addEventListener("focus",c),()=>window.removeEventListener("focus",c)},[i]),l.useEffect(()=>{if(!s||n)return;const c=()=>{document.visibilityState==="visible"&&i(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,n,i]),l.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),i())};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[i])},iv=()=>{l.useEffect(()=>{let s=!1;return(async()=>{try{const t=await Re.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const i=a,c=i.type==="busy"||i.type==="retry"?"busy":"idle";n.set(o,c)}),n.size>0&&he.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function lv(){const{git:s}=Tr(),r=wt(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=he(),{setActiveDirectory:a,startPolling:i,stopPolling:c,fetchAll:d}=It(),u=l.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]);l.useEffect(()=>{if(!u||!s){c();return}return a(u),d(u,s),i(s),()=>{c()}},[u,s,a,i,c,d])}function cv({children:s}){return lv(),e.jsx(e.Fragment,{children:s})}const dv=()=>{const[{isUpdating:s,message:r},t]=l.useState(()=>gp());return l.useEffect(()=>hp(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(Ni,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},uv=({open:s,onOpenChange:r})=>{const[t,n]=l.useState(null);l.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:c}=await Kt(async()=>{const{getVersion:u}=await import("./vendor-.bun-COPXsM7o.js").then(m=>m.cb);return{getVersion:u}},__vite__mapDeps([0,1])),d=await c();n(d)}catch{n("1.4.2")}})():n("1.4.2")},[s]);const o=t;return e.jsx(as,{open:s,onOpenChange:r,children:e.jsx(is,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(Ni,{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(Ia,{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(nd,{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(Ta,{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 zc({apis:s,children:r}){return e.jsx(hi.Provider,{value:s,children:r})}const mv="curl -fsSL https://opencode.ai/install | bash",fv=3e3;function pv({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(qs,{className:"h-4 w-4"})})]})}const hv=3e4;function gv({onCliAvailable:s}){const[r,t]=l.useState(!1),[n,o]=l.useState(!1),[a,i]=l.useState(!1);l.useEffect(()=>{const m=setTimeout(()=>o(!0),hv);return()=>clearTimeout(m)},[]),l.useEffect(()=>{i(typeof window.opencodeDesktop<"u")},[]);const c=l.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await Kt(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-COPXsM7o.js").then(w=>w.ca);return{getCurrentWindow:h}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=l.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=l.useCallback(async()=>{try{await navigator.clipboard.writeText(mv),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return l.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,fv);return m(),()=>clearInterval(f)},[d,s]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:c,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(Da,{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(Dt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(pv,{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(Da,{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 xv=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=Fe();return e.jsx(uv,{open:s,onOpenChange:r})};function yv({apis:s}){const{initializeApp:r,isInitialized:t}=ut(),{error:n,clearError:o,loadSessions:a}=he(),i=wt(N=>N.currentDirectory),c=wt(N=>N.isSwitchingDirectory),[d,u]=l.useState(!1),{uiFont:m,monoFont:f}=Mu(),[p,h]=l.useState(()=>s.runtime.isDesktop),[w,g]=l.useState(()=>s.runtime.isVSCode),[y,x]=l.useState(()=>s.runtime.isDesktop?Qf():!0);l.useEffect(()=>{h(s.runtime.isDesktop),g(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),l.useEffect(()=>(Gi(s),()=>Gi(null)),[s]),l.useEffect(()=>{if(typeof document>"u")return;const N=document.documentElement,j=hc[m]?.stack??hc[Ub].stack,k=wr[f]?.stack??wr[no].stack;N.style.setProperty("--font-sans",j),N.style.setProperty("--font-heading",j),N.style.setProperty("--font-family-sans",j),N.style.setProperty("--font-mono",k),N.style.setProperty("--font-family-mono",k),N.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=j)},[m,f]),l.useEffect(()=>{if(t){const j=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},150);return()=>clearTimeout(j)}},[t]),l.useEffect(()=>{const N=setTimeout(()=>{const j=document.getElementById("initial-loading");j&&!t&&(j.classList.add("fade-out"),setTimeout(()=>{j.remove()},300))},5e3);return()=>clearTimeout(N)},[t]),l.useEffect(()=>{(async()=>await r())()},[r]),l.useEffect(()=>{if(c)return;(async()=>(Re.setDirectory(i),await a()))()},[i,c,a]),tv(),sv();const v=l.useCallback(()=>{u(N=>!N)},[]);rv(v),av(),iv(),Fu(),l.useEffect(()=>{const N=j=>{hs(j)&&j.shiftKey&&j.key==="D"&&(j.preventDefault(),u(k=>!k))};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[]),l.useEffect(()=>{n&&setTimeout(()=>o(),5e3)},[n,o]);const S=l.useCallback(()=>{x(!0),window.location.reload()},[]);return p&&!y?e.jsx(Ut,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(gv,{onCliAvailable:S})})}):w?e.jsx(Ut,{children:e.jsx(zc,{apis:s,children:e.jsx(dc,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Ww,{}),e.jsx(Tc,{})]})})})}):e.jsx(Ut,{children:e.jsx(zc,{apis:s,children:e.jsx(cv,{children:e.jsx(dc,{children:e.jsxs("div",{className:`h-full text-foreground ${p?"bg-transparent":"bg-background"}`,children:[e.jsx(Hw,{}),e.jsx(Tc,{}),e.jsx(dv,{}),e.jsx(xv,{}),d&&e.jsx(Gw,{onClose:()=>u(!1)})]})})})})})}const _u=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=wt.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&t.setDirectory(r,{showOverlay:!1})},Bu="/auth/session",bv=async()=>fetch(Bu,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),wv=async s=>fetch(Bu,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),Ti=({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})]}),vv=({message:s="Preparing workspace…"})=>e.jsx(Ti,{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})})}),jv=({onRetry:s})=>e.jsx(Ti,{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(ve,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),Sv=({children:s})=>{const r=l.useMemo(()=>Ht(),[]),t=l.useMemo(()=>Et(),[]),n=r||t,[o,a]=l.useState(()=>n?"authenticated":"pending"),[i,c]=l.useState(""),[d,u]=l.useState(!1),[m,f]=l.useState(""),p=l.useRef(null),h=l.useRef(n),w=l.useCallback(async()=>{if(n){a("authenticated");return}a(y=>y==="authenticated"?y:"pending");try{const y=await bv();if(y.ok){a("authenticated"),f("");return}if(y.status===401){a("locked");return}a("error")}catch(y){console.warn("Failed to check session status:",y),a("error")}},[n]);l.useEffect(()=>{n||w()},[w,n]),l.useEffect(()=>{!n&&o==="locked"&&(h.current=!1)},[n,o]),l.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),l.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await pd(),await hd(),await _u()))())},[n,o]);const g=async y=>{if(y.preventDefault(),!(!i||d)){u(!0),f("");try{const x=await wv(i);if(x.ok){c(""),a("authenticated");return}if(x.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(x){console.warn("Failed to submit UI password:",x),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(vv,{}):o==="error"?e.jsx(jv,{onRetry:()=>{w()}}):o==="locked"?e.jsx(Ti,{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:g,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(Ff,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(dt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:y=>{c(y.target.value),m&&f("")},className:"pl-10","aria-invalid":!!m||void 0,"aria-describedby":m?"oc-ui-auth-error":void 0,disabled:d})]}),e.jsx(ve,{type:"submit",size:"icon",disabled:!i||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Qt,{className:"h-4 w-4 animate-spin"}):e.jsx(Pf,{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})},Na=s=>{if(!s||typeof s!="string")return null;const r=s.trim();if(!r.startsWith("#"))return null;let t=r.slice(1);if((t.length===3||t.length===4)&&(t=t.split("").map(c=>c+c).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const n=Number.parseInt(t,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,i=n&255;return`${o} ${a} ${i}`};class kv{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(`
|
|
102
|
+
`)}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=Na(r.colors.surface.muted),o=Na(r.colors.surface.subtle),a=Na(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",c=i?.8:.95,d=i?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=r.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(u,c)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return r.colors.charts?.series&&Array.isArray(r.colors.charts.series)&&r.colors.charts.series.forEach((u,m)=>{t.push(` --chart-${m+1}: ${u};`)}),r.colors.loading?(t.push(` --loading-spinner: ${r.colors.loading.spinner||r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.loading.spinnerTrack||r.colors.surface.muted};`)):(t.push(` --loading-spinner: ${r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.surface.muted};`)),t}apply(r){const t=this.generate(r),n=document.createElement("style");n.id="opencode-theme-variables";let o="";r.metadata.variant==="dark"?(o=`:root {
|
|
103
|
+
${t}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
.dark {
|
|
107
|
+
${t}
|
|
108
|
+
}`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
|
|
109
|
+
${t}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
:root:not(.dark) {
|
|
113
|
+
${t}
|
|
114
|
+
}`,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=Et()?ip:li;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,c=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(c<255?c<0?0:c: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,c=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(c<255?c<0?0:c: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 Fi={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"}}},Pi={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"}}},kn=[Fi,Pi];function Co(s){return kn.find(r=>r.metadata.id===s)}const zu=Fi.metadata.id,Hu=Pi.metadata.id,Nv=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Uu=s=>s==="dark"?Pi:Fi,Cv=s=>(kn.find(t=>t.metadata.variant===s)??Uu(s)).metadata.id,Kn=(s,r)=>{const t=Co(s);return t&&t.metadata.variant===r?t:kn.find(o=>o.metadata.variant===r)??Uu(r)},Mv=typeof window<"u"?l.useLayoutEffect:l.useEffect,Mo=(s,r)=>{if(!s)return r==="light"?zu:Hu;const t=Co(s);return t&&t.metadata.variant===r?t.metadata.id:Cv(r)},Dv=s=>{let r=zu,t=Hu,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),c=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(c!==null){if(c==="true")n="system";else if(d){const f=Co(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=Mo(a,"light"),t=Mo(i,"dark")}if(s){const o=Co(s);o&&(o.metadata.variant==="light"?r=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:t}};function Av({children:s,defaultThemeId:r}){const t=Ne.useMemo(()=>new kv,[]),[n,o]=Ne.useState(()=>Dv(r)),[a,i]=Ne.useState(()=>Nv()),[c,d]=Ne.useState(()=>typeof window>"u"||!Et()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Ne.useMemo(()=>Et(),[]),m=Ne.useMemo(()=>u&&c?c:n.themeMode==="light"?Kn(n.lightThemeId,"light"):n.themeMode==="dark"||a?Kn(n.darkThemeId,"dark"):Kn(n.lightThemeId,"light"),[u,n,a,c]),f=Ne.useMemo(()=>u&&c?[c,...kn]:kn,[u,c]);Ne.useEffect(()=>{if(!u)return;const N=F=>{d(F);const A=F.metadata.variant==="dark"?"dark":"light",M=Fe.getState();M.theme!==A&&M.setTheme(A)},j=F=>{const A=F.detail;A?.theme&&N(A.theme)},k=window.__OPENCHAMBER_VSCODE_THEME__;return k&&N(k),window.addEventListener("openchamber:vscode-theme",j),()=>window.removeEventListener("openchamber:vscode-theme",j)},[u]);const p=Ne.useCallback(N=>{if(typeof document>"u")return;const j=N.colors.surface.background;Ht()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=j;let k=document.querySelector('meta[name="theme-color"]');k||(k=document.createElement("meta"),k.setAttribute("name","theme-color"),document.head.appendChild(k)),k.setAttribute("content",j);const F=N.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let A=document.querySelector(`meta[name="theme-color"][media="${F}"]`);A||(A=document.createElement("meta"),A.setAttribute("name","theme-color"),A.setAttribute("media",F),document.head.appendChild(A)),A.setAttribute("content",j)},[]),h=Ne.useCallback(N=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",N)},[]);Mv(()=>{if(typeof window>"u")return;t.apply(m),h(u),p(m);const N=document.documentElement;N.classList.remove("light","dark"),N.classList.add(m.metadata.variant)},[h,t,m,u,p]),Ne.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const N=window.matchMedia("(prefers-color-scheme: dark)"),j=k=>{i(k.matches)};return i(N.matches),N.addEventListener("change",j),()=>N.removeEventListener("change",j)},[n.themeMode]),Ne.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]),Ne.useEffect(()=>{ns({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]),Ne.useEffect(()=>{if(typeof window>"u")return;const N=j=>{const k=j.detail;k&&o(F=>{let A=F.themeMode;k.useSystemTheme===!0?A="system":k.useSystemTheme===!1&&(k.themeVariant==="dark"||k.themeVariant==="light")&&(A=k.themeVariant);let M=F.lightThemeId;typeof k.lightThemeId=="string"&&k.lightThemeId.length>0&&(M=Mo(k.lightThemeId,"light"));let b=F.darkThemeId;return typeof k.darkThemeId=="string"&&k.darkThemeId.length>0&&(b=Mo(k.darkThemeId,"dark")),A===F.themeMode&&M===F.lightThemeId&&b===F.darkThemeId?F:{themeMode:A,lightThemeId:M,darkThemeId:b}})};return window.addEventListener("openchamber:settings-synced",N),()=>window.removeEventListener("openchamber:settings-synced",N)},[]);const w=Ne.useCallback(N=>{const j=f.find(k=>k.metadata.id===N);j&&o(k=>j.metadata.variant==="dark"?k.darkThemeId===j.metadata.id&&k.themeMode==="dark"?k:{...k,darkThemeId:j.metadata.id,themeMode:"dark"}:k.lightThemeId===j.metadata.id&&k.themeMode==="light"?k:{...k,lightThemeId:j.metadata.id,themeMode:"light"})},[f]),g=Ne.useCallback(N=>{o(j=>j.themeMode===N?j:{...j,themeMode:N})},[]),y=Ne.useCallback(N=>{if(N){o(k=>k.themeMode==="system"?k:{...k,themeMode:"system"});return}const j=m.metadata.variant==="dark"?"dark":"light";o(k=>k.themeMode===j?k:{...k,themeMode:j})},[m.metadata.variant]),x=Ne.useCallback(N=>{const j=f.find(k=>k.metadata.id===N&&k.metadata.variant==="light");j&&o(k=>k.lightThemeId===j.metadata.id?k:{...k,lightThemeId:j.metadata.id})},[f]),v=Ne.useCallback(N=>{const j=f.find(k=>k.metadata.id===N&&k.metadata.variant==="dark");j&&o(k=>k.darkThemeId===j.metadata.id?k:{...k,darkThemeId:j.metadata.id})},[f]),S={currentTheme:m,availableThemes:f,setTheme:w,isSystemPreference:n.themeMode==="system",setSystemPreference:y,themeMode:n.themeMode,setThemeMode:g,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:x,setDarkThemePreference:v};return e.jsx(gi.Provider,{value:S,children:s})}const Ev=({children:s})=>{const{theme:r,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:i}=Fe();return l.useLayoutEffect(()=>{t(),o(),i()},[r,t,n,o,a,i]),l.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&t()};return c.addEventListener("change",d),()=>{c.removeEventListener("change",d)}},[r,t]),e.jsx(e.Fragment,{children:s})},Iv={getLastAssistantMessage(){const s=he.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),c=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!i&&!c&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:i,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!c}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!i&&!c&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(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=he.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=wt.getState(),r=he.getState(),t=s.currentDirectory||null,n=Re.getDirectory()??null,o=r.sessions||[],a=new Set,i={};o.forEach(k=>{const F=k.directory;typeof F=="string"&&F.trim().length>0?(a.add(F),i[F]=(i[F]??0)+1):i["(none)"]=(i["(none)"]??0)+1});const c=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(k){return{available:!1,error:k instanceof Error?k.message:String(k)}}})(),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 k=>{try{return await k.json()}catch{return null}},p=async k=>{try{return await k.text()}catch{return null}},h=async k=>{try{const F=await fetch(k);return F.ok?await f(F):{status:F.status}}catch(F){return{error:F instanceof Error?F.message:String(F)}}};let w=null,g=null,y=null,x=null;const v=t?`/api/path?directory=${encodeURIComponent(t)}`:"/api/path";w=await h(v);const S=t?`/api/project/current?directory=${encodeURIComponent(t)}`:"/api/project/current";g=await h(S),y=await h("/api/config/settings");try{const k=await fetch("/api/health"),F=k.headers.get("content-type")||"",A=await p(k);x={status:k.status,ok:k.ok,contentType:F,type:F.includes("application/json")?"json":"html",preview:A?A.slice(0,120):null}}catch(k){x={error:k instanceof Error?k.message:String(k)}}let N={isGitRepo:null};if(t)try{N.isGitRepo=await sn(t)}catch(k){N={isGitRepo:null,error:k instanceof Error?k.message:String(k)}}const j={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:w?.directory||w?.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:N,localStorage:c,opencode:{pathInfo:w,projectInfo:g,health:x},openchamber:{settingsInfo:y}};return console.log("[DEBUG] App status snapshot:",j),j},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=he.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=he.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),c=a.some(d=>d.type==="tool");return a.length===0||!i&&!c});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
|
|
115
|
+
`),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
|
|
116
|
+
`),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
|
|
117
|
+
`),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)
|
|
118
|
+
`),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=he.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const i=o.messages.get(a)||[],c=r?i:i.filter(p=>p.info.role==="assistant"),d={totalMessages:i.length,analyzedMessages:c.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const h=p.filter(w=>typeof w=="number");return h.length>0?Math.max(...h):null},f=c.map((p,h)=>{const w=p.info??{},g=Array.isArray(p.parts)?p.parts:[],y=w.time??{},x=u(y.completed),v=x!==null,S=g.filter(D=>D.type==="tool"),N=g.filter(D=>D.type==="reasoning"),j=m(S.map(D=>u(D.state?.time?.end??D.state?.time?.start))),k=m(N.map(D=>u(D.time?.end??D.time?.start))),F=m([j,k].filter(D=>D!==null)),A=S.some(D=>["pending","running","started"].includes(D.state?.status)),M=N.some(D=>typeof D.time?.end!="number");S.length>0&&(d.withTools+=1),N.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const b=!!(v&&typeof j=="number"&&x<j);b&&(d.completedBeforeTool+=1);const C=!!(v&&typeof k=="number"&&x<k);return C&&(d.completedBeforeReasoning+=1),v&&A&&(d.runningToolsWhenCompleted+=1),v&&M&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:w.id,role:w.role,completedAt:x,latestToolTimestamp:j,latestReasoningTimestamp:k,latestPartTimestamp:F,completed_missing:!v,completed_before_tool:b,completed_before_reasoning:C,running_tools_when_completed:!!(v&&A),reasoning_open_when_completed:!!(v&&M),has_tools:S.length>0,has_reasoning:N.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=he.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const n=(s.messages.get(r)||[]).filter(y=>y.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(y=>y.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,w=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:",w?.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=Iv,Bt()&&(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 Hc=!1;const Tv=()=>{if(Hc||typeof window>"u")return;Hc=!0;let s={showReasoningTraces:Fe.getState().showReasoningTraces,autoDeleteEnabled:Fe.getState().autoDeleteEnabled,autoDeleteAfterDays:Fe.getState().autoDeleteAfterDays},r=null,t=null;const n=()=>{const a=r;r=null,t=null,a&&Object.keys(a).length>0&&ns(a)},o=a=>{r={...r??{},...a},!t&&(t=setTimeout(n,150))};Fe.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},c={};i.showReasoningTraces!==s.showReasoningTraces&&(c.showReasoningTraces=i.showReasoningTraces),i.autoDeleteEnabled!==s.autoDeleteEnabled&&(c.autoDeleteEnabled=i.autoDeleteEnabled),i.autoDeleteAfterDays!==s.autoDeleteAfterDays&&(c.autoDeleteAfterDays=i.autoDeleteAfterDays),s=i,Object.keys(c).length>0&&o(c)})};let Uc=!1;const Wc="openchamber-typography-base",Fv=()=>{if(typeof document>"u")return;const r=`:root {
|
|
119
|
+
${Object.entries(li).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
|
|
120
|
+
`)}
|
|
121
|
+
}
|
|
122
|
+
`,t=document.getElementById(Wc);if(t){t.textContent=r;return}const n=document.createElement("style");n.id=Wc,n.textContent=r,document.head.appendChild(n)},Pv=()=>{Uc||typeof window>"u"||(Uc=!0,Fv())},Rv=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await pd();await hd();Tv();Pv();await _u();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 c=window.__zustand_config_store__;if(c){const d=c.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const Wu=document.getElementById("root");if(!Wu)throw new Error("Root element not found");Rf.createRoot(Wu).render(e.jsx(Ne.StrictMode,{children:e.jsx(Av,{children:e.jsx(Ev,{children:e.jsx(Sv,{children:e.jsx(yv,{apis:Rv})})})})}));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 $v=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{as as D,Nr as S,is as a,ig as b,O as c,cy as d,dy as e,ec as f,Ir as g,uy as h,fy as i,$v as m,xu as p,my as r,Qn as t};
|