@openchamber/web 1.4.3 → 1.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +44 -9
- package/dist/assets/{ToolOutputDialog-C7D95isZ.js → ToolOutputDialog-BXPi0SDL.js} +3 -3
- package/dist/assets/{index-C9fZPpn0.js → index-CqQbtUxU.js} +2 -2
- package/dist/assets/index-DR2OFuzB.css +1 -0
- package/dist/assets/main-j7ViaNnX.js +127 -0
- package/dist/assets/{vendor-.bun-B7CnnRlj.js → vendor-.bun-BEzqubWg.js} +418 -414
- package/dist/index.html +3 -3
- package/package.json +3 -2
- package/server/index.js +880 -90
- package/server/lib/git-service.js +30 -1
- package/server/lib/opencode-config.js +306 -29
- package/dist/assets/index-BFtIIPKJ.css +0 -1
- package/dist/assets/main-DzISCzsJ.js +0 -122
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-B7CnnRlj.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-C7D95isZ.js","assets/index-C9fZPpn0.js","assets/index-BFtIIPKJ.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{t as rm,c as nm,j as e,R as om,T as am,P as im,C as lm,A as cm,a as dm,b as Tt,d as _t,p as vs,e as js,f as um,_ as Jt,g as l,r as mm,i as Vt,I as fm,k as pm,l as hm,m as gm,n as xm,o as ym,q as bm,s as wm,u as Dt,v as vm,S as jm,L as Sm,w as Xc,x as Nm,y as km,z as Cm,B as Ne,D as zi,E as Ia,F as Mm,G as Nt,K as ti,H as Dm,U as es,Z as Am,Y as Gs,Q as mr,W as Ft,O as To,J as Em,M as Cr,N as Dr,V as Gr,X as Ta,$ as xs,a0 as Qc,a1 as Im,a2 as Tm,a3 as Fm,a4 as Pm,a5 as Rm,a6 as Lm,a7 as $m,a8 as eo,a9 as Om,aa as _m,ab as fo,ac as qr,ad as se,ae as Ut,af as sr,ag as Ar,ah as In,ai as Gt,aj as qs,ak as Bm,al as zm,am as Jc,an as si,ao as Jr,ap as Zc,aq as Kr,ar as Hm,as as Fo,at as Es,au as Go,av as Zr,aw as Zs,ax as Ys,ay as Um,az as Ls,aA as gs,aB as ed,aC as Wm,aD as Vm,aE as Gm,aF as qm,aG as Km,aH as Ym,aI as Xm,aJ as Qm,aK as Jm,aL as Zm,aM as ef,aN as tf,aO as sf,aP as Hr,aQ as qo,aR as rf,aS as ri,aT as ni,aU as nf,aV as of,aW as af,aX as er,aY as po,aZ as rr,a_ as Ws,a$ as lf,b0 as cf,b1 as Po,b2 as df,b3 as Tn,b4 as oi,b5 as uf,b6 as mf,b7 as ff,b8 as vn,b9 as pf,ba as hf,bb as gf,bc as xf,bd as yf,be as Fa,bf as to,bg as Ro,bh as bf,bi as wf,bj as jn,bk as Or,bl as td,bm as sd,bn as vf,bo as jf,bp as ws,bq as rd,br as Sf,bs as nd,bt as Nf,bu as kf,bv as Pa,bw as Cf,bx as od,by as Bs,bz as Sn,bA as Mf,bB as en,bC as Df,bD as ad,bE as ai,bF as ii,bG as li,bH as Af,bI as Ef,bJ as If,bK as Tf,bL as Ff,bM as Pf,bN as Rf,bO as Hi,bP as id,bQ as Lf,bR as Ui,bS as Nn,bT as ci,bU as ld,bV as cd,bW as dr,bX as Wi,bY as Lo,bZ as dd,b_ as Ra,b$ as ud,c0 as La,c1 as $f,c2 as Of,c3 as _f,c4 as Bf,c5 as zf,c6 as Hf,c7 as Uf,c8 as Wf,c9 as Vf}from"./vendor-.bun-B7CnnRlj.js";import{c as Gf,l as qf,g as Kf,r as Yf,d as Xf,a as Qf,b as Jf,e as Zf,u as ep,f as tp,h as sp,i as rp,j as np,k as op}from"./index-C9fZPpn0.js";const Xt=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Et=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,di=()=>typeof window>"u"?!1:!Xt()&&!Et(),fr=()=>Xt()?window.opencodeDesktop??null:null,md=()=>{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},fd=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},ap=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}},ip=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,tn=async()=>{const s=md();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},lp=async s=>{const r=md();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},cp=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)}}},dp=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)}}},up=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)}}},mp=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}},fp=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}},pp=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 rm(nm(s))}const pd=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),hs=s=>pd()&&Xt()?s.metaKey:s.ctrlKey,ss=()=>pd()&&Xt()?"⌘":"Ctrl",hd=(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}`},ho=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function fs(s,r){if(!s)return"";const t=ho(s);if(t==="/")return"/";const n=r?ho(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 Ko(s,r){if(!s)return"/";const t=ho(s);if(!t||t==="/")return"/";const n=r?ho(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function hp({delayDuration:s=0,...r}){return e.jsx(dm,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function Xe({delayDuration:s=0,...r}){return e.jsx(hp,{delayDuration:s,children:e.jsx(om,{"data-slot":"tooltip",...r})})}function Qe({...s}){return e.jsx(am,{"data-slot":"tooltip-trigger",...s})}function Ye({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(im,{children:e.jsxs(lm,{"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(cm,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Yo=null;const Vi=()=>{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}}},gp=()=>{if(typeof window>"u"||!window.localStorage)return Vi();const s=window.localStorage,r=Vi();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=()=>(Yo||(Yo=gp()),Yo),ui={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},xp={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Gi(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const tr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},so={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...tr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:so.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...tr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:so.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...tr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:so.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...tr.tool.inline})},Fe=Tt()(_t(vs((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(ui);if(o===1){for(const[i]of a)n.style.removeProperty(Gi(i));return}for(const[i,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Gi(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:js(()=>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 yp(){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 bp(){return Xt()?"desktop":di()?"web":null}const qi={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},$o=Tt()((s,r)=>({...qi,checkForUpdates:async()=>{const t=bp();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await mp():t==="web"&&(n=await yp()),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 fp(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 pp()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(qi)}})),wp="/api",vp=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,jp=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(vp.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}},Sp=()=>{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},Rn=s=>s.replace(/\\/g,"/"),Xo=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class Np{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(r=wp){const n=Sp()||r;this.baseUrl=jp(n),this.client=um({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 Jt(async()=>{const{default:f}=await import("./vendor-.bun-B7CnnRlj.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 b=h.data;b&&typeof b=="object"&&r(b)}};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(b=>setTimeout(b,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=Xo();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=Xo();if(t)try{const n=await t.listDirectory(r||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:Rn(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=Xo(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?Rn(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=Rn(f.path),h=p.split("/").filter(Boolean).pop()||p,b=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?Rn(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:b,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 fd();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 Np,$a=new Set;function Oo(s){return $a.add(s),()=>{$a.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 $a)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 kn(s,r){return s.scopes.includes("all")||s.scopes.includes(r)}const mi="Updating OpenCode configuration...";let Vs=0,ur=mi;const Oa=new Set;function go(){const s={isUpdating:Vs>0,message:ur};Oa.forEach(r=>r(s))}function Is(s){Vs+=1,Vs===1?(ur=s||mi,go()):s&&(ur=s,go())}function os(){Vs!==0&&(Vs-=1,Vs===0&&(ur=mi,go()))}function Ts(s){ur===s&&Vs>0||(ur=s,Vs>0&&go())}function kp(s){return Oa.add(s),s({isUpdating:Vs>0,message:ur}),()=>{Oa.delete(s)}}function Cp(){return{isUpdating:Vs>0,message:ur}}const Ln=()=>{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},gd=s=>{const r=s;return r.hidden===!0||r.options?.hidden===!0},xd=s=>s.filter(r=>!gd(r)),hn="useAgentsStore",xo=s=>new Promise(r=>setTimeout(r,s)),Mp=2e4,Ki=300,Yi=4,Dp=800,Ap=200,Ep=2e3,sn=Tt()(_t(vs((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=Ln(),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=>{Is("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=Ln(),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:hn}),m}catch{return!1}finally{n||os()}},updateAgent:async(t,n)=>{Is("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=Ln(),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:hn}),f}catch{return!1}finally{o||os()}},deleteAgent:async t=>{Is("Deleting agent configuration…");let n=!1;try{const o=Ln(),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:hn}),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 xd(t)}}),{name:"agents-store",storage:js(()=>ls()),partialize:s=>({selectedAgentName:s.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=sn);async function Ip(s){const r=typeof s=="number"&&s>0?Math.min(s,Ki):0;r>0&&await xo(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Mp;){n+=1,Ts(`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<=Yi&&a<1200?Ki:Math.min(Dp+Math.max(0,n-Yi)*Ap,Ep);await xo(i)}throw o||new Error("OpenCode did not become ready in time")}async function Ur(s={}){const{message:r,delayMs:t}=s;try{Ts(r||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("agents-store"),window.localStorage.removeItem("config-store"))}catch{}try{await Ip(t),Ts("Refreshing providers and agents…");const n=ut.getState(),o=sn.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),ys("agents",{source:hn})}catch{Ts("OpenCode reload failed. Please retry refreshing configuration manually."),await xo(1500)}finally{os()}}async function Tp(s){await Ur(s)}async function gn(s){Is("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),Ts("Failed to reload configuration. Please try again."),await xo(2e3),os(),r}}let Xi=null;Xi||(Xi=Oo(s=>{if(s.source!==hn&&kn(s,"agents")){const{loadAgents:r}=sn.getState();r()}}));let yd=null;const Qi=s=>{yd=s},Er=()=>yd,zs=Tt()(_t(vs((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:js(()=>ls()),partialize:s=>({queuedMessages:s.queuedMessages,queueModeEnabled:s.queueModeEnabled})}),{name:"message-queue-store"})),Ji=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},Fp=s=>!s||typeof s!="object"?null:{showReasoningTraces:s.showReasoningTraces},Pp=s=>{const r=Fe.getState();typeof s.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(s.showReasoningTraces)},Rp=async()=>{if(typeof window>"u")return null;if(Xt()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const t=await r.load();return Ji(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=Fp(r);return Ji(t)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}},ro=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"))},Lp=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},bd=()=>{const s=Fe.persist;if(s&&typeof s=="object")return s},wd=()=>Er()?.settings??null,no=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)},Zi=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=Lp(r.skillCatalogs);return n&&(t.skillCatalogs=n),t},$p=async()=>{const s=wd();if(s)try{const r=await s.load();return Zi(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 Zi(t)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},vd=async()=>{if(typeof window>"u")return;const s=bd(),r=t=>{ro(t);const n=()=>no(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=Xt()?await tn():await $p();t&&r(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},ns=async s=>{if(typeof window>"u")return;if(Xt()){try{const t=await lp(s);t&&(ro(t),no(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const r=wd();if(r)try{const t=await r.save(s);t&&(ro(t),no(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&&(ro(n),no(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},jd=async()=>{if(typeof window>"u")return;const s=bd();try{const r=await Rp();if(!r)return;const t=()=>Pp(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)}},Op="https://models.dev/api.json",_p="/api/openchamber/models-metadata",el="opencode",tl="big-pickle",Bp=async()=>{try{if(Xt()){const n=await tn();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{}}},sl=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]}},zp=s=>s?.toLowerCase?.()??"",Hp=s=>s==="primary"||s==="all"||s===void 0||s===null,Cn=s=>typeof s=="object"&&s!==null,yo=s=>Array.isArray(s)&&s.every(r=>typeof r=="string"),Up=s=>{if(!Cn(s))return!1;const r=s;if(r.modalities){const{input:t,output:n}=r.modalities;if(t&&!yo(t)||n&&!yo(n))return!1}return!0},Wp=s=>{if(!Cn(s))return!1;const r=s;return r.models===void 0||Cn(r.models)},Sd=(s,r)=>{const t=zp(s);return!t||!r?"":`${t}/${r}`},Vp=s=>{const r=new Map;if(!Cn(s))return r;for(const[t,n]of Object.entries(s)){if(!Wp(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!Cn(a)))for(const[i,c]of Object.entries(a)){if(!Up(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:yo(c.modalities.input)?c.modalities.input:void 0,output:yo(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=Sd(o,d);m&&r.set(m,u)}}return r},Gp=async()=>{if(typeof fetch!="function")return new Map;const s=[_p,Op];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 Vp(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},qp=s=>new Promise(r=>setTimeout(r,s)),ut=Tt()(_t(vs((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=Gp(),c=await Re.getProviders(),d=Array.isArray(c?.providers)?c.providers:[],u=c?.default||{},m=d.map(p=>{const h=p.models??{},b=Object.keys(h).map(g=>h[g]);return{...p,models:b}});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(),Bp()]),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=>Hp(x.mode)),f=u.find(x=>x.name==="build")||u[0]||c[0];let p;const h=(x,w)=>{const S=d.find(k=>k.id===x);return S?S.models.some(k=>k.id===w):!1},b={};if(i.defaultAgent){const x=c.find(w=>w.name===i.defaultAgent);x?p=x:b.defaultAgent=""}p||(p=f),s({currentAgentName:p.name});let g,y;if(i.defaultModel){const x=sl(i.defaultModel);x&&h(x.providerId,x.modelId)?(g=x.providerId,y=x.modelId):b.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(el,tl))g=el,y=tl;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(b).length>0&&(s({settingsDefaultModel:b.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultAgent:b.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),ns(b).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=sl(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 qp(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=Sd(t,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=r();return xd(t)}}),{name:"config-store",storage:js(()=>ls()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=ut);let rl=null;rl||(rl=Oo(async s=>{const r=[];if(kn(s,"agents")){const{loadAgents:t}=ut.getState();r.push(t().then(()=>{}))}if(kn(s,"providers")){const{loadProviders:t}=ut.getState();r.push(t())}r.length>0&&await Promise.all(r)}));const Zt={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Kp=180,ms=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function rn(s){const r=ms();return r?r.checkIsGitRepository(s):Gf(s)}async function Yp(s){const r=ms();return r?r.getGitStatus(s):Kf(s)}async function Nd(s){const r=ms();return r?r.getGitBranches(s):op(s)}async function Xp(s,r){const t=ms();return t?t.deleteGitBranch(s,r):Xf(s,r)}async function Qp(s,r){const t=ms();return t?t.deleteRemoteBranch(s,r):Qf(s,r)}async function Jp(s){const r=ms();return r?r.listGitWorktrees(s):qf(s)}async function Zp(s,r){const t=ms();return t?t.addGitWorktree(s,r):Jf(s,r)}async function kd(s,r){const t=ms();return t?t.removeGitWorktree(s,r):Yf(s,r)}async function eh(s){const r=ms();return r?r.ensureOpenChamberIgnored(s):np(s)}async function th(){const s=ms();return s?s.getGitIdentities():rp()}async function sh(s){const r=ms();return r?r.createGitIdentity(s):tp(s)}async function rh(s,r){const t=ms();return t?t.updateGitIdentity(s,r):ep(s,r)}async function nh(s){const r=ms();return r?r.deleteGitIdentity(s):Zf(s)}async function oh(s){const r=ms();return r?r.getCurrentGitIdentity(s):sp(s)}const ah=".openchamber",nr=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},nl=(s,r)=>{const t=nr(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Cd=s=>s?s.startsWith("refs/heads/")?s.substring(11):s.startsWith("heads/")?s.substring(6):s.startsWith("refs/")?s.substring(5):s:"",ih=async s=>{try{await Re.createDirectory(s)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function lh(s,r){const t=nr(s),n=nl(t,ah);return await ih(n),nl(n,r)}async function Md(s){const{projectDirectory:r,worktreeSlug:t,branch:n,createBranch:o,startPoint:a}=s,i=nr(r),c=await lh(i,t),d={path:c,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await Zp(i,d),{path:c,branch:n,label:Cd(n),projectDirectory:i,relativePath:c.startsWith(`${i}/`)?c.slice(i.length+1):c}}async function ol(s){const{projectDirectory:r,path:t,force:n}=s,o=nr(r);await kd(o,{path:t,force:n})}async function Dd(s){const{projectDirectory:r,path:t,branch:n,force:o,deleteRemote:a,remote:i}=s,c=nr(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await kd(c,{path:t,force:o}),d&&(await Xp(c,{branch:d,force:!0}),a))try{await Qp(c,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Mn(s){const r=nr(s);return Jp(r)}async function _a(s){const r=nr(s),t=await Yp(r);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function Dn(s,r){const t=nr(s),n=nr(r.worktree);return{path:n,branch:r.branch??"",label:Cd(r.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}const ch=new Set(["init","review"]),Br=s=>ch.has(s.name),xn="useCommandsStore",Ba=s=>new Promise(r=>setTimeout(r,s)),dh=2e4,al=300,il=4,uh=800,mh=200,fh=2e3,nn=Tt()(_t(vs((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=ht.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=>{Is("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=ht.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:xn}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||os()}},updateCommand:async(t,n)=>{Is("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=ht.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:xn}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||os()}},deleteCommand:async t=>{Is("Deleting command configuration…");let n=!1;try{const o=ht.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:xn}),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:js(()=>ls()),partialize:s=>({selectedCommandName:s.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=nn);async function ph(s){const r=typeof s=="number"&&s>0?Math.min(s,al):0;r>0&&await Ba(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<dh;){n+=1,Ts(`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<=il&&a<1200?al:Math.min(uh+Math.max(0,n-il)*mh,fh);await Ba(i)}throw o||new Error("OpenCode did not become ready in time")}async function Qo(s={}){const{message:r,delayMs:t}=s;try{Ts(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 ph(t),Ts("Refreshing providers and commands…");const n=ut.getState(),o=nn.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),ys("commands",{source:xn})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Ts("OpenCode reload failed. Please retry refreshing configuration manually."),await Ba(1500)}finally{os()}}let ll=null;ll||(ll=Oo(s=>{if(s.source!==xn&&kn(s,"commands")){const{loadCommands:r}=nn.getState();r()}}));const hh=3e4,gh=40,xh=60,yh=(s,r,t)=>{const n=s.trim(),o=r.trim().toLowerCase();return`${n}::${o}::${t}`},fi=Tt()(_t((s,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=xh){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",c=yh(a,i,o),d=Date.now(),u=r().cache[c];if(u&&d-u.timestamp<hh)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 b={...h.cache,[c]:{files:p,timestamp:Date.now()}},g=h.cacheKeys.filter(y=>y!==c);for(g.push(c);g.length>gh;){const y=g.shift();y&&delete b[y]}return{cache:b,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"})),Ht=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var bh={};let As=null;const Ds=ls(),cl=Ds.getItem("lastDirectory"),wh=typeof cl=="string"&&cl.length>0,$n=(s,r)=>((r?.showOverlay??!0)&&Is("Switching project directory…"),Re.setOpenCodeWorkingDirectory(s).catch(n=>{throw console.warn("Failed to synchronize OpenCode working directory:",n),n})),On=(s,r,t)=>{const{showOverlay:n}=r,o=()=>{try{pe.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&&(Ts("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 Tp({message:"Refreshing OpenCode configuration…"});try{await nn.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&&(Ts("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),os())}finally{t?.(a),o()}})()},_n=s=>{try{fi.getState().invalidateDirectory(s)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},vh=s=>{const r=s.trim();if(!r)return r;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},jh=(s,r)=>{const t=s.trim();return t.startsWith("~")?t==="~"?r||t:(t.startsWith("~/")||t.startsWith("~\\"))&&r?`${r}${t.slice(1)}`:t:t},oo=(s,r)=>{const t=jh(s,r);return vh(t)},bo=()=>{if(typeof window<"u"){const r=Ds.getItem("homeDirectory")||As||null,t=Ds.getItem("lastDirectory");if(t)return oo(t,r);if(As)return As;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 As=n,Ds.setItem("homeDirectory",n),n;if(r)return As=r,r}const s=typeof process<"u"&&bh?.HOME;return s||process?.cwd?.()||"/"},Sh=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},Nh=s=>(As=s,typeof window<"u"&&Ds.setItem("homeDirectory",s),ns({homeDirectory:s}),s),Ad=async()=>{const s=n=>{const o=Sh(n);return o?Nh(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 fd(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=bo(),t=s(r);return t||r},Nr=bo();Nr&&Re.setDirectory(Nr);const kh=!!(Nr&&Nr!=="/"),ht=Tt()(_t((s,r)=>({currentDirectory:Nr,directoryHistory:[Nr],historyIndex:0,homeDirectory:Nr,hasPersistedDirectory:wh,isHomeReady:kh,isSwitchingDirectory:!1,setDirectory:(t,n)=>{const o=As||r().homeDirectory||Ds.getItem("homeDirectory"),a=oo(t,o);Ht()&&console.log("[DirectoryStore] setDirectory called with path:",a);const i=n?.showOverlay??!0;Re.setDirectory(a),_n();const c=$n(a,{showOverlay:i});Ht()&&console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),s(d=>{const u=[...d.directoryHistory.slice(0,d.historyIndex+1),a];return Ds.setItem("lastDirectory",a),ns({lastDirectory:a}),{currentDirectory:a,directoryHistory:u,historyIndex:u.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}}),On(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),_n();const a=$n(o);Ds.setItem("lastDirectory",o),ns({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),On(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),_n();const a=$n(o);Ds.setItem("lastDirectory",o),ns({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),On(a,{showOverlay:!0},()=>{s(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=r(),o=As||r().homeDirectory||bo();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=As||bo();n(c)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=As||r().homeDirectory||await Ad();r().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=r(),o=t;As=o;const a=n.homeDirectory!==o,i=Ds.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?oo(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(g=>oo(g,o)),p=f.some((g,y)=>g!==n.directoryHistory[y]),h=!!(m&&m!==n.currentDirectory),b={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d?(b.currentDirectory=o,b.directoryHistory=[o],b.historyIndex=0,b.isSwitchingDirectory=!0):(h||p)&&(b.currentDirectory=m,b.directoryHistory=f,b.historyIndex=Math.min(n.historyIndex,f.length-1),b.isSwitchingDirectory=!0),s(()=>b),(d||h)&&u){const g=d?o:m;Re.setDirectory(g),_n(),Ds.setItem("lastDirectory",g),ns({lastDirectory:g});const y=$n(g,{showOverlay:!1});On(y,{showOverlay:!1},()=>{s(x=>x.currentDirectory!==g?{}:x.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}ns({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Ad().then(s=>{ht.getState().synchronizeHomeDirectory(s)});const Ed=ls(),Id="oc.sessionSelectionByDirectory",Jo=".openchamber",Ch=()=>{try{const s=Ed.getItem(Id);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 ao=null;const pi=()=>(ao||(ao=Ch()),ao),Td=s=>{ao=s;try{Ed.setItem(Id,JSON.stringify(s))}catch{}},Fd=s=>{if(!s)return null;const t=pi()[s];return typeof t=="string"?t:null},gr=(s,r)=>{if(!s)return;const t={...pi()};r?t[s]=r:delete t[s],Td(t)},dl=(s,r)=>{if(!s)return;const t=Fd(s);if(!t)return;if(!new Set(r).has(t)){const o={...pi()};delete o[s],Td(o)}},ul=async(s,r)=>{const t=s.status??await _a(s.path).catch(()=>{});await Dd({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},or=(s,r)=>{const t=s.find(n=>n.id===r);return t?Qt(t.directory??null):null},Mh=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 Mn(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const m=new Map(t);return o.forEach(({id:f})=>{m.delete(f)&&(u=!0)}),u?m:null}const i=new Map;a.forEach(u=>{const m=Dn(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(vs((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=ht.getState().currentDirectory??Re.getDirectory()??null,o=Re.getApiClient(),a=async v=>{const C=await o.session.list(v?{directory:v}:void 0);return Array.isArray(C.data)?C.data:[]},i=Qt(n),c=i?await rn(i).catch(()=>!1):!1,d=await a(i||null),u=[];let m=[];if(n&&c&&i){const v=`${i}/${Jo}`;try{const C=new Set;(await Re.listLocalDirectory(i)).some(R=>R.isDirectory&&R.name===Jo)&&(await Re.listLocalDirectory(v)).filter(H=>H.isDirectory).forEach(H=>{const Y=/^([A-Za-z]:)?\//.test(H.path)?H.path:`${v}/${H.name}`;C.add(Qt(Y)??Y)});const $=await Mn(i);Array.isArray($)&&(m=$.map(R=>Dn(i,R)).filter(R=>R.path.includes(`/${Jo}/`)),m.forEach(R=>C.add(R.path))),C.size>0&&(await Promise.allSettled(Array.from(C).map(H=>a(H)))).forEach(H=>{H.status==="fulfilled"&&Array.isArray(H.value)&&u.push(...H.value)})}catch{m=[]}}const f=new Set;i&&f.add(i),m.forEach(v=>{const C=Qt(v.path);C&&f.add(C)});const p=[...d,...u].filter(v=>{const C=v.directory??i??null,A=Qt(C);return A?f.has(A):!1}),h=r(),b=h.lastLoadedDirectory??null,g=n!==b;let y=[...p],x=h.currentSessionId;const w=v=>{y=[v,...y.filter(C=>C.id!==v.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(A=>A.id===x);if(C)w(C);else try{const A=await Re.getSession(x);w(A)}catch{x=y.length>0?y[0].id:null}}}else x=y.length>0?y[0].id:null;const S=y.reduce((v,C)=>(v.some(A=>A.id===C.id)||v.push(C),v),[]);x&&!S.some(v=>v.id===x)&&(x=S.length>0?S[0].id:null);const k=new Set(S.map(v=>v.id)),N=(v=>{if(!v)return null;const C=or(S,v);if(C)return C;const A=or(h.sessions,v);return A||null})(x)??i??n??null;if(n&&dl(n,k),N){dl(N,k);const v=Fd(N);v&&k.has(v)&&(x=v)}let L=null;try{L=await Mh(S,n,h.worktreeMetadata)}catch(v){console.debug("Failed to refresh worktree metadata during session load:",v)}const D=(()=>{const v=L??h.worktreeMetadata;if(!g||!i)return v;const C=new Map;return v.forEach((A,P)=>{Qt(A.projectDirectory)===i&&C.set(P,A)}),C})(),M=(()=>{if(!x)return i??null;const v=D.get(x)?.path;if(v)return Qt(v)??v;const C=or(S,x);return C||(i??null)})();try{Re.setDirectory(M??void 0)}catch(v){console.warn("Failed to sync OpenCode directory after session load:",v)}s({sessions:S,currentSessionId:x,lastLoadedDirectory:n,isLoading:!1,worktreeMetadata:D,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=ht.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(b=>b.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(b=>({sessions:[f,...b.sessions],currentSessionId:d,webUICreatedSessions:new Set([...b.webUICreatedSessions,d]),isLoading:!1})),c)try{Re.setDirectory(c)}catch(b){console.warn("Failed to sync OpenCode directory after session creation:",b)}const p=b=>{s(g=>({sessions:g.sessions.map(x=>x.id===d?b:x),currentSessionId:b.id,webUICreatedSessions:new Set([...Array.from(g.webUICreatedSessions).filter(x=>x!==d),b.id])})),gr(c??null,b.id)},h=async()=>{const b=Re.getApiClient(),g=20;for(let y=0;y<g;y+=1){try{const x=await b.session.list(c?{directory:c}:void 0),S=(Array.isArray(x.data)?x.data:[]).find(k=>!(m.has(k.id)||t&&k.title&&k.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 b=()=>Re.createSession({title:t,parentID:o??void 0});let g=null;try{g=c?await Re.withDirectory(c,b):await b()}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(b){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:b instanceof Error?b.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{s({isLoading:!0,error:null});const o=r().worktreeMetadata.get(t),a=or(r().sessions,t),i=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await ul(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 b=new Map(p.worktreeMetadata);b.delete(t),h.worktreeMetadata=b}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 b=new Map(p.worktreeMetadata);b.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:b,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),w=or(r().sessions,y),S=x?.path??w;x&&n?.archiveWorktree&&!m.has(x.path)&&(await ul(x,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(y),u.push({path:x.path,projectDirectory:x.projectDirectory}),m.add(x.path));const k=()=>Re.deleteSession(y);(S?await Re.withDirectory(S,k):await k())?(i.push(y),x?.path&&!u.some(N=>N.path===x.path)&&u.push({path:x.path,projectDirectory:x.projectDirectory})):c.push(y)}catch{c.push(y)}const f=ht.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 b=null;s(y=>{const x=y.sessions.filter(j=>!p.has(j.id));y.currentSessionId&&p.has(y.currentSessionId)?b=null:b=y.currentSessionId;const w=new Map(y.worktreeMetadata);for(const j of p)w.delete(j);for(const j of d)w.delete(j);const S=new Set(u.map(j=>Qt(j.path)).filter(j=>!!j)),k=S.size>0?y.availableWorktrees.filter(j=>!S.has(Qt(j.path)??j.path)):y.availableWorktrees;return{sessions:x,currentSessionId:b,...a?{}:{isLoading:!1,error:h},worktreeMetadata:w,availableWorktrees:k}});const g=Re.getDirectory()??null;return gr(g,b),{deletedIds:i,failedIds:c}},updateSessionTitle:async(t,n)=>{try{const o=or(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=or(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=or(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:js(()=>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"})),Pd="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.",Dh="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: ",Zo=s=>typeof s=="string"&&s.trim()===Pd.trim(),ea=(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},an=(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},ml=new Map,Rd=s=>{const r=ml.get(s);r&&(clearTimeout(r),ml.delete(s))},xr=s=>{for(const r of s)Rd(r)},An=s=>{if(!s)return"";if(typeof s=="string")return s;if(Array.isArray(s))return s.map(r=>An(r)).join("");if(typeof s=="object"){if(typeof s.text=="string")return s.text;if(Array.isArray(s.content))return s.content.map(r=>An(r)).join("")}return""},yn=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:yn(n)).join("");const t=An(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||An(o.delta)||""}return""}).join(""):"")},ln=(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=An(s.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},fl=10*1024*1024,Ah=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"}},Eh=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"}},Ih=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},Th=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(vs((s,r)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=r();if(n.some(b=>b.filename===t.name&&b.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=fl;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=Eh(t);!i.some(b=>c.startsWith(b)||c===b||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const u=new FileReader,m=await new Promise((b,g)=>{u.onload=()=>b(u.result),u.onerror=g,u.readAsDataURL(t)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${c}`):m,p=b=>{const g=b.replace(/\\/g,"/").split("/");return g[g.length-1]||b},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(b=>({attachedFiles:[...b.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(),w=t.lastIndexOf("/"),S=w>0?t.substring(0,w):"/",k=w>0?t.substring(w+1):t,j=await x.file.read({path:k,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||Ah(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const w=new TextEncoder().encode(c||"");return Th(w)})(),h=d==="base64"?Ih(p):new TextEncoder().encode(c||"").length;if(h>fl)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const b=new File([],n,{type:f}),g=`data:${f};base64,${p}`,y={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:b,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:js(()=>ls()),partialize:s=>({attachedFiles:s.attachedFiles})}),{name:"file-store"})),Fh=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Ph=s=>s?Fh.has(s.toLowerCase()):!1,Rh=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Lh=s=>{if(s)try{const r=Rh();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===s)}catch{}},io=s=>{const r=Lh(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"},pl=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},ta=s=>{const r=s.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return pl(r);const t=s.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:pl(t.tokens)},sa=(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}},cn=["ask","allow","full"],xt=Tt()(_t(vs((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(),b=h.get(t);if(b&&n.find(g=>g.name===b))return b;if(p>0&&f.providerID&&f.modelID){const y=(o.get(t)||[]).filter(x=>x.info.role==="assistant").sort((x,w)=>x.info.time.created-w.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(N=>N.name===S.mode))return S.mode;const k=n.find(j=>j.model?.providerID===S.providerID&&j.model?.modelID===S.modelID);if(k)return k.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,b=h;if(b.providerID&&b.modelID){const g=c(b,m.indexOf(p));if(g&&n.find(y=>y.name===g)){const y={providerId:b.providerID,modelId:b.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=sa(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,b=S=>{const k=()=>{s(j=>{const N=j.sessionContextUsage.get(t);if(N&&N.totalTokens===S.totalTokens&&N.percentage===S.percentage&&N.contextLimit===S.contextLimit&&(N.outputLimit??0)===(S.outputLimit??0)&&(N.normalizedOutput??0)===(S.normalizedOutput??0)&&N.thresholdLimit===S.thresholdLimit&&N.lastMessageId===S.lastMessageId)return j;const L=new Map(j.sessionContextUsage);return L.set(t,S),{sessionContextUsage:L}})};typeof queueMicrotask=="function"?queueMicrotask(k):typeof window<"u"?window.setTimeout(k,0):setTimeout(k,0)},g=r().sessionContextUsage.get(t);if(g&&g.lastMessageId===h){const S=g.normalizedOutput??g.outputLimit??0,k=g.contextLimit!==c||S!==d||g.thresholdLimit!==u;if(k&&g.totalTokens>0){const j=g.totalTokens/u*100,N={totalTokens:g.totalTokens,percentage:Math.min(j,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return b(N),N}if(!k&&g.totalTokens>0)return g}const y=ta(p);if(y===0)return g||null;const x=sa(y,n,o),w={totalTokens:y,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit,normalizedOutput:x.normalizedOutput,thresholdLimit:x.thresholdLimit,lastMessageId:h};return b(w),w},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=ta(d);if(u===0)return;const m=sa(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"&&ta(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=io(n))=>!t||!n?o:r().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=io(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||cn.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=io(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=r().getSessionAgentEditMode(t,n,a),c=cn.indexOf(i),d=cn.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%cn.length,f=cn[m];r().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:js(()=>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"})),hl=(s,r)=>{const t=new Map(s);return t.delete(r),t};let ra=[],na=null;const $h=50,Oh=3e4,yr=new Map,Bn=new Map,Rr=new Map,_h=10,wo=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<_h?null:n},zn=(s,r)=>{const t=wo(s),n=wo(r);return!t||!n||t.length!==n.length?!0:t>n},Bh=()=>{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),vo=s=>s?.finish==="stop",gl=s=>{if(s){if(typeof s.id=="string"&&s.id.length>0)return s.id;if(s.type){const r=s.reason,t=s.callID;return`${s.type}-${r??""}-${t??""}`}}},xl=new Set,jo=(s=[],r=[])=>{if(!r.length)return[...s];const t=[...s],n=new Set(s.map(gl).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=gl(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},zh=(s,r)=>{const t=Array.isArray(s.parts)?s.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=zr(t),a=zr(n),i=vo(s.info),c=vo(r.info);let d=n;return i&&o>=a?d=jo(t,n):c&&a>=o?d=jo(n,t):o>=a&&(d=t),{...r,info:{...s.info,...r.info},parts:d}},oa=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]=zh(r[a],n)}return r},Hh=(s,r)=>{let t=r,n=r?wo(r):null;for(const o of s){const a=o?.info?.id,i=wo(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},Os=(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},Hn=(s,r)=>{const t=new Map(s);let n=!1;for(const o of r)t.delete(o)&&(n=!0);return n?t:s},Uh=(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},yl=(s,r,t)=>s.streamingMessageIds.get(r)===t?!0:s.messageSessionIndex.get(t)===r&&s.messageStreamStates.has(t),Wh=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}},bl=s=>{if(!s)return null;try{return Je.getState().sessions.find(n=>n.id===s)?.revert?.messageID??null}catch{return null}},wl=(s,r)=>{if(!r)return s;const t=s.findIndex(n=>n.info.id===r);return t===-1?s:s.slice(0,t)},aa=async(s,r)=>{const t=await Wh(s);return t?Re.withDirectory(t,r):r()},at=Tt()(_t(vs((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=Zt.VIEWPORT_MESSAGES)=>{const o=await aa(t,()=>Re.getSessionMessages(t)),a=bl(t),i=wl(o,a),c=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,u=(c?i.filter(m=>{const f=m?.info?.id;return f?zn(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])),b=u.map(M=>{const v={...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 $=P.text??P.content??"";if(Zo($))return{...P,synthetic:!0}}return P}),A=v?.id?h.get(v.id):void 0;if(A&&A.info.role==="assistant"){const P=Array.isArray(A.parts)?A.parts:[],$=zr(P),R=zr(C);if(vo(A.info)&&$>R){const U=jo(P,C);return{...M,info:v,parts:U}}}return{...M,info:v,parts:C}}),g=oa(b),y=new Set(p.map(M=>M.info.id)),x=new Set(g.map(M=>M.info.id)),w=[];y.forEach(M=>{x.has(M)||w.push(M)}),f.set(t,g);const S=new Map(m.sessionMemoryState),k=m.sessionMemoryState.get(t);S.set(t,{...k,viewportAnchor:g.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>u.length,trimmedHeadMaxId:k?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const j={messages:f,sessionMemoryState:S};xr(w);const N=an(m.messageStreamStates,w);if(N!==m.messageStreamStates&&(j.messageStreamStates=N),w.length>0){const M=m.streamingMessageIds.get(t);M&&w.includes(M)&&(j.streamingMessageIds=Os(j.streamingMessageIds??m.streamingMessageIds,t,null))}if(w.length>0){const M=Hn(j.messageSessionIndex??m.messageSessionIndex,w);M!==(j.messageSessionIndex??m.messageSessionIndex)&&(j.messageSessionIndex=M)}if(w.length>0){const M=new Map(m.pendingAssistantParts);let v=!1;w.forEach(C=>{M.delete(C)&&(v=!0)}),v&&(j.pendingAssistantParts=M)}const L=j.messageSessionIndex??m.messageSessionIndex;let D=L;return g.forEach(M=>{const v=M?.info?.id;typeof v=="string"&&v.length>0&&(D=Lr(D,v,t))}),D!==L&&(j.messageSessionIndex=D),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 aa(m,async()=>{try{let f=t;if(t.startsWith("/")){const h=t.indexOf(" "),b=h===-1?t.substring(1):t.substring(1,h),g=h===-1?"":t.substring(h+1).trim(),y=Re.getApiClient(),x=Re.getDirectory();if(b==="init"){const w=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await y.session.init({sessionID:m,...x?{directory:x}:{},messageID:w,providerID:n,modelID:o});return}if(b==="summarize"){await y.session.summarize({sessionID:m,...x?{directory:x}:{},providerID:n,modelID:o});return}try{const w=await Re.getCommandDetails(b);w?.template?f=w.template.replace(/\$ARGUMENTS/g,g):f=t}catch(w){console.error("Command template resolution failed:",w),f=t}}s({lastUsedProvider:{providerID:n,modelID:o}}),s(h=>{const b=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,{...b,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 b=(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 w=new Map(y.pendingUserMessageMetaBySession);return w.set(m,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o}),{pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:w}});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:b.length>0?b:void 0,additionalParts:g,agentMentions:d?[{name:d}]:void 0}),b.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 b="Network error while sending message. The message may still be processing.";if(h.name==="AbortError")b="Request timed out. The message may still be processing.";else if(h.message?.includes("504")||h.message?.includes("Gateway")){b="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&&(b=h.message);throw s(g=>{const y=new Map(g.abortControllers);y.delete(m);const x=new Set(g.pendingAssistantHeaderSessions);x.delete(m);const w=new Map(g.pendingUserMessageMetaBySession);return w.delete(m),{abortControllers:y,pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:w}}),new Error(b)}}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 b=new Map(h.abortControllers);b.delete(m);const g=new Set(h.pendingAssistantHeaderSessions);g.delete(m);const y=new Map(h.pendingUserMessageMetaBySession);return y.delete(m),{abortControllers:b,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=Uh(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(b=>b.type==="reasoning"||b.type==="tool"||b.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),Bn.delete(u))}c.size>0&&xr(c);const d=Date.now();s(u=>{const m=an(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(w=>{if(!c.has(w.info.id)&&c.size>0)return w;const S=(w.parts??[]).map(k=>{if(k.type==="reasoning"){const j=k,N={...j.time??{}};return typeof N.end!="number"&&(N.end=d),{...j,time:N}}if(k.type==="tool"){const j=k,N={...j.state??{}};return(N.status==="running"||N.status==="pending")&&(N.status="aborted"),{...j,state:N}}return k.type==="step-start"?{...k,type:"step-finish",aborted:!0}:k});return p=!0,{...w,info:{...w.info,abortedAt:d,streaming:!1,status:"aborted"},parts:S}});p&&(h=new Map(u.messages),h.set(t,x))}const b=u.sessionMemoryState.get(t);let g=u.sessionMemoryState;if(b){const x=new Map(u.sessionMemoryState);x.set(t,{...b,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:Os(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(xl.has(n))return;const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!zn(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>Zt.ZOMBIE_TIMEOUT){p.isZombie||s(b=>{const g=new Map(b.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 w=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 v=M||"",C=Bn.get(n);if(v&&C===v){const $=r();if(yl($,t,n)){const R=yr.get(n);R&&(clearTimeout(R),yr.delete(n)),setTimeout(()=>{const H=r();typeof H.forceCompleteMessage=="function"&&H.forceCompleteMessage(t,n,"timeout"),H.completeStreamingMessage(t,n)},100)}}Bn.set(n,v);const A=yr.get(n);A&&clearTimeout(A);const P=setTimeout(()=>{const $=r();typeof $.forceCompleteMessage=="function"&&$.forceCompleteMessage(t,n,"timeout"),yl($,t,n)&&$.completeStreamingMessage(t,n),yr.delete(n),Bn.delete(n)},8e3);yr.set(n,P)},k=t!==i,j=h.sessionMemoryState.get(t);if(k&&j?.isStreaming){g.length>=Zt.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 v=Date.now(),C=new Map(h.sessionMemoryState);C.set(t,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??v,lastAccessedAt:v,isZombie:!1}),h.sessionMemoryState=C}}const N=yn(o);if(Zo(N)&&(o.synthetic=!0),Bh()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:N.length,snapshotParts:u.length})}catch{}const L=y.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const M=Os(L,t,n);M!==L&&(y.streamingMessageIds=M,window.__messageTracker?.(n,"streamingId_set_latest"))}const D=g.findIndex(M=>M.info.id===n);if(D!==-1&&f==="user"){const M=g[D],v=M.parts.findIndex(R=>R.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const C=ln(o,v!==-1?M.parts[v]:void 0);window.__messageTracker?.(n,`user_part_type:${C.type||"unknown"}`);const A={...M};v!==-1?A.parts=A.parts.map((R,H)=>H===v?C:R):A.parts=[...A.parts,C];const P=[...g];P[D]=A;const $=new Map(h.messages);return $.set(t,P),w({messages:$})}if(f==="assistant"&&D!==-1){const M=g[D],v=M.parts.findIndex(H=>H.id===o.id),C=ln(o,v!==-1?M.parts[v]:void 0);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`);const A={...M};v!==-1?A.parts=A.parts.map((H,U)=>U===v?C:H):A.parts=[...A.parts,C];const P=[...g];P[D]=A;const $=new Map(h.messages);$.set(t,P),y.messageStreamStates=ea(h.messageStreamStates,n);const R=Os(y.streamingMessageIds??h.streamingMessageIds,t,n);return R!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=R,window.__messageTracker?.(n,"streamingId_set")),C.type==="text"?S(C.text||""):S(""),w({messages:$,...y})}if(D===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const xe=ln(o);window.__messageTracker?.(n,`new_user_part_type:${xe.type||"unknown"}`);const Me=h.pendingUserMessageMetaBySession.get(t),Q=xt.getState(),re=Me?.mode??Q.getSessionAgentSelection(t)??Q.getCurrentAgent(t),oe=typeof re=="string"&&re.trim().length>0?re.trim():void 0,W=Me?.providerID??(h.lastUsedProvider?.providerID||void 0),me=Me?.modelID??(h.lastUsedProvider?.modelID||void 0);Me&&(y.pendingUserMessageMetaBySession=hl(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:[xe]},ce=[...g,ye];ce.sort((Ee,Pe)=>{const G=Ee.info?.time?.created||0,K=Pe.info?.time?.created||0;return G-K});const Ce=new Map(h.messages);return Ce.set(t,ce),w({messages:Ce})}if(o?.type==="text"){const xe=yn(o).trim();if(xe.length>0){const Me=[...g].reverse().find(Q=>Q.info.role==="user");if(Me){const Q=Me.parts.map(re=>yn(re)).join("").trim();if(Q.length>0&&Q===xe)return xl.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const M=ln(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?S(M.text||""):S("");const v=h.pendingAssistantParts.get(n),C=v?[...v.parts]:[],A=C.findIndex(xe=>xe.id===M.id);A!==-1?C[A]=M:C.push(M);const P=new Map(h.pendingAssistantParts);P.set(n,{sessionId:t,parts:C});const $=h.lastUsedProvider?.providerID||"",R=h.lastUsedProvider?.modelID||"",H=Date.now(),U=Re.getDirectory()??"/",Y=xt.getState(),F=Y.getSessionAgentSelection(t)??Y.getCurrentAgent(t),B=typeof F=="string"&&F.trim().length>0?F.trim():void 0,T=h.pendingAssistantHeaderSessions.has(t);if(T){const xe=new Set(h.pendingAssistantHeaderSessions);xe.delete(t),y.pendingAssistantHeaderSessions=xe}const X={info:f==="user"?{id:n,sessionID:t,role:"user",time:{created:H},agent:B||"default",model:{providerID:$,modelID:R},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:t,role:"assistant",time:{created:H},parentID:n,modelID:R,providerID:$,mode:B||"default",...T?{openchamberHeaderAnchor:!0}:{},path:{cwd:U,root:U},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:C},fe=[...g,X],ae=new Map(h.messages);if(ae.set(t,fe),f==="assistant"){y.messageStreamStates=ea(h.messageStreamStates,n);const xe=Os(y.streamingMessageIds??h.streamingMessageIds,t,n);xe!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=xe,window.__messageTracker?.(n,"streamingId_set"))}return w({messages:ae,pendingAssistantParts:P,...y})}else{const M=g[D],v=M.parts.findIndex(R=>R.id===o.id),C=ln(o,v!==-1?M.parts[v]:void 0);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`);const A={...M};v!==-1?A.parts=A.parts.map((R,H)=>H===v?C:R):A.parts=[...A.parts,C];const P=[...g];P[D]=A;const $=new Map(h.messages);if($.set(t,P),A.info.role==="assistant"){y.messageStreamStates=ea(h.messageStreamStates,n);const R=Os(y.streamingMessageIds??h.streamingMessageIds,t,n);R!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=R,window.__messageTracker?.(n,"streamingId_set"))}return C.type==="text"?S(C.text||""):S(""),w({messages:$,...y})}})},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){r()._addStreamingPartImmediate(t,n,o,a,i);return}ra.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),na||(na=setTimeout(()=>{const c=[...ra];ra=[],na=null;const d=r();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},$h))},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 b=!1;const g={...p};h||(g.time={...p.time??{},completed:f},b=!0),g.status!=="completed"&&(g.status="completed",b=!0),g.streaming&&(g.streaming=!1,b=!0);let y=!1;const x=m.parts.map(j=>{if(!j)return j;if(j.type==="tool"){const N=j.state;if(!N)return j;const L=N.status,D=L==="running"||L==="pending"||L==="started",M=!N.time||typeof N.time?.end!="number";if(D||M){const v={...N};return D&&(v.status="completed"),M&&(v.time={...N.time??{},end:f}),y=!0,{...j,state:v}}return j}if(j.type==="reasoning"){const N=j.time;return!N||typeof N.end!="number"?(y=!0,{...j,time:{...N??{},end:f}}):j}if(j.type==="text"){const N=j.time;return N&&typeof N.end!="number"?(y=!0,{...j,time:{...N,end:f}}):j}return j});if(!b&&!y)return i;window.__messageTracker?.(n,`force_complete:${o}`);const w={...m,info:g,parts:y?x:m.parts},S=[...d];S[u]=w;const k=new Map(i.messages);return k.set(c,S),{messages:k}})},markMessageStreamSettled:t=>{s(n=>{Rd(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 b=new Map(n.messages);b.set(u,h),a=b,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),xr([t])},updateMessageInfo:(t,n,o)=>{s(c=>{const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!zn(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(t)??[]],f=m.findIndex(D=>D.info.id===n),p=c.pendingAssistantParts.get(n),h=(D=[],M=[])=>{if(!M.length)return D;const v=[...D];return M.forEach(C=>{const A=v.findIndex(P=>P.id===C.id);A===-1?v.push(C):v[A]=C}),v},b=D=>{if(!D)return D;const M=D.clientRole??D.role,v=M==="user"?!0:D.userMessageMarker;return{...D,clientRole:M,...v?{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 U=m[0]?.info,Y=typeof U?.time?.created=="number"?U.time.created:null,F=typeof U?.id=="string"?U.id:null,B=o,T=typeof B?.time?.created=="number"?B.time.created:null,V=typeof B?.id=="string"?B.id:n;let X=!1;if(T!==null&&Y!==null&&(X=T<Y),!X&&V&&F&&(X=V.localeCompare(F)<0),X)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const D=b(o);if(D&&D.role==="user"){const H=p?.parts??[],U=c.pendingUserMessageMetaBySession.get(t),Y={info:{...D,userMessageMarker:!0,clientRole:"user",...U?.mode?{mode:U.mode}:{},...U?.providerID?{providerID:U.providerID}:{},...U?.modelID?{modelID:U.modelID}:{}},parts:H.length>0?[...H]:[]},F=new Map(c.messages),B=[...m,Y];B.sort((X,fe)=>{const ae=X.info?.time?.created||0,xe=fe.info?.time?.created||0;return ae-xe}),F.set(t,B);const T={messages:F,...U?{pendingUserMessageMetaBySession:hl(c.pendingUserMessageMetaBySession,t)}:{}},V=Lr(T.messageSessionIndex??c.messageSessionIndex,n,t);if(V!==(T.messageSessionIndex??c.messageSessionIndex)&&(T.messageSessionIndex=V),p){const X=new Map(c.pendingAssistantParts);X.delete(n),T.pendingAssistantParts=X}return T}if(!D||D.role!=="assistant")return c;const M=p?.parts??[],v=c.pendingAssistantHeaderSessions.has(t),C={info:{...D,animationSettled:D?.animationSettled??!1,...v?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},A=new Map(c.messages),P=[...m,C];A.set(t,P);const $={messages:A,...v?{pendingAssistantHeaderSessions:(()=>{const H=new Set(c.pendingAssistantHeaderSessions);return H.delete(t),H})()}:{}},R=Lr($.messageSessionIndex??c.messageSessionIndex,n,t);if(R!==($.messageSessionIndex??c.messageSessionIndex)&&($.messageSessionIndex=R),p){const H=new Map(c.pendingAssistantParts);H.delete(n),$.pendingAssistantParts=H}return $}const g=m[f],y=g.info;if(y.userMessageMarker===!0||y.clientRole==="user"||y.role==="user"){const D={...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&&!D.mode&&M.mode&&(D.mode=M.mode);const v={...g,info:D},C=new Map(c.messages),A=[...m];if(A[f]=v,C.set(t,A),M){const P=new Map(c.pendingUserMessageMetaBySession);return P.delete(t),{messages:C,pendingUserMessageMetaBySession:P}}return{messages:C}}const w={...g.info,...o};o.role&&o.role!==g.info.role&&(w.role=g.info.role),w.clientRole=w.clientRole??g.info.clientRole??g.info.role,w.clientRole==="user"&&(w.userMessageMarker=!0);const S=p?.parts?h(g.parts,p.parts):g.parts,k={...g,info:w,parts:S},j=new Map(c.messages),N=[...m];N[f]=k,j.set(t,N);const L={messages:j};if(p){const D=new Map(c.pendingAssistantParts);D.delete(n),L.pendingAssistantParts=D}return L});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=Os(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,...b}=f;return p.set(t,b),{sessionMemoryState:p}}),Rr.delete(t)},2e3);Rr.set(t,u)}},syncMessages:(t,n)=>{const o=bl(t),a=wl(n,o),i=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=i?a.filter(d=>{const u=d?.info?.id;return u?zn(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 N={...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},L=(Array.isArray(j.parts)?j.parts:[]).map(v=>{if(v?.type==="text"){const C=v.text??v.content??"";if(Zo(C))return{...v,synthetic:!0}}return v}),D=typeof N?.id=="string"?N.id:void 0,M=D?f.get(D):void 0;if(M&&M.info.role==="assistant"){const v=Array.isArray(M.parts)?M.parts:[],C=zr(v),A=zr(L);if(vo(M.info)&&C>A){const $=jo(v,L);return{...j,info:N,parts:$}}}return{...j,info:N,parts:L}}),h=oa(p),b=new Set(m.map(j=>j.info.id)),g=new Set(h.map(j=>j.info.id)),y=[];b.forEach(j=>{g.has(j)||y.push(j)}),u.set(t,h);const x={messages:u,isSyncing:!0};xr(y);const w=an(d.messageStreamStates,y);if(w!==d.messageStreamStates&&(x.messageStreamStates=w),y.length>0){const j=d.streamingMessageIds.get(t);j&&y.includes(j)&&(x.streamingMessageIds=Os(x.streamingMessageIds??d.streamingMessageIds,t,null))}if(y.length>0){const j=Hn(x.messageSessionIndex??d.messageSessionIndex,y);j!==(x.messageSessionIndex??d.messageSessionIndex)&&(x.messageSessionIndex=j)}if(y.length>0){const j=new Map(d.pendingAssistantParts);let N=!1;y.forEach(L=>{j.delete(L)&&(N=!0)}),N&&(x.pendingAssistantParts=j)}const S=x.messageSessionIndex??d.messageSessionIndex;let k=S;return h.forEach(j=>{const N=j?.info?.id;typeof N=="string"&&N.length>0&&(k=Lr(k,N,t))}),k!==S&&(x.messageSessionIndex=k),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+Oh;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=Zt.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)),b=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),w={...c,viewportAnchor:d-u,trimmedHeadMaxId:Hh(p,c.trimmedHeadMaxId)};x.set(t,w);const S={messages:y,sessionMemoryState:x};xr(b);const k=an(g.messageStreamStates,b);if(k!==g.messageStreamStates&&(S.messageStreamStates=k),b.length>0){const L=g.streamingMessageIds.get(t);L&&b.includes(L)&&(S.streamingMessageIds=Os(S.streamingMessageIds??g.streamingMessageIds,t,null))}if(b.length>0){const L=Hn(S.messageSessionIndex??g.messageSessionIndex,b);L!==(S.messageSessionIndex??g.messageSessionIndex)&&(S.messageSessionIndex=L)}const j=S.messageSessionIndex??g.messageSessionIndex;let N=j;return f.forEach(L=>{const D=L?.info?.id;typeof D=="string"&&D.length>0&&(N=Lr(N,D,t))}),N!==j&&(S.messageSessionIndex=N),S})},evictLeastRecentlyUsed:t=>{const n=r();if(n.messages.size<=Zt.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(k=>k.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(c),p.delete(c);const h={messages:f,sessionMemoryState:p},b=new Map(d.pendingAssistantParts);let g=!1;b.forEach((k,j)=>{k.sessionId===c&&(b.delete(j),g=!0)}),g&&(h.pendingAssistantParts=b);const y=new Map(d.sessionCompactionUntil);y.delete(c)&&(h.sessionCompactionUntil=y),xr(m);const x=an(d.messageStreamStates,m);x!==d.messageStreamStates&&(h.messageStreamStates=x);const w=Hn(h.messageSessionIndex??d.messageSessionIndex,m);w!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=w);const S=Os(d.streamingMessageIds,c,null);if(S!==d.streamingMessageIds&&(h.streamingMessageIds=S),d.abortControllers.has(c)){const k=new Map(d.abortControllers);k.delete(c),h.abortControllers=k}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 aa(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(Zt.VIEWPORT_MESSAGES,u),f=c.slice(u-m,u);s(p=>{const h=[...f,...a],b=oa(h),g=new Map(p.messages);g.set(t,b);const y=Math.max(0,b.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:js(()=>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"})),Vh=s=>typeof s=="object"&&s!==null,Gh=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},qh=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()},So=Tt()(_t(vs((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=io(i),d=n?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&Ph(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 qh(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:js(()=>ls()),partialize:s=>({permissions:Array.from(s.permissions.entries())}),merge:(s,r)=>{if(!Vh(s))return r;const t=Gh(s.permissions);return{...r,permissions:new Map(t)}}}),{name:"permission-store"})),hi=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
|
-
`),bn=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},vl=(s,r,t)=>{if(!r)return null;const n=t(r)?.path;if(typeof n=="string"&&n.trim().length>0)return bn(n);const o=s.find(a=>a.id===r);return o?bn(o.directory??null):null},pe=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)=>xt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>xt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>xt.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,w)=>{const S=x.find(k=>k.info?.id===t);S&&!i&&(i=S,c=w)}),!i||i.info.role!=="assistant")return;const d=hi(i.parts);if(!d.trim())return;const u=Je.getState(),m=vl(u.sessions,c??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:b}=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:Pd,agent:b??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=vl(Je.getState().sessions,t,Je.getState().getWorktreeMetadata),a=Re.getDirectory()??ht.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,Zt.VIEWPORT_MESSAGES)}Je.getState().setCurrentSession(t),t&&(r().messages.get(t)||await r().loadMessages(t),r().trimToViewportWindow(t,Kp)),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(w=>{const S=new Map(w.sessionActivityPhase??new Map);return S.set(x,"busy"),{sessionActivityPhase:S}})},p=x=>{s(w=>{const S=new Map(w.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 w=ut.getState(),S=w.currentAgentName,k=m??S,j=w.currentProviderId,N=w.currentModelId;if(j&&N)try{xt.getState().saveSessionModelSelection(x.id,j,N)}catch{}if(k){try{xt.getState().saveSessionAgentSelection(x.id,k)}catch{}if(j&&N)try{xt.getState().saveAgentModelForSession(x.id,k,j,N)}catch{}}try{Je.getState().initializeNewOpenChamberSession(x.id,w.agents)}catch{}r().closeNewSessionDraft(),f(x.id);try{return await at.getState().sendMessage(t,n,o,k,x.id,i,c,d)}catch(L){throw p(x.id),L}}const h=Je.getState().currentSessionId,b=h?xt.getState().getSessionAgentSelection(h):null,g=ut.getState().currentAgentName,y=m||b||g||void 0;if(h&&y)try{xt.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:xt.getState().currentAgentContext,sessionAgentSelections:xt.getState().sessionAgentSelections,getSessionAgentEditMode:xt.getState().getSessionAgentEditMode};return So.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>So.getState().respondToPermission(t,n,o),clearError:()=>Je.getState().clearError(),getSessionsByDirectory:t=>Je.getState().getSessionsByDirectory(t),getLastMessageModel:t=>at.getState().getLastMessageModel(t),getCurrentAgent:t=>xt.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)=>xt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>xt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>xt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>xt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>xt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>xt.getState().getAgentModelForSession(t,n),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=at.getState().messages;return xt.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 xt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=at.getState().messages;return xt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=at.getState().messages;return xt.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 xt.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 Jt(async()=>{const{toast:p}=await import("./vendor-.bun-B7CnnRlj.js").then(h=>h.ca);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 Jt(async()=>{const{toast:h}=await import("./vendor-.bun-B7CnnRlj.js").then(b=>b.ca);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 Jt(async()=>{const{toast:p}=await import("./vendor-.bun-B7CnnRlj.js").then(h=>h.ca);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 Jt(async()=>{const{toast:p}=await import("./vendor-.bun-B7CnnRlj.js").then(h=>h.ca);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 Jt(async()=>{const{toast:p}=await import("./vendor-.bun-B7CnnRlj.js").then(h=>h.ca);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 Jt(async()=>{const{toast:f}=await import("./vendor-.bun-B7CnnRlj.js").then(p=>p.ca);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 Jt(async()=>{const{toast:d}=await import("./vendor-.bun-B7CnnRlj.js").then(u=>u.ca);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=pe.getState().newSessionDraft?.open;pe.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}}}}}),pe.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&&pe.setState({attachedFiles:s.attachedFiles})});xt.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||pe.setState({sessionModelSelections:s.sessionModelSelections,sessionAgentSelections:s.sessionAgentSelections,sessionAgentModelSelections:s.sessionAgentModelSelections,currentAgentContext:s.currentAgentContext,sessionContextUsage:s.sessionContextUsage,sessionAgentEditModes:s.sessionAgentEditModes})});So.subscribe((s,r)=>{s.permissions!==r.permissions&&pe.setState({permissions:s.permissions})});ht.subscribe((s,r)=>{const t=bn(s.currentDirectory??null),n=bn(r.currentDirectory??null);if(t===n)return;const o=pe.getState().newSessionDraft;if(!o?.open)return;const a=bn(o.directoryOverride);a&&a!==n||pe.setState(i=>({newSessionDraft:{...i.newSessionDraft,directoryOverride:t,parentID:null}}))});const Kh=pe.getState().newSessionDraft?.open;pe.setState({sessions:Je.getState().sessions,currentSessionId:Kh?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:So.getState().permissions,attachedFiles:Hs.getState().attachedFiles,sessionModelSelections:xt.getState().sessionModelSelections,sessionAgentSelections:xt.getState().sessionAgentSelections,sessionAgentModelSelections:xt.getState().sessionAgentModelSelections,currentAgentContext:xt.getState().currentAgentContext,sessionContextUsage:xt.getState().sessionContextUsage,sessionAgentEditModes:xt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=pe);const gi=({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),b=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:v,clientHeight:C,scrollTop:A,scrollWidth:P,clientWidth:$,scrollLeft:R}=M,H=8;if(v>C){const U=Math.max(C-H*2,0),Y=C/v*U,F=Math.max(r,Math.min(U,Y)),B=Math.max(U-F,0),T=Math.max(v-C,1),V=A/T*B;d({length:F,offset:V})}else d({length:0,offset:0});if(!o&&P>$){const U=Math.max($-H*2,0),Y=$/P*U,F=Math.max(r,Math.min(U,Y)),B=Math.max(U-F,0),T=Math.max(P-$,1),V=R/T*B;m({length:F,offset:V})}else m({length:0,offset:0})},[s,r,o]),x=l.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>i(!1),t)},[t]),w=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",w,{passive:!0});const v=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null;v?.observe(M);const C=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return C?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",w),v?.disconnect(),C?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[s,w,x,y]);const S=(M,v)=>{const C=s.current;C&&(h.current=!0,b.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:C.scrollTop,scrollLeft:C.scrollLeft},g.current=v,i(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},k=M=>{if(!h.current)return;const v=s.current;if(!v)return;const C=g.current;if(C==="vertical"){const{pointerY:A,scrollTop:P}=b.current,$=M.clientY-A,R=v.clientHeight,H=Math.max(R-c.length,1),U=Math.max(v.scrollHeight-v.clientHeight,1),Y=$/H*U;v.scrollTop=P+Y}else if(C==="horizontal"){const{pointerX:A,scrollLeft:P}=b.current,$=M.clientX-A,R=v.clientWidth,H=Math.max(R-u.length,1),U=Math.max(v.scrollWidth-v.clientWidth,1),Y=$/H*U;v.scrollLeft=P+Y}},j=M=>{h.current&&(h.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),x())},N=c.length>0,L=u.length>0;if(!N&&!L)return null;const D=8;return e.jsxs("div",{className:O("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[N&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${D+c.offset}px`,right:`${D/2}px`},onPointerDown:M=>S(M,"vertical"),onPointerMove:k,onPointerUp:j,onPointerCancel:j}),L&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${D+u.offset}px`,bottom:`${D/2}px`},onPointerDown:M=>S(M,"horizontal"),onPointerMove:k,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(gi,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});tt.displayName="ScrollableOverlay";const jl="mobile-overlay-root",Yh=()=>{if(typeof document>"u")return null;let s=document.getElementById(jl);return s||(s=document.createElement("div"),s.id=jl,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=Yh()),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(Vt,{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 mm.createPortal(m,d.current)},za=({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)},[]),b=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?b:void 0,children:[e.jsx(fm,{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))})})]})},dn={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Ld=(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 ia(){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>dn.md&&s<=dn.lg,m=s<=dn.md;let f=d&&m,p=d&&!f&&u,h=!d||s>dn.lg,b="desktop";c?(f=!1,p=!1,h=!0,b="desktop"):f?b="mobile":p?b="tablet":(h=!0,b="desktop"),Ld(c,b,d);let g="xs";for(const[y,x]of Object.entries(dn))s>=x&&(g=y);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:b,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}:ia());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{r(ia())};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(ia())},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;Ld(t,s.deviceType,u)},[s.deviceType,s.hasTouchInput]),s}const Un=5e3,Xh=1e4,Qh=5e3,Jh=1e4,Zh=25,eg=4,Sl=15e3,_s=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),tg=(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},sg=(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!!tg(s.diffStats,r.diffStats)},rg=(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:Un,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(sg(c.status,m)){d=!0;const f=new Map(r().directories),p=f.get(t)??_s(),h=rg(p.status,m),b=new Set((p.status?.files??[]).map(w=>w.path)),g=new Set((m.files??[]).map(w=>w.path)),y=new Map(p.diffCache);for(const w of b)g.has(w)||y.delete(w);for(const w of h)y.delete(w);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>Jh||!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(w=>!o.diffCache.has(w.path)).slice(0,Zh);if(c.length===0)return;let d=0;const u=[],m=()=>{const w=d;return d+=1,w<c.length?c[w]:null},f=async w=>{const S=n.getGitFileDiff(t,{path:w}),k=new Promise((N,L)=>{setTimeout(()=>L(new Error(`Timed out after ${Sl}ms`)),Sl)}),j=await Promise.race([S,k]);return{path:w,diff:{original:j.original??"",modified:j.modified??""}}},p=async()=>{for(;;){const w=m();if(!w)return;try{u.push(await f(w.path))}catch{}}},h=Math.min(eg,c.length);await Promise.allSettled(Array.from({length:h},()=>p()));const b=new Map(r().directories),g=b.get(t);if(!g)return;const y=new Map(g.diffCache),x=Date.now();u.forEach(w=>{y.set(w.path,{...w.diff,fetchedAt:x})}),b.set(t,{...g,diffCache:y}),s({directories:b})},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:Un});else{const m=Math.min(a+Qh,Xh);s({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&s({pollIntervalId:o()})},a)};s({pollIntervalId:o(),currentPollInterval:Un})},stopPolling:()=>{const{pollIntervalId:t}=r();t&&(clearTimeout(t),s({pollIntervalId:null,currentPollInterval:Un}))},refresh:async(t,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,t,n)}}),{name:"git-store"})),$d=s=>It(r=>s?r.directories.get(s)?.status??null:null),ng=s=>It(r=>s?r.directories.get(s)?.branches??null:null),og=s=>It(r=>s?r.directories.get(s)?.log??null:null),ag=s=>It(r=>s?r.directories.get(s)?.identity??null:null),Od=s=>It(r=>s?r.directories.get(s)?.isGitRepo??null:null),ig=s=>It(r=>s?r.directories.get(s)?.status?.files?.length??0:0);function qt({...s}){return e.jsx(pm,{"data-slot":"dropdown-menu",...s})}function Kt({...s}){return e.jsx(hm,{"data-slot":"dropdown-menu-trigger",...s})}function Yt({className:s,sideOffset:r=4,...t}){return e.jsx(gm,{children:e.jsx(xm,{"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 St({className:s,inset:r,variant:t="default",...n}){return e.jsx(vm,{"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 lg({...s}){return e.jsx(ym,{"data-slot":"dropdown-menu-radio-group",...s})}function cg({className:s,children:r,...t}){return e.jsxs(bm,{"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(wm,{children:e.jsx(Dt,{className:"size-3"})})}),r]})}function Wr({className:s,inset:r,...t}){return e.jsx(Sm,{"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(jm,{"data-slot":"dropdown-menu-separator",className:O("bg-border -mx-1 my-0.5 h-px",s),...r})}const dg={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 xi(s){return dg[s]||{displayName:s.charAt(0).toUpperCase()+s.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function ug(s,r,t){const n=xi(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 mg=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function _d(s){const r=s.split(".").pop()?.toLowerCase();return mg.includes(r||"")}function fg(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 pg(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 yi=l.createContext(null),Tr=()=>{const s=l.useContext(yi);if(!s)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return s},Bd=s=>{const r=Tr();return s(r)},hg=()=>Bd(s=>s.runtime.isDesktop),zd=()=>Bd(s=>s.runtime.isVSCode),gg=Nm("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?Xc:"button";return e.jsx(a,{"data-slot":"button",className:O(gg({variant:r,size:t,className:s})),...o})}const xg=({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(km,{className:"h-3 w-3"}):e.jsx(Cm,{className:"h-3 w-3"})})},bi=Ne.createContext(void 0);function Fr(){const s=Ne.useContext(bi);if(!s)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return s}function _o(){return Ne.useContext(bi)}const yg="Flexoki",bg="dark",wg={"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"},vg=[{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"}}],jg={name:yg,type:bg,colors:wg,tokenColors:vg},Sg="Flexoki",Ng="light",kg={"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"},Cg=[{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"}}],Mg={name:Sg,type:Ng,colors:kg,tokenColors:Cg},wi="flexoki-dark",vi="flexoki-light",Dg=jg,Ag=Mg;function Hd(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 Ud(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 ji=Ud(Dg,wi,"dark"),Si=Ud(Ag,vi,"light");Hd(ji,wi);Hd(Si,vi);const Yr={dark:wi,light:vi},Nl=[Si,ji];let kl=!1;function Wd(){kl||(zi(Yr.dark,async()=>ji),zi(Yr.light,async()=>Si),kl=!0)}const Eg=`
|
|
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 Ig(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 Cl=({original:s,modified:r,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const c=_o()?.currentTheme?.metadata?.variant==="dark";Wd();const d=Ne.useRef(null),u=Ne.useMemo(()=>{const f=Ig(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}`},b=Ia(p,h);return d.current={key:f,fileDiff:b},b},[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:Eg}),[c,o,a]);return typeof window>"u"?null:e.jsx(tt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(Mm,{fileDiff:u,options:m})})},Tg=1100,Fg=s=>{const{index:r,working_dir:t}=s;return r==="A"||t==="A"||r==="?"||t==="?"},Ml=(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]})},Pg=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(qt,{children:[e.jsx(Kt,{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)}),Ml(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Nt,{className:"size-4 opacity-50"})]})}),e.jsx(Yt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(lg,{value:r??"",onValueChange:n,children:s.map(i=>e.jsx(cg,{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:Ml(i.insertions,i.deletions)})]})},i.path))})})]})}),Rg=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"}})]})]})})}),Lg=l.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=l.useMemo(()=>Ir(s)||"text",[s]);return _d(s)?e.jsx(Rg,{filePath:s,diff:r,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(Cl,{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(Cl,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})})}),$g=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(Lg,{filePath:r,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),Og=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=pe(),{currentDirectory:n}=ht(),o=s?t.get(s)??void 0:void 0,i=r.find(c=>c.id===s)?.directory;return o?.path??i??n??void 0},_g=()=>{const{git:s}=Tr(),r=Og(),{screenWidth:t,isMobile:n}=Ct(),o=Od(r??null),a=$d(r??null),i=It(F=>F.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=It(),[m,f]=l.useState(null),[p,h]=l.useState(0),[b,g]=l.useState(null),y=l.useRef(null),x=Fe(F=>F.pendingDiffFile),w=Fe(F=>F.setPendingDiffFile),S=Fe(F=>F.diffLayoutPreference),k=Fe(F=>F.diffFileLayout),j=Fe(F=>F.setDiffFileLayout),N=Fe(F=>F.diffWrapLines),L=Fe(F=>F.setDiffWrapLines),D=n||N,M=l.useMemo(()=>{if(!a?.files)return[];const F=a.diffStats??{};return a.files.map(B=>({...B,insertions:F[B.path]?.insertions??0,deletions:F[B.path]?.deletions??0,isNew:Fg(B)})).sort((B,T)=>B.path.localeCompare(T.path))},[a]),v=l.useMemo(()=>m?M.find(F=>F.path===m)??null:null,[M,m]),C=l.useMemo(()=>{if(!v)return null;const F=k[v.path];if(F)return F;if(S==="inline")return"inline";if(S==="side-by-side")return"side-by-side";const B=t<Tg;return v.isNew||B?"inline":"side-by-side"},[v,k,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),w(null))},[x,w]),l.useEffect(()=>{!m&&!x&&M.length>0&&f(M[0].path)},[M,m,x]),l.useEffect(()=>{m&&M.length>0&&(M.some(B=>B.path===m)||f(M[0]?.path??null))},[M,m]);const A=l.useCallback(F=>{f(F)},[]),P=(C??"side-by-side")==="side-by-side",$=It(l.useCallback(F=>!r||!m?null:F.directories.get(r)?.diffCache.get(m)??null,[r,m])),R=!!$,H=!!m&&!R;l.useEffect(()=>{if(g(null),!r||!m){y.current=null;return}if($){y.current=null;return}const F=`${r}::${m}::${p}`;if(y.current===F)return;y.current=F;let B=!1;return(async()=>{try{const T=s.getGitFileDiff(r,{path:m}),V=15e3,X=new Promise((ae,xe)=>{setTimeout(()=>xe(new Error(`Timed out after ${V}ms`)),V)}),fe=await Promise.race([T,X]);if(B)return;u(r,m,{original:fe.original??"",modified:fe.modified??""})}catch(T){if(B)return;const V=T instanceof Error?T.message:String(T);g(V)}})(),()=>{B=!0,y.current===F&&(y.current=null)}},[r,m,$,s,u,p]);const U=()=>!r||M.length===0?null:M.map(F=>e.jsx($g,{directory:r,filePath:F.path,isVisible:F.path===m,renderSideBySide:P,wrapLines:D},F.path)),Y=()=>r?i&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(es,{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:[U(),H&&!R&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:b?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:b}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{g(null),h(F=>F+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{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(ti,{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(Pg,{changedFiles:M,selectedFile:m,selectedFileEntry:v,onSelectFile:A,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),v&&e.jsx("button",{type:"button",onClick:()=>L(!N),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${D?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:D?"Disable line wrap":"Enable line wrap",children:e.jsx(Dm,{className:"size-4"})}),v&&C&&e.jsx(xg,{mode:C==="side-by-side"?"side-by-side":"unified",onModeChange:F=>{if(!v)return;const B=F==="side-by-side"?"side-by-side":"inline";j(v.path,B)}})]}),Y()]})},Bg=()=>{const{git:s}=Tr(),{currentSessionId:r,sessions:t,worktreeMetadata:n}=pe(),{currentDirectory:o}=ht(),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=ig(d??null);return l.useEffect(()=>{d&&(u(d),It.getState().directories.get(d)?.status||m(d,s))},[d,u,m,s]),f},zg=()=>{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(To,{className:"h-5 w-5"})})})},Dl=()=>{const s=Fe(T=>T.setSessionSwitcherOpen),r=Fe(T=>T.toggleSidebar),t=Fe(T=>T.setSettingsDialogOpen),n=Fe(T=>T.toggleCommandPalette),o=Fe(T=>T.toggleHelpDialog),a=Fe(T=>T.isSidebarOpen),i=Fe(T=>T.sidebarWidth),c=Fe(T=>T.activeMainTab),d=Fe(T=>T.setActiveMainTab),{getCurrentModel:u}=ut(),m=pe(T=>T.getContextUsage),{isMobile:f}=Ct(),p=Bg(),h=$o(T=>T.available),b=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 T=typeof window.opencodeDesktop<"u";y(T)},[]);const w=u(),S=w&&typeof w.limit=="object"&&w.limit!==null?w.limit:null,k=S&&typeof S.context=="number"?S.context:0,j=S&&typeof S.output=="number"?S.output:0,N=m(k,j),L=Fe(T=>T.isSessionSwitcherOpen),D=l.useCallback(()=>{if(typeof document>"u")return;const T=document.activeElement;if(!T)return;const V=T.tagName;(V==="INPUT"||V==="TEXTAREA"||V==="SELECT"||T.isContentEditable)&&T.blur()},[]),M=l.useCallback(()=>{if(f){D(),s(!L);return}r()},[D,f,L,s,r]),v=l.useCallback(()=>{f&&D(),s(!1),t(!0)},[D,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",A=l.useMemo(()=>g&&x?a?"pl-0":"pl-[8.0rem]":"pl-3",[g,x,a]),P=l.useCallback(()=>{if(typeof document>"u")return;const T=b.current?.getBoundingClientRect().height;T&&document.documentElement.style.setProperty("--oc-header-height",`${T}px`)},[]);Ne.useEffect(()=>{if(typeof window>"u")return;P();const T=b.current;if(!T||typeof ResizeObserver>"u")return()=>{};const V=new ResizeObserver(()=>{P()});return V.observe(T),window.addEventListener("resize",P),window.addEventListener("orientationchange",P),()=>{V.disconnect(),window.removeEventListener("resize",P),window.removeEventListener("orientationchange",P)}},[P]),Ne.useEffect(()=>{P()},[P,f]);const $=l.useCallback(async T=>{if(!T.target.closest("button, a, input, select, textarea")&&T.button===0&&g)try{const{getCurrentWindow:V}=await Jt(async()=>{const{getCurrentWindow:fe}=await import("./vendor-.bun-B7CnnRlj.js").then(ae=>ae.cb);return{getCurrentWindow:fe}},__vite__mapDeps([0,1]));await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[g]),R=l.useCallback(async T=>{if(T.button===0&&g)try{const{getCurrentWindow:V}=await Jt(async()=>{const{getCurrentWindow:fe}=await import("./vendor-.bun-B7CnnRlj.js").then(ae=>ae.cb);return{getCurrentWindow:fe}},__vite__mapDeps([0,1]));await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[g]),H=l.useMemo(()=>[{id:"chat",label:"Chat",icon:Am},{id:"diff",label:"Diff",icon:Gs,badge:!f&&p>0?p:void 0},{id:"terminal",label:"Terminal",icon:mr},{id:"git",label:"Git",icon:Ft,showDot:f&&p>0}],[p,f]);Ne.useEffect(()=>{const T=V=>{if(hs(V)&&!V.shiftKey&&!V.altKey){const X=parseInt(V.key,10);X>=1&&X<=H.length&&(V.preventDefault(),d(H[X-1].id))}};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[H,d]);const U=(T,V)=>{const X=c===T.id,fe=T.icon,ae=T.id==="chat",xe=T.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(T.id),onMouseDown:X?R:void 0,className:O("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",X?"app-region-drag":"app-region-no-drag","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",X?"text-foreground":"text-muted-foreground",X&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",X&&ae&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",ae&&!(g&&x&&a)&&"border-l",xe&&"border-r",ae&&!f&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...X&&ae&&a?{"--sidebar-w":g&&x?`${i}px`:"64px"}:{},...ae&&!(g&&x&&a)||xe?{borderColor:"var(--interactive-border)"}:{}},"aria-label":T.label,"aria-selected":X,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:T.label})]}),ae&&!f&&N&&N.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(za,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact"})}),T.badge!==void 0&&T.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:T.badge})]}),!V&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},T.id)},Y=()=>e.jsxs("div",{onMouseDown:$,className:O("app-region-drag relative flex h-12 select-none items-center",A),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(To,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:H.map((T,V)=>U(T,V===H.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(),"+.)"]})})]})]})]}),F=()=>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(Em,{className:"h-5 w-5"})}),N&&N.totalTokens>0&&c==="chat"&&e.jsx(za,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact",isMobile:!0})]}),e.jsxs("div",{className:"app-region-no-drag flex items-center gap-1.5",children:[e.jsx("div",{className:"flex items-center",role:"tablist","aria-label":"Main navigation",children:H.map(T=>{const V=c===T.id,X=T.icon;return e.jsxs(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{f&&D(),d(T.id)},"aria-label":T.label,"aria-selected":V,role:"tab",className:O(C,"relative",V&&"text-foreground"),children:[e.jsx(X,{className:"h-5 w-5"}),T.badge!==void 0&&T.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:T.badge}),T.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:T.label})})]},T.id)})}),e.jsxs(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:v,"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"})})]})]})]}),B=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:b,className:B,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:f?F():Y()})};function Ni({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 Vd({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 Gd({className:s,...r}){return e.jsx("div",{"data-slot":"card-title",className:O("leading-none font-semibold",s),...r})}function qd({className:s,...r}){return e.jsx("div",{"data-slot":"card-content",className:O("px-6",s),...r})}class Wt 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(Ni,{className:"w-full max-w-md",children:[e.jsx(Vd,{className:"text-center",children:e.jsxs(Gd,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Ta,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(qd,{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 Wn=0;function as({...s}){return e.jsx(Im,{"data-slot":"dialog",...s})}function Hg({...s}){return e.jsx(Pm,{"data-slot":"dialog-portal",...s})}const Kd=Ne.forwardRef(({className:s,...r},t)=>(Ne.useEffect(()=>(Wn+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Wn=Math.max(0,Wn-1),Wn===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(Qc,{ref:t,"data-slot":"dialog-overlay",className:O("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",s),...r})));Kd.displayName=Qc.displayName;function is({className:s,children:r,showCloseButton:t=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Hg,{"data-slot":"dialog-portal",children:[e.jsx(Kd,{className:"rounded-none"}),e.jsxs(Tm,{"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(Fm,{"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(Vt,{}),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 Ks({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(Rm,{"data-slot":"dialog-title",className:O("typography-markdown leading-none font-semibold text-foreground",s),...r})}function Ss({className:s,...r}){return e.jsx(Lm,{"data-slot":"dialog-description",className:O("text-muted-foreground typography-ui-label",s),...r})}const Al="https://github.com/btriapitsyn/openchamber/releases";async function Ug(){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 Wg(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 Ha=({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"),[b,g]=Ne.useState(null),y=t?.version?`${Al}/tag/v${t.version}`:Al,x=a?.total?Math.round(a.downloaded/a.total*100):0,w=u==="web",S=t?.updateCommand||"openchamber update";Ne.useEffect(()=>{s||(h("idle"),g(null))},[s]);const k=async()=>{try{await navigator.clipboard.writeText(S),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},j=Ne.useCallback(async()=>{h("updating"),g(null);const L=await Ug();if(!L.success){h("error"),g(L.error||"Update failed");return}h("restarting"),await new Promise(M=>setTimeout(M,2e3)),h("reconnecting"),await Wg()?window.location.reload():(h("error"),g("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),N=p!=="idle"&&p!=="error";return e.jsx(as,{open:s,onOpenChange:N?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($m,{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})]}),w&&N&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(eo,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"text-sm",children:[p==="updating"&&"Installing update...",p==="restarting"&&"Server restarting...",p==="reconnecting"&&"Waiting for server..."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),t?.body&&!N&&e.jsx(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((L,D)=>/^\d+\.\d+\.\d+$/.test(L.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",L.trim(),`
|
|
58
|
-
`]},D):L.replace(/^- /gm,"• ").trim()+`
|
|
59
|
-
|
|
60
|
-
`)})}),w&&p==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Om,{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:k,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(_m,{className:"h-4 w-4"})})]})]}),!w&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[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||b)&&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||b})}),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(fo,{className:"h-4 w-4"}),"GitHub"]}),!w&&!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"]}),!w&&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(eo,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!w&&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"]}),w&&!N&&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"]}),w&&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(eo,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},El=264,Il=200,Tl=500,Vg=40,Fl="openchamber:check-for-updates",Gg=({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||El),[f,p]=l.useState(!1),h=$o(),b=l.useRef(!1),g=h.checkForUpdates,{available:y,downloaded:x,checking:w}=h,[S,k]=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 v=typeof window.opencodeDesktop<"u";k(v)},[]),l.useEffect(()=>{if(typeof window>"u")return;const v=()=>{typeof window.opencodeDesktop<"u"&&(b.current=!0,g())};return window.addEventListener(Fl,v),()=>{window.removeEventListener(Fl,v)}},[g]),l.useEffect(()=>{b.current&&(w||(y||x?p(!0):se.success("No updates available",{description:"You are running the latest version."}),b.current=!1))},[y,x,w]),l.useEffect(()=>{if(r||!c)return;const v=A=>{const P=A.clientX-u.current,$=Math.min(Tl,Math.max(Il,m.current+P));o($)},C=()=>{d(!1)};return window.addEventListener("pointermove",v),window.addEventListener("pointerup",C,{once:!0}),()=>{window.removeEventListener("pointermove",v),window.removeEventListener("pointerup",C)}},[r,c,o]),l.useEffect(()=>{r&&c&&d(!1)},[r,c]);const N=l.useCallback(async v=>{if(v.button===0&&S)try{const{getCurrentWindow:C}=await Jt(async()=>{const{getCurrentWindow:P}=await import("./vendor-.bun-B7CnnRlj.js").then($=>$.cb);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 L=s?Math.min(Tl,Math.max(Il,n||El)):0,D=S&&j,M=v=>{s&&(d(!0),u.current=v.clientX,m.current=L,v.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:`${L}px`,minWidth:`${L}px`,maxWidth:`${L}px`,pointerEvents:s?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!s||L===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:`${L}px`,overflowX:"hidden"},"aria-hidden":!s,children:[D&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${Vg}px`},onMouseDown:N,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Wt,{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(Ut,{className:"h-4 w-4"})})}),e.jsx(Ye,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Ha,{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 Yd({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 qg({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(Ss,{children:r})]}),e.jsx(is,{className:O("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Yd,{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 Xd({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(sr,{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 Qd({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 Jd({...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 No({className:s,...r}){return e.jsx(Ar.Separator,{"data-slot":"command-separator",className:O("bg-border -mx-1 h-px",s),...r})}function Bt({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 Xs({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(In,{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 Kg=()=>{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}=pe(),{currentDirectory:p}=ht(),{themeMode:h,setThemeMode:b}=Fr(),g=()=>{r(!1)},y=async()=>{o("chat"),i(!1),u(),g()},x=R=>{m(R),g()},w=R=>{b(R),g()},S=()=>{t(!0),g()},k=()=>{n(!0),g()},{isMobile:j}=Ct(),N=()=>{if(j){const{isSessionSwitcherOpen:R}=Fe.getState();i(!R)}else d();g()},L=()=>{o("diff"),g()},D=()=>{o("git"),g()},M=()=>{o("terminal"),g()},v=()=>{a(!0),g()},C=()=>{gn(),g()},A=()=>{c(!0),g()},P=f(p??""),$=l.useMemo(()=>P.slice(0,5),[P]);return e.jsxs(qg,{open:s,onOpenChange:r,children:[e.jsx(Xd,{placeholder:"Type a command or search..."}),e.jsxs(Qd,{children:[e.jsx(Jd,{children:"No results found."}),e.jsxs(Vr,{heading:"Actions",children:[e.jsxs(Bt,{onSelect:N,children:[e.jsx(To,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(Xs,{children:[ss()," + L"]})]}),e.jsxs(Bt,{onSelect:y,children:[e.jsx(Gt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsxs(Xs,{children:[ss()," + N"]})]}),e.jsxs(Bt,{onSelect:k,children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsxs(Xs,{children:["Shift + ",ss()," + N"]})]}),e.jsxs(Bt,{onSelect:S,children:[e.jsx(Gr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(Xs,{children:[ss()," + ."]})]}),e.jsxs(Bt,{onSelect:L,children:[e.jsx(Gs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(Xs,{children:[ss()," + 2"]})]}),e.jsxs(Bt,{onSelect:M,children:[e.jsx(mr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(Xs,{children:[ss()," + 3"]})]}),e.jsxs(Bt,{onSelect:D,children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(Xs,{children:[ss()," + 4"]})]}),e.jsxs(Bt,{onSelect:A,children:[e.jsx(qs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(Xs,{children:[ss()," + T"]})]}),e.jsxs(Bt,{onSelect:v,children:[e.jsx(Cr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(Xs,{children:[ss()," + ,"]})]}),e.jsxs(Bt,{onSelect:C,children:[e.jsx(xs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(No,{}),e.jsxs(Vr,{heading:"Theme",children:[e.jsxs(Bt,{onSelect:()=>w("light"),children:[e.jsx(Bm,{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(Bt,{onSelect:()=>w("dark"),children:[e.jsx(zm,{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(Bt,{onSelect:()=>w("system"),children:[e.jsx(Jc,{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"})]})]}),$.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(No,{}),e.jsx(Vr,{heading:"Recent Sessions",children:$.map(R=>e.jsxs(Bt,{onSelect:()=>x(R.id),children:[e.jsx(si,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:R.title||"Untitled Session"})]},R.id))})]})]})]})},Yg=(s,r)=>{const t=s.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(Fo,{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}`)},Xg=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:"+"}),Yg(t,n)]},`${t}-${n}`))},Qg=()=>{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:To},{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:Ft},{keys:[`${t} + I`],description:"Focus Chat Input",icon:Zc},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Kr}]},{category:"Interface",items:[{keys:[`${t} + /`],description:"Cycle Theme (Light → Dark → System)",icon:Hm},{keys:[`${t} + 2`],description:"Open Diff Panel",icon:Gs},{keys:[`${t} + 3`],description:"Open Terminal",icon:mr},{keys:[`${t} + 4`],description:"Open Git Panel",icon:Ft},{keys:[`${t} + T`],description:"Open Timeline",icon:qs},{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(Ss,{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:Xg(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"})]})]})]})})]})})},la=new Set,ca=new Set,da=new Set,vr={onDeleteRequest(s){return la.add(s),()=>{la.delete(s)}},requestDelete(s){!s.sessions.length&&s.mode!=="worktree"||la.forEach(r=>r(s))},onCreateRequest(s){return ca.add(s),()=>{ca.delete(s)}},requestCreate(s){const r=s??{};ca.forEach(t=>t(r))},onDirectoryRequest(s){return da.add(s),()=>{da.delete(s)}},requestDirectoryDialog(){da.forEach(s=>s())}};function Zd(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 Jg=".openchamber",Pl="oc.sessions.groupCollapse",Rl="oc.sessions.expandedParents",Ll=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(",","")},Js=s=>{if(!s)return null;const r=s.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},Zg=(s,r)=>{const t=Js(s),n=Array.from(r.values())[0];if(n?.projectDirectory)return Js(n.projectDirectory);if(!t)return null;const o=`/${Jg}`,a=t.indexOf(o);return a>0?t.slice(0,a):t},Ua=({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),[b,g]=l.useState(()=>new Map),y=l.useRef(new Set),x=l.useMemo(()=>ls(),[]),[w,S]=l.useState(new Set),[k,j]=l.useState(null),[N,L]=l.useState(new Set),[D,M]=l.useState(null),[v,C]=l.useState(new Set),A=l.useRef(new Map),P=ht(Z=>Z.currentDirectory),$=ht(Z=>Z.homeDirectory),R=ht(Z=>Z.setDirectory),H=Fe(Z=>Z.setActiveMainTab),U=Fe(Z=>Z.setSessionSwitcherOpen),Y=Fe(Z=>Z.openMultiRunLauncher),F=pe(Z=>Z.getSessionsByDirectory),B=pe(Z=>Z.currentSessionId),T=pe(Z=>Z.setCurrentSession),V=pe(Z=>Z.updateSessionTitle),X=pe(Z=>Z.shareSession),fe=pe(Z=>Z.unshareSession),ae=pe(Z=>Z.sessionMemoryState),xe=pe(Z=>Z.sessionActivityPhase),Me=pe(Z=>Z.worktreeMetadata),Q=pe(Z=>Z.availableWorktrees),re=pe(Z=>Z.openNewSessionDraft),[oe,W]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{try{const Z=x.getItem(Pl);if(Z){const ne=JSON.parse(Z);Array.isArray(ne)&&S(new Set(ne.filter(ie=>typeof ie=="string")))}const De=x.getItem(Rl);if(De){const ne=JSON.parse(De);Array.isArray(ne)&&h(new Set(ne.filter(ie=>typeof ie=="string")))}}catch{}},[x]),l.useEffect(()=>{typeof window>"u"||W(typeof window.opencodeDesktop<"u")},[]);const me=F(P),ye=l.useMemo(()=>[...me].sort((Z,De)=>(De.time?.created||0)-(Z.time?.created||0)),[me]);l.useEffect(()=>{if(!P){j(null);return}let Z=!1;return rn(P).then(De=>{Z||j(De)}).catch(()=>{Z||j(null)}),()=>{Z=!0}},[P]);const ce=l.useMemo(()=>new Map(ye.map(Z=>[Z.id,Z])),[ye]),Ce=l.useMemo(()=>{const Z=new Map;return ye.forEach(De=>{const ne=De.parentID;ne&&Z.set(De.id,ne)}),Z},[ye]),Ee=l.useMemo(()=>{const Z=new Map;return ye.forEach(De=>{const ne=De.parentID;if(!ne)return;const ie=Z.get(ne)??[];ie.push(De),Z.set(ne,ie)}),Z.forEach(De=>De.sort((ne,ie)=>(ie.time?.created||0)-(ne.time?.created||0))),Z},[ye]);l.useEffect(()=>{B&&h(Z=>{const De=new Set(Z);let ne=Ce.get(B)||null,ie=!1;for(;ne;)De.has(ne)||(De.add(ne),ie=!0),ne=Ce.get(ne)||null;return ie?De:Z})},[B,Ce]);const Pe=l.useMemo(()=>Zg(P,Me),[P,Me]);l.useEffect(()=>{const Z=new Set;ye.forEach(De=>{const ne=Js(De.directory??null);ne&&Z.add(ne)}),Pe&&Z.add(Pe),Z.forEach(De=>{const ne=b.get(De);ne&&ne!=="unknown"||y.current.has(De)||(y.current.add(De),Re.listLocalDirectory(De).then(()=>{g(ie=>{const Ie=new Map(ie);return Ie.get(De)==="exists"?ie:(Ie.set(De,"exists"),Ie)})}).catch(()=>{g(ie=>{const Ie=new Map(ie);return Ie.get(De)==="missing"?ie:(Ie.set(De,"missing"),Ie)})}).finally(()=>{y.current.delete(De)}))})},[ye,Pe,b]),l.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const G=l.useMemo(()=>Ko(P,$),[P,$]),K=l.useMemo(()=>fs(P,$),[P,$]),I=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."})]}),J=l.useCallback((Z,De)=>{if(!De){if(s&&(H("chat"),U(!1)),!t&&Z===B){r?.(Z);return}T(Z),r?.(Z)}},[t,B,s,r,H,T,U]),E=l.useCallback(async()=>{a&&c.trim()&&(await V(a,c.trim()),i(null),d(""))},[a,c,V]),z=l.useCallback(()=>{i(null),d("")},[]),q=l.useCallback(async Z=>{const De=await X(Z.id);De&&De.share?.url?se.success("Session shared",{description:"You can copy the link from the menu."}):se.error("Unable to share session")},[X]),be=l.useCallback((Z,De)=>{navigator.clipboard.writeText(Z).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")})},[]),ee=l.useCallback(async Z=>{await fe(Z)?se.success("Session unshared"):se.error("Unable to unshare session")},[fe]),he=l.useCallback(Z=>{const De=[],ne=ie=>{(Ee.get(ie)??[]).forEach(_e=>{De.push(_e),ne(_e.id)})};return ne(Z),De},[Ee]),He=pe(Z=>Z.deleteSession),We=pe(Z=>Z.deleteSessions),Be=l.useCallback(async Z=>{const De=he(Z.id);if(De.length===0)await He(Z.id)?se.success("Session deleted"):se.error("Failed to delete session");else{const ne=[Z.id,...De.map(_e=>_e.id)],{deletedIds:ie,failedIds:Ie}=await We(ne);ie.length>0&&se.success(`Deleted ${ie.length} session${ie.length===1?"":"s"}`),Ie.length>0&&se.error(`Failed to delete ${Ie.length} session${Ie.length===1?"":"s"}`)}},[he,He,We]),Ze=l.useCallback(Z=>{H("chat"),s&&U(!1),re({directoryOverride:Z??null})},[re,H,U,s]),lt=l.useCallback(()=>{vr.requestCreate({worktreeMode:"create"})},[]),ct=l.useCallback(()=>{oe&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(Z=>{Z.success&&Z.path?R(Z.path,{showOverlay:!0}):Z.error&&Z.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:Z.error})}).catch(Z=>{console.error("Desktop: Error selecting directory:",Z),se.error("Failed to select directory")}):vr.requestDirectoryDialog()},[oe,R]),dt=l.useCallback(Z=>{h(De=>{const ne=new Set(De);ne.has(Z)?ne.delete(Z):ne.add(Z);try{x.setItem(Rl,JSON.stringify(Array.from(ne)))}catch{}return ne})},[x]),mt=l.useCallback(Z=>{const De=Ee.get(Z.id)??[];return{session:Z,children:De.map(ne=>mt(ne))}},[Ee]),yt=l.useMemo(()=>{const Z=new Map,De=Js(Pe??null),ne=new Map,ie=new Set;Q.forEach(ze=>{if(ze.path){const Ge=Js(ze.path)??ze.path;ie.add(Ge),ne.set(Ge,ze)}});const Ie=ze=>{const Ge=Js(ze.directory??null),rt=Me.get(ze.id),ue=((rt?.path?ie.has(Js(rt.path)??rt.path):!1)?rt:null)??(Ge?ne.get(Ge)??null:null),je=!ue&&(Ge&&De?Ge===De:!Ge&&!!De),ke=je?"main":ue?.path??Ge??ze.id,Te=ue?.path??Ge??De??null;if(!Z.has(ke)){const Ue=je?"Main workspace":ue?.label||ue?.branch||Ko(Te||"",$)||"Worktree",wt=ue?.relativePath?fs(ue.relativePath,$):Te?fs(Te,$):null;Z.set(ke,{id:ke,label:Ue,description:wt,isMain:je,worktree:ue,directory:Te,sessions:[]})}return Z.get(ke)};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)}),Z.has("main")||Z.set("main",{id:"main",label:"Main workspace",description:De?fs(De,$):null,isMain:!0,worktree:null,directory:De,sessions:[]}),ne.forEach((ze,Ge)=>{const rt=ze.path;Z.has(rt)||Z.set(rt,{id:rt,label:ze.label||ze.branch||Ko(Ge,$)||"Worktree",description:ze.relativePath?fs(ze.relativePath,$):fs(Ge,$),isMain:!1,worktree:ze,directory:Ge,sessions:[]})}),Z.forEach(ze=>{ze.sessions.sort((Ge,rt)=>(rt.session.time?.created||0)-(Ge.session.time?.created||0))}),Array.from(Z.values()).sort((ze,Ge)=>ze.isMain!==Ge.isMain?ze.isMain?-1:1:(ze.label||"").localeCompare(Ge.label||""))},[ye,Me,Q,Pe,$,mt,ce]),vt=l.useCallback(Z=>{S(De=>{const ne=new Set(De);ne.has(Z)?ne.delete(Z):ne.add(Z);try{x.setItem(Pl,JSON.stringify(Array.from(ne)))}catch{}return ne})},[x]),gt=l.useCallback(Z=>{L(De=>{const ne=new Set(De);return ne.has(Z)?ne.delete(Z):ne.add(Z),ne})},[]);l.useEffect(()=>{if(!oe)return;const Z=new IntersectionObserver(De=>{De.forEach(ne=>{const ie=ne.target.dataset.groupId;ie&&C(Ie=>{const _e=new Set(Ie);return ne.isIntersecting?_e.delete(ie):_e.add(ie),_e})})},{threshold:0});return A.current.forEach(De=>{De&&Z.observe(De)}),()=>Z.disconnect()},[oe,yt]);const bt=l.useCallback((Z,De=0,ne)=>{const ie=Z.session,Ie=Js(ie.directory??null)??Js(ne??null),ze=(Ie?b.get(Ie):null)==="missing",Ge=ae.get(ie.id),rt=B===ie.id,le=ie.title||"Untitled Session",ue=Z.children.length>0,je=p.has(ie.id),ke=ie.summary?.additions,Te=ie.summary?.deletions,Ue=typeof ke=="number"||typeof Te=="number";if(a===ie.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(),E()},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"&&z()}}),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:z,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Vt,{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:je?e.jsx(Nt,{className:"h-3 w-3"}):e.jsx(Es,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Ll(ie.time?.created||Date.now())}),ie.share?e.jsx(Go,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Ue&&((ke??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,ke??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:[Z.children.length," ",Z.children.length===1?"task":"tasks"]}):null]})]})},ie.id);const wt=xe?.get(ie.id)??"idle",At=wt==="busy"||wt==="cooldown",Mt=Ge&&Ge.isZombie?e.jsx(Ta,{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:()=>J(ie.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:le})}),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(),dt(ie.id)},onKeyDown:pt=>{(pt.key==="Enter"||pt.key===" ")&&(pt.preventDefault(),pt.stopPropagation(),dt(ie.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":je?"Collapse subsessions":"Expand subsessions",children:je?e.jsx(Nt,{className:"h-3 w-3"}):e.jsx(Es,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Ll(ie.time?.created||Date.now())}),ie.share?e.jsx(Go,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Ue&&((ke??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,ke??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:[Z.children.length," ",Z.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(Ta,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Mt,e.jsxs(qt,{children:[e.jsx(Kt,{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(Zr,{className:s?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(St,{onClick:()=>{i(ie.id),d(le)},className:"[&>svg]:mr-1",children:[e.jsx(Zs,{className:"mr-1 h-4 w-4"}),"Rename"]}),ie.share?e.jsxs(e.Fragment,{children:[e.jsx(St,{onClick:()=>{ie.share?.url&&be(ie.share.url,ie.id)},className:"[&>svg]:mr-1",children:u===ie.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(Ys,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(St,{onClick:()=>ee(ie.id),className:"[&>svg]:mr-1",children:[e.jsx(Um,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(St,{onClick:()=>q(ie),className:"[&>svg]:mr-1",children:[e.jsx(Go,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(St,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Be(ie),children:[e.jsx(Ls,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),ue&&je?Z.children.map(pt=>bt(pt,De+1,Ie??ne)):null]},ie.id)},[b,ae,xe,B,p,a,c,E,z,dt,J,q,be,ee,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:ct,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:G||"/"})})]}),k?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:lt,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(ed,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}),e.jsx("button",{type:"button",onClick:Y,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(Zd,{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:yt.length===0?I:n&&yt.length===1&&yt[0].isMain||o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const Z=yt.find(ze=>ze.isMain)??yt[0],De=n?10:7,ne=Z.sessions.length,ie=N.has(Z.id),Ie=ie?Z.sessions:Z.sessions.slice(0,De),_e=ne-Ie.length;return ne===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=>bt(ze,0,Z.directory)),_e>0&&!ie?e.jsxs("button",{type:"button",onClick:()=>gt(Z.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,ie&&ne>De?e.jsx("button",{type:"button",onClick:()=>gt(Z.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]})})()}):yt.map(Z=>e.jsxs("div",{className:"relative",children:[oe&&e.jsx("div",{ref:De=>{A.current.set(Z.id,De)},"data-group-id":Z.id,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("button",{type:"button",onClick:()=>vt(Z.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?v.has(Z.id)?"bg-sidebar":"bg-transparent":"bg-sidebar"),style:{borderColor:D===Z.id?"var(--color-border)":w.has(Z.id)?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>M(Z.id),onMouseLeave:()=>M(null),"aria-label":w.has(Z.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:Z.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(Z.directory)},onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.stopPropagation(),Ze(Z.directory))},children:e.jsx(Gt,{className:"h-4.5 w-4.5"})})]})}),w.has(Z.id)?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const De=N.has(Z.id),ne=n?10:7,ie=Z.sessions.length,Ie=De?Z.sessions:Z.sessions.slice(0,ne),_e=ie-Ie.length;return e.jsxs(e.Fragment,{children:[Ie.map(ze=>bt(ze,0,Z.directory)),ie===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:()=>gt(Z.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&&ie>ne?e.jsx("button",{type:"button",onClick:()=>gt(Z.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]})})()})]},Z.id))})]})};function it({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(Wm,{"data-slot":"select",...s})}function jr({...s}){return e.jsx(Qm,{"data-slot":"select-group",...s})}function ko({...s}){return e.jsx(qm,{"data-slot":"select-value",...s})}function Ps({className:s,size:r="default",children:t,...n}){return e.jsxs(Vm,{"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(Gm,{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(Km,{children:e.jsx(Ym,{"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:Xm,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(Jm,{"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(Zm,{"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(ef,{children:e.jsx(Dt,{className:"size-4"})})}),e.jsx(tf,{children:r})]})}function Co({className:s,...r}){return e.jsx(sf,{"data-slot":"select-separator",className:O("bg-border pointer-events-none -mx-1 my-1 h-px",s),...r})}function ki({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,b=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(b).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 eu=()=>{const[s,r]=Ne.useState(!1);Ne.useEffect(()=>{r(Xt())},[]);const t=Ne.useCallback(async a=>s?await cp(a):{success:!0,path:a},[s]),n=Ne.useCallback(async a=>s?await dp(a):{success:!0},[s]),o=Ne.useCallback(async a=>s?await up(a):{success:!0},[s]);return{isDesktop:s,requestAccess:t,startAccessing:n,stopAccessing:o}},$l=({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(()=>Xt(),[]),[p,h]=l.useState([]),[b,g]=l.useState(new Set),[y,x]=l.useState(!0),[w,S]=l.useState(!1),[k,j]=l.useState(""),[N,L]=l.useState(new Set),[D,M]=l.useState(null),[v,C]=l.useState(""),[A,P]=l.useState(!0),$=l.useRef(null),{requestAccess:R,startAccessing:H,isDesktop:U}=eu(),Y=l.useRef(c),F=l.useCallback(G=>{if(!G)return G;if(G==="/"||G.length===0)return"/";let K=G;for(;K.length>1&&K.endsWith("/");)K=K.slice(0,-1);return K.length===0?"/":K},[]),B=l.useMemo(()=>{if(!k)return null;const G=k.replace(/\\/g,"/");return F(G)},[k,F]),T=l.useMemo(()=>{if(typeof d=="string"&&d.length>0){const G=d.replace(/\\/g,"/"),K=F(G);if(K&&K!=="/")return K}return B&&B!=="/"?B:null},[d,B,F]),V=l.useMemo(()=>typeof u=="boolean"?!!(u&&T):!!T,[u,T]);l.useEffect(()=>{V||(x(!0),h([]))},[V]);const X=l.useCallback(G=>{if(!G||!V||!T)return!1;const K=G.replace(/\\/g,"/"),I=F(K)??K;if(I===T)return!0;const J=`${T}/`;return I.startsWith(J)},[V,T,F]),fe=async G=>{if(V){if(a==="deferred"){r(G);return}if(U){const K=await R(G);K.success&&K.path?(await H(K.path),r(K.path)):(console.error("Failed to get directory access:",K.error),r(G))}else r(G)}};l.useEffect(()=>{let G=!1;const K=E=>{if(!E)return!1;const z=F(E.replace(/\\/g,"/"));return!z||z==="/"?!1:(j(typeof z=="string"?z:E.replace(/\\/g,"/")),!0)};return d&&K(d)||(async()=>{try{const E=await Re.getFilesystemHome();if(!G&&K(E))return}catch(E){console.warn("Failed to resolve filesystem home directory:",E)}try{const E=await Re.getSystemInfo();if(!G&&K(E?.homeDirectory))return}catch(E){console.warn("Failed to resolve home directory from system info:",E)}})(),()=>{G=!0}},[d,F]),l.useEffect(()=>{let G=!1;const K=z=>{if(G)return;const q=z.filter(be=>typeof be=="string"&&be.length>0).map(be=>{const ee=be.replace(/\\/g,"/");return F(ee)??ee});L(new Set(q))},I=()=>{try{const z=localStorage.getItem("pinnedDirectories");if(!z)return;const q=JSON.parse(z);Array.isArray(q)&&K(q)}catch(z){console.warn("Failed to load pinned directories from local storage:",z)}},J=async()=>{try{let z=[];if(f){const q=await tn();z=Array.isArray(q?.pinnedDirectories)?q.pinnedDirectories:[]}else{const q=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(q.ok){const be=await q.json();z=Array.isArray(be?.pinnedDirectories)?be.pinnedDirectories:[]}}if(G)return;K(z)}catch(z){console.warn("Failed to load pinned directories:",z)}};I();const E=z=>{const q=z.detail;q&&Array.isArray(q.pinnedDirectories)&&K(q.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",E),J(),()=>{G=!0,window.removeEventListener("openchamber:settings-synced",E)}},[f,F]);const ae=l.useRef(!0);l.useEffect(()=>{if(ae.current){ae.current=!1;return}const G={pinnedDirectories:Array.from(N)};ns(G)},[N]),l.useEffect(()=>{T&&L(G=>{const K=Array.from(G).map(I=>F(I.replace(/\\/g,"/"))??I).filter(I=>X(I));return new Set(K)})},[T,X,F]),l.useEffect(()=>{Y.current!==c&&(Y.current=c,g(new Set))},[c]);const xe=G=>{L(K=>{if(!X(G))return K;const I=F(G.replace(/\\/g,"/"))??G.replace(/\\/g,"/"),J=new Set(K);return J.has(I)?J.delete(I):J.add(I),J})},Me=l.useMemo(()=>Array.from(N).map(G=>F(G.replace(/\\/g,"/"))??G).filter(G=>X(G)).map(G=>({path:G,name:G.split("/").pop()||G})).sort((G,K)=>G.name.localeCompare(K.name)),[N,X,F]),Q=l.useCallback(async G=>{const K=q=>c||!q.startsWith("."),I=T;if(!V||!I)return[];const J=G&&G.length>0?G:I,E=J?J.replace(/\\/g,"/"):null,z=E?F(E)??E:null;if(z){const q=`${I}/`;if(!(z===I||z.startsWith(q)))return[]}try{return(await Re.listLocalDirectory(G)).filter(be=>{if(!be.isDirectory||!K(be.name))return!1;const ee=be.path.replace(/\\/g,"/"),he=F(ee)??ee,He=he===I?I:`${I}/`;return he===I||he.startsWith(He)}).map(be=>({name:be.name,path:be.path.replace(/\\/g,"/"),isDirectory:!0})).sort((be,ee)=>be.name.localeCompare(ee.name))}catch{try{const be=await Re.getApiClient().file.list({path:".",directory:G});return be.data?be.data.filter(ee=>{if(ee.type!=="directory"||!ee.name||!K(ee.name))return!1;const he=String(ee.absolute||ee.path||ee.name).replace(/\\/g,"/"),He=F(he)??he,We=He===I?I:`${I}/`;return He===I||He.startsWith(We)}).map(ee=>({name:ee.name||"",path:String(ee.absolute||ee.path||ee.name).replace(/\\/g,"/"),isDirectory:!0})).filter(ee=>ee.name!=="").sort((ee,he)=>ee.name.localeCompare(he.name)):[]}catch{return[]}}},[c,T,F,V]),re=l.useCallback(async()=>{if(!V||!T){x(!0),h([]);return}x(!0);try{const G=await Q(T);h(G)}catch{}finally{x(!1)}},[V,T,Q]);l.useEffect(()=>{V&&(n==="inline"||w)&&re()},[n,w,V,re]);const oe=async G=>{if(!V)return;const K=b.has(G.path),I=new Set(b);if(K){I.delete(G.path),g(I);return}I.add(G.path),g(I);const J=await Q(G.path),E=z=>z.map(q=>q.path===G.path?{...q,children:J}:q.children?{...q,children:E(q.children)}:q);h(z=>E(z))};l.useEffect(()=>{D&&$.current&&($.current.focus(),$.current.select())},[D]);const W=(G,K=[])=>{const I="new_directory",J=K.map(be=>be.name);if(!J.includes(I))return I;let E=1;const z=new RegExp(`^${I}(\\d+)$`);for(const be of J){const ee=be.match(z);if(ee){const he=parseInt(ee[1],10);he>E&&(E=he)}}let q=2;for(;J.includes(`${I}${q}`);)q++;return`${I}${Math.max(q,E+1)}`},me=async G=>{if(V){if(b.has(G.path)){const K=W(G.path,G.children);C(K)}else{const K=new Set(b);if(K.add(G.path),g(K),G.children){const I=W(G.path,G.children);C(I)}else{const I=await Q(G.path),J=z=>z.map(q=>q.path===G.path?{...q,children:I}:q.children?{...q,children:J(q.children)}:q);h(z=>J(z));const E=W(G.path,I);C(E)}}M(G.path)}},ye=async()=>{if(!D||!V)return;const G=v.trim()||"new_directory",K=`${D}/${G}`;try{await Re.createDirectory(K);const I=await Q(D),J=E=>E.map(z=>z.path===D?{...z,children:I}:z.children?{...z,children:J(z.children)}:z);h(E=>J(E)),M(null),C("")}catch(I){console.error("Failed to create directory:",I)}},ce=()=>{M(null),C("")},Ce=(G,K=0)=>{const I=b.has(G.path),J=G.isDirectory,E=N.has(G.path),z=s===G.path,q=n==="inline",be=e.jsxs(e.Fragment,{children:[J&&e.jsx("button",{onClick:ee=>{ee.stopPropagation(),oe(G)},className:"p-0.5 hover:bg-accent rounded",children:I?e.jsx(Nt,{className:"h-3 w-3"}):e.jsx(Es,{className:"h-3 w-3"})}),!J&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:ee=>{ee.stopPropagation(),fe(G.path),n==="dropdown"&&a==="immediate"&&S(!1)},onDoubleClick:ee=>{ee.stopPropagation(),i&&i(G.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",q&&z?"text-primary":"text-foreground"),children:[I?e.jsx(gs,{className:O("h-3.5 w-3.5 text-muted-foreground",q&&z&&"text-primary")}):e.jsx(gs,{className:O("h-3.5 w-3.5 text-muted-foreground",q&&z&&"text-primary")}),e.jsx("span",{className:O("typography-ui-label font-medium truncate",q&&z?"text-primary":"text-foreground"),children:G.name})]}),e.jsx("button",{onClick:ee=>{ee.stopPropagation(),me(G)},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:ee=>{ee.stopPropagation(),xe(G.path)},className:O("p-1 hover:bg-accent rounded transition-opacity",m?"opacity-70":"opacity-0 group-hover:opacity-100"),title:E?"Unpin directory":"Pin directory",children:E?e.jsx(qo,{className:"h-3 w-3 text-primary"}):e.jsx(rf,{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",z?"text-primary":"text-foreground"),style:{paddingLeft:`${K*12+8}px`},children:be}),I&&e.jsxs(e.Fragment,{children:[D===G.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(it,{ref:$,value:v,onChange:ee=>C(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"?(ee.preventDefault(),ee.stopPropagation(),ye()):ee.key==="Escape"&&(ee.preventDefault(),ee.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:ee=>{ee.preventDefault(),ee.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:ee=>{ee.preventDefault(),ee.stopPropagation(),ce()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Vt,{className:"h-3 w-3 text-muted-foreground"})})]}),G.children&&G.children.map(ee=>Ce(ee,K+1))]})]},G.path):e.jsxs("div",{children:[e.jsxs(St,{className:O("flex items-center gap-1 cursor-pointer group",s===G.path&&"bg-accent"),style:{paddingLeft:`${K*12+8}px`},onSelect:ee=>{ee.preventDefault()},children:[J&&e.jsx("button",{onClick:ee=>{ee.stopPropagation(),oe(G)},className:"p-0.5 hover:bg-accent rounded",children:I?e.jsx(Nt,{className:"h-3 w-3"}):e.jsx(Es,{className:"h-3 w-3"})}),!J&&e.jsx("div",{className:"w-4"}),be]}),I&&e.jsxs("div",{children:[D===G.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(it,{ref:$,value:v,onChange:ee=>C(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"?(ee.preventDefault(),ee.stopPropagation(),ye()):ee.key==="Escape"&&(ee.preventDefault(),ee.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:ee=>{ee.preventDefault(),ee.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:ee=>{ee.preventDefault(),ee.stopPropagation(),ce()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Vt,{className:"h-3 w-3 text-muted-foreground"})})]}),G.children&&G.children.map(ee=>Ce(ee,K+1))]})]},G.path)},Ee=(G,K)=>{if(n==="inline"){const I=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:J=>{J.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",I?"text-primary":"text-foreground"),children:[e.jsx(gs,{className:O("h-3.5 w-3.5 text-muted-foreground",I&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:O("typography-ui-label font-medium truncate",I?"text-primary":"text-foreground"),children:G}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:fs(K,k)})]})]}),e.jsx("button",{onClick:()=>xe(K),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(qo,{className:"h-3 w-3 text-primary"})})]},K)}return e.jsxs(St,{onSelect:I=>{I.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:G}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:fs(K,k)})]}),e.jsx("button",{onClick:I=>{I.stopPropagation(),I.preventDefault(),xe(K)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(qo,{className:"h-3 w-3 text-primary"})})]},K)},Pe=e.jsx(e.Fragment,{children:V?e.jsxs(e.Fragment,{children:[Me.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>P(G=>!G),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:[A?e.jsx(Nt,{className:"h-3.5 w-3.5"}):e.jsx(Es,{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:Me.length})]}),A&&Me.map(({name:G,path:K})=>Ee(G,K)),n==="dropdown"&&e.jsx(Us,{}),n==="inline"&&A&&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(G=>Ce(G)),!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(qt,{open:w,onOpenChange:S,children:[e.jsx(Kt,{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,k)})]}),e.jsx(Nt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Yt,{align:"start",className:"w-[350px]",children:e.jsx(tt,{outerClassName:"h-full",className:"w-full",children:Pe})})]})},Ol="directoryTreeShowHidden",ex=({open:s,onOpenChange:r})=>{const{currentDirectory:t,homeDirectory:n,setDirectory:o,isHomeReady:a}=ht(),[i,c]=l.useState(null),[d,u]=l.useState(""),[m,f]=l.useState(!1),[p,h]=l.useState(!1),[b,g]=l.useState(()=>{if(typeof window>"u")return!1;try{const B=window.localStorage.getItem(Ol);if(B==="true")return!0;if(B==="false")return!1}catch{}return!1}),{isDesktop:y,requestAccess:x,startAccessing:w}=eu(),{isMobile:S}=Ct(),k=l.useCallback(B=>B?fs(B,n):"",[n]);l.useEffect(()=>{if(s){f(!1),h(!1);const B=t||n||"";c(B),u(k(B))}},[s,t,n,k]),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(Ol,b?"true":"false")}catch{}},[b]);const j=l.useCallback(()=>{r(!1)},[r]),N=l.useCallback(async B=>{if(!(!B||p)){if(B===t){j();return}h(!0);try{let T=B;if(y){const V=await x(B);if(!V.success){se.error("Unable to access directory",{description:V.error||"Desktop denied directory access."});return}T=V.path??B;const X=await w(T);if(!X.success){se.error("Failed to open directory",{description:X.error||"Desktop could not grant file access."});return}}o(T),j()}catch(T){se.error("Failed to select directory",{description:T instanceof Error?T.message:"Unknown error occurred."})}finally{h(!1)}}},[t,j,y,x,o,w,p]),L=l.useCallback(async()=>{const B=d.trim()||i;B&&await N(B)},[N,d,i]),D=l.useCallback(B=>{c(B),f(!0),u(k(B))},[k]),M=l.useCallback(async B=>{c(B),f(!0),u(k(B)),await N(B)},[N,k]),v=l.useCallback(B=>{const T=B.target.value;if(u(T),f(!0),T.startsWith("/")||T.startsWith("~")){const V=T.startsWith("~")&&n?T.replace(/^~/,n):T;c(V)}},[n]),C=l.useCallback(B=>{B.key==="Enter"&&(B.preventDefault(),L())},[L]),A=l.useCallback(()=>{g(B=>!B)},[]),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(Ss,{className:"hidden sm:block",children:"Choose the working directory for sessions and OpenCode operations."})]}),$=e.jsx(it,{value:d,onChange:v,onKeyDown:C,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),R=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($l,{variant:"inline",currentPath:i??t,onSelectPath:D,onDoubleClickPath:M,className:"h-full sm:min-h-[280px] sm:h-[380px]",selectionBehavior:"deferred",showHidden:b,rootDirectory:a?n:null,isRootReady:a})}),H=e.jsxs("button",{type:"button",onClick:A,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:[b?e.jsx(ri,{className:"h-4 w-4 text-primary"}):e.jsx(ni,{className:"h-4 w-4"}),"Show hidden"]}),U=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:$}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:H}),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($l,{variant:"inline",currentPath:i??t,onSelectPath:D,onDoubleClickPath:M,className:"h-full",selectionBehavior:"deferred",showHidden:b,rootDirectory:a?n:null,isRootReady:a,alwaysShowActions:!0})})]}),Y=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:[$,e.jsx("div",{className:"flex items-center justify-end",children:H}),R]}),F=()=>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:L,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:F()}),children:U}):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:B=>{B.preventDefault()},children:[P,Y,e.jsx(Ks,{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:F()})]})})},Mo=".openchamber",Vn=s=>s?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:s}):void 0,tx=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),tu=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),su=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Gn=(s,r)=>{const t=su(s),n=tu(r),o=!t||t==="/"?`/${Mo}`:`${t}/${Mo}`;return n?`${o}/${n}`:o},sx=()=>{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"}]),[b,g]=l.useState(!1),[y,x]=l.useState([]),[w,S]=l.useState(!1),[k,j]=l.useState(null),[N,L]=l.useState(!1),[D,M]=l.useState(null),[v,C]=l.useState(!1),A=l.useRef(new Set),[P,$]=l.useState(null),[R,H]=l.useState([]),[U,Y]=l.useState(!1),[F,B]=l.useState(!1),{sessions:T,createSession:V,deleteSession:X,deleteSessions:fe,loadSessions:ae,initializeNewOpenChamberSession:xe,setWorktreeMetadata:Me,setSessionDirectory:Q,getWorktreeMetadata:re,isLoading:oe}=pe(),{currentDirectory:W,homeDirectory:me,hasPersistedDirectory:ye,isHomeReady:ce}=ht(),{agents:Ce}=ut(),{isSessionCreateDialogOpen:Ee,setSessionCreateDialogOpen:Pe}=Fe(),{isMobile:G,isTablet:K,hasTouchInput:I}=Ct(),J=G||K||I,E=l.useMemo(()=>su(W),[W]),z=l.useMemo(()=>tx(i),[i]),q=l.useMemo(()=>o==="existing"?d.trim():z,[d,z,o]),be=l.useMemo(()=>tu(q),[q]),ee=l.useMemo(()=>!E||!be?"":Gn(E,be),[E,be]),he=D===!0,He=l.useMemo(()=>{const le=p.find(ue=>ue.value===m);return le?le.label:m==="HEAD"?"Current (HEAD)":m},[p,m]),We=l.useMemo(()=>(P?.worktree?.status?.isDirty??!1)||R.some(le=>le.metadata.status?.isDirty),[P?.worktree?.status?.isDirty,R]),Be=l.useMemo(()=>{const le=P?.worktree;return le&&typeof le.branch=="string"&&le.branch.trim().length>0?!0:R.length>0&&R.every(({metadata:ue})=>typeof ue.branch=="string"&&ue.branch.trim().length>0)},[P?.worktree,R]),Ze=P?.mode==="worktree",lt=Ze,ct=F||!Ze||!Be;l.useEffect(()=>{E&&(A.current.has(E)||eh(E).then(()=>A.current.add(E)).catch(le=>{console.warn("Failed to ensure .openchamber directory is ignored:",le),A.current.delete(E)}))},[E]),l.useEffect(()=>{ae()},[ae,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),L(!1),M(null),C(!1);return}if(!E){a("new"),u(""),h([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),f("HEAD"),x([]),M(null),L(!1);return}let le=!1;return S(!0),g(!0),L(!0),j(null),(async()=>{try{const ue=await rn(E);if(le)return;if(M(ue),!ue)a("new"),u(""),h([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),f("HEAD"),x([]),j(null);else{const[je,ke]=await Promise.all([Mn(E),Nd(E).catch(()=>null)]);if(le)return;const Te=[],Ue=ke?.current?`Current (HEAD: ${ke.current})`:"Current (HEAD)";if(Te.push({value:"HEAD",label:Ue,group:"special"}),ke){const st=ke.all.filter(ot=>!ot.startsWith("remotes/")).sort((ot,Ae)=>ot.localeCompare(Ae)),jt=ke.current&&!ke.current.startsWith("remotes/")?ke.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"})}),ke.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 wt=je.map(st=>Dn(E,st)),Mt=`${Gn(E,"")}/`,pt=wt.filter(st=>st.path.startsWith(Mt));x(pt)}}catch(ue){if(le)return;const je=ue instanceof Error?ue.message:"Failed to load worktrees";j(je)}finally{le||(S(!1),g(!1),L(!1))}})(),()=>{le=!0}},[Ee,E]);const dt=l.useCallback(le=>{$({sessions:le.sessions,dateLabel:le.dateLabel,mode:le.mode??"session",worktree:le.worktree??null})},[]),mt=l.useCallback(()=>{$(null),H([]),Y(!1),B(!1)},[]);l.useEffect(()=>vr.onDeleteRequest(le=>{dt(le)}),[dt]),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){H([]),Y(!1);return}const le=P.sessions.map(je=>{const ke=re(je.id);return ke?{session:je,metadata:ke}:null}).filter(je=>!!je);if(H(le),Y(!1),le.length===0)return;let ue=!1;return(async()=>{const je=await Promise.all(le.map(async({metadata:ke})=>{if(ke.status&&typeof ke.status.isDirty=="boolean")return ke.status;try{return await _a(ke.path)}catch{return ke.status}})).catch(ke=>(console.warn("Failed to inspect worktree status before deletion:",ke),le.map(({metadata:Te})=>Te.status)));ue||!Array.isArray(je)||H(ke=>ke.map((Te,Ue)=>({session:Te.session,metadata:{...Te.metadata,status:je[Ue]??Te.metadata.status}})))})(),()=>{ue=!0}},[P,re]),l.useEffect(()=>{Be||Y(!1)},[Be]);const yt=l.useCallback(le=>{c(le),j(null)},[]),vt=l.useCallback(async()=>{if(!(!E||!D))try{const ue=(await Mn(E)).map(Ue=>Dn(E,Ue)),ke=`${Gn(E,"")}/`,Te=ue.filter(Ue=>Ue.path.startsWith(ke));x(Te)}catch{}},[E,D]),gt=l.useRef(null);l.useEffect(()=>{gt.current?.mode==="worktree"&&!P&&vt(),gt.current=P},[P,vt]);const bt=l.useCallback(()=>{if(!E){const ke="Select a project directory first.";return j(ke),se.error(ke),!1}const le=q,ue=be;if(!le){const ke=o==="existing"?"Select an existing branch for the new worktree.":"Provide a branch name for the new worktree.";return j(ke),se.error(ke),!1}if(!ue){const ke="Provide a branch name that can be used as a folder.";return j(ke),se.error(ke),!1}const je=Gn(E,ue);if(y.some(ke=>ke.path===je)){const ke="A worktree with this folder already exists.";return j(ke),se.error(ke),!1}return j(null),!0},[E,o,q,be,y]),Z=async()=>{if(v||oe||!bt())return;C(!0),j(null);let le=null;try{const ue=q,je=be,ke=o==="new",Ue=await Md({projectDirectory:E,worktreeSlug:je,branch:ue,createBranch:ke,startPoint:ke&&m&&m!=="HEAD"?m:void 0});le=Ue;const wt=await _a(Ue.path).catch(()=>{}),At=wt?{...Ue,status:wt}:Ue,Mt=await V(void 0,Ue.path);if(!Mt){await ol({projectDirectory:E,path:Ue.path,force:!0}).catch(()=>{});const pt="Failed to create session for worktree";j(pt),se.error(pt);return}xe(Mt.id,Ce),Q(Mt.id,Ue.path),Me(Mt.id,At),await vt(),c(""),u(""),se.success("Worktree created")}catch(ue){le&&await ol({projectDirectory:E,path:le.path,force:!0}).catch(()=>{});const je=ue instanceof Error?ue.message:"Failed to create worktree";j(je),se.error(je)}finally{C(!1)}},De=l.useCallback(le=>{const ue=T.filter(je=>re(je.id)?.path===le.path);vr.requestDelete({sessions:ue,mode:"worktree",worktree:le})},[T,re]),ne=l.useCallback(async()=>{if(P){B(!0);try{const le=lt,ue=le&&U;if(P.sessions.length===0&&Ze&&P.worktree){const je=U&&Be;await Dd({projectDirectory:E,path:P.worktree.path,branch:P.worktree.branch,force:!0,deleteRemote:je});const ke=je?"Worktree and remote branch removed.":"Worktree removed.";se.success("Worktree removed",{description:Vn(ke)}),mt(),ae();return}if(P.sessions.length===1){const je=P.sessions[0];if(!await X(je.id,{archiveWorktree:le,deleteRemoteBranch:ue})){se.error("Failed to delete session"),B(!1);return}const Te=le?ue?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;se.success("Session deleted",{description:Vn(Te)})}else{const je=P.sessions.map(Ue=>Ue.id),{deletedIds:ke,failedIds:Te}=await fe(je,{archiveWorktree:le,deleteRemoteBranch:ue});if(ke.length>0){const Ue=le?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 ${ke.length} session${ke.length===1?"":"s"}`,{description:Vn(At||void 0)})}if(Te.length>0&&(se.error(`Failed to delete ${Te.length} session${Te.length===1?"":"s"}`,{description:Vn("Please try again in a moment.")}),ke.length===0)){B(!1);return}}mt()}finally{B(!1)}}},[P,U,X,fe,mt,lt,Ze,Be,E,ae]),ie=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:Mo}),"."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ki,{tabs:[{value:"new",label:"New branch"},{value:"existing",label:"Existing branch"}],value:o,onValueChange:le=>{if(a(le),j(null),le==="existing"&&!d){const ue=p.find(je=>je.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:!he||N||b,children:[e.jsx(Ps,{id:"worktree-base-branch-select",size:"lg",className:"w-full typography-meta text-foreground",children:e.jsx(ko,{placeholder:b?"Loading branches…":"Select a branch"})}),e.jsxs(Rs,{children:[e.jsxs(jr,{children:[e.jsx(Sr,{children:"Default"}),p.filter(le=>le.group==="special").map(le=>e.jsx(Ot,{value:le.value,children:le.label},le.value))]}),p.some(le=>le.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(Co,{}),e.jsxs(jr,{children:[e.jsx(Sr,{children:"Local branches"}),p.filter(le=>le.group==="local").map(le=>e.jsx(Ot,{value:le.value,children:le.label},le.value))]})]}),p.some(le=>le.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(Co,{}),e.jsxs(jr,{children:[e.jsx(Sr,{children:"Remote branches"}),p.filter(le=>le.group==="remote").map(le=>e.jsx(Ot,{value:le.value,children:le.label},le.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(it,{id:"worktree-branch-input",value:i,onChange:le=>yt(le.target.value),placeholder:"feature/new-branch",className:"h-8 flex-1 typography-meta text-foreground placeholder:text-muted-foreground/70",disabled:!he||N,onKeyDown:le=>{le.key==="Enter"&&!v&&Z()}}),e.jsx(ve,{onClick:Z,disabled:v||oe||!he||!q,className:"h-8",children:v?"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:le=>{u(le),j(null)},disabled:!he||N||b||!p.some(le=>le.group==="local"),children:[e.jsx(Ps,{id:"worktree-existing-branch-select",size:"lg",className:"flex-1 typography-meta text-foreground",children:e.jsx(ko,{placeholder:b?"Loading branches…":"Select a branch"})}),e.jsx(Rs,{children:e.jsxs(jr,{children:[e.jsx(Sr,{children:"Local branches"}),p.filter(le=>le.group==="local").map(le=>e.jsx(Ot,{value:le.value,children:le.label},le.value))]})})]}),e.jsx(ve,{onClick:Z,disabled:v||oe||!he||!q,className:"h-8",children:v?"Creating…":"Create"})]}),!b&&!p.some(le=>le.group==="local")?e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"No local branches found. Fetch or create a branch first."}):null]}),q?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:q})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:fs(ee,me)})]}):e.jsxs(e.Fragment,{children:["Creates branch"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:q})," ","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(ee,me)})]})}):null]}),k&&e.jsx("p",{className:"typography-meta text-destructive",children:k}),!he&&!N&&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"})}),w?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:Mo}),"."]}):e.jsx("div",{className:"space-y-1.5 min-w-0",children:y.map(le=>{const ue=le.relativePath||(le.path.startsWith(E+"/")?le.path.slice(E.length+1):le.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:le.label||le.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70 break-all",children:ue})]}),e.jsx("button",{type:"button",onClick:()=>De(le),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 ${le.branch||le.label}`,children:e.jsx(Ls,{className:"h-4 w-4"})})]},le.path)})})]})]}),Ie=e.jsx(ve,{variant:"ghost",onClick:()=>Pe(!1),disabled:v,children:"Close"}),_e=P?.worktree??R[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(le=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:le.title||"Untitled Session"},le.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:()=>{ct||Y(le=>!le)},disabled:ct,className:O("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",ct?"cursor-not-allowed opacity-60":"hover:bg-sidebar/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[e.jsx("span",{className:"mt-0.5 flex size-5 items-center justify-center text-muted-foreground",children:U?e.jsx(ri,{className:"size-4 text-primary"}):e.jsx(ni,{className:"size-4"})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Delete remote branch"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:U?"Remote branch on origin will also be removed.":"Keep the remote branch intact."})]})]}):e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Remote branch information unavailable for this worktree."})]}):e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,rt=e.jsxs(e.Fragment,{children:[e.jsx(ve,{variant:"ghost",onClick:mt,disabled:F,children:"Cancel"}),e.jsx(ve,{variant:"destructive",onClick:ne,disabled:F,children:F?"Deleting…":Ze?"Delete worktree":P?.sessions.length===1?"Delete session":"Delete sessions"})]});return e.jsxs(e.Fragment,{children:[J?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:ie})}):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"})}),ie,e.jsx(Ks,{className:"mt-2 gap-2 pt-1 pb-1",children:Ie})]})}),J?e.jsx(ps,{open:!!P,onClose:()=>{F||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:le=>{if(!le){if(F)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(Ss,{children:ze})]}),Ge,e.jsx(Ks,{className:"mt-2 gap-2 pt-1 pb-1",children:rt})]})}),e.jsx(ex,{open:s,onOpenChange:r})]})};function rx(){return new Worker(nf,{type:"module"})}const nx=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function ox(s,r,t){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${s}:${r.length}:${t.length}:${n.length}:${o.length}`}function _l(s){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>s(void 0),0);return()=>window.clearTimeout(r)}const ax=({children:s})=>{const r=af(),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=Ia(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=b=>{if(u)return;const g=Date.now();for(;p<f.length&&!(b&&b.timeRemaining()<8||!b&&Date.now()-g>8);){const[y,x]=f[p];p+=1,Ir(y);const w=ox(y,x.original,x.modified),S={name:y,contents:x.original,cacheKey:`old-${w}`},k={name:y,contents:x.modified,cacheKey:`new-${w}`},j=Ia(S,k),N={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(N,j)}p<f.length&&(m=_l(h))};return h(void 0),p<f.length&&(m=_l(h)),()=>{u=!0,m?.()}},[r,t,n,o]),e.jsx(e.Fragment,{children:s})},ix=({children:s})=>{const t=_o()?.currentTheme?.metadata?.variant==="dark";Wd();const n=Ne.useMemo(()=>({theme:{dark:Yr.dark,light:Yr.light},themeType:t?"dark":"light",langs:nx}),[t]);return e.jsx(of,{poolOptions:{workerFactory:rx,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(ax,{children:s})})},bs=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}));bs.displayName="Textarea";const Wa=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),lx=(s,r)=>{const t=Wa(s),n=Wa(r);return`${t}-${n}`.substring(0,60)},Bl=(s,r)=>`${s}/${r}`,cx=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),dx=()=>ht.getState().currentDirectory??null,wn=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=dx();if(!c)return s({error:"No directory selected",isLoading:!1}),null;if(!await rn(c))return s({error:"Not in a git repository",isLoading:!1}),null;const u=Wa(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 w of o){const S=`${w.providerID}:${w.modelID}`;h.set(S,(h.get(S)||0)+1)}const b=new Map;for(const w of o){const S=`${w.providerID}:${w.modelID}`,k=h.get(S)||1,j=(b.get(S)||0)+1;b.set(S,j);const N=lx(w.providerID,w.modelID),L=k>1?Bl(u,`${N}/${j}`):Bl(u,N);if(!L)return s({error:"Branch name is required for worktree creation",isLoading:!1}),null;const D=cx(L);if(!D)return s({error:`Invalid branch name: ${L}`,isLoading:!1}),null;try{const M=await Md({projectDirectory:c,worktreeSlug:D,branch:L,createBranch:!0,startPoint:f}),v=k>1?`${u}/${w.providerID}/${w.modelID}/${j}`:`${u}/${w.providerID}/${w.modelID}`,C=await Re.withDirectory(M.path,()=>Re.createSession({title:v}));Je.getState().setWorktreeMetadata(C.id,M),p.push({sessionId:C.id,worktreePath:M.path,providerID:w.providerID,modelID:w.modelID})}catch(M){console.warn("[MultiRun] Failed to create session:",M)}}const g=p.map(w=>w.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(w=>({type:"file",mime:w.mime,filename:w.filename,url:w.url}));return(async()=>{try{await Promise.allSettled(p.map(async w=>{try{await Re.withDirectory(w.worktreePath,()=>Re.sendMessage({id:w.sessionId,providerID:w.providerID,modelID:w.modelID,text:n,agent:a,files:x}))}catch(S){console.warn("[MultiRun] Failed to start run:",S)}}))}catch(w){console.warn("[MultiRun] Failed to start runs:",w)}})(),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"})),ux="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",mx=Object.assign({"../assets/provider-logos/gocode.svg":ux}),Va=new Map;for(const[s,r]of Object.entries(mx)){const t=s.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&r&&Va.set(t[1].toLowerCase(),r)}function ru(s){const r=s?.toLowerCase()??null,t=r?Va.has(r):!1,n=r?Va.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 zt=({providerId:s,alt:r,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=ru(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})},Ci=()=>{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}},nu="h-7",Do=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,fx=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),px=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=fx.format(s);return r.endsWith(".0")?r.slice(0,-2):r},hx=({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",nu),children:[e.jsx(zt,{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(Vt,{className:"h-3.5 w-3.5"})})]})},ou=({selectedModels:s,onAdd:r,onRemove:t,minModels:n,addButtonLabel:o="Add model",showChips:a=!0,maxModels:i})=>{const{providers:c,modelsMetadata:d}=ut(),{favoriteModelsList:u,recentModelsList:m}=Ci(),[f,p]=l.useState(!1),[h,b]=l.useState(""),[g,y]=l.useState(0),x=l.useRef(null),w=l.useRef(null),S=l.useRef([]),k=l.useMemo(()=>{const $=new Map;for(const R of s){const H=`${R.providerID}:${R.modelID}`;$.set(H,($.get(H)||0)+1)}return $},[s]),j=l.useCallback($=>s.filter(H=>H.providerID===$.providerID&&H.modelID===$.modelID).findIndex(H=>H.instanceId===$.instanceId)+1,[s]),N=($,R)=>{const H=`${$}/${R}`;return d.get(H)},L=$=>{const R=$?.name||$?.id||"",H=String(R);return H.length>40?H.substring(0,37)+"...":H},D=l.useCallback(($,R)=>{if(!h.trim())return!0;const H=h.toLowerCase();return $.toLowerCase().includes(H)||R.toLowerCase().includes(H)},[h]),M=l.useMemo(()=>u.filter(({model:$,providerID:R})=>{const U=c.find(F=>F.id===R)?.name||R,Y=L($);return D(Y,U)}),[u,c,D]),v=l.useMemo(()=>m.filter(({model:$,providerID:R})=>{const U=c.find(F=>F.id===R)?.name||R,Y=L($);return D(Y,U)}),[m,c,D]),C=l.useMemo(()=>c.map($=>{const H=(Array.isArray($.models)?$.models:[]).filter(U=>{const Y=L(U);return D(Y,$.name||$.id||"")});return{...$,models:H}}).filter($=>$.models.length>0),[c,D]),A=M.length>0||v.length>0||C.length>0;l.useEffect(()=>{f&&x.current&&x.current.focus()},[f]),l.useEffect(()=>{if(!f)return;const $=R=>{w.current&&!w.current.contains(R.target)&&(p(!1),b(""),y(0))};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[f]),l.useEffect(()=>{y(0)},[h]);const P=($,R,H,U,Y,F)=>{const B=`${R}:${H}`,T=k.get(B)||0,V=N(R,H),X=px(V?.limit?.context);return e.jsxs("button",{ref:fe=>{S.current[Y]=fe},type:"button",onClick:()=>{r({providerID:R,modelID:H,displayName:$.name||H,instanceId:Do()})},onMouseEnter:()=>y(Y),className:O("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",F?"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:L($)}),X&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:X})]}),T>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",T]})]},`${U}-${B}`)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsxs("div",{className:"relative",ref:w,children:[e.jsxs(ve,{type:"button",variant:"outline",size:"sm",className:nu,onClick:()=>p(!f),children:[e.jsx(Gt,{className:"h-3.5 w-3.5 mr-1"}),o]}),f&&(()=>{const $=[];M.forEach(({model:Y,providerID:F,modelID:B})=>{$.push({model:Y,providerID:F,modelID:B,section:"fav"})}),v.forEach(({model:Y,providerID:F,modelID:B})=>{$.push({model:Y,providerID:F,modelID:B,section:"recent"})}),C.forEach(Y=>{Y.models.forEach(F=>{$.push({model:F,providerID:Y.id,modelID:F.id,section:"provider"})})});const R=$.length,H=Y=>{if(Y.key==="ArrowDown"){Y.preventDefault(),Y.stopPropagation();const F=(g+1)%Math.max(1,R);y(F),setTimeout(()=>{S.current[F]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Y.key==="ArrowUp"){Y.preventDefault(),Y.stopPropagation();const F=(g-1+Math.max(1,R))%Math.max(1,R);y(F),setTimeout(()=>{S.current[F]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Y.key==="Enter"){Y.preventDefault(),Y.stopPropagation();const F=$[g];F&&r({providerID:F.providerID,modelID:F.modelID,displayName:F.model.name||F.modelID,instanceId:Do()})}else Y.key==="Escape"&&(Y.preventDefault(),Y.stopPropagation(),p(!1),b(""),y(0))};let U=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(sr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(it,{ref:x,type:"text",placeholder:"Search models",value:h,onChange:Y=>b(Y.target.value),onKeyDown:H,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"}),M.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(er,{className:"h-4 w-4 text-primary"}),"Favorites"]}),M.map(({model:Y,providerID:F,modelID:B})=>{const T=U++;return P(Y,F,B,"fav",T,g===T)})]}),v.length>0&&e.jsxs(e.Fragment,{children:[M.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(qs,{className:"h-4 w-4"}),"Recent"]}),v.map(({model:Y,providerID:F,modelID:B})=>{const T=U++;return P(Y,F,B,"recent",T,g===T)})]}),(M.length>0||v.length>0)&&C.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),C.map((Y,F)=>e.jsxs(l.Fragment,{children:[F>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(zt,{providerId:Y.id,className:"h-4 w-4 flex-shrink-0"}),Y.name]}),Y.models.map(B=>{const T=U++;return P(B,Y.id,B.id,"provider",T,g===T)})]},Y.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),a&&s.map(($,R)=>{const H=`${$.providerID}:${$.modelID}`,U=k.get(H)||1,Y=j($);return e.jsx(hx,{model:$,instanceIndex:Y,totalSameModel:U,onRemove:()=>t(R)},$.instanceId)})]}),n!==void 0&&s.length<n&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select at least ",n," model",n>1?"s":""," ",i!==void 0?`and at most ${i} models`:"","."]})]})};function Mi(s){const[r,t]=l.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=l.useState(!1),[a,i]=l.useState(null);return l.useEffect(()=>{let c=!1;if(!s){i(null),o(!1),t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),i(null),(async()=>{try{const d=await rn(s);if(c)return;if(i(d),!d){t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await Nd(s).catch(()=>null);if(c)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(b=>!b.startsWith("remotes/")).sort((b,g)=>b.localeCompare(g)).forEach(b=>{m.push({value:b,label:b,group:"local"})}),u.all.filter(b=>b.startsWith("remotes/")).map(b=>b.replace(/^remotes\//,"")).sort((b,g)=>b.localeCompare(g)).forEach(b=>{m.push({value:b,label:b,group:"remote"})})),t(m)}finally{c||o(!1)}})(),()=>{c=!0}},[s]),{branches:r,isLoading:n,isGitRepository:a}}const au=({directory:s,value:r,onChange:t,className:n,disabled:o,id:a})=>{const{branches:i,isLoading:c,isGitRepository:d}=Mi(s);l.useEffect(()=>{!i.some(f=>f.value===r)&&i.length>0&&t("HEAD")},[i,r,t]);const u=o||!d||c;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Fs,{value:r,onValueChange:t,disabled:u,children:[e.jsx(Ps,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:e.jsx(ko,{placeholder:c?"Loading branches…":"Select a branch"})}),e.jsxs(Rs,{fitContent:!0,children:[e.jsxs(jr,{children:[e.jsx(Sr,{children:"Default"}),i.filter(m=>m.group==="special").map(m=>e.jsx(Ot,{value:m.value,className:"w-auto whitespace-nowrap",children:m.label},m.value))]}),i.some(m=>m.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(Co,{}),e.jsxs(jr,{children:[e.jsx(Sr,{children:"Local branches"}),i.filter(m=>m.group==="local").map(m=>e.jsx(Ot,{value:m.value,className:"w-auto whitespace-nowrap",children:m.label},m.value))]})]}):null,i.some(m=>m.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(Co,{}),e.jsxs(jr,{children:[e.jsx(Sr,{children:"Remote branches"}),i.filter(m=>m.group==="remote").map(m=>e.jsx(Ot,{value:m.value,className:"w-auto whitespace-nowrap",children:m.label},m.value))]})]}):null]})]}),d===!1&&e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."})]})},gx=10*1024*1024,zl=5,Hl=({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),b=ht(U=>U.currentDirectory??null),g=Fe(U=>U.isSidebarOpen),[y,x]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const U=typeof window.opencodeDesktop<"u";x(U)},[]);const S=l.useMemo(()=>y&&w?g?"pl-0":"pl-[8.0rem]":"pl-3",[y,w,g]),[k,j]=l.useState("HEAD"),{isLoading:N,isGitRepository:L}=Mi(b),D=wn(U=>U.createMultiRun),M=wn(U=>U.error),v=wn(U=>U.clearError);l.useEffect(()=>{typeof s=="string"&&s.trim().length>0&&i(U=>U.trim().length>0?U:s)},[s]);const C=U=>{c.length>=zl||(d(Y=>[...Y,U]),v())},A=U=>{d(Y=>Y.filter((F,B)=>B!==U)),v()},P=async U=>{const Y=U.target.files;if(!Y)return;let F=0;for(let B=0;B<Y.length;B++){const T=Y[B];if(T.size>gx){se.error(`File "${T.name}" is too large (max 10MB)`);continue}try{const V=await new Promise((fe,ae)=>{const xe=new FileReader;xe.onload=()=>fe(xe.result),xe.onerror=ae,xe.readAsDataURL(T)}),X={id:Do(),filename:T.name,mimeType:T.type||"application/octet-stream",size:T.size,dataUrl:V};m(fe=>[...fe,X]),F++}catch(V){console.error("File attach failed",V),se.error(`Failed to attach "${T.name}"`)}}F>0&&se.success(`Attached ${F} file${F>1?"s":""}`),h.current&&(h.current.value="")},$=U=>{m(Y=>Y.filter(F=>F.id!==U))},R=async U=>{if(U.preventDefault(),!!a.trim()&&!(c.length<2)){p(!0),v();try{const Y=c.map(({instanceId:V,...X})=>X),F=u.map(V=>({mime:V.mimeType,filename:V.filename,url:V.dataUrl})),B={name:n.trim(),prompt:a.trim(),models:Y,worktreeBaseBranch:k,files:F.length>0?F:void 0},T=await D(B);T&&(T.firstSessionId&&pe.getState().setCurrentSession(T.firstSessionId),r?.())}finally{p(!1)}}},H=!!(n.trim()&&a.trim()&&c.length>=2&&L&&!N);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&&w&&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(Vt,{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:R,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(it,{id:"group-name",value:n,onChange:U=>o(U.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body max-w-full sm:max-w-xs",required:!0}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch names"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Worktrees"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Create one worktree per model by creating a new branch from a base branch."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"multirun-worktree-base-branch",children:"Base branch"}),e.jsx(au,{directory:b,value:k,onChange:j,id:"multirun-worktree-base-branch"}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:k||"HEAD"}),"."]})]})]}),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(bs,{id:"prompt",value:a,onChange:U=>i(U.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:P,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(po,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),u.map(U=>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:[U.mimeType.startsWith("image/")?e.jsx(rr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Ws,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:U.filename,children:U.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",U.size<1024?`${U.size}B`:U.size<1024*1024?`${(U.size/1024).toFixed(1)}KB`:`${(U.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>$(U.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Vt,{className:"h-3.5 w-3.5"})})]},U.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(ou,{selectedModels:c,onAdd:C,onRemove:A,minModels:2,maxModels:zl})]}),M&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:M}),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:!H||f,children:f?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(lf,{className:"h-4 w-4 mr-2"}),"Start (",c.length," models)"]})})]})]})})})]})},xx=(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=b=>{const g=b.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=b=>{if(!d.current)return;const g=b.touches[0];if(!g)return;g.clientX-d.current.x>10&&b.preventDefault()},p=b=>{if(!d.current)return;const g=b.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:w}=d.current,{x:S,y:k,time:j}=u.current,N=S-y,L=k-x,D=j-w,M=Math.abs(L)<Math.abs(N),v=D<=n,C=Math.abs(L)<t;N>=t&&M&&v&&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},pn=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}=pe(),{isMobile:t}=Fe(),n=zd(),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=pe.getState().attachedFiles.length;try{await r(p),pe.getState().attachedFiles.length>h&&m++}catch(b){console.error("File attach failed",b),se.error(b instanceof Error?b.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 b=p.map(g=>`${g?.name||"file"}: ${g?.reason||"skipped"}`).join(`
|
|
61
|
-
`);se.error(`Some files were skipped:
|
|
62
|
-
${b}`)}const h=f.map(b=>{if(!b?.dataUrl)return null;try{const[g,y]=b.dataUrl.split(","),x=b.mimeType||g?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!y)return null;const w=atob(y),S=new Uint8Array(w.length);for(let j=0;j<w.length;j++)S[j]=w.charCodeAt(j);const k=new Blob([S],{type:x});return new File([k],b.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(po,{className:O(a,"text-current")})})]})});const yx=Ne.memo(({file:s,onRemove:r})=>{const t=()=>s.mimeType.startsWith("image/")?e.jsx(rr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("text")||s.mimeType.includes("code")?e.jsx(Ws,{className:"h-3.5 w-3.5"}):s.mimeType.includes("json")||s.mimeType.includes("xml")?e.jsx(Po,{className:"h-3.5 w-3.5"}):e.jsx(Ws,{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(cf,{className:"h-3 w-3 text-primary"}):e.jsx(Jc,{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(Vt,{className:"h-3 w-3"})})]})}),bx=Ne.memo(()=>{const{attachedFiles:s,removeAttachedFile:r}=pe();return s.length===0?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Attached:"}),s.map(t=>e.jsx(yx,{file:t,onRemove:()=>r(t.id)},t.id))]})})}),iu=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(rr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(Ws,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Po,{className:"h-3.5 w-3.5"}):e.jsx(Ws,{className:"h-3.5 w-3.5"}):e.jsx(Ws,{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(rr,{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}`)})})})]})}),lu=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(df,{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(Vt,{className:"h-3 w-3"})})]})});lu.displayName="QueuedMessageChip";const Ul=[],cu=Ne.memo(({onEditMessage:s})=>{const r=pe(a=>a.currentSessionId),t=zs(l.useCallback(a=>r?a.queuedMessages[r]??Ul:Ul,[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(lu,{message:a,sessionId:r,onEdit:o},a.id))]})})});cu.displayName="QueuedMessageChips";const du=(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},wx=l.forwardRef(({searchQuery:s,onFileSelect:r,onClose:t},n)=>{const{currentDirectory:o}=ht(),{addServerFile:a}=pe(),i=fi(C=>C.searchFiles),c=du(s,180),[d,u]=l.useState([]),[m,f]=l.useState(!1),[p,h]=l.useState(0),[b,g]=l.useState(360),[y,x]=l.useState({}),[w,S]=l.useState({}),k=l.useRef([]),j=l.useRef([]),N=l.useRef([]),L=l.useRef(null),D=l.useCallback((C,A)=>{const P=C.trim().toLowerCase();if(!P)return 0;const $=A.toLowerCase();let R=0,H=-1,U=0;for(let Y=0;Y<P.length;Y+=1){const F=P[Y];if(!F||F===" ")continue;const B=$.indexOf(F,H+1);if(B===-1)return null;const T=B-H-1;if(T===0?U+=1:U=0,R+=10,R+=Math.max(0,18-B),R-=Math.max(0,T),B===0)R+=12;else{const V=$[B-1];(V==="/"||V==="_"||V==="-"||V==="."||V===" ")&&(R+=10)}R+=U>0?12:0,H=B}return R+=Math.max(0,24-Math.round($.length/3)),R},[]);l.useEffect(()=>{const C=A=>{const P=A.target;!P||!L.current||L.current.contains(P)||t()};return document.addEventListener("pointerdown",C,!0),()=>{document.removeEventListener("pointerdown",C,!0)}},[t]),l.useEffect(()=>{if(!o){u([]);return}const A=(c??"").trim().toLowerCase();let P=!1;return f(!0),i(o,A,80).then($=>{if(P)return;const R=A?$.map(H=>{const U=H.relativePath||H.name||H.path,Y=D(A,U);return Y===null?null:{file:H,score:Y,labelLength:U.length}}).filter(Boolean):$.map(H=>({file:H,score:0,labelLength:(H.relativePath||H.name||H.path).length}));R.sort((H,U)=>U.score-H.score||H.labelLength-U.labelLength||H.file.path.localeCompare(U.file.path)),u(R.slice(0,15).map(H=>H.file))}).catch(()=>{P||u([])}).finally(()=>{P||f(!1)}),()=>{P=!0}},[o,c,D,i]),l.useEffect(()=>{h(0),x({}),S({})},[d]),l.useEffect(()=>{k.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]),l.useEffect(()=>{let C=null;const A=()=>{C!==null&&cancelAnimationFrame(C),C=requestAnimationFrame(()=>{const P={},$={};j.current.forEach((R,H)=>{if(!R)return;const Y=N.current[H]?.offsetWidth??R.scrollWidth,F=Math.max(0,Y-R.clientWidth),B=F>8;if(P[H]=B,B){const T=Math.max(.6,F/110);$[H]=T}}),x(P),S($)})};return A(),window.addEventListener("resize",A),()=>{C!==null&&cancelAnimationFrame(C),window.removeEventListener("resize",A)}},[d]),l.useEffect(()=>{const C=j.current[p];if(!C)return;const A=()=>{const $=C.clientWidth;$>0&&g($)};if(A(),typeof ResizeObserver>"u")return;const P=new ResizeObserver(A);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 A=d.length;if(A!==0){if(C==="ArrowDown"){h(P=>(P+1)%A);return}if(C==="ArrowUp"){h(P=>(P-1+A)%A);return}if(C==="Enter"||C==="Tab"){const P=(p%A+A)%A,$=d[P];$&&M($)}}}}),[d,p,t,M]);const v=C=>{switch(C.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(Gs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Gs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Ws,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(rr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Po,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:L,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(Tn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((C,A)=>{const P=C.relativePath||C.name,$=hd(P,{maxLength:45}),R=p===A,H=y[A]??!1,U=w[A]??2.6,Y=e.jsxs("div",{ref:F=>{k.current[A]=F},className:O("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",R&&"bg-muted"),onClick:()=>M(C),onMouseEnter:()=>h(A),children:[v(C),e.jsxs("span",{ref:F=>{j.current[A]=F},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:R?{"--file-mention-marquee-width":`${b}px`,"--file-mention-marquee-duration":`${U}s`}:void 0,"aria-label":P,children:[e.jsx("span",{ref:F=>{N.current[A]=F},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:P}),H&&R?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:P}):e.jsx("span",{className:"block truncate",children:$})]})]});return e.jsx(l.Fragment,{children:Y},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"})]})}),uu=l.forwardRef(({searchQuery:s,onCommandSelect:r,onClose:t},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=pe(oi(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([]),b=l.useRef(null);l.useEffect(()=>{const y=x=>{const w=x.target;!w||!b.current||b.current.contains(w)||t()};return document.addEventListener("pointerdown",y,!0),()=>{document.removeEventListener("pointerdown",y,!0)}},[t]),l.useEffect(()=>{(async()=>{m(!0);try{const w=(await Re.listCommands()).map(D=>({name:D.name,description:D.description,agent:D.agent,model:D.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}],k=new Map;S.forEach(D=>k.set(D.name,D)),w.forEach(D=>k.set(D.name,D));const j=Array.from(k.values()),N=!o,L=(s?j.filter(D=>D.name.toLowerCase().includes(s.toLowerCase())||D.description&&D.description.toLowerCase().includes(s.toLowerCase())):j).filter(D=>N||D.name!=="init");L.sort((D,M)=>{const v=D.name.toLowerCase().startsWith(s.toLowerCase()),C=M.name.toLowerCase().startsWith(s.toLowerCase());return v&&!C?-1:!v&&C?1:D.name.localeCompare(M.name)}),d(L)}catch{const x=!o,w=[...i&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...i?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],S=(s?w.filter(k=>k.name.toLowerCase().includes(s.toLowerCase())||k.description&&k.description.toLowerCase().includes(s.toLowerCase())):w).filter(k=>x||k.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(w=>(w+1)%x);return}if(y==="ArrowUp"){p(w=>(w-1+x)%x);return}if(y==="Enter"||y==="Tab"){const w=(f%x+x)%x,S=c[w];S&&r(S)}}}}),[c,f,t,r]);const g=y=>{switch(y.name){case"init":return e.jsx(Ws,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(vn,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(ff,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(qs,{className:"h-3.5 w-3.5 text-blue-500"});case"summarize":return e.jsx(mf,{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(uf,{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:b,className:"absolute z-[100] min-w-0 w-full max-w-[450px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(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(Tn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[c.map((y,x)=>e.jsxs("div",{ref:w=>{h.current[x]=w},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"})]})});uu.displayName="CommandAutocomplete";const vx=s=>s?s!=="primary":!1,mu=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=>vx(g.mode)).map(g=>({name:g.name,description:g.description,mode:g.mode??void 0})),h=s.trim().toLowerCase(),b=h.length?p.filter(g=>g.name.toLowerCase().includes(h)):p;b.sort((g,y)=>g.name.localeCompare(y.name)),d(b),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"})]})});mu.displayName="AgentMentionAutocomplete";function jx({className:s,children:r,...t}){return e.jsxs(pf,{"data-slot":"scroll-area",className:O("relative",s),...t,children:[e.jsx(hf,{"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(Sx,{}),e.jsx(gf,{})]})}function Sx({className:s,orientation:r="vertical",...t}){return e.jsx(xf,{"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(yf,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const Nx=({onFilesSelected:s,multiSelect:r=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=Ct(),c=i,{currentDirectory:d}=ht(),u=fi(I=>I.searchFiles),[m,f]=l.useState(!1),[p,h]=l.useState(!1),[b,g]=l.useState(""),y=du(b,200),[x,w]=l.useState(new Set),[S,k]=l.useState(new Set),[j,N]=l.useState({}),L=l.useRef(new Set),D=l.useRef(new Set),[M,v]=l.useState([]),[C,A]=l.useState(!1),[P,$]=l.useState(!1),[R,H]=l.useState(!1),[U,Y]=l.useState(null),F=n??m,B=o??f,T=l.useCallback(I=>I.slice().sort((J,E)=>J.type!==E.type?J.type==="directory"?-1:1:J.name.localeCompare(E.name)),[]),V=l.useCallback((I,J)=>T(J.filter(E=>!E.name.startsWith(".")).map(E=>{const z=E.name,q=!E.isDirectory&&z.includes(".")?z.split(".").pop()?.toLowerCase():void 0;return{name:z,path:E.path||`${I}/${z}`,type:E.isDirectory?"directory":"file",size:0,extension:q}})),[T]),X=l.useCallback(async I=>{$(!0),Y(null);try{const J=await Re.listLocalDirectory(I),E=V(I,J.map(z=>({name:z.name,path:z.path,isDirectory:z.isDirectory})));L.current=new Set([I]),D.current=new Set,N({[I]:E}),k(new Set)}catch{Y("Failed to load directory contents"),L.current=new Set([I]),D.current=new Set,N({[I]:[]}),k(new Set)}finally{$(!1)}},[V]),fe=l.useCallback(async I=>{const J=I.trim();if(J&&!L.current.has(J)&&!D.current.has(J)){D.current=new Set(D.current),D.current.add(J);try{const E=await Re.listLocalDirectory(J),z=V(J,E.map(q=>({name:q.name,path:q.path,isDirectory:q.isDirectory})));L.current=new Set(L.current),L.current.add(J),N(q=>({...q,[J]:z}))}catch{N(E=>E[J]?E:{...E,[J]:[]})}finally{D.current=new Set(D.current),D.current.delete(J)}}},[V]);l.useEffect(()=>{(F||p)&&d&&X(d)},[F,p,d,X]),l.useEffect(()=>{if(!(F||p)||!d){v([]),A(!1);return}const I=y.trim();if(!I){v([]),A(!1);return}let J=!1;return A(!0),u(d,I,150).then(E=>{if(J)return;const z=E.map(q=>({name:q.name,path:q.path,type:"file",extension:q.extension,relativePath:q.relativePath,size:0}));v(z)}).catch(()=>{J||v([])}).finally(()=>{J||A(!1)}),()=>{J=!0}},[F,p,d,y,u]),l.useEffect(()=>{!F&&!p&&(w(new Set),g(""),v([]),A(!1))},[F,p]);const ae=I=>{if(I.type==="directory")return S.has(I.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(I.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(Gs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Gs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Fa,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(rr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Fa,{className:"h-3.5 w-3.5 text-muted-foreground"})}},xe=async I=>{S.has(I)?k(E=>{const z=new Set(E);return z.delete(I),z}):(k(E=>{const z=new Set(E);return z.add(I),z}),await fe(I))},Me=I=>{w(r?J=>{const E=new Set(J);return E.has(I)?E.delete(I):E.add(I),E}:new Set([I]))},Q=async()=>{const I=new Map;Object.values(j).forEach(z=>{z.forEach(q=>{q.type==="file"&&I.set(q.path,q)})});const J=new Map(M.map(z=>[z.path,z])),E=Array.from(x).map(z=>I.get(z)??J.get(z)).filter(z=>!!z);H(!0);try{await s(E),w(new Set),B(!1),h(!1)}finally{H(!1)}},re=l.useMemo(()=>d?j[d]??[]:[],[j,d]),oe=b.trim().length>0,W=I=>j[I]??[],me=I=>{if(d&&I.startsWith(d)){const J=I.substring(d.length);return J.startsWith("/")?J.substring(1):J}return I.split("/").pop()||I},ye=(I,J)=>{const E=oe?I.relativePath||me(I.path):I.name,z=oe&&E.includes("/")&&E.length>45,q=z?hd(E,{maxLength:c?42:48}):E,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",I.type==="file"&&x.has(I.path)&&"bg-primary/10"),style:{paddingLeft:`${J*12}px`},onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),I.type==="file"&&Me(I.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ae(I)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":E,children:q})]}),I.type==="file"&&x.has(I.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return z?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:E})})]},I.path):l.cloneElement(be,{key:I.path})},ce=(I,J)=>{const E=I.type==="directory",z=E?W(I.path):[],q=S.has(I.path),be=E&&q&&D.current.has(I.path)&&z.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",!E&&x.has(I.path)&&"bg-primary/10"),style:{paddingLeft:`${J*12}px`},onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),E?xe(I.path):Me(I.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ae(I)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:I.name}),!E&&x.has(I.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),E&&q&&z.length>0&&e.jsx("div",{children:z.map(ee=>ce(ee,J+1))}),E&&q&&be&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(J+1)*12}px`},children:"Loading…"})]},I.path)},Ce=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:Ce}),e.jsx(ve,{size:"sm",onClick:Q,disabled:x.size===0||R,className:"h-6 typography-meta",children:R?"Attaching...":"Attach Files"})]}),Pe=c?"flex-1 min-h-[240px]":"h-[300px]",G=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(sr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(it,{value:b,onChange:I=>g(I.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:I=>I.stopPropagation()}),b&&e.jsx("button",{onClick:I=>{I.stopPropagation(),g("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(Vt,{className:"h-3 w-3"})})]})}),e.jsxs(jx,{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..."})}),U&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:U})}),!P&&!U&&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(I=>ye(I,0)):re.map(I=>ce(I,0)),!oe&&re.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),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:I=>{I.preventDefault(),I.stopPropagation(),h(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:I=>{I.preventDefault(),I.stopPropagation(),B(!0)},children:t}):null,e.jsx(ps,{open:F,onClose:()=>B(!1),title:"Select Project Files",footer:Ee,children:e.jsx("div",{className:"flex flex-col gap-0",children:G})})]}):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:G})})]}):e.jsxs(qt,{open:F,onOpenChange:B,children:[e.jsx(Kt,{asChild:!0,children:t}),e.jsxs(Yt,{className:O("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[G,e.jsx(Us,{}),Ee]})]})},qn=[{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 ir(s){if(!s||s==="build")return qn[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)%(qn.length-1);return qn[t]}const kx=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),fu=s=>kx(s),Cx=s=>s?typeof s=="string"?s==="ask":fu(s)?Object.values(s).some(r=>r==="ask"):!1:!1,Mx=s=>s?typeof s=="string"?s==="deny":fu(s)?Object.values(s).some(r=>r==="deny"):!1:!1,pu=({agentDefaultEditMode:s,webfetchPermission:r,bashPermission:t})=>{const n=Cx(t),o=Mx(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}},Kn=s=>s==="primary"||s==="all"||s===void 0||s===null,Dx=[{key:"tool_call",icon:Ro,label:"Tool calling",isActive:s=>s?.tool_call===!0},{key:"reasoning",icon:Jr,label:"Reasoning",isActive:s=>s?.reasoning===!0}],Ax={text:{icon:Zc,label:"Text"},image:{icon:rr,label:"Image"},video:{icon:wf,label:"Video"},audio:{icon:bf,label:"Audio"},pdf:{icon:Po,label:"PDF"}},Ex=s=>s.trim().toLowerCase(),un=(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=>Ex(o)))).map(o=>{const a=Ax[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Ix=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Tx=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=Ix.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Yn=s=>typeof s!="number"||!Number.isFinite(s)?"—":Tx.format(s),ua=s=>Dx.filter(r=>r.isActive(s)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Wl=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},Vl=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)},Gl=({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:b,saveSessionAgentSelection:g,getSessionAgentSelection:y,saveAgentModelForSession:x,getAgentModelForSession:w,analyzeAndSaveExternalSessionChoices:S,getSessionAgentEditMode:k,setSessionAgentEditMode:j}=pe(),N=xt(ge=>ge.hasHydrated),{toggleFavoriteModel:L,isFavoriteModel:D,addRecentModel:M,isModelSelectorOpen:v,setModelSelectorOpen:C}=Fe(),{favoriteModelsList:A,recentModelsList:P}=Ci(),{isMobile:$}=Ct(),R=hg(),H=zd(),U=$,[Y,F]=l.useState(null),[B,T]=l.useState(null),[V,X]=l.useState(""),fe=l.useCallback(()=>F(null),[]),ae=l.useCallback(()=>T(null),[]),xe=l.useRef(void 0),[Me,Q]=l.useState(()=>{const ge=new Set;return t&&ge.add(t),ge}),[re,oe]=l.useState(!1),W=v,me=C,[ye,ce]=l.useState(!1),Ce=l.useId(),[Ee,Pe]=l.useState(""),[G,K]=l.useState(0),I=l.useRef([]);l.useEffect(()=>{Y==="model"&&Q(()=>{const ge=new Set;return t&&ge.add(t),ge})},[Y,t]),l.useEffect(()=>{Y!=="agent"&&oe(!1),Y!=="model"&&X("")},[Y]);const J=l.useRef(W);l.useEffect(()=>{const ge=J.current;J.current=W,W||(ce(!1),Pe(""),K(0),ge&&!U&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[W,U]),l.useEffect(()=>{K(0)},[Ee]);const E=m?.(),z=E?.permission?.edit;let q="ask";(z==="allow"||z==="ask"||z==="deny"||z==="full")&&(q=z);const be=E?E.tools?.edit!==!1:!1;(!E||!be)&&(q="deny");const ee=E?.permission?.webfetch,he=E?.permission?.bash,He=l.useMemo(()=>pu({agentDefaultEditMode:q,webfetchPermission:ee,bashPermission:he}),[q,ee,he]),{cascadeDefaultMode:We,modeAvailability:Be,autoApproveAvailable:Ze}=He,lt=!!(h&&o),ct=lt&&h&&o?k(h,o,We):We,dt={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},mt=l.useCallback(ge=>!Be[ge],[Be]),yt=l.useMemo(()=>!lt||mt(ct)&&ct!==We?We:ct,[We,mt,lt,ct]),vt=[{mode:"ask",label:dt.ask,disabled:mt("ask")},{mode:"allow",label:dt.allow,disabled:mt("allow")},{mode:"full",label:dt.full,disabled:mt("full")}],gt=l.useMemo(()=>pn(yt),[yt]),bt=!lt||!Ze;l.useEffect(()=>{bt&&(oe(!1),ce(!1))},[bt]);const Z=$?"mobile":H?"vscode":"default",De=Z==="mobile"?"h-9":Z==="vscode"?"h-6":"h-8",ne=Z==="mobile"?"h-5 w-5":"h-4 w-4",ie=Z==="mobile"?"h-5 w-5":"h-4 w-4",Ie=U?"typography-micro":"typography-meta",_e=Z==="mobile"?"gap-x-2":Z==="vscode"?"gap-x-1":"gap-x-3",ze=dt[yt],Ge=l.useCallback((ge,_=ne)=>{const te=O(_,"flex-shrink-0"),we=pn(ge),Oe={color:we?we.text:"var(--foreground)"};return ge==="full"?e.jsx(Zs,{className:te,style:Oe}):ge==="allow"?e.jsx(to,{className:te,style:Oe}):ge==="deny"?e.jsx(Kr,{className:te,style:Oe}):e.jsx(Gr,{className:te,style:Oe})},[ne]),rt=l.useCallback(ge=>{bt||!h||!o||mt(ge)||(j(h,o,ge,We),me(!1),oe(!1),ce(!1))},[We,bt,h,o,j,me,ce,mt]),le=d(),ue=Array.isArray(le?.models)?le.models:[],je=t&&n?u(t,n):void 0,ke=ua(je),Te=un(je,"input"),Ue=un(je,"output"),wt=[{label:"Input",value:Yn(je?.cost?.input)},{label:"Output",value:Yn(je?.cost?.output)},{label:"Cache read",value:Yn(je?.cost?.cache_read)},{label:"Cache write",value:Yn(je?.cost?.cache_write)}],At=[{label:"Context",value:ks(je?.limit?.context)},{label:"Output",value:ks(je?.limit?.output)}],Mt=l.useRef(void 0),pt=h?b.get(h)?.length??-1:-1,st=l.useRef(null),jt=l.useCallback((ge,_,te)=>{if(!ge||!_)return"model-missing";const we=r.find(de=>de.id===ge);return we?(Array.isArray(we.models)?we.models:[]).find(de=>de.id===_)?(a(ge),i(_),h&&te&&x(h,te,ge,_),"applied"):"model-missing":"provider-missing"},[r,a,i,h,x]);l.useEffect(()=>{if(!h){st.current=null;return}if(!N||r.length===0||p.length===0)return;(!st.current||st.current.sessionId!==h)&&(st.current={sessionId:h,resolved:!1,inFlight:!1});const ge=st.current;if(!ge||ge.resolved||ge.inFlight)return;let _=!1;const te=()=>{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=w(h,de);if(Le){const Se=jt(Le.providerId,Le.modelId,de);if(Se==="applied")return"resolved";if(Se==="provider-missing")return"waiting"}else return"resolved"}for(const Le of p){const Se=w(h,Le.name);if(!Se)continue;o!==Le.name&&c(Le.name),g(h,Le.name);const Ve=jt(Se.providerId,Se.modelId,Le.name);if(Ve==="applied")return"resolved";if(Ve==="provider-missing")return"waiting"}return"continue"},$e=()=>{if(p.length===0)return;const de=p.filter(Se=>Kn(Se.mode)),Le=p.find(Se=>Se.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"){te();return}if(de==="waiting"||pt===-1)return;if(pt>0){ge.inFlight=!0;try{const Le=await S(h,p);if(_)return;if(Le.size>0){let Se=null,Ve=-1/0;for(const[et,nt]of Le)nt.timestamp>Ve&&(Ve=nt.timestamp,Se=et);if(Se){g(h,Se),o!==Se&&c(Se);const et=Le.get(Se);if(et){const nt=jt(et.providerId,et.modelId,Se);if(nt==="applied"){te();return}if(nt==="provider-missing")return}else{te();return}}}}catch(Le){_||console.error("[ModelControls] Error resolving session from messages:",Le)}finally{const Le=st.current;!_&&Le&&Le.sessionId===h&&(Le.inFlight=!1)}}$e(),te()}catch(de){_||console.error("[ModelControls] Error in session switch:",de)}})(),()=>{_=!0}},[h,pt,p,o,y,w,c,jt,S,g,N,r]),l.useEffect(()=>{if(!N||!h||r.length===0||p.length===0)return;const _=y(h)||o;if(!_)return;const te=w(h,_);if(!te)return;const we=r.find(Le=>Le.id===te.providerId);if(!we||!(Array.isArray(we.models)?we.models.some(Le=>Le.id===te.modelId):!1))return;const Oe=t===te.providerId,de=n===te.modelId;Oe&&de||(_!==o&&c(_),jt(te.providerId,te.modelId,_))},[N,h,o,t,n,r,p,y,w,jt,c]),l.useEffect(()=>{if(!N)return;(async()=>{try{if(o!==Mt.current&&(Mt.current=o,o&&h)){await new Promise(we=>setTimeout(we,50));const _=w(h,o);if(_){const we=jt(_.providerId,_.modelId,o);if(we==="applied"||we==="provider-missing")return}const te=p.find(we=>we.name===o);if(te?.model?.providerID&&te?.model?.modelID&&jt(te.model.providerID,te.model.modelID,o)==="provider-missing")return}}catch(_){console.error("[ModelControls] Agent change error:",_)}})()},[o,h,w,jt,p,N]);const Pt=ge=>{try{c(ge),me(!1),h&&g(h,ge),U&&fe()}catch(_){console.error("[ModelControls] Handle agent change error:",_)}},ot=(ge,_)=>{try{const te=jt(ge,_,o||void 0);if(te!=="applied"){te==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",ge):te==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:ge,modelId:_});return}M(ge,_),me(!1),U&&fe(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(te){console.error("[ModelControls] Handle model change error:",te)}},Ae=ge=>{const _=typeof ge?.name=="string"?ge.name:typeof ge?.id=="string"?ge.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 ge=ue.find(_=>_.id===n);return Ae(ge)},ft=()=>{if(!o){const _=p.filter($e=>Kn($e.mode)),we=_.find($e=>$e.name==="build")||_[0];return we?kt(we.name):"Select Agent"}const ge=p.find(_=>_.name===o);return kt(ge?ge.name:o)},kt=ge=>ge.charAt(0).toUpperCase()+ge.slice(1),Rt=(ge,_,te)=>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(ge,{className:"h-3.5 w-3.5"})},te),cs=l.useCallback(ge=>{Q(_=>{const te=new Set(_);return te.has(ge)?te.delete(ge):te.add(ge),te})},[]),$s=l.useCallback(ge=>{xe.current&&clearTimeout(xe.current),xe.current=setTimeout(()=>{T(ge)},500)},[]),Ns=l.useCallback(()=>{xe.current&&clearTimeout(xe.current)},[]);l.useEffect(()=>()=>{xe.current&&clearTimeout(xe.current)},[]);const on=()=>!U||B!=="model"?null:e.jsx(ps,{open:!0,onClose:ae,title:je?.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()})]}),ke.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:ke.map(({key:ge,icon:_,label:te})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Rt(_,te,`cap-${ge}`),e.jsx("span",{className:"typography-meta text-foreground",children:te})]},ge))})]}),(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:ge,icon:_,label:te})=>Rt(_,`${te} input`,`input-${ge}`))})]}),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:ge,icon:_,label:te})=>Rt(_,`${te} output`,`output-${ge}`))})]})]})]}),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(je?.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(je?.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:Wl(je?.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:Vl(je?.release_date)})]})]})]})]})}),zo=()=>{if(!U||B!=="agent"||!E)return null;const ge=Object.entries(E.tools||{}).filter(([,de])=>de).map(([de])=>de).sort(),_=!!(E.prompt&&E.prompt.trim().length>0),te=E.model?.providerID&&E.model?.modelID,we=E.temperature!==void 0||E.topP!==void 0,$e=de=>Ge(de==="full"||de==="allow"||de==="deny"?de:"ask","h-3.5 w-3.5"),Oe=de=>de==="full"?"Full":de==="allow"?"Allow":de==="deny"?"Deny":"Ask";return e.jsx(ps,{open:!0,onClose:ae,title:kt(E.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[E.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:E.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:E.mode==="primary"?"Primary":E.mode==="subagent"?"Subagent":E.mode==="all"?"All":"—"})]}),(te||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"}),te&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[E.model.providerID," / ",E.model.modelID]}),we&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[E.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:E.temperature})]}),E.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:E.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"}),ge.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:ge.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:[$e(E.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Oe(E.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:[$e(typeof E.permission?.bash=="string"?E.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Oe(typeof E.permission?.bash=="string"?E.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:[$e(E.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Oe(E.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(to,{className:"h-4 w-4 text-foreground"})]})})]})})},Ho=()=>{if(!U)return null;const ge=V.trim().toLowerCase(),_=r.map(te=>{const we=Array.isArray(te.models)?te.models:[],$e=ge.length===0?!0:te.name.toLowerCase().includes(ge)||te.id.toLowerCase().includes(ge),Oe=ge.length===0?we:we.filter(de=>{const Le=Ae(de).toLowerCase(),Se=typeof de.id=="string"?de.id.toLowerCase():"";return Le.includes(ge)||Se.includes(ge)});return{provider:te,providerModels:Oe,matchesProvider:$e}}).filter(({matchesProvider:te,providerModels:we})=>te||we.length>0);return e.jsx(ps,{open:Y==="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(sr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(it,{value:V,onChange:te=>X(te.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),V&&e.jsx("button",{type:"button",onClick:()=>X(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(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."}),!V&&A.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(er,{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:A.map(({model:te,providerID:we,modelID:$e})=>{const Oe=we===t&&$e===n,de=u(we,$e);return e.jsxs("button",{type:"button",onClick:()=>ot(we,$e),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",Oe?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(zt,{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(te)})]}),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}-${$e}`)})})]}),!V&&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(qs,{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:te,providerID:we,modelID:$e})=>{const Oe=we===t&&$e===n,de=u(we,$e);return e.jsxs("button",{type:"button",onClick:()=>ot(we,$e),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",Oe?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(zt,{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(te)})]}),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}-${$e}`)})})]}),_.map(({provider:te,providerModels:we})=>{if(we.length===0&&!ge.length)return null;const $e=te.id===t,Oe=Me.has(te.id)||ge.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(te.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Oe,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{providerId:te.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:te.name}),$e&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Oe?e.jsx(Nt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Es,{className:"h-3 w-3 text-muted-foreground"})]}),Oe&&we.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:we.map(de=>{const Le=$e&&de.id===n,Se=u(te.id,de.id),Ve=ua(Se).slice(0,3),et=un(Se,"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(te.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:[(Se?.limit?.context||Se?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Se?.limit?.context?e.jsxs("span",{children:[ks(Se?.limit?.context)," ctx"]}):null,Se?.limit?.context&&Se?.limit?.output?e.jsx("span",{children:"•"}):null,Se?.limit?.output?e.jsxs("span",{children:[ks(Se?.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:Lt})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Lt,"aria-label":Lt,children:e.jsx(ts,{className:"h-3 w-3"})},`meta-${te.id}-${de.id}-${nt}`))})]})]}),e.jsx("button",{type:"button",onClick:nt=>{nt.preventDefault(),nt.stopPropagation(),L(te.id,de.id)},className:O("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",D(te.id,de.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":D(te.id,de.id)?"Unfavorite":"Favorite",title:D(te.id,de.id)?"Remove from favorites":"Add to favorites",children:D(te.id,de.id)?e.jsx(er,{className:"h-4 w-4"}):e.jsx(Hr,{className:"h-4 w-4"})})]},de.id)})})]},te.id)})]})})},pr=()=>{if(!U)return null;const ge=p.filter(_=>Kn(_.mode));return e.jsx(ps,{open:Y==="agent",onClose:fe,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[ge.map(_=>{const te=_.name===o,we=ir(_.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,te?"active":"border-border/40"),onClick:()=>Pt(_.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:te?{color:`var(${we.var})`}:void 0,children:kt(_.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:bt,onClick:()=>{bt||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",bt?"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:gt?gt.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",!gt&&"text-muted-foreground"),style:gt?{color:gt.text}:void 0,children:Ge(yt,ne)}),e.jsx(Nt,{className:O("h-4 w-4 text-muted-foreground transition-transform",re?"rotate-180":"")})]})]}),re&&!bt&&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 te=_.mode===yt,we=pn(_.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",te?"bg-primary/10":void 0),style:te&&we?{backgroundColor:we.background??void 0}:void 0,children:[Ge(_.mode,ne),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:je?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:je.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:ke.length>0?ke.map(({key:ge,icon:_,label:te})=>Rt(_,te,`cap-${ge}`)):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:ge,icon:_,label:te})=>Rt(_,`${te} input`,`input-${ge}`)):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:ge,icon:_,label:te})=>Rt(_,`${te} output`,`output-${ge}`)):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)"}),wt.map(ge=>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:ge.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ge.value})]},ge.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(ge=>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:ge.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ge.value})]},ge.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:Wl(je.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:Vl(je.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),Fn=(ge,_,te,we,$e,Oe)=>{const de=u(_,te),Le=ua(de).map($t=>({...$t,id:`cap-${$t.key}`})),Se=[...un(de,"input"),...un(de,"output")],Ve=Array.from(new Map(Se.map($t=>[$t.key,$t])).values()).map($t=>({...$t,id:`mod-${$t.key}`})),et=[...Le,...Ve],nt=ks(de?.limit?.context),ts=t===_&&n===te,Lt=D(_,te);return e.jsxs("div",{ref:$t=>{I.current[$e]=$t},className:O("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",Oe?"bg-accent":"hover:bg-accent/50"),onClick:()=>ot(_,te),onMouseEnter:()=>K($e),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(ge)}),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",Oe?"flex":"hidden group-hover:flex"),children:et.map(({id:$t,icon:sm,label:Bi})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":Bi,role:"img",title:Bi,children:e.jsx(sm,{className:"h-2.5 w-2.5"})},$t))}),ts&&e.jsx(Dt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:$t=>{$t.preventDefault(),$t.stopPropagation(),L(_,te)},className:O("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Lt?"text-yellow-500":"text-muted-foreground"),"aria-label":Lt?"Unfavorite":"Favorite",title:Lt?"Remove from favorites":"Add to favorites",children:Lt?e.jsx(er,{className:"h-3.5 w-3.5"}):e.jsx(Hr,{className:"h-3.5 w-3.5"})})]})]},`${we}-${_}-${te}`)},Pr=(ge,_,te)=>{if(!te.trim())return!0;const we=te.toLowerCase();return ge.toLowerCase().includes(we)||_.toLowerCase().includes(we)},Uo=()=>{const ge=A.filter(({model:Se,providerID:Ve})=>{const nt=r.find(Lt=>Lt.id===Ve)?.name||Ve,ts=Ae(Se);return Pr(ts,nt,Ee)}),_=P.filter(({model:Se,providerID:Ve})=>{const nt=r.find(Lt=>Lt.id===Ve)?.name||Ve,ts=Ae(Se);return Pr(ts,nt,Ee)}),te=r.map(Se=>{const et=(Array.isArray(Se.models)?Se.models:[]).filter(nt=>{const ts=Ae(nt);return Pr(ts,Se.name||Se.id||"",Ee)});return{...Se,models:et}}).filter(Se=>Se.models.length>0),we=ge.length>0||_.length>0||te.length>0,$e=[];ge.forEach(({model:Se,providerID:Ve,modelID:et})=>{$e.push({model:Se,providerID:Ve,modelID:et,section:"fav"})}),_.forEach(({model:Se,providerID:Ve,modelID:et})=>{$e.push({model:Se,providerID:Ve,modelID:et,section:"recent"})}),te.forEach(Se=>{Se.models.forEach(Ve=>{$e.push({model:Ve,providerID:Se.id,modelID:Ve.id,section:"provider"})})});const Oe=$e.length,de=Se=>{if(Se.key==="ArrowDown")Se.preventDefault(),Se.stopPropagation(),K(Ve=>(Ve+1)%Math.max(1,Oe)),setTimeout(()=>{const Ve=(G+1)%Math.max(1,Oe);I.current[Ve]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Se.key==="ArrowUp")Se.preventDefault(),Se.stopPropagation(),K(Ve=>(Ve-1+Math.max(1,Oe))%Math.max(1,Oe)),setTimeout(()=>{const Ve=(G-1+Math.max(1,Oe))%Math.max(1,Oe);I.current[Ve]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Se.key==="Enter"){Se.preventDefault(),Se.stopPropagation();const Ve=$e[G];Ve&&ot(Ve.providerID,Ve.modelID)}else Se.key==="Escape"&&(Se.preventDefault(),Se.stopPropagation(),me(!1))};let Le=0;return e.jsxs(Xe,{delayDuration:1e3,children:[U?e.jsxs("button",{type:"button",onClick:()=>F("model"),onTouchStart:()=>$s("model"),onTouchEnd:Ns,onTouchCancel:Ns,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(zt,{providerId:t,className:O(ie,"flex-shrink-0")}):e.jsx(Zs,{className:O(ie,"text-muted-foreground")}),e.jsx("span",{className:O("model-controls__model-label typography-micro font-medium truncate min-w-0",!$&&"max-w-[220px]"),children:Ke()})]}):e.jsxs(qt,{open:W,onOpenChange:me,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(Kt,{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(zt,{providerId:t,className:O(ie,"flex-shrink-0")}),e.jsx(Zs,{className:O(ie,"text-primary/60 hidden")})]}):e.jsx(Zs,{className:O(ie,"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(Yt,{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(sr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(it,{type:"text",placeholder:"Search models",value:Ee,onChange:Se=>Pe(Se.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"}),ge.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(er,{className:"h-4 w-4 text-primary"}),"Favorites"]}),ge.map(({model:Se,providerID:Ve,modelID:et})=>{const nt=Le++;return Fn(Se,Ve,et,"fav",nt,G===nt)})]}),_.length>0&&e.jsxs(e.Fragment,{children:[ge.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(qs,{className:"h-4 w-4"}),"Recent"]}),_.map(({model:Se,providerID:Ve,modelID:et})=>{const nt=Le++;return Fn(Se,Ve,et,"recent",nt,G===nt)})]}),(ge.length>0||_.length>0)&&te.length>0&&e.jsx(Us,{}),te.map((Se,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(zt,{providerId:Se.id,className:"h-4 w-4 flex-shrink-0"}),Se.name]}),Se.models.map(et=>{const nt=Le++;return Fn(et,Se.id,et.id,"provider",nt,G===nt)})]},Se.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()]})},Wo=()=>{if(!E)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 ge=Object.entries(E.tools||{}).filter(([,de])=>de).map(([de])=>de).sort(),_=!!(E.prompt&&E.prompt.trim().length>0),te=E.model?.providerID&&E.model?.modelID,we=E.temperature!==void 0||E.topP!==void 0,$e=de=>Ge(de==="full"||de==="allow"||de==="deny"?de:"ask","h-3.5 w-3.5"),Oe=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:kt(E.name)}),E.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:E.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:E.mode==="primary"?"Primary":E.mode==="subagent"?"Subagent":E.mode==="all"?"All":"—"})]}),(te||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"}),te?e.jsxs("span",{className:"typography-meta text-foreground",children:[E.model.providerID," / ",E.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:[E.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:E.temperature})]}),E.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:E.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"}),ge.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:ge.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:[$e(E.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Oe(E.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:[$e(typeof E.permission?.bash=="string"?E.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Oe(typeof E.permission?.bash=="string"?E.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:[$e(E.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Oe(E.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(to,{className:"h-4 w-4 text-foreground"})]})]})})},Pn=()=>U?e.jsxs("button",{type:"button",onClick:()=>F("agent"),onTouchStart:()=>$s("agent"),onTouchEnd:Ns,onTouchCancel:Ns,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",U&&"ml-1"),children:[e.jsx(jn,{className:O(ie,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${ir(o).var})`}:void 0}),e.jsx("span",{className:O("model-controls__agent-label",Ie,"font-medium truncate min-w-0"),style:o?{color:`var(${ir(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(qt,{children:[e.jsx(Qe,{asChild:!0,children:e.jsx(Kt,{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(jn,{className:O(ie,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${ir(o).var})`}:void 0}),e.jsx("span",{className:O("model-controls__agent-label",Ie,"font-medium min-w-0 truncate",R?"max-w-[220px]":void 0),style:o?{color:`var(${ir(o).var})`}:void 0,children:ft()})]})})}),e.jsxs(Yt,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[p.filter(ge=>Kn(ge.mode)).map(ge=>e.jsx(St,{className:"typography-meta",onSelect:()=>Pt(ge.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",ir(ge.name).class)}),e.jsx("span",{className:"font-medium",children:kt(ge.name)})]}),ge.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:ge.description})]})},ge.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:bt,onClick:()=>{bt||ce(ge=>!ge)},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",bt?"cursor-not-allowed opacity-60":void 0),"aria-expanded":ye,"aria-controls":Ce,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:gt?gt.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",!gt&&"text-muted-foreground"),style:gt?{color:gt.text}:void 0,children:Ge(yt)}),e.jsx(Nt,{className:O("h-3.5 w-3.5 transition-transform text-muted-foreground",ye?"rotate-180":"")})]})]}),ye&&!bt&&e.jsx("div",{id:Ce,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(ge=>{const _=ge.mode===yt,te=pn(ge.mode);return e.jsxs("button",{type:"button",disabled:ge.disabled,onClick:()=>rt(ge.mode),className:O("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",ge.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",_?"bg-primary/10":void 0),style:_&&te?{backgroundColor:te.background??void 0}:void 0,children:[Ge(ge.mode,ne),e.jsx("span",{className:"typography-meta font-medium",style:{color:te?te.text:"var(--foreground)"},children:ge.label})]},ge.mode)})})]})]})]}),Wo()]})}),Vo=O("@container/model-controls flex items-center min-w-0",_e,$&&"w-full",s);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Vo,children:[e.jsx("div",{className:O("flex items-center min-w-0 flex-1 justify-end",$&&"overflow-hidden"),children:Uo()}),e.jsx("div",{className:O("flex items-center min-w-0",_e,$&&"flex-shrink-0"),children:Pn()})]}),Ho(),pr(),on(),zo()]})},Fx=s=>s?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(s):!0,ql=(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(!Fx(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}},hu=s=>({id:s.id,content:s.content,status:s.status||"pending",priority:s.priority||"medium"}),Ga=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(hu);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"})),Px=(s,r)=>{const t=r.map(hu);Ga.getState().updateTodos(s,t)},Kl=[{variant:"shine",component:({children:s,className:r,...t})=>e.jsx(Or.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(Or.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(Or.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(Or.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(Or.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 ma({variant:s="shine",className:r,...t}){const a=Kl.find(i=>i.variant===s)?.component||Kl[0].component;return e.jsx(Xc,{children:e.jsx(a,{...t,className:r})})}const Yl=1500,Rx=2e3;function Lx({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),b=Ne.useRef(null),g=Ne.useRef(null),y=Ne.useRef(null),x=Ne.useRef(null),w=Ne.useRef(!1),S=Ne.useRef(!1),k=Ne.useRef(!1),j=Ne.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),y.current&&(clearTimeout(y.current),y.current=null)},[]),N=Ne.useCallback((P,$)=>{j(),b.current=null,m(P),p($),d("showing"),h.current=Date.now(),w.current=!0},[j]),L=Ne.useCallback(()=>{if(g.current)return;const P=Date.now()-h.current,$=Math.max(0,Yl-P);g.current=setTimeout(()=>{g.current=null;const R=b.current;R&&N(R.text,R.permission)},$)},[N]),D=Ne.useCallback(P=>{if(j(),b.current=null,!w.current){d("idle"),m(null),i?.(!1);return}if(P==="done"&&o&&x.current===o){d("idle"),m(null),w.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"),w.current=!1,i?.(!1)},Rx)},[j,o,i]);if(Ne.useEffect(()=>{if(n&&!k.current){k.current=!0,D("aborted");return}if(k.current=!!n,a&&!S.current){S.current=!0,D("done");return}if(!a&&S.current&&(S.current=!1),!(c==="done"||c==="aborted")&&s){const $=Date.now()-h.current;if(c==="idle"||!u)N(s,!!t);else if(s!==u||!!t!==f){if(r)return;$>=Yl?N(s,!!t):(b.current={text:s,permission:!!t},L())}}},[s,t,n,a,c,u,f,N,D,L,r]),Ne.useEffect(()=>()=>j(),[j]),Ne.useEffect(()=>{const P=()=>{typeof document>"u"||document.visibilityState==="visible"&&(c==="done"||c==="aborted")&&(j(),d("idle"),m(null),w.current=!1)};return document.addEventListener("visibilitychange",P),()=>document.removeEventListener("visibilitychange",P)},[c,j]),c==="idle"&&!u)return null;let M,v=!0;c==="done"?(M="Done",v=!1):c==="aborted"?(M="Aborted",v=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const C=v?`${M}...`:M,A=c!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${A?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":M,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:c==="done"?e.jsx(ma,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):c==="aborted"?e.jsx(ma,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(ma,{variant:"shine",className:"typography-ui-header",children:C})})})}const Xl={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},$x=({todo:s})=>{const r=Xl[s.status]||Xl.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})})},Ql=[],Ox=({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=pe($=>$.currentSessionId),b=Ga($=>h?$.sessionTodos.get(h)??Ql:Ql),g=Ga($=>$.loadTodos),{isMobile:y}=Fe(),x=y||Et();l.useEffect(()=>{h&&g(h)},[h,g]);const w=l.useMemo(()=>{const $={in_progress:0,pending:1,completed:2,cancelled:3};return[...b].filter(R=>R.status!=="cancelled").sort((R,H)=>$[R.status]-$[H.status])},[b]),S=l.useMemo(()=>w.find($=>$.status==="in_progress")||w.find($=>$.status==="pending")||null,[w]),k=l.useMemo(()=>{const $=b.filter(H=>H.status!=="cancelled").length;return{completed:b.filter(H=>H.status==="completed").length,total:$}},[b]),j=w.length>0,N=!m&&(o||!a),[L,D]=l.useState(!1),M=s||c||o||L||j||m,v=l.useRef(null);if(l.useEffect(()=>{if(!f)return;const $=R=>{v.current&&!v.current.contains(R.target)&&p(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[f]),!M)return null;const C=()=>p($=>!$),A=d&&u?e.jsx("button",{type:"button",onClick:u,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:e.jsx(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:[k.completed,"/",k.total]}),f?e.jsx(Fo,{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"]})}):N?e.jsx(Lx,{statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,completionId:i??null,isComplete:c,onResultVisibilityChange:D},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:v,children:[A,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:[k.completed,"/",k.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:w.map($=>e.jsx($x,{todo:$},$.id))})]})]})]})})},qa=s=>!s||typeof s!="object"?!1:!!s.synthetic,Jl=s=>!Array.isArray(s)||s.length===0?!1:s.every(r=>qa(r)),_x=s=>!Array.isArray(s)||s.length===0?[]:s.some(t=>!qa(t))?s.filter(t=>!qa(t)):s,Bx={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function zx(s){const r=pe(t=>!s||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(s)??"idle");return l.useMemo(()=>{if(r==="idle")return Bx;const t=r==="busy",n=r==="cooldown";return{phase:r,isWorking:t||n,isBusy:t,isCooldown:n}},[r])}function Di(){const s=pe(r=>r.currentSessionId);return zx(s)}const Hx={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},Zl=s=>s.role==="assistant",Ux=s=>s.type==="reasoning",gu=s=>s.type==="text",ec=s=>{if(gu(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},tc=s=>(gu(s)||Ux(s),s.time),Wx=s=>{if(s.tool)return s.tool;const r=s;return typeof r.name=="string"?r.name:"tool"};function xu(){const{currentSessionId:s,messages:r,permissions:t,sessionAbortFlags:n}=pe(oi(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=Di(),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=>Zl(M.info)&&!Jl(M.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const b=[...h].sort((M,v)=>{const C=typeof M.info.time?.created=="number"?M.info.time.created:null,A=typeof v.info.time?.created=="number"?v.info.time.created:null;return C!==null&&A!==null&&C!==A?C-A:M.info.id.localeCompare(v.info.id)}),g=b[b.length-1];let y,x;const w=new Set(["edit","write"]);for(let M=(g.parts??[]).length-1;M>=0;M-=1){const v=g.parts?.[M];if(v)switch(v.type){case"reasoning":{const C=v.time??tc(v);(!C||typeof C.end>"u")&&!y&&(y="reasoning");break}case"tool":{const C=v.state?.status;if((C==="running"||C==="pending")&&!y){const A=Wx(v);w.has(A)?y="editing":(y="tool",x=A)}break}case"text":{const C=ec(v)??"";if(typeof C=="string"&&C.trim().length>0){const A=tc(v);(!A||typeof A.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"},k=["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}`,N=()=>k[Math.floor(Math.random()*k.length)],L=y===void 0,D=y==="editing"?"editing file":y==="tool"&&x?j(x):y==="reasoning"?"thinking":y==="text"?"composing":N();return{activePartType:y,activeToolName:x,statusText:D,isGenericStatus:L}},[c]),u=l.useMemo(()=>{const h=s,b=h?n?.get(h)??null:null,g=!!(b&&!b.acknowledged);return{wasAborted:g,abortActive:g}},[s,n]),m=l.useMemo(()=>{if(u.wasAborted)return{...Hx,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,b=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:b,isCooldown:g,lifecyclePhase:b?"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 b=c.filter(x=>Zl(x.info)&&!Jl(x.parts));if(b.length===0)return{isActive:h,characterCount:0};const g=b[b.length-1];let y=0;return(g.parts??[]).forEach(x=>{if(x.type!=="text")return;const w=ec(x)??"";typeof w=="string"&&w.trim().length>0&&(y+=w.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 Vx=8,sc=[],Gx=s=>s==="primary"||s==="all"||s===void 0||s===null,Xn=({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(""),[b,g]=l.useState(!1),[y,x]=l.useState(""),[w,S]=l.useState(null),k=l.useRef(null),j=l.useRef(null),N=l.useRef(null),L=l.useRef(null),D=l.useRef(null),M=pe(_=>_.sendMessage),v=pe(_=>_.currentSessionId),C=pe(_=>_.newSessionDraft?.open),A=pe(_=>_.abortCurrentOperation),P=pe(_=>_.acknowledgeSessionAbort),$=pe(_=>_.abortPromptSessionId),R=pe(_=>_.abortPromptExpiresAt),H=pe(_=>_.clearAbortPrompt),U=pe(_=>_.sessionAbortFlags),Y=pe(_=>_.attachedFiles),F=pe(_=>_.addAttachedFile),B=pe(_=>_.addServerFile),T=pe(_=>_.clearAttachedFiles),V=pe(_=>_.saveSessionAgentSelection),X=pe(_=>_.consumePendingInputText),fe=pe(_=>_.pendingInputText),{currentProviderId:ae,currentModelId:xe,currentAgentName:Me,setAgent:Q,getVisibleAgents:re}=ut(),oe=re(),{isMobile:W,inputBarOffset:me,isKeyboardOpen:ye,setTimelineDialogOpen:ce}=Fe(),{working:Ce}=xu(),[Ee,Pe]=l.useState(!1),G=l.useRef(null),K=l.useRef(!1),I=l.useRef(!1),J=zs(_=>_.queueModeEnabled),E=zs(l.useCallback(_=>v?_.queuedMessages[v]??sc:sc,[v])),z=zs(_=>_.addToQueue),q=zs(_=>_.clearQueue),{phase:be}=Di(),ee=l.useRef(be),he=l.useRef(!1),He=l.useCallback(_=>{if(!W||_.pointerType!=="touch")return;const te=k.current;if(!te||document.activeElement===te)return;_.preventDefault(),_.stopPropagation();const we=document.scrollingElement;we&&we.scrollTop!==0&&(we.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{te.focus({preventScroll:!0})}catch{te.focus()}const $e=te.value.length;try{te.setSelectionRange($e,$e)}catch{}},[W]);l.useEffect(()=>{if(fe!==null){const _=X();_&&(n(_),setTimeout(()=>{k.current?.focus()},0))}},[fe,X]);const We=l.useMemo(()=>{if(Me)return oe.find(_=>_.name===Me)},[oe,Me]),Be=l.useMemo(()=>{const _=We?.permission?.edit;let te="ask";(_==="allow"||_==="ask"||_==="deny"||_==="full")&&(te=_);const we=We?We.tools?.edit!==!1:!1;return(!We||!we)&&(te="deny"),te},[We]),Ze=pe(l.useCallback(_=>!v||!Me?void 0:_.sessionAgentEditModes.get(v)?.get(Me),[v,Me])),lt=We?.permission?.webfetch,ct=We?.permission?.bash,dt=l.useMemo(()=>pu({agentDefaultEditMode:Be,webfetchPermission:lt,bashPermission:ct}),[Be,lt,ct]),mt=!!(v&&Me),yt=l.useMemo(()=>mt&&Ze&&dt.modeAvailability[Ze]?Ze:dt.cascadeDefaultMode,[dt,mt,Ze]),vt=l.useMemo(()=>pn(yt),[yt]),gt=l.useCallback(_=>Et()?`color-mix(in srgb, ${_} 55%, transparent)`:_,[]),bt=l.useMemo(()=>{const _=Et()?1:2;if(!vt)return{borderWidth:_};const te=vt.border??vt.text;return{borderColor:gt(te),borderWidth:_}},[vt,gt]),Z=t.trim()||Y.length>0,De=E.length>0,ne=Z||De,ie=Ce.isWorking,Ie=l.useMemo(()=>v?$===v&&!!R:!1,[$,R,v]),_e=l.useCallback(()=>{if(!Z||!v)return;const _=t.replace(/^\n+|\n+$/g,""),te=Y.map(we=>({...we}));z(v,{content:_,attachments:te.length>0?te:void 0}),n(""),te.length>0&&T(),W||k.current?.focus()},[Z,v,t,Y,z,T,W]),ze=async _=>{if(_?.preventDefault(),!ne||!v&&!C)return;if(r?.({instant:!0,force:!0}),!ae||!xe){console.warn("Cannot send message: provider or model not selected");return}let te="",we=[],$e;const Oe=[];for(let Se=0;Se<E.length;Se++){const Ve=E[Se],{sanitizedText:et,mention:nt}=ql(Ve.content,oe);!$e&&nt?.name&&($e=nt.name),Se===0?(te=et,we=Ve.attachments??[]):Oe.push({text:et,attachments:Ve.attachments})}if(Z){const Se=t.replace(/^\n+|\n+$/g,""),{sanitizedText:Ve,mention:et}=ql(Se,oe),nt=Y.map(ts=>({...ts}));!$e&&et?.name&&($e=et.name),E.length===0?(te=Ve,we=nt):Oe.push({text:Ve,attachments:nt.length>0?nt:void 0})}if(!te&&Oe.length===0)return;v&&De&&q(v),n(""),Y.length>0&&T(),W&&k.current?.blur();const de=te.trimStart();if(de.startsWith("/")){const Se=de.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(Se==="undo"&&v){await pe.getState().handleSlashUndo(v),r?.({instant:!0,force:!0});return}else if(Se==="redo"&&v){await pe.getState().handleSlashRedo(v),r?.({instant:!0,force:!0});return}else if(Se==="timeline"&&v){ce(!0),n("");return}else Se==="summarize"&&r?.({instant:!0,force:!0})}const Le=[...we,...Oe.flatMap(Se=>Se.attachments??[])];await M(te,ae,xe,Me,we,$e,Oe.length>0?Oe:void 0).catch(Se=>{const Ve=Se instanceof Error?Se.message:typeof Se=="string"?Se:String(Se??""),et=Ve.toLowerCase();console.error("Message send failed:",Ve||Se),!(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||k.current?.focus()},Ge=l.useRef(ze);Ge.current=ze,l.useEffect(()=>{const _=ee.current==="busy"||ee.current==="cooldown",te=be==="idle",we=v&&U.has(v)&&(()=>{const $e=U.get(v);return $e?Date.now()-$e.timestamp<2e3:!1})();_&&te&&E.length>0&&!he.current&&!we&&(he.current=!0,setTimeout(()=>{v&&ae&&xe&&Ge.current(),he.current=!1},100)),ee.current=be},[be,E.length,v,ae,xe,U]);const rt=_=>{if(m&&L.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),L.current.handleKeyDown(_.key);return}if(b&&D.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),D.current.handleKeyDown(_.key);return}if(i&&N.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),N.current.handleKeyDown(_.key);return}if(_.key==="Tab"&&!m&&!i){_.preventDefault(),je();return}if(_.key==="Enter"&&!_.shiftKey&&!W){_.preventDefault();const te=_.ctrlKey||_.metaKey,we=Z&&v&&be!=="idle";J?te||!we?ze():_e():te&&we?_e():ze()}},le=l.useCallback(()=>{G.current&&(clearTimeout(G.current),G.current=null),Pe(!0),G.current=setTimeout(()=>{Pe(!1),G.current=null},1800)},[]),ue=l.useCallback(()=>{H(),le(),A()},[A,H,le]),je=()=>{const _=oe.filter(Oe=>Gx(Oe.mode));if(_.length<=1)return;const we=(_.findIndex(Oe=>Oe.name===Me)+1)%_.length,$e=_[we];Q($e.name),v&&V(v,$e.name)},ke=l.useCallback(()=>{const _=k.current;if(!_)return;_.style.height="auto";const te=_.ownerDocument?.defaultView,we=te?te.getComputedStyle(_):null,$e=we?parseFloat(we.lineHeight):NaN,Oe=we?parseFloat(we.paddingTop):NaN,de=we?parseFloat(we.paddingBottom):NaN,Le=22,Ve=Number.isNaN(Oe)||Number.isNaN(de)?16:Oe+de,nt=(Number.isNaN($e)?Le:$e)*Vx+Ve,ts=_.scrollHeight||_.offsetHeight,Lt=Math.min(ts,nt);_.style.height=`${Lt}px`,_.style.maxHeight=`${nt}px`,S($t=>$t&&$t.height===Lt&&$t.maxHeight===nt?$t:{height:Lt,maxHeight:nt})},[]);l.useLayoutEffect(()=>{ke()},[ke,t,W]);const Te=l.useCallback((_,te)=>{if(_.startsWith("/")){const de=_.indexOf(" "),Le=_.indexOf(`
|
|
64
|
-
`),Se=Math.min(de===-1?_.length:de,Le===-1?_.length:Le);if(te<=Se&&de===-1){const Ve=_.substring(1,Se);h(Ve),f(!0),c(!1),g(!1)}else f(!1);return}f(!1);const we=_.substring(0,te),$e=we.lastIndexOf("#");if($e!==-1){const de=$e>0?we[$e-1]:null,Le=we.substring($e+1),Se=Le.includes(" ")||Le.includes(`
|
|
65
|
-
`);if((!de||/\s/.test(de))&&!Se){x(Le),g(!0),c(!1);return}}g(!1),x("");const Oe=we.lastIndexOf("@");if(Oe!==-1){const de=we.substring(Oe+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 te=k.current;if(!te){const Le=t+_;n(Le),Te(Le,Le.length),requestAnimationFrame(()=>ke());return}const we=te.selectionStart??t.length,$e=te.selectionEnd??t.length,Oe=`${t.substring(0,we)}${_}${t.substring($e)}`;n(Oe);const de=we+_.length;requestAnimationFrame(()=>{const Le=k.current;Le&&(Le.selectionStart=de,Le.selectionEnd=de),ke()}),Te(Oe,de)},[ke,t,Te]),wt=_=>{const te=_.target.value,we=_.target.selectionStart??te.length;n(te),ke(),Te(te,we)},At=l.useCallback(async _=>{const te=new Map;Array.from(_.clipboardData.files||[]).forEach(de=>{de.type.startsWith("image/")&&te.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&&te.set(`${Le.name}-${Le.size}`,Le)}});const we=Array.from(te.values());if(we.length===0||!v&&!C)return;_.preventDefault();const $e=_.clipboardData.getData("text");$e&&Ue($e);let Oe=0;for(const de of we){const Le=pe.getState().attachedFiles.length;try{await F(de),pe.getState().attachedFiles.length>Le&&(Oe+=1)}catch(Se){console.error("Clipboard image attach failed",Se),se.error(Se instanceof Error?Se.message:"Failed to attach image from clipboard")}}Oe>0&&se.success(`Attached ${Oe} image${Oe>1?"s":""} from clipboard`)},[F,v,C,Ue]),Mt=_=>{const te=k.current?.selectionStart||0,$e=t.substring(0,te).lastIndexOf("@");if($e!==-1){const Oe=t.substring(0,$e)+_.name+t.substring(te);n(Oe)}c(!1),u(""),k.current?.focus()},pt=_=>{const we=k.current?.selectionStart??t.length,Oe=t.substring(0,we).lastIndexOf("#");if(Oe!==-1){const de=t.substring(0,Oe)+`#${_} `+t.substring(we);n(de);const Le=Oe+_.length+2;requestAnimationFrame(()=>{k.current&&(k.current.selectionStart=Le,k.current.selectionEnd=Le),ke(),Te(de,Le)})}g(!1),x(""),k.current?.focus()},st=_=>{n(`/${_.name} `);const te=k.current;te&&(te._commandMetadata=_),f(!1),h(""),setTimeout(()=>{k.current&&(k.current.focus(),k.current.setSelectionRange(k.current.value.length,k.current.value.length))},0)};l.useEffect(()=>{v&&k.current&&!W&&k.current.focus()},[v,W]),l.useEffect(()=>{$&&$!==v&&H()},[$,v,H]);const jt=_=>{_.preventDefault(),_.stopPropagation(),(v||C)&&!o&&a(!0)},Pt=_=>{_.preventDefault(),_.stopPropagation(),_.currentTarget===_.target&&a(!1)},ot=async _=>{if(_.preventDefault(),_.stopPropagation(),a(!1),!v&&!C)return;const te=Array.from(_.dataTransfer.files);let we=0;for(const $e of te){const Oe=pe.getState().attachedFiles.length;try{await F($e),pe.getState().attachedFiles.length>Oe&&(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 te=0;for(const we of _){const $e=pe.getState().attachedFiles.length;try{await B(we.path,we.name),pe.getState().attachedFiles.length>$e&&(te+=1)}catch(Oe){console.error("Server file attach failed",Oe),se.error(Oe instanceof Error?Oe.message:"Failed to attach file")}}te>0&&se.success(`Attached ${te} file${te>1?"s":""}`)},[B]),qe=l.useRef(null),[Ke,ft]=l.useState(!1),kt=l.useCallback(async _=>{let te=0;const we=Array.isArray(_)?_:Array.from(_);for(const $e of we){const Oe=pe.getState().attachedFiles.length;try{await F($e),pe.getState().attachedFiles.length>Oe&&(te+=1)}catch(de){console.error("File attach failed",de),se.error(de instanceof Error?de.message:"Failed to attach file")}}te>0&&se.success(`Attached ${te} file${te>1?"s":""}`)},[F]),Rt=l.useCallback(async()=>{try{const te=await(await fetch("/api/vscode/pick-files")).json(),we=Array.isArray(te?.files)?te.files:[],$e=Array.isArray(te?.skipped)?te.skipped:[];if($e.length>0){const de=$e.map(Le=>`${Le?.name||"file"}: ${Le?.reason||"skipped"}`).join(`
|
|
67
|
-
`);se.error(`Some files were skipped:
|
|
68
|
-
${de}`)}const Oe=we.map(de=>{if(!de?.dataUrl)return null;try{const[Le,Se]=de.dataUrl.split(","),Ve=de.mimeType||Le?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Se)return null;const et=atob(Se),nt=new Uint8Array(et.length);for(let Lt=0;Lt<et.length;Lt++)nt[Lt]=et.charCodeAt(Lt);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);Oe.length>0&&await kt(Oe)}catch(_){console.error("VS Code file pick failed",_),se.error(_ instanceof Error?_.message:"Failed to pick files in VS Code")}},[kt]),cs=l.useCallback(()=>{if(Et()){Rt();return}qe.current?.click()},[Rt]),$s=l.useCallback(async _=>{const te=_.target.files;te&&(await kt(te),_.target.value="")},[kt]),Ns="gap-x-1.5 gap-y-0",on=Et(),zo=W?"px-1.5 py-1.5":on?"px-1.5 py-1":"px-2.5 py-1.5",Ho=W?"h-9 w-9":on?"h-[22px] w-[22px]":"h-7 w-7",pr=W?"h-5 w-5":on?"h-4 w-4":"h-[18px] w-[18px]",hr=O(Ho,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),Pr=!W&&Ie&&ie?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:!ne||!v&&!C,onPointerDownCapture:_=>{!W||_.pointerType!=="touch"||!ne||!v&&!C||(I.current=!0,_.preventDefault(),_.stopPropagation(),ze())},onClick:_=>{if(W){if(I.current){I.current=!1;return}_.preventDefault(),ze()}},className:O(hr,ne&&(v||C)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(td,{className:O(pr)})}),Uo=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:qe,type:"file",multiple:!0,className:"hidden",onChange:$s,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(Nx,{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(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx("button",{type:"button",className:hr,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(sd,{className:O(pr,"text-current")})})}),e.jsxs(Yt,{align:"start",children:[e.jsxs(St,{onSelect:()=>{requestAnimationFrame(()=>cs())},children:[e.jsx(po,{}),"Attach files"]}),e.jsxs(St,{onSelect:()=>{requestAnimationFrame(()=>{ft(!0)})},children:[e.jsx(vf,{}),"Attach from project"]})]})]})]})]}),Wo=s?e.jsx("button",{type:"button",onClick:s,className:hr,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(jn,{className:O(pr,"text-current")})}):null,Pn=e.jsxs(e.Fragment,{children:[Uo,Wo]}),Vo=Ce.statusText;l.useEffect(()=>{const _=!!Ce.wasAborted;!K.current&&_&&!Ee&&(le(),v&&P(v)),K.current=_},[P,v,Ee,le,Ce.wasAborted]),l.useEffect(()=>()=>{G.current&&(clearTimeout(G.current),G.current=null)},[]);const ge=W&&ie;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(Ox,{isWorking:Ce.isWorking,statusText:Vo,isGenericStatus:Ce.isGenericStatus,isWaitingForPermission:Ce.isWaitingForPermission,wasAborted:Ce.wasAborted,abortActive:Ce.abortActive,completionId:Ce.lastCompletionId,isComplete:Ce.isComplete,showAbort:ge,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:Pt,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(po,{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(bx,{}),e.jsx(cu,{onEditMessage:_=>{n(_),setTimeout(()=>{k.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:bt,children:[m&&e.jsx(uu,{ref:L,searchQuery:p,onCommandSelect:st,onClose:()=>f(!1)}),b&&e.jsx(mu,{ref:D,searchQuery:y,onAgentSelect:pt,onClose:()=>g(!1)}),i&&e.jsx(wx,{ref:N,searchQuery:d,onFileSelect:Mt,onClose:()=>c(!1)}),e.jsx(bs,{ref:k,"data-chat-input":"true",value:t,onChange:wt,onKeyDown:rt,onPaste:At,onPointerDownCapture:He,placeholder:v||C?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!v&&!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:w?`${w.height}px`:void 0,maxHeight:w?`${w.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:O("rounded-b-xl bg-transparent",zo,W?"flex items-center gap-x-1.5":O("flex items-center justify-between",Ns)),"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:Pn}),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(Gl,{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",Ns),children:Pn}),e.jsxs("div",{className:O("flex items-center flex-1 justify-end",Ns,"md:gap-x-3"),children:[e.jsx(Gl,{className:O("flex-1 min-w-0 justify-end")}),Pr]})]})})]})]})]})};function fa({className:s,...r}){return e.jsx("div",{"data-slot":"skeleton",className:O("bg-accent animate-pulse rounded-xl",s),...r})}const rc=(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=(w,S,k)=>w+(S-w)*k,h=(w,S,k,j,N,L)=>{const D=p(w,S,N),M=p(j,k,N);return p(D,M,L)},b={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${b.x} ${b.y} L${g.x} ${g.y} L${y.x} ${y.y} L${x.x} ${x.y} Z`,row:i,col:c})}return a},Ai=({className:s="",width:r=70,height:t=70,isAnimated:n=!1})=>{const o=_o();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,b={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},w={x:50-m*f,y:h+m*p},S={x:50+m*f,y:h+m*p},k={x:50,y:h+m},N=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(b.y+g.y+x.y+y.y)/4})`,L=rc(g,x,k,w),D=rc(x,y,S,k),M=Ne.useMemo(()=>{const v=[];for(let C=0;C<32;C++)v.push(.1+Math.random()*.5);return v},[]);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${w.x} ${w.y} L${k.x} ${k.y} Z`,fill:c,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),L.map((v,C)=>e.jsx("path",{d:v.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${k.x} ${k.y} Z`,fill:c,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),D.map((v,C)=>e.jsx("path",{d:v.path,fill:u,opacity:M[C+16]},`right-${C}`)),e.jsx("path",{d:`M${b.x} ${b.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:`${N} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function qx({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(b=>{const g=(b+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(jf,{mode:c,initial:!1,children:e.jsx(Or.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const Kx=["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"],Yx=()=>{const s=_o();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(Ai,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(qx,{className:"text-body-md",interval:4,transition:{duration:.5},children:Kx.map(n=>e.jsxs("span",{style:{color:t},children:['"',n,'…"']},n))})]})},pa=l.memo(Yx),Xx={'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"}},Qx={'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 lr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return lr.instance||(lr.instance=new lr),lr.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 yu(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})},Jx=({isUser:s,providerID:r,agentName:t,modelName:n,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:c}=ru(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(ws,{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(${ir(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",ir(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},Zx=l.memo(Jx),nc=(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},oc=()=>{if(!Et()||typeof window>"u")return Nl;const s=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(s?.light&&s?.dark){const r=nc({...s.light},`vscode-shiki-light:${String(s.light?.name??"theme")}`),t=nc({...s.dark},`vscode-shiki-dark:${String(s.dark?.name??"theme")}`);return[r,t]}return Nl},bu=()=>{const[s,r]=l.useState(oc);return l.useEffect(()=>{if(!Et()||typeof window>"u")return;const t=n=>{r(oc())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),s},wu=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}},vu=({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
|
-
`)},ey=({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
|
-
`)},ty=({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
|
-
`)},sy=(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)},ry=({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=wu(d),m=c==="csv"?vu(u):ey(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(Ys,{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"})]})]})},ny=({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=wu(i),d=a==="csv"?vu(c):ty(c);sy(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"})]})]})},oy=({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(ry,{tableRef:t}),e.jsx(ny,{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})})]})},ay=({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=b=>{if(typeof b!="string")return{value:void 0,vars:{}};const[g,...y]=b.split(";").map(w=>w.trim()).filter(Boolean),x={};for(const w of y){const S=w.indexOf(":");if(S===-1)continue;const k=w.slice(0,S).trim(),j=w.slice(S+1).trim();!k.startsWith("--")||j.length===0||(x[k]=j)}return{value:g,vars:x}},p=f(t.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[b,g]of Object.entries(p.vars))m[b]=g;const h=f(t.color);h.value&&(m.color=h.value,m["--shiki-light"]=h.value);for(const[b,g]of Object.entries(h.vars))m[b]=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(Ys,{className:"size-3.5"})})})]})},ju={pre:ay,table:oy},iy=({content:s,part:r,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const c=bu(),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(rd,{mode:a?"streaming":"static",shikiTheme:c,className:u,controls:{code:!1,table:!1},components:ju,children:s})});return n?e.jsx(rs,{children:m},d):m},kr=({content:s,className:r,variant:t="assistant"})=>{const n=bu(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:O("break-words",r),children:e.jsx(rd,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:ju,children:s})})},ly={thinking:{label:"Thinking",Icon:Jr},justification:{label:"Justification",Icon:si}},Su=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(),cy=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},Ei=({text:s,variant:r,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>cy(s),[s]),{label:c,Icon:d}=ly[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(Es,{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})})]})},Nu=({part:s,onContentChange:r,messageId:t})=>{const n=s,o=n.text||n.content||"",a=l.useMemo(()=>Su(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Ei,{text:a,variant:"thinking",onContentChange:r,blockId:s.id||`${t}-reasoning`}):null},dy=s=>Su(s),uy=({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?dy(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(Ei,{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(iy,{content:u,part:s,messageId:r,isAnimated:n,isStreaming:!1})},s.id||`${r}-text`)},my=s=>`https://opencode.ai/docs/agents/#${encodeURIComponent(s)}`,fy=({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 b=()=>{u(h.scrollHeight>h.clientHeight)};b();const g=new ResizeObserver(b);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),b=a.slice(0,h),g=a.slice(h+t.token.length);return e.jsxs(e.Fragment,{children:[b,e.jsx("a",{href:my(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`)},py=l.memo(fy),hy=s=>{let r=s.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},ku=s=>s?s.includes("<file_diagnostics>")||s.includes("This file has errors")||s.includes("please fix"):!1,gy=s=>s?s.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",ac=(s,r)=>!s||typeof s!="object"?String(s):pg(s,r||""),ha=(s,r,t)=>{let n=hy(s);if((r==="edit"||r==="multiedit")&&ku(n)&&(n=gy(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},xy=(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:tr.tool.popup,children:n.map((o,a)=>e.jsx("div",{className:"min-w-0",style:{paddingLeft:`${o.depth*20}px`},children:o.isFile?e.jsx("span",{className:"text-foreground/90 block truncate",children:o.name}):e.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[o.name,"/"]})},a))})}catch{return null}},yy=(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:tr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,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}},by=(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:tr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(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}},wy=(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:tr.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",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}},vy=(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:tr.tool.popup,children:e.jsx(kr,{content:s,variant:"tool"})})}catch{return null}},Cu=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},Ka=(s,r,t)=>ug(r,s,t),Mu=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(Sf,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(nd,{className:r}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(Fa,{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(Nf,{className:r}):t==="glob"?e.jsx(kf,{className:r}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(Pa,{className:r}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(Pa,{className:r}):t==="todowrite"||t==="todoread"?e.jsx(Cf,{className:r}):t==="skill"?e.jsx(od,{className:r}):t.startsWith("git")?e.jsx(Ft,{className:r}):e.jsx(Ro,{className:r})},jy=(s,r,t=Date.now())=>{const o=(r?r-s:t-s)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},Sy=({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:jy(s,r,n)})},Ny=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}},Ya=(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},ky=(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 Ya(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 Ya(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:""},Xa=({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})}),Cy=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"},My=s=>s.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Dy=({entries:s,isExpanded:r,hasPrevTool:t,hasNextTool:n,output:o,sessionId:a})=>{const i=pe(g=>g.setCurrentSession),c=l.useMemo(()=>s.filter(g=>g.state?.status==="completed"),[s]),d=typeof o=="string"?My(o):"",u=d.length>0,[m,f]=l.useState(!1),p=g=>{g.stopPropagation(),a&&i(a)};if(c.length===0&&!u&&!a)return null;const h=r?c:c.slice(-6),b=Math.max(0,c.length-h.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:[c.length>0?e.jsx(Xa,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[b>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",b," more…"]}):null,h.map((g,y)=>{const x=typeof g.tool=="string"&&g.tool.trim().length>0?g.tool:"tool",w=Cy(g),S=xi(x).displayName;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:Mu(x)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:S}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:w})]},g.id??`${x}-${y}`)})]})}):null,a&&e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:g=>g.stopPropagation(),onClick:p,children:[e.jsx(fo,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-primary font-medium",children:"Open subAgent session"})]}),u?e.jsxs("div",{className:O("space-y-1",(c.length>0||a)&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:g=>g.stopPropagation(),onClick:g=>{g.stopPropagation(),f(y=>!y)},children:[m?e.jsx(Nt,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Es,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?e.jsx(Xa,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(kr,{content:d,variant:"tool"})})}):null]}):null]})},Ay=({diff:s,syntaxTheme:r,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Cu(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))}),Ey=({content:s,syntaxTheme:r,filePath:t,displayPath:n})=>{const o=s.split(`
|
|
82
|
-
`),a=Ir(t??"")||Ka(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))})]})},Iy=({content:s,filePath:r,displayPath:t})=>{const n=fg(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"}})})]})},Ty=({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,b=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=b?_d(b):!1,w=y?b?Ya(b,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"?ac(u,s.tool):typeof u.content=="string"?u.content??"":ac(u,s.tool),[u,s.tool]),k=S.trim().length>0,j=(L,D)=>e.jsx(Xa,{maxHeightClass:D?.maxHeightClass,className:D?.className,disableHorizontal:D?.disableHorizontal,outerClassName:D?.outerClassName,children:L}),N=()=>{if(s.tool==="todowrite"||s.tool==="todoread"){if(r.status==="completed"&&f){const L=wy(p,{unstyled:!0});return j(L??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 L=xy(p,{unstyled:!0});return j(L??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 L=yy(p,n,{unstyled:!0});return j(L??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 L=by(p,n,{unstyled:!0});return j(L??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(kr,{content:p,variant:"tool"})}));if((s.tool==="web-search"||s.tool==="websearch"||s.tool==="search_web")&&f){const L=vy(p,t,{unstyled:!0});return j(L??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(kr,{content:p,variant:"tool"})}));if(s.tool==="skill"&&f)return j(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(kr,{content:p,variant:"tool"})}));if((s.tool==="edit"||s.tool==="multiedit")&&(!f&&h||p.trim().length===0||ku(p))&&h)return j(e.jsx(Ay,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&p.trim()){if(s.tool==="read"){const L=ha(p,s.tool,d),D=L.split(`
|
|
83
|
-
`),M=typeof u?.offset=="number"?u.offset:0,v=typeof u?.limit=="number"?u.limit:void 0,C=A=>A.trim().startsWith("(");return j(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:D.map((A,P)=>{const $=C(A),R=M+P+1,H=!$&&(v===void 0||P<v);return e.jsxs("div",{className:O("typography-code font-mono flex w-full min-w-0",$&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-3 self-start select-none",children:H?R:""}),e.jsx("div",{className:"flex-1 min-w-0",children:$?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:A}):e.jsx(Bs,{style:t,language:Ka(L,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:A})})]},P)})}),{className:"p-1"})}return j(e.jsx(Bs,{style:t,language:Ka(ha(p,s.tool,d),s.tool,u),PreTag:"div",customStyle:{...so.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:ha(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"?N():e.jsxs(e.Fragment,{children:[y&&x?e.jsx("div",{className:"my-1",children:j(e.jsx(Iy,{content:g,filePath:b,displayPath:w??"New file"}))}):y?e.jsx("div",{className:"my-1",children:j(e.jsx(Ey,{content:g,syntaxTheme:t,filePath:b,displayPath:w??"New file"}))}):k?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:"}),N()]}),r.status==="error"&&"error"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]})]})})},lo=({part:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=s.state,u=ht(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",b=l.useRef(r);l.useEffect(()=>{!f&&!m||b.current!==r&&(b.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const g=d,y=g.metadata,x=g.input,w=g.time,S=l.useRef({}),k=l.useRef(s.id);if(k.current!==s.id&&(k.current=s.id,S.current={}),m){if(typeof w?.start=="number"){const R=S.current.start;(typeof R!="number"||w.start<R)&&(S.current.start=w.start)}typeof w?.end=="number"&&(S.current.end=w.end)}const j=m?S.current.start??w?.start:w?.start,N=m?S.current.end??w?.end:w?.end,L=l.useMemo(()=>{if(!m)return;const R=y;return typeof R?.sessionId=="string"?R.sessionId:void 0},[m,y]),D=l.useMemo(()=>{if(!m)return[];const R=y?.summary;return Array.isArray(R)?R.filter(H=>typeof H=="object"&&H!==null):[]},[m,y]),M=l.useRef(D.length);l.useEffect(()=>{m&&M.current!==D.length&&(M.current=D.length,a?.("structural"))},[m,a,D.length]);const v=s.tool==="edit"||s.tool==="multiedit"?Ny(y):null,C=ky(s,d,o,u),A=xi(s.tool).displayName,P=l.useContext(yi),$=R=>{if(m||!P?.editor){t(s.id);return}let H;if((s.tool==="edit"||s.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(s.tool))&&(H=x?.filePath||x?.file_path||x?.path||y?.filePath||y?.file_path||y?.path),typeof H=="string"){R.stopPropagation();let U=H;H.startsWith("/")||(U=u.endsWith("/")?u+H:u+"/"+H),P.editor.openFile(U)}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:$,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:Mu(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(Es,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:A})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[C&&e.jsx("span",{className:O("truncate",o&&"max-w-[120px]"),children:C}),v&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",v.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",v.removed]})]}),typeof j=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(Sy,{start:j,end:typeof N=="number"?N:void 0,active:!!(m&&p&&typeof N!="number")})})]})]}),m&&(D.length>0||p||f||L)?e.jsx(Dy,{entries:D,isExpanded:r,hasPrevTool:i,hasNextTool:c,output:typeof g.output=="string"?g.output:void 0,sessionId:L}):null,!m&&r?e.jsx(Ty,{part:s,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:c}):null]})},Fy=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(),Py=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=l.useMemo(()=>Fy(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Ei,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},Ry=l.memo(Py),Ly=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(", ")},ic=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}),$y=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},Oy=({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(w=>w+1)},[r,c]);const b=l.useMemo(()=>ic(d?s.filter(x=>x.part.id&&u.has(x.id)):s),[s,d,u]),g=Ly(b),y=$y(b);return b.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(Sn,{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(Es,{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:b.map((x,w)=>{const S=x.part.id||`group-part-${w}`,k=y[S],j=`${S}-exp${p}`;switch(x.kind){case"tool":return e.jsx(rs,{children:e.jsx(lo,{part:x.part,isExpanded:a.has(S),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:k?.hasPrev??!1,hasNextTool:k?.hasNext??!1})},j);case"reasoning":return e.jsx(rs,{children:e.jsx(Nu,{part:x.part,messageId:x.messageId,onContentChange:c})},j);case"justification":return e.jsx(rs,{children:e.jsx(Ry,{part:x.part,messageId:x.messageId,onContentChange:c})},j);default:return null}})})]})})},_y=l.memo(Oy),By=({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}),ga=l.memo(By),Du=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},Au=s=>{if(s.type!=="text")return!1;const r=Du(s);return!r||r.trim().length===0},zy=(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"))},Hy=(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}},Uy=new Set(["task"]),$r=s=>typeof s=="string"&&Uy.has(s.toLowerCase()),Wy=({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),b=l.useMemo(()=>r.filter(D=>D.type!=="text"?!1:!Au(D)),[r]),g=d?.token;let y=!1;const x=!!a,w=!!i,S=!!(n??t),k=!!o,j=l.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),N=l.useCallback(()=>{!S||!x||!k||typeof window>"u"||(j(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[x,j,k,S]);l.useEffect(()=>{k||(p(!1),j())},[j,k]);const L=l.useCallback(D=>{!a||!k||(D.stopPropagation(),D.preventDefault(),a(),S&&N())},[k,S,a,N]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&x&&k?N:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:b.map((D,M)=>{let v;return d&&g&&!y&&Du(D).includes(g)&&(v=d,y=!0),e.jsx(rs,{children:e.jsx(py,{part:D,messageId:s,isMobile:t,agentMention:v})},`user-text-${M}`)})}),e.jsx(iu,{files:r,onShowPopup:c}),x&&k||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:D=>D.stopPropagation(),onClick:D=>{D.stopPropagation(),u()},children:e.jsx(vn,{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:D=>D.stopPropagation(),onClick:D=>{D.stopPropagation(),m()},children:e.jsx(Ft,{className:"h-3.5 w-3.5"})})}),e.jsx(Ye,{sideOffset:6,children:"Fork from here"})]}),x&&k&&e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{type:"button",variant:"ghost",size:"icon","data-visible":f||w?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:D=>D.stopPropagation(),onClick:L,onFocus:()=>p(!0),onBlur:()=>{w||p(!1)},children:w?e.jsx(Dt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ys,{className:"h-3.5 w-3.5"})})}),e.jsx(Ye,{sideOffset:6,children:"Copy message"})]})]}):null]})},Vy=({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:b,copiedMessage:g=!1,onAuxiliaryContentComplete:y,showReasoningTraces:x=!1,turnGroupingContext:w,errorMessage:S})=>{const[k,j]=l.useState(!1),N=l.useRef(null),L=!!b,D=!!g,M=!!(i??a),v=!t,C=l.useMemo(()=>r.filter(ue=>!Au(ue)).filter(ue=>ue.type!=="compaction"),[r]),A=l.useMemo(()=>C.filter(ue=>ue.type==="tool"),[C]),P=l.useMemo(()=>C.filter(ue=>ue.type==="text"),[C]),$=pe(ue=>ue.createSessionFromAssistantMessage),R=Fe(ue=>ue.openMultiRunLauncherWithPrompt),H=w?.isLastAssistantInTurn??!1,U=n==="stop",Y=A.length>0,F=l.useMemo(()=>A.some(ue=>{const ke=(ue.state??{})?.status;return ke==="pending"||ke==="running"||ke==="started"}),[A]),B=l.useCallback(ue=>{const je=ue.state??{},ke=je?.status;if(ke==="pending"||ke==="running"||ke==="started")return!1;const Te=je?.time??{},Ue=typeof Te?.end=="number"?Te.end:void 0,wt=typeof Te?.start=="number"?Te.start:void 0;return!(typeof Ue!="number"||typeof wt=="number"&&Ue<wt)},[]),T=l.useMemo(()=>A.length===0?!0:F?!1:A.every(ue=>B(ue)),[A,F,B]),V=l.useMemo(()=>P.length===0?!0:P.every(ue=>typeof ue.time?.end=="number"),[P]),X=l.useMemo(()=>C.filter(ue=>ue.type==="reasoning"),[C]),fe=l.useMemo(()=>X.length===0?!0:X.every(ue=>typeof ue.time?.end=="number"),[X]),ae=typeof n!="string",xe=X.length>0&&Y&&(F||ae||!T),Me=l.useMemo(()=>Y?P.length===0?ae||F||!T:!0:P.length>0?xe:!1,[P.length,ae,F,Y,xe,T]),Q=v||Me&&(!V||!T||F||ae)||xe,re=v||Y&&(F||ae||!T),oe=v||xe,W=Y||X.length>0,me=P.length===0,ye=W&&me&&!re&&!oe&&T&&fe,ce=l.useRef(!1),Ce=l.useRef(!1);l.useEffect(()=>{Ce.current=!1},[s]),l.useEffect(()=>{if(!ye){ce.current=!1;return}ce.current||(ce.current=!0,y?.())},[ye,y]),l.useEffect(()=>{if(v){Ce.current=!1;return}if(Y){Ce.current=!1;return}X.length!==0&&(oe||!fe||Ce.current||(Ce.current=!0,p?.("structural")))},[v,Y,p,fe,X.length,oe]);const Ee=!!h&&!v,Pe=l.useCallback(()=>{N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null)},[]),G=l.useCallback(()=>{!M||!L||!Ee||typeof window>"u"||(Pe(),j(!0),N.current=window.setTimeout(()=>{j(!1),N.current=null},1800))},[L,Pe,Ee,M]);l.useEffect(()=>{Ee||(j(!1),Pe())},[Pe,Ee]);const K=l.useCallback(ue=>{!b||!Ee||(ue.stopPropagation(),ue.preventDefault(),b(),M&&G())},[Ee,M,b,G]),I=l.useCallback(ue=>{ue.stopPropagation(),ue.preventDefault(),$&&$(s)},[$,s]),J=l.useCallback(ue=>{ue.stopPropagation(),ue.preventDefault();const je=hi(P);if(!je.trim())return;const ke=`${Dh}
|
|
86
|
-
|
|
87
|
-
${je}`;R(ke)},[P,R]);l.useEffect(()=>()=>{Pe()},[Pe]);const E=l.useMemo(()=>{const ue={},je=A.filter(ke=>$r(ke.tool)||re?!1:B(ke));return je.forEach((ke,Te)=>{ue[ke.id]={hasPrev:Te>0,hasNext:Te<je.length-1}}),ue},[A,re,B]),z=l.useMemo(()=>w?.activityParts??[],[w]),q=l.useMemo(()=>w?z.filter(ue=>ue.messageId===s):[],[z,s,w]),be=l.useMemo(()=>w?w.activityGroupSegments.filter(ue=>ue.anchorMessageId===s):[],[s,w]),ee=l.useMemo(()=>{const ue=new Map;return q.forEach(je=>{ue.set(je.part,je)}),ue},[q]),he=l.useMemo(()=>w?(x?z:z.filter(je=>je.kind==="tool")).filter(je=>{if(je.kind!=="tool")return!0;const ke=je.part.tool;return!$r(ke)}):[],[z,x,w]),[He,We]=l.useState(!1);l.useEffect(()=>{if(!w)return;const ue=w.activityGroupSegments.some(je=>je.afterToolPartId!==null);(he.length>1||ue&&he.length>0)&&We(!0)},[w,he.length]);const Be=!!(w&&He),Ze=l.useMemo(()=>{if(!w)return[];if(!Be)return[];if(!w.isWorking)return[];const ue=[];return q.forEach(je=>{if(w.previewedPartIds.has(je.id)||!x&&je.kind!=="tool")return;const ke=je.part;if(je.kind==="tool"){const Te=ke;if($r(Te.tool)||re||!B(Te))return}else if(je.kind==="reasoning"){if(!x||oe||typeof ke.time?.end!="number")return}else if(je.kind==="justification"&&(!x||Q||typeof ke.time?.end!="number"))return;ue.push(je)}),ue},[q,B,Q,oe,re,x,Be,w]),lt=l.useMemo(()=>{const ue=new Set;return Ze.forEach(je=>{ue.add(je.id)}),ue},[Ze]),{isAnimating:ct}=Hy(w,lt),dt=!!(w&&Be&&he.length>0&&be.length>0),mt=l.useMemo(()=>A.filter(ue=>$r(ue.tool)),[A]),yt=l.useMemo(()=>{const ue=[],je=Te=>{!w||!dt||be.filter(Ue=>(Ue.afterToolPartId??null)===Te).forEach(Ue=>{const wt=x?Ue.parts:Ue.parts.filter(At=>At.kind==="tool");wt.length!==0&&ue.push(e.jsx(_y,{parts:wt,isExpanded:w.isGroupExpanded,onToggle:w.toggleGroup,syntaxTheme:o,isMobile:a,expandedTools:c,onToggleTool:d,onShowPopup:u,onContentChange:p,isWorking:w.isWorking,previewedPartIds:w.previewedPartIds,diffStats:w.diffStats},`progressive-group-${Ue.id}`))})};je(null),mt.forEach(Te=>{ue.push(e.jsx(rs,{children:e.jsx(lo,{part:Te,isExpanded:c.has(Te.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Te.id}`)),je(Te.id)});const ke=[];return C.forEach((Te,Ue)=>{const wt=ee.get(Te);if(!wt||!w)return;let At=null,Mt=null;if(!Be){if(wt.kind==="tool"){const st=Te;if($r(st.tool))return;const Pt=st.state?.time,ot=B(st);if(!(!re&&ot))return;const qe=E[st.id];Mt=e.jsx(rs,{children:e.jsx(lo,{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 Pt?.end=="number"?Pt.end:null}Mt&&ke.push({part:Te,index:Ue,endTime:At,element:Mt});return}if(!w.isWorking||w.isGroupExpanded||w.previewedPartIds.has(wt.id)||!x&&wt.kind!=="tool")return;const pt=lt.has(wt.id);switch(wt.kind){case"tool":{const st=Te;if($r(st.tool))break;const Pt=st.state?.time,ot=B(st);if(!(!re&&ot))break;const qe=E[st.id],Ke=e.jsx(rs,{children:e.jsx(lo,{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(ga,{isMigrating:ct,children:Ke},`migrating-tool-${st.id}`):Ke,At=ot&&typeof Pt?.end=="number"?Pt.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(Nu,{part:Te,messageId:s,onContentChange:p})},`reasoning-${Ue}`);Mt=pt?e.jsx(ga,{isMigrating:ct,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&&!Q))break;const ot=e.jsx(rs,{children:e.jsx(uy,{part:Te,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:p,renderAsReasoning:!0})},`assistant-text-${Ue}`);Mt=pt?e.jsx(ga,{isMigrating:ct,children:ot},`migrating-text-${Ue}`):ot,At=jt?st?.end??null:null;break}}Mt&&ke.push({part:Te,index:Ue,endTime:At,element:Mt})}),ke.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),ke.forEach(({element:Te})=>{ue.push(Te)}),ue},[ee,be,c,ct,a,B,s,p,u,d,lt,Q,oe,re,Be,x,o,E,w,C,mt,dt]),vt=w?.turnId,gt=pe(ue=>ue.currentSessionId),bt=at(ue=>{if(!vt||!gt)return;const je=ue.messages.get(gt);if(!je)return;const ke=je.find(wt=>wt.info?.id===vt);if(!ke)return;const Ue=ke.info.summary?.body;return typeof Ue=="string"&&Ue.trim().length>0?Ue:void 0}),Z=typeof w?.summaryBody=="string"&&w.summaryBody.trim().length>0?w.summaryBody:bt,De=l.useRef(void 0);Z&&Z.trim().length>0&&(De.current=Z);const ne=l.useRef(vt);ne.current!==vt&&(ne.current=vt,De.current=void 0);const ie=De.current,Ie=w?.isLastAssistantInTurn&&ie&&ie.trim().length>0,_e=!!S,ze=H&&h&&(U||!!S),[Ge,rt]=l.useState(!1),le=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:I,children:e.jsx(Mf,{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:J,children:e.jsx(Zd,{className:"h-4 w-4"})})}),e.jsx(Ye,{sideOffset:6,children:"Start new multi-run from this answer"})]}),b&&e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(ve,{type:"button",variant:"ghost",size:"icon","data-visible":k||D?"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:()=>{D||j(!1)},children:D?e.jsx(Dt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ys,{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&&L&&Ee?G: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:[yt,_e&&e.jsx(rs,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(kr,{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(kr,{content:ie}),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:le})]})},"summary-body")]}),e.jsx(iu,{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:le})]})})},Gy=({isUser:s,...r})=>s?e.jsx(Wy,{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(Vy,{...r}),lc=l.memo(Gy),xa=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}},qy=l.lazy(()=>Jt(()=>import("./ToolOutputDialog-C7D95isZ.js"),__vite__mapDeps([2,0,1,3,4]))),Ky=new Set(["task","edit","multiedit","write","bash"]),cc=s=>typeof s=="string"&&Ky.has(s.toLowerCase());function ya(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 Qs=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},Yy=({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=pe(oi(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:b,getCurrentAgent:g,getSessionAgentSelection:y,getAgentModelForSession:x,getSessionModelSelection:w}=f,S=ut(Ae=>Ae.providers),k=Fe(Ae=>Ae.showReasoningTraces),j=Fe(Ae=>Ae.toolCallExpansion);l.useEffect(()=>{b&&lr.getInstance().recordSessionStart(b)},[b]);const[N,L]=l.useState(null),[D,M]=l.useState(!1),[v,C]=l.useState(new Set),[A,P]=l.useState({open:!1,title:"",content:""});l.useEffect(()=>{C(new Set)},[s.info.id,j]);const R=l.useMemo(()=>xa(s.info),[s.info]).isUser,H=l.useMemo(()=>R?s.parts.map(Ae=>Ae.type==="compaction"?{type:"text",text:"/summarize"}:Ae):s.parts,[R,s.parts]),U=l.useMemo(()=>{if(R||!r)return null;const Ae=Qs(r.info,"clientRole"),qe=Qs(r.info,"role");if((typeof Ae=="string"?Ae:typeof qe=="string"?qe:void 0)!=="user")return null;const ft=Qs(r.info,"mode"),kt=Qs(r.info,"providerID"),Rt=Qs(r.info,"modelID"),cs=typeof ft=="string"&&ft.trim().length>0?ft:void 0,$s=typeof kt=="string"&&kt.trim().length>0?kt:void 0,Ns=typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0;return!cs&&!$s&&!Ns?null:{agentName:cs,providerId:$s,modelId:Ns}},[R,r]),Y=l.useMemo(()=>{if(R)return;const Ae=Qs(s.info,"mode");if(typeof Ae=="string"&&Ae.trim().length>0)return Ae;if(U?.agentName)return U.agentName;const qe=s.info.sessionID;if(!qe)return;const Ke=g(qe);return Ke||(y(qe)??void 0)},[R,s.info,U,g,y]),F=s.info.sessionID,B=R?null:Qs(s.info,"providerID"),T=R?null:Qs(s.info,"modelID"),V=l.useMemo(()=>{if(R||!F)return null;if(U?.providerId&&U?.modelId)return{providerId:U.providerId,modelId:U.modelId};if(Y){const qe=x(F,Y);if(qe?.providerId&&qe?.modelId)return qe}const Ae=w(F);return Ae?.providerId&&Ae?.modelId?Ae:null},[R,F,Y,U,x,w]),X=l.useMemo(()=>R?null:typeof B=="string"&&B.trim().length>0?B:V?.providerId??null,[R,B,V]),fe=l.useMemo(()=>R?null:typeof T=="string"&&T.trim().length>0?T:V?.modelId??null,[R,T,V]),ae=l.useMemo(()=>{if(!R&&X&&fe&&S.length>0){const Ae=S.find(qe=>qe.id===X);if(Ae?.models&&Array.isArray(Ae.models)){const ft=Ae.models.find(kt=>kt.id===fe)?.name;return typeof ft=="string"?ft:void 0}}},[R,X,fe,S]),xe=ya(Y),Me=ya(X??void 0),Q=ya(ae),re=xe??void 0,oe=Me??null,W=Q??void 0,me=l.useMemo(()=>{const Ae=s.info.time;return typeof Ae?.completed=="number"?Ae.completed:null},[s.info.time]),ye=l.useMemo(()=>R?!0:!!(me&&me>0),[R,me]),ce=l.useMemo(()=>{const Ae=s.info.finish;return typeof Ae=="string"?Ae:void 0},[s.info]),Ce=l.useMemo(()=>zy(H,{includeReasoning:k}),[H,k]),Ee=l.useMemo(()=>R||ye?Ce:[],[R,ye,Ce]),Pe=l.useMemo(()=>R?[]:Ce.filter(Ae=>Ae.type==="text"),[R,Ce]),G=l.useMemo(()=>R?[]:Ce.filter(qe=>qe.type==="tool"),[R,Ce]),K=l.useMemo(()=>{if(j==="collapsed"||j==="activity")return v;const Ae=new Set;for(const Ke of G){const ft=Ke.tool;Ke.id&&cc(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&&cc(ft.tool)&&Ae.add(ft.id)}const qe=new Set(Ae);for(const Ke of v)qe.has(Ke)?qe.delete(Ke):qe.add(Ke);return qe},[v,j,G,i]),I=l.useMemo(()=>{if(!R)return;const Ae=s.parts.find(kt=>kt.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}},[R,s.parts]),J=typeof ce!="string",E=l.useMemo(()=>R?!1:Pe.length===0||G.length===0?J:!0,[Pe.length,G.length,J,R]),z=u?.metadata.variant,q=l.useMemo(()=>z?z==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[z]),be=l.useMemo(()=>u?yu(u):q?Xx:Qx,[u,q]),ee=l.useMemo(()=>R?!1:lr.getInstance().shouldAnimateMessage(s.info,b||s.info.sessionID),[s.info,b,R]),he=l.useRef(!1),He=l.useMemo(()=>r?xa(r.info):null,[r]),We=l.useMemo(()=>t?xa(t.info):null,[t]),Be=l.useMemo(()=>R||!We?!1:!We.isUser&&We.role==="assistant",[R,We]),Ze=l.useMemo(()=>ye?"completed":p||(h?"streaming":"completed"),[ye,p,h]),lt=l.useMemo(()=>{if(R)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=he.current;return Ke&&!ft&&(he.current=!0),ft||Ke}return!1}return He?He.isUser:!0},[R,He,i,Ze,s.info]),ct=l.useCallback(Ae=>{navigator.clipboard.writeText(Ae),L(Ae),setTimeout(()=>L(null),2e3)},[]),dt=i?.turnId,mt=at(Ae=>{if(!dt)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===dt);if(!ft)return;const Rt=ft.info.summary?.body;return typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0}),yt=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:mt,vt=l.useRef(void 0);yt&&yt.trim().length>0&&(vt.current=yt);const gt=l.useRef(dt);gt.current!==dt&&(gt.current=dt,vt.current=void 0);const bt=vt.current,Z=l.useMemo(()=>{if(R)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,kt=qe||Ke||ft;if(kt)return`Opencode failed to send message with error:
|
|
88
|
-
\`${kt}\``},[R,s.info]),De=l.useMemo(()=>R?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
|
-
`):Z&&Z.trim().length>0?Z:bt&&bt.trim().length>0?bt:hi(Ee),[Z,bt,Ee,R]),ne=De.length>0,ie=l.useCallback(()=>{navigator.clipboard.writeText(De),M(!0),setTimeout(()=>M(!1),2e3)},[De]),Ie=pe(Ae=>Ae.revertToMessage),_e=pe(Ae=>Ae.forkFromMessage),ze=l.useCallback(()=>{!F||!s.info.id||Ie(F,s.info.id)},[F,s.info.id,Ie]),Ge=l.useCallback(()=>{!F||!s.info.id||_e(F,s.info.id)},[F,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})},[]),le=o??null,ue=l.useRef(!1),je=l.useRef(!1),ke=l.useRef(!1),Te=l.useRef(!1),Ue=l.useRef(!1);l.useEffect(()=>{je.current=!1,ke.current=!1,Te.current=!1,Ue.current=!1,ue.current=!1},[s.info.id]);const wt=l.useCallback(()=>{R||ue.current||(ue.current=!0,n?.("structural"))},[R,n]),At=l.useCallback(Ae=>{Ae.image&&P(Ae)},[]),Mt=l.useCallback(Ae=>{P(qe=>({...qe,open:Ae}))},[]),pt=!!Qs(s.info,"animationSettled"),st=Ze==="streaming",jt=l.useMemo(()=>R?!1:Ce.some(Ae=>Ae.type==="reasoning"),[R,Ce]),Pt=ee&&!pt&&!st,ot=!R&&ee&&Pe.length>0&&!E;return l.useEffect(()=>{if(le?.onStreamingCandidate){if(!ot){ke.current&&(jt&&le?.onReasoningBlock?le.onReasoningBlock():le?.onReservationCancelled&&le.onReservationCancelled(),ke.current=!1);return}Ue.current||(Ue.current=!0,le.onStreamingCandidate(),ke.current=!0)}},[le,ot,jt]),l.useEffect(()=>{le?.onAnimationStart&&Pt&&(Te.current||(le.onAnimationStart(),Te.current=!0))},[le,Pt]),l.useEffect(()=>{if(R)return;const Ae=le?.onAnimatedHeightChange;if(!Ae||!(Pt||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 kt=cs=>{if(typeof window>"u"){Ae(cs);return}ft!==null&&window.cancelAnimationFrame(ft),ft=window.requestAnimationFrame(()=>{Ae(cs)})},Rt=new ResizeObserver(cs=>{const $s=cs[0];$s&&kt($s.contentRect.height)});return Rt.observe(Ke),kt(Ke.getBoundingClientRect().height),()=>{ft!==null&&(window.cancelAnimationFrame(ft),ft=null),Rt.disconnect()}},[Pt,R,le,ot]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:O("group w-full",lt?"pt-2":"pt-0",R?"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:R?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(lc,{messageId:s.info.id,parts:Ce,isUser:R,isMessageCompleted:ye,messageFinish:ce,syntaxTheme:be,isMobile:c,hasTouchInput:d,copiedCode:N,onCopyCode:ct,expandedTools:v,onToggleTool:rt,onShowPopup:At,streamPhase:Ze,allowAnimation:Pt,onContentChange:n,shouldShowHeader:!1,hasTextContent:ne,onCopyMessage:ie,copiedMessage:D,showReasoningTraces:k,onAuxiliaryContentComplete:wt,agentMention:I,onRevert:ze,onFork:R?Ge:void 0,errorMessage:Z})})})}):e.jsxs("div",{children:[lt&&e.jsx(Zx,{isUser:R,providerID:oe,agentName:re,modelName:W,isDarkTheme:q}),e.jsx(lc,{messageId:s.info.id,parts:Ce,isUser:R,isMessageCompleted:ye,messageFinish:ce,syntaxTheme:be,isMobile:c,hasTouchInput:d,copiedCode:N,onCopyCode:ct,expandedTools:K,onToggleTool:rt,onShowPopup:At,streamPhase:Ze,allowAnimation:Pt,onContentChange:n,shouldShowHeader:lt,hasTextContent:ne,onCopyMessage:ie,copiedMessage:D,onAuxiliaryContentComplete:wt,showReasoningTraces:k,agentMention:I,turnGroupingContext:i,errorMessage:Z})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(qy,{popup:A,onOpenChange:Mt,syntaxTheme:be,isMobile:c})})]})},Xy=l.memo(Yy),Qy=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Cu(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))}),Jy=({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))})]})},Zy=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(Zs,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(nd,{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(Pa,{className:r}):e.jsx(Ro,{className:r})},eb=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},tb=({permission:s,onResponse:r})=>{const[t,n]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=pe(),{currentTheme:c}=Fr(),d=l.useMemo(()=>yu(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,w="")=>{const S=s.metadata[x];return typeof S=="string"?S:typeof S=="number"?String(S):w},h=x=>{const w=s.metadata[x];return typeof w=="number"?w:void 0},b=x=>!!s.metadata[x],g=eb(m),y=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const S=p("command")||p("cmd")||p("script"),k=p("description"),j=p("cwd")||p("working_directory")||p("directory")||p("path"),N=h("timeout"),L=s.title===S;return e.jsxs(e.Fragment,{children:[k&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:k}),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})]}),N&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",N,"ms"]}),S&&!L&&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"),k=p("changes")||p("diff"),j=b("replace_all")||b("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"})}),k&&e.jsx(tt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Qy,{diff:k,syntaxTheme:d,filePath:S})})]})}if(f==="write"||f==="create"||f==="file_write"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),k=p("content")||p("text")||p("data");return k?e.jsx(tt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Jy,{content:k,syntaxTheme:d,filePath:S})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const S=p("url")||p("uri")||p("endpoint"),k=p("method")||"GET",j=s.metadata.headers&&typeof s.metadata.headers=="object"?s.metadata.headers:void 0,N=p("body")||p("data")||p("payload"),L=h("timeout"),D=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:k}),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)})})]}),N&&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 N=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof N=="object"?JSON.stringify(N,null,2):String(N)})})]}),(L||D)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[L&&e.jsxs("span",{children:["Timeout: ",L,"ms"]}),L&&D&&e.jsx("span",{children:" • "}),D&&e.jsxs("span",{children:["Response format: ",D]})]})]})}const x=p("command")||p("content")||p("action")||p("operation"),w=p("description");return e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:w}),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&&!w&&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:[Zy(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:g})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[s.patterns&&s.patterns.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Patterns:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:s.patterns.join(", ")})]}),!(s.patterns&&s.patterns.length>0)&&s.pattern&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Pattern:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:Array.isArray(s.pattern)?s.pattern.join(", "):s.pattern})]}),(()=>{let x="",w="text",S=!1;f==="bash"||f==="shell"||f==="shell_command"?(x=p("command")||p("cmd")||p("script"),w="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 k=s.title===x;return k&&x&&S?e.jsx("div",{className:"mb-3",children:e.jsx(Bs,{language:w,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})}):k&&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"]}),s.always&&s.always.length>0?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(qs,{className:"h-3 w-3"}),(()=>{const x=s.always||s.metadata.always||[];if(x.length===0)return"Always Allow";const S=x.slice(0,2).join(", ");return x.length>2?`Always: ${S}...`:`Always: ${S}`})()]}):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(qs,{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(Vt,{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"})})]})]})})})},sb=new Set(["task"]),dc=s=>typeof s=="string"&&sb.has(s.toLowerCase()),rb=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},nb=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}}},ob=s=>{const r=nb(s);let t;const o=s.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let x=0,w=0,S=0;o.forEach(k=>{if(!k)return;const j=typeof k.additions=="number"?k.additions:0,N=typeof k.deletions=="number"?k.deletions:0;(j!==0||N!==0)&&(S+=1),x+=j,w+=N}),S>0&&(t={additions:x,deletions:w,files:S})}let a=!1,i=!1;s.assistantMessages.forEach(x=>{x.parts.forEach(w=>{w.type==="tool"?a=!0:w.type==="reasoning"&&(i=!0)})});const c=[];let d=0;s.assistantMessages.forEach(x=>{const w=x.info.id;x.info.finish,x.parts.forEach(S=>{const k=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${w}-activity-${d++}`;if(S.type==="tool"){const N=S.state?.time,L=typeof N?.end=="number"?N.end:void 0;c.push({id:k,turnId:s.turnId,messageId:w,kind:"tool",part:S,endedAt:L});return}if(S.type==="reasoning"){const j=S.text??S.content;if(typeof j!="string"||j.trim().length===0)return;const N=S.time,L=typeof N?.end=="number"?N.end:void 0;c.push({id:k,turnId:s.turnId,messageId:w,kind:"reasoning",part:S,endedAt:L});return}})});const u=[],m=new WeakMap;c.forEach(x=>{m.set(x.part,x)});const f=new Map,p=[],h=new Map;let b=null;s.assistantMessages.forEach(x=>{const w=x.info.id;x.parts.forEach(S=>{if(S.type==="tool"){const N=S.tool;if(dc(N)){const L=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${w}-task-${p.length+1}`;f.has(L)||(f.set(L,w),p.push(L)),b=L;return}}const k=m.get(S);if(!k)return;if(k.kind==="tool"){const N=k.part.tool;if(dc(N))return}const j=h.get(b)??[];j.push(k),h.set(b,j)})});const g=x=>{if(x.length===0)return;const w=new Map;x.forEach(j=>{w.set(j.messageId,(w.get(j.messageId)??0)+1)});let S,k=0;for(const j of s.assistantMessages){const N=w.get(j.info.id)??0;if(N>0&&!S&&(S=j.info.id),k+=N,k>=2)return j.info.id}return S};return[null,...p].forEach(x=>{const w=h.get(x)??[];if(w.length===0)return;const S=x===null?g(w):f.get(x);S&&u.push({id:`${s.turnId}:${S}:${x??"start"}`,anchorMessageId:S,afterToolPartId:x,parts:w})}),{activityParts:c,activityGroupSegments:u,hasTools:a,hasReasoning:i,summaryBody:r,diffStats:t}},ab=s=>{const{isWorking:r}=Di(),t=l.useMemo(()=>rb(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,ob(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),w=x.get(g)??{isExpanded:u,previewedPartIds:new Set};return x.set(g,{...w,isExpanded:!w.isExpanded}),x})},[u]),p=l.useCallback((g,y)=>{y.length!==0&&c(x=>{const w=new Map(x),S=w.get(g)??{isExpanded:u,previewedPartIds:new Set},k=new Set(S.previewedPartIds);return y.forEach(j=>{j&&j.trim().length>0&&k.add(j)}),w.set(g,{...S,previewedPartIds:k}),w})},[u]),h=l.useCallback(g=>o.get(g),[o]),b=l.useCallback(g=>{const y=o.get(g);if(!y||!y.assistantMessages.some(H=>H.info.id===g))return;const w=a.get(y.turnId),S=w?.activityParts??[],k=w?.activityGroupSegments??[],j=!!w?.hasTools,N=!!w?.hasReasoning,L=w?.summaryBody,D=w?.diffStats,M=y.assistantMessages[0]?.info.id,v=g===M,C=y.assistantMessages[y.assistantMessages.length-1]?.info.id,A=g===C,P=M,$=m(y.turnId),R=r&&n===y.turnId;return{turnId:y.turnId,isFirstAssistantInTurn:v,isLastAssistantInTurn:A,summaryBody:L,activityParts:S,activityGroupSegments:k,headerMessageId:P,hasTools:j,hasReasoning:N,diffStats:D,isWorking:R,isGroupExpanded:$.isExpanded,previewedPartIds:$.previewedPartIds,toggleGroup:()=>f(y.turnId),markPartsPreviewed:H=>p(y.turnId,H)}},[m,n,p,o,r,f,a]);return{turns:t,getTurnForMessage:h,getContextForMessage:b}},ib=({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:_x(p.parts)}))},[s]),{getContextForMessage:m}=ab(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(Xy,{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(tb,{permission:f},f.id))})]})},lb=l.memo(ib);function cb(...s){return r=>{s.forEach(t=>{typeof t=="function"?t(r):t&&typeof t=="object"&&(t.current=r)})}}const Eu=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 b=l.useMemo(()=>{const w={...i};return w["--scroll-shadow-size"]=`${t}px`,w},[t,i]),g=l.useCallback((w,S,k,j,N)=>{const L=`${j}${N.charAt(0).toUpperCase()}${N.slice(1)}Scroll`;S&&k?(w.dataset[L]="true",w.removeAttribute(`data-${j}-scroll`),w.removeAttribute(`data-${N}-scroll`)):(w.dataset[`${j}Scroll`]=String(S),w.dataset[`${N}Scroll`]=String(k),w.removeAttribute(`data-${j}-${N}-scroll`))},[]),y=l.useCallback(w=>{["top","bottom","top-bottom","left","right","left-right"].forEach(S=>{w.removeAttribute(`data-${S}-scroll`)})},[]),x=l.useCallback(()=>{const w=f.current;if(!w)return;if(!n){y(w);return}const S=s==="vertical"?w.scrollTop>r:w.scrollLeft>r;let k=s==="vertical"?w.scrollTop+w.clientHeight+r<w.scrollHeight:w.scrollLeft+w.clientWidth+r<w.scrollWidth;o&&s==="vertical"&&(k=!1),g(w,S,k,s==="vertical"?"top":"left",s==="vertical"?"bottom":"right");const j=S&&k?"both":S?s==="vertical"?"top":"left":k?s==="vertical"?"bottom":"right":"none";j!==p.current&&(p.current=j,a?.(j))},[y,o,n,r,a,s,g]);return l.useEffect(()=>{const w=f.current;if(!w)return;const S=()=>x(),k=typeof ResizeObserver<"u"?new ResizeObserver(()=>x()):null,j=typeof MutationObserver<"u"?new MutationObserver(()=>x()):null;return x(),w.addEventListener("scroll",S,{passive:!0}),k?.observe(w),j?.observe(w,{childList:!0,subtree:!0,characterData:!0}),()=>{w.removeEventListener("scroll",S),k?.disconnect(),j?.disconnect()}},[x]),e.jsx("div",{...u,ref:cb(f,m),className:c,"data-orientation":s,"data-scroll-shadow":h??!0,style:b,children:d})});Eu.displayName="ScrollShadow";const db=160,ub=({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 k=s.current;if(!k){u();return}i.current===null&&(i.current=S);const j=Math.min(1,(S-i.current)/db),N=1-Math.pow(1-j,3),L=c.current,D=d.current,M=L+(D-L)*N;if(k.scrollTop=M,j<1){a.current=window.requestAnimationFrame(m);return}k.scrollTop=D,u(),n.current&&(n.current=!1,t(!1))},[u,s,t]),f=l.useCallback((S,k)=>{const j=s.current;if(!j)return;const N=Math.max(0,S),L=k?.instant??!1;if(o.current=!1,typeof window>"u"||L){u(),j.scrollTop=N;const M=N<=1;n.current!==M&&(n.current=M,t(M));return}if(u(),Math.abs(N-j.scrollTop)<=.5){j.scrollTop=N;const M=N<=1;n.current!==M&&(n.current=M,t(M));return}c.current=j.scrollTop,d.current=N,i.current=null,a.current=window.requestAnimationFrame(m)},[u,s,m,t]),p=l.useCallback(()=>{o.current=!0},[]),h=l.useCallback(()=>{o.current=!0},[]),b=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]),w=l.useCallback(()=>{const S=s.current;if(!S)return;o.current&&a.current!==null&&u();const k=S.scrollTop<=1;n.current!==k&&(n.current=k,t(k))},[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:w,scrollToPosition:f,forceManualMode:p,isAtTop:r,isManualOverrideActive:b,getScrollTop:g,getScrollHeight:y,getClientHeight:x}),[w,f,p,r,b,g,y,x])},uc=typeof window<"u"?l.useLayoutEffect:l.useEffect,mc=50,fc=40,mb=.2,fb=.1,pb=150,Cs=s=>{const r=s.info;return typeof r?.id=="string"?r.id:null},hb=s=>{const r=s.info;if(r?.userMessageMarker===!0)return!0;const t=r?.clientRole,n=r?.role;return t==="user"||n==="user"},gb=({currentSessionId:s,sessionMessages:r,updateViewportAnchor:t,updateActiveTurnAnchor:n,getActiveTurnAnchor:o,isSyncing:a,isMobile:i,sessionActivityPhase:c})=>{const d=l.useRef(null),u=ub({containerRef:d}),[m,f]=l.useState(null),[p,h]=l.useState(0),[b,g]=l.useState(!1),[y,x]=l.useState(null),w=l.useRef(null),S=l.useRef(null),k=l.useRef(r.length),j=l.useRef(r.length>0?Cs(r[0]):null),N=l.useRef(r.length>0?Cs(r[r.length-1]):null),L=l.useRef(0),D=l.useRef(0),M=l.useRef(void 0),v=l.useRef(null),C=l.useRef(!1),A=l.useRef(!1),P=l.useRef(null),$=s?c?.get(s)??"idle":"idle",R=l.useCallback(Q=>{const re=Math.max(0,Q);L.current!==re&&(L.current=re,h(re))},[]),H=l.useCallback(()=>{const Q=d.current;Q&&(D.current=Q.clientHeight)},[]),U=l.useCallback(()=>{if(!m)return null;const Q=d.current;return Q?Q.querySelector(`[data-message-id="${m}"]`):null},[m]),Y=l.useCallback(()=>{const Q=d.current,re=L.current;if(!Q||re<=0)return!0;const oe=Q.scrollHeight-re;return Q.scrollTop+Q.clientHeight<oe},[]),F=l.useCallback((Q,re)=>{const oe=Q.offsetHeight,W=Q.offsetTop;if(oe>re*mb){const ye=re*fb;return W+oe-ye}else return W-mc},[]),B=l.useCallback(()=>{const Q=d.current;if(!Q||!v.current)return;const re=U();if(!re)return;const oe=Q.clientHeight,W=Q.scrollHeight,ye=F(re,oe)+oe,ce=L.current,Ce=W-ce;if(!C.current&&Ce<ye){const Ee=ye-Ce;Ee>ce&&(R(Ee),s&&v.current&&n(s,v.current,Ee))}},[F,s,U,n,R]),T=l.useCallback(()=>{const Q=d.current;if(!Q){g(!1);return}if(y){g(!1);return}if(!(Q.scrollHeight>Q.clientHeight)){g(!1);return}const oe=Q.scrollHeight-Q.scrollTop-Q.clientHeight,W=L.current;if(W>0){const me=Q.scrollHeight-W,ye=Q.scrollTop+Q.clientHeight;g(ye<me)}else g(oe>fc)},[y]),V=l.useCallback(Q=>{const re=d.current;if(!re)return;const oe=re.scrollHeight-re.scrollTop-re.clientHeight;if(A.current&&$==="idle"&&!a&&!Q?.force&&oe>fc)return;Q?.force&&(A.current=!1);const me=re.scrollHeight-re.clientHeight;u.scrollToPosition(Math.max(0,me),Q)},[$,a,u]),X=l.useCallback(Q=>{if(w.current===Q)return;w.current=Q,x(Q);const re=d.current;if(!re){x(null);return}const oe=re.scrollHeight,W=L.current,me=oe-W,ye=D.current>0?D.current:re.clientHeight,Ce=me-mc,Ee=Ce+ye;let Pe=0;me<Ee&&(Pe=Ee-me),Pe!==W&&R(Pe),s&&n(s,Q,Pe),C.current=!0,window.requestAnimationFrame(()=>{u.scrollToPosition(Ce,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[s,u,n,R]),fe=l.useCallback(Q=>{const re=d.current;if(!re||!s)return;Q?.isTrusted&&(A.current=!0),u.handleScroll(),T(),$==="idle"&&L.current>0&&Y()&&(R(0),v.current=null,f(null),n(s,null,0));const{scrollTop:oe,scrollHeight:W,clientHeight:me}=re,ye=(oe+me/2)/Math.max(W,1),ce=Math.floor(ye*r.length);t(s,ce)},[s,$,Y,u,r.length,n,T,R,t]);l.useEffect(()=>{const Q=d.current;if(Q)return Q.addEventListener("scroll",fe,{passive:!0}),()=>{Q.removeEventListener("scroll",fe)}},[fe]),uc(()=>{if(typeof window>"u")return;H();const Q=()=>{M.current!==void 0&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{H()},pb)};return window.addEventListener("resize",Q),()=>{window.removeEventListener("resize",Q),M.current!==void 0&&window.clearTimeout(M.current)}},[H]),l.useEffect(()=>{if(s&&s!==S.current){S.current=s,lr.getInstance().recordSessionStart(s),k.current=r.length,j.current=r.length>0?Cs(r[0]):null,N.current=r.length>0?Cs(r[r.length-1]):null;const Q=o(s);$!=="idle"&&Q&&Q.anchorId?(v.current=Q.anchorId,w.current=Q.anchorId,C.current=!0,f(Q.anchorId),L.current=Q.spacerHeight,h(Q.spacerHeight),window.requestAnimationFrame(()=>{const oe=d.current;if(!oe)return;const W=oe.querySelector(`[data-message-id="${Q.anchorId}"]`);if(W){const me=oe.clientHeight,ye=F(W,me);u.scrollToPosition(ye,{instant:!0})}})):(w.current=null,v.current=null,C.current=!1,f(null),L.current=0,h(0),window.requestAnimationFrame(()=>{V({instant:!0,force:!0})})),x(null),g(!1),A.current=!1,P.current=null}},[$,s,V,r.length,o]),uc(()=>{if(a){k.current=r.length,j.current=r.length>0?Cs(r[0]):null,N.current=r.length>0?Cs(r[r.length-1]):null;return}if(S.current!==s)return;const Q=k.current,re=r.length;if(re>Q&&Q>0){const oe=j.current,W=Cs(r[0]),me=Cs(r[re-1]),ye=N.current,ce=oe!==null&&W!==oe,Ce=ye!==null&&me!==ye,Ee=ce&&!Ce,Pe=Ce&&!ce;if(Ee){v.current=null,C.current=!1,f(null),R(0),k.current=re,j.current=W,N.current=me;return}if(Pe){const K=r.slice(Q,re).find(hb);if(K){const I=Cs(K);I&&(v.current=I,f(I),X(I))}else B()}}k.current=re,j.current=r.length>0?Cs(r[0]):null,N.current=r.length>0?Cs(r[r.length-1]):null},[s,a,B,X,r]),l.useEffect(()=>{const Q=d.current;if(!Q||typeof ResizeObserver>"u")return;const re=new ResizeObserver(()=>{B(),T()});return re.observe(Q),()=>{re.disconnect()}},[B,T]),l.useEffect(()=>{if(typeof window>"u"){T();return}const Q=window.requestAnimationFrame(()=>{T()});return()=>{window.cancelAnimationFrame(Q)}},[s,r.length,T]),l.useEffect(()=>{m&&(B(),T())},[m,B,T]),l.useEffect(()=>{const Q=P.current;P.current=$,Q!==null&&Q!=="idle"&&$==="idle"&&L.current>0&&Y()&&v.current!==null&&(R(0),v.current=null,C.current=!1,f(null),s&&n(s,null,0))},[$,s,Y,n,R]),l.useEffect(()=>{T()},[p,T]);const ae=l.useRef(new Map),xe=l.useCallback(()=>{B(),T()},[B,T]),Me=l.useCallback(Q=>{const re=ae.current.get(Q);if(re)return re;const oe={onChunk:()=>{B()},onComplete:()=>{B()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{B()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return ae.current.set(Q,oe),oe},[B]);return{scrollRef:d,handleMessageContentChange:xe,getAnimationHandlers:Me,showScrollButton:b,scrollToBottom:V,spacerHeight:p,pendingAnchorId:y,hasActiveAnchor:m!==null}};function xb(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 yb=({open:s,onOpenChange:r,onScrollToMessage:t})=>{const n=pe(g=>g.currentSessionId),o=at(g=>n?g.messages.get(n)||[]:[]),a=pe(g=>g.revertToMessage),i=pe(g=>g.forkFromMessage),c=pe(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=>pc(y.parts).toLowerCase().includes(g))},[p,m]),b=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(qs,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Ss,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(it,{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=pc(g.parts),x=g.info.time.created,w=xb(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:w}),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 k=>{k.stopPropagation(),await a(n,g.info.id),r(!1)},children:e.jsx(vn,{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:k=>{k.stopPropagation(),b(g.info.id)},disabled:d===g.info.id,children:d===g.info.id?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(Ft,{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(vn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Undo to this point (message text will populate input)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function pc(s){const r=s.find(t=>t.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const Iu=()=>{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:b,sessionActivityPhase:g,newSessionDraft:y}=pe(),{isTimelineDialogOpen:x,setTimelineDialogOpen:w}=Fe(),S=l.useMemo(()=>s?n.get(s)??null:null,[s,n]),{isMobile:k}=Ct(),j=!!y?.open;l.useEffect(()=>{!s&&!j&&f()},[s,j,f]);const N=l.useMemo(()=>s?r.get(s)||[]:[],[s,r]),L=l.useMemo(()=>s?t.get(s)||[]:[],[s,t]),{scrollRef:D,handleMessageContentChange:M,getAnimationHandlers:v,showScrollButton:C,scrollToBottom:A,spacerHeight:P,pendingAnchorId:$,hasActiveAnchor:R}=gb({currentSessionId:s,sessionMessages:N,updateViewportAnchor:c,updateActiveTurnAnchor:d,getActiveTurnAnchor:u,isSyncing:p,isMobile:k,sessionActivityPhase:g}),U=!!l.useMemo(()=>s?m.get(s)??null:null,[s,m])?.hasMoreAbove,[Y,F]=l.useState(!1);l.useEffect(()=>{F(!1)},[s]);const B=l.useRef(null);l.useLayoutEffect(()=>{if(!(!s||s===B.current)&&(B.current=s,!R)){const X=D.current;X&&(X.scrollTop=X.scrollHeight-X.clientHeight)}},[s,D,R]);const T=l.useCallback(async()=>{if(!s||Y)return;const X=D.current,fe=X?.scrollHeight??null,ae=X?.scrollTop??null;F(!0);try{if(await i(s,"up"),X&&fe!==null&&ae!==null){const xe=X.scrollHeight-fe;X.scrollTop=ae+xe}}finally{F(!1)}},[s,Y,i,D]),V=l.useCallback(X=>{const fe=D.current;if(!fe)return;const ae=fe.querySelector(`[data-message-id="${X}"]`);if(ae){const xe=fe.getBoundingClientRect(),re=ae.getBoundingClientRect().top-xe.top+fe.scrollTop-50;fe.scrollTo({top:re,behavior:"smooth"})}},[D]);return l.useEffect(()=>{if(!s||(r.has(s)?r.get(s)??[]:[]).length>0)return;(async()=>{try{await a(s)}finally{typeof window>"u"?A():window.requestAnimationFrame(()=>{A()})}})()},[s,a,r,A]),!s&&!j?e.jsx("div",{className:"flex flex-col h-full bg-background",style:k?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(pa,{})}):!s&&j?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:k?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(pa,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Xn,{scrollToBottom:A})})]}):s?o&&N.length===0&&!S&&!r.has(s)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:k?{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(fa,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(fa,{className:"h-4 w-24"}),e.jsx(fa,{className:"h-20 w-full"})]})]},fe))})}),e.jsx(Xn,{scrollToBottom:A})]}):N.length===0&&!S?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:k?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(pa,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Xn,{scrollToBottom:A})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:k?{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(Eu,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:D,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!$,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(lb,{messages:N,permissions:L,onMessageContentChange:M,getAnimationHandlers:v,hasMoreAbove:U,isLoadingOlder:Y,onLoadOlder:T,scrollToBottom:A,pendingAnchorId:$}),P>0&&R&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:P},"aria-hidden":"true"})]})}),e.jsx(gi,{containerRef:D})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[C&&N.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:()=>A({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-accent","aria-label":"Scroll to bottom",children:e.jsx(en,{className:"h-4 w-4"})})}),e.jsx(Xn,{scrollToBottom:A})]}),e.jsx(yb,{open:x,onOpenChange:w,onScrollToMessage:V})]}):null};class Tu 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(Ni,{className:"w-full max-w-md",children:[e.jsx(Vd,{className:"text-center",children:e.jsxs(Gd,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Df,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(qd,{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 Qa=()=>{const s=pe(r=>r.currentSessionId);return e.jsx(Tu,{sessionId:s||void 0,children:e.jsx(Iu,{})})},hc=12,bb=[{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"}],wb=({isActive:s,burstKey:r=0,className:t,durationMs:n=900,bursts:o=bb,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:hc},(d,u)=>{const m=Math.PI*2*u/hc;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,b={"--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:b},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},vb=({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}},Fu=l.createContext(void 0),gc=({children:s})=>{const{isActive:r,burstKey:t,triggerFireworks:n,dismissFireworks:o}=vb(),a=l.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(Fu.Provider,{value:a,children:[s,e.jsx(wb,{isActive:r,burstKey:t})]})},jb=()=>{const s=l.useContext(Fu);if(!s)throw new Error("useFireworksCelebration must be used within FireworksProvider");return s},Bo=Tt()(_t(vs((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 th();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 oh("");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 sh(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 rh(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 nh(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:js(()=>ls()),partialize:s=>({selectedProfileId:s.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Bo);const Sb=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Nb=({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,b]=l.useState(""),[g,y]=l.useState(!1),x=l.useRef(null),w=l.useMemo(()=>Sb(h),[h]),S=l.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(v=>v.toLowerCase().includes(M)):r},[u,r]),k=l.useMemo(()=>{const M=u.toLowerCase();return M?t.filter(v=>v.toLowerCase().includes(M)):t},[u,t]),j=M=>{if(M===s){d(!1);return}o(M),d(!1),m("")},N=()=>{p(!0),setTimeout(()=>x.current?.focus(),50)},L=async()=>{if(!(!w||g)){y(!0);try{await a(w),b(""),p(!1),d(!1)}finally{y(!1)}}},D=()=>{b(""),p(!1)};return l.useEffect(()=>{c||(m(""),p(!1),b(""))},[c]),e.jsxs(qt,{open:c,onOpenChange:d,children:[e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(Kt,{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(Ft,{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(Yt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Yd,{className:"h-full min-h-0",children:[e.jsx(Xd,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(Qd,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Jd,{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=>b(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),L()):M.key==="Escape"&&(M.preventDefault(),D())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:L,disabled:!w||g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:g?e.jsx(es,{className:"size-4 animate-spin"}):e.jsx(Gt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:D,disabled:g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Vt,{className:"size-4"})})]}):e.jsxs(Bt,{onSelect:N,children:[e.jsx(Gt,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(No,{}),e.jsxs(Vr,{heading:"Local branches",children:[S.map(M=>e.jsxs(Bt,{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(Bt,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(No,{}),e.jsxs(Vr,{heading:"Remote branches",children:[k.map(M=>e.jsx(Bt,{onSelect:()=>j(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),k.length===0&&e.jsx(Bt,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},kb=({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(es,{className:"size-4 animate-spin"}):e.jsx(Tn,{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(es,{className:"size-4 animate-spin"}):e.jsx(en,{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(es,{className:"size-4 animate-spin"}):e.jsx(In,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(Ye,{sideOffset:8,children:"Push changes"})]})]})},Cb={branch:Ft,briefcase:li,house:ii,graduation:ai,code:Gs,heart:ad,user:ws},Mb={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 Pu(s){return s&&Mb[s]||"var(--primary)"}const xc=({icon:s,className:r,colorToken:t})=>{const n=Cb[s??"branch"]??ws;return e.jsx(n,{className:r,style:{color:Pu(t)}})},Db=({activeProfile:s,identities:r,onSelect:t,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(qt,{children:[e.jsxs(Xe,{delayDuration:1e3,children:[e.jsx(Qe,{asChild:!0,children:e.jsx(Kt,{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:Pu(s?.color)},disabled:o,children:[n?e.jsx(es,{className:"size-4 animate-spin"}):e.jsx(xc,{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(Yt,{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(St,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(xc,{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))})]})},Ab=({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:b})=>s?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[!b&&e.jsx(Nb,{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(In,{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(en,{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(kb,{syncAction:o,onFetch:a,onPull:i,onPush:c,disabled:!s}),e.jsx("div",{className:"flex-1"}),e.jsx(Db,{activeProfile:m,identities:f,onSelect:p,isApplying:h})]}):null,Eb=({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(ti,{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(es,{className:"size-4 animate-spin"}):e.jsx(en,{className:"size-4"}),"Pull ",s," commit",s===1?"":"s"]})]}),Ru={"?":{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"}},Ib=Ru.M;function Tb(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 Fb(s){const r=Tb(s);return Ru[r]??Ib}const Pb=l.memo(function({file:r,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:i,stats:c}){const d=Ne.useMemo(()=>Fb(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]),b=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(ri,{className:"size-4 text-primary"}):e.jsx(ni,{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:b,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(es,{className:"size-3.5 animate-spin"}):e.jsx(Tn,{className:"size-3.5"})})}),e.jsx(Ye,{sideOffset:8,children:"Revert changes"})]})]})})}),Rb=({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(Pb,{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))})})]})},Lu=Af,Lb=({className:s,...r})=>e.jsx(If,{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}),$u=({className:s,...r})=>e.jsx(Ef,{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 ba=38,yc=200,$b=({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=`${ba}px`;const i=Math.min(Math.max(a.scrollHeight,ba),yc);a.style.height=`${i}px`},[s]),e.jsx(bs,{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:ba,maxHeight:yc}})},Ob=({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(en,{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))})]})},_b=({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(Lu,{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($u,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(Ob,{highlights:n,onInsert:o,onClear:a}),e.jsx($b,{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(es,{className:"size-4 animate-spin"}):e.jsx(Tf,{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(es,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ti,{className:"size-4"}),"Commit"]})}),e.jsx(Mr,{variant:"default",onClick:u,disabled:!h||c,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(In,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function bc(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 Bb(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 zb=({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:bc(s.date),children:bc(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(Ys,{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(es,{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",Bb(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))})})]}),Hb=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],Ub=({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(Lu,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Lb,{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(ko,{placeholder:"Commits"})}),e.jsx(Rs,{children:Hb.map(f=>e.jsx(Ot,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(Fo,{className:"size-4 text-muted-foreground"}):e.jsx(Nt,{className:"size-4 text-muted-foreground"})]})]}),e.jsx($u,{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(zb,{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 mn=null;const Wb=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=pe(),{currentDirectory:n}=ht(),o=s?t.get(s)??void 0:void 0,i=r.find(c=>c.id===s)?.directory;return o?.path??i??n??void 0},Vb=()=>{const{git:s}=Tr(),r=Wb(),{currentSessionId:t,worktreeMetadata:n}=pe(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=Bo(),u=Od(r??null),m=$d(r??null),f=ng(r??null),p=og(r??null),h=ag(r??null),b=It(ne=>ne.isLoadingStatus),g=It(ne=>ne.isLoadingLog),{setActiveDirectory:y,fetchAll:x,fetchStatus:w,fetchBranches:S,fetchLog:k,fetchIdentity:j,setLogMaxCount:N}=It(),L=l.useMemo(()=>!mn||mn.directory!==r?null:mn,[r]),[D,M]=l.useState(L?.commitMessage??""),[v,C]=l.useState(null),[A,P]=l.useState(null),[$,R]=l.useState(25),[H,U]=l.useState(!1),{triggerFireworks:Y}=jb(),[F,B]=l.useState(()=>new Set(L?.selectedPaths??[])),[T,V]=l.useState(!1),[X,fe]=l.useState(new Set),[ae,xe]=l.useState(!1),[Me,Q]=l.useState([]),re=l.useCallback(()=>{Q([])},[]),[oe,W]=l.useState(new Set),[me,ye]=l.useState(new Map),[ce,Ce]=l.useState(new Set),Ee=l.useCallback(ne=>{navigator.clipboard.writeText(ne).then(()=>{se.success("Commit hash copied")}).catch(()=>{se.error("Failed to copy")})},[]),Pe=l.useCallback(ne=>{W(ie=>{const Ie=new Set(ie);return Ie.has(ne)?Ie.delete(ne):Ie.add(ne),Ie})},[]);l.useEffect(()=>{if(!r||!s)return;const ne=Array.from(oe).filter(ie=>!me.has(ie)&&!ce.has(ie));ne.length!==0&&(Ce(ie=>{const Ie=new Set(ie);return ne.forEach(_e=>Ie.add(_e)),Ie}),ne.forEach(ie=>{s.getCommitFiles(r,ie).then(Ie=>{ye(_e=>new Map(_e).set(ie,Ie.files))}).catch(Ie=>{console.error("Failed to fetch commit files:",Ie),ye(_e=>new Map(_e).set(ie,[]))}).finally(()=>{Ce(Ie=>{const _e=new Set(Ie);return _e.delete(ie),_e})})}))},[oe,r,s,me,ce]),l.useEffect(()=>()=>{if(!r){mn=null;return}mn={directory:r,selectedPaths:Array.from(F),commitMessage:D}},[D,r,F]),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 G=l.useCallback(async(ne=!0)=>{if(r)try{await Promise.all([w(r,s),S(r,s)])}catch(ie){if(ne){const Ie=ie instanceof Error?ie.message:"Failed to refresh repository state";se.error(Ie)}}},[r,s,w,S]),K=l.useCallback(async()=>{r&&await k(r,s,$)},[r,s,k,$]),I=l.useCallback(async()=>{r&&await j(r,s)},[r,s,j]),J=l.useMemo(()=>{if(!m)return[];const ne=m.files??[],ie=new Map;return ne.forEach(Ie=>{ie.set(Ie.path,Ie)}),Array.from(ie.values()).sort((Ie,_e)=>Ie.path.localeCompare(_e.path))},[m]);l.useEffect(()=>{if(!m||J.length===0){B(new Set),V(!1);return}B(ne=>{const ie=new Set,Ie=ne??new Set;return J.forEach(_e=>{Ie.has(_e.path)?ie.add(_e.path):T||ie.add(_e.path)}),ie})},[m,J,T]);const E=async ne=>{if(r){C(ne);try{if(ne==="fetch")await s.gitFetch(r),se.success("Fetched latest updates");else if(ne==="pull"){const ie=await s.gitPull(r);se.success(`Pulled ${ie.files.length} file${ie.files.length===1?"":"s"}`)}else ne==="push"&&(await s.gitPush(r),se.success("Pushed to remote"));await G(!1),await K()}catch(ie){const Ie=ie instanceof Error?ie.message:`Failed to ${ne==="pull"?"pull":ne}`;se.error(Ie)}finally{C(null)}}},z=async(ne={})=>{if(!r)return;if(!D.trim()){se.error("Please enter a commit message");return}const ie=Array.from(F).sort();if(ie.length===0){se.error("Select at least one file to commit");return}const Ie=ne.pushAfter?"commitAndPush":"commit";P(Ie);try{await s.createGitCommit(r,D.trim(),{files:ie}),se.success("Commit created successfully"),M(""),B(new Set),V(!1),re(),await G(),ne.pushAfter?(await s.gitPush(r),se.success("Pushed to remote"),Y(),await G(!1)):await G(!1),await K()}catch(_e){const ze=_e instanceof Error?_e.message:"Failed to create commit";se.error(ze)}finally{P(null)}},q=l.useCallback(async()=>{if(r){if(F.size===0){se.error("Select at least one file to describe");return}xe(!0);try{const{message:ne}=await s.generateCommitMessage(r,Array.from(F)),ie=ne.subject?.trim()??"",Ie=Array.isArray(ne.highlights)?ne.highlights:[];ie&&M(ie),Q(Ie),se.success("Commit message generated")}catch(ne){const ie=ne instanceof Error?ne.message:"Failed to generate commit message";se.error(ie)}finally{xe(!1)}}},[r,F,s]),be=async ne=>{if(!r||!m)return;const ie=m.current??null;try{await s.createBranch(r,ne,ie??"HEAD"),se.success(`Created branch ${ne}`);let Ie=!1;try{await s.checkoutBranch(r,ne),await s.gitPush(r,{remote:"origin",branch:ne,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(ie)try{await s.checkoutBranch(r,ie)}catch(_e){console.warn("Failed to restore original branch after creation:",_e)}}await G(),await K(),Ie&&se.success(`Upstream set for ${ne}`)}catch(Ie){const _e=Ie instanceof Error?Ie.message:"Failed to create branch";throw se.error(_e),Ie}},ee=async ne=>{if(!r)return;const ie=ne.replace(/^remotes\//,"");if(m?.current!==ie)try{await s.checkoutBranch(r,ie),se.success(`Checked out ${ie}`),await G(),await K()}catch(Ie){const _e=Ie instanceof Error?Ie.message:`Failed to checkout ${ie}`;se.error(_e)}},he=async ne=>{if(r){U(!0);try{await s.setGitIdentity(r,ne.id),se.success(`Applied "${ne.name}" to repository`),await I()}catch(ie){const Ie=ie instanceof Error?ie.message:"Failed to apply git identity";se.error(Ie)}finally{U(!1)}}},He=l.useMemo(()=>f?.all?f.all.filter(ne=>!ne.startsWith("remotes/")).sort():[],[f]),We=l.useMemo(()=>f?.all?f.all.filter(ne=>ne.startsWith("remotes/")).map(ne=>ne.replace(/^remotes\//,"")).sort():[],[f]),Be=l.useMemo(()=>{const ne=new Map;i&&ne.set(i.id,i);for(const ie of a)ne.set(ie.id,ie);return Array.from(ne.values())},[a,i]),Ze=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const ne=a.find(ie=>ie.userName===h.userName&&ie.userEmail===h.userEmail);return ne||(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]),lt=J.length,ct=F.size,dt=b||v!==null||A!==null,mt=lt>0,yt=ne=>{B(ie=>{const Ie=new Set(ie);return Ie.has(ne)?Ie.delete(ne):Ie.add(ne),Ie}),V(!0)},vt=()=>{const ne=new Set(J.map(ie=>ie.path));B(ne),V(!0)},gt=()=>{B(new Set),V(!0)},bt=l.useCallback(async ne=>{if(r){fe(ie=>{const Ie=new Set(ie);return Ie.add(ne),Ie});try{await s.revertGitFile(r,ne),se.success(`Reverted ${ne}`),await G(!1)}catch(ie){const Ie=ie instanceof Error?ie.message:"Failed to revert changes";se.error(Ie)}finally{fe(ie=>{const Ie=new Set(ie);return Ie.delete(ne),Ie})}}},[r,G,s]),Z=l.useCallback(()=>{if(Me.length===0)return;const ne=Me.map(ie=>ie.trim()).filter(Boolean);if(ne.length===0){re();return}M(ie=>{const Ie=ie.trim(),_e=Ie.length>0?`
|
|
92
|
-
|
|
93
|
-
`:"";return`${Ie}${_e}${ne.join(`
|
|
94
|
-
`)}`.trim()})},[Me,re]),De=l.useCallback(ne=>{R(ne),r&&(N(r,ne),k(r,s,ne))},[r,N,k,s]);return r?b&&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(es,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):u===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Ft,{className:"mb-3 size-6 text-muted-foreground"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:"Not a Git repository"}),e.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:"Choose a different directory or initialize Git to use this workspace."})]}):e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background","data-keyboard-avoid":"true",children:[e.jsx(Ab,{status:m,localBranches:He,remoteBranches:We,branchInfo:f?.branches,syncAction:v,onFetch:()=>E("fetch"),onPull:()=>E("pull"),onPush:()=>E("push"),onCheckoutBranch:ee,onCreateBranch:be,activeIdentityProfile:Ze,availableIdentities:Be,onSelectIdentity:he,isApplyingIdentity:H,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(Rb,{changeEntries:J,selectedPaths:F,diffStats:m?.diffStats,revertingPaths:X,onToggleFile:yt,onSelectAll:vt,onClearSelection:gt,onViewDiff:ne=>Fe.getState().navigateToDiff(ne),onRevertFile:bt}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(Eb,{behind:m?.behind??0,onPull:()=>E("pull"),isPulling:v==="pull"})}),J.length>0&&e.jsx(_b,{selectedCount:ct,commitMessage:D,onCommitMessageChange:M,generatedHighlights:Me,onInsertHighlights:Z,onClearHighlights:re,onGenerateMessage:q,isGeneratingMessage:ae,onCommit:()=>z({pushAfter:!1}),onCommitAndPush:()=>z({pushAfter:!0}),commitAction:A,isBusy:dt})]}),e.jsx(Ub,{log:p,isLogLoading:g,logMaxCount:$,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."})})},Gb=1e6;function br(s){let r=s.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const Qn=s=>({directory:s,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),wc=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?Qn(o):c??Qn(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)??Qn(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)??Qn(o),d=a.nextChunkId,u={id:d,data:n},m=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>Gb&&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})}})),Ou=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),qb=[{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'}],Kb=[{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'}],_u=s=>Object.fromEntries(s.map(r=>[r.id,r])),vc=_u(qb),wr=_u(Kb),Yb="ibm-plex-sans",co="ibm-plex-mono";function Xb(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 Qb(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 wa=null;function Jb(){return wa||(wa=Rf.load()),wa}function Zb(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 Ja=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),b=l.useRef(t),g=l.useRef(n),y=l.useRef(null),x=l.useRef(""),w=l.useRef(null),S=l.useRef(!1),k=l.useRef(null),j=l.useRef(null),N=l.useRef(null),L=l.useRef(0),D=l.useRef(null),[,M]=l.useReducer(F=>F+1,0),[v,C]=l.useReducer(F=>F+1,0);b.current=t,g.current=n;const A=l.useCallback((F,B)=>{const T=D.current,V=m.current;if(!T||!V)return;const X=V.getBoundingClientRect(),fe=X.left+X.width/2,ae=X.top+X.height-12,xe=typeof F=="number"?F:fe,Me=typeof B=="number"?B:ae,Q=8,re=Math.max(Q,Math.min(X.width-Q,xe-X.left)),oe=Math.max(Q,Math.min(X.height-Q,Me-X.top));T.style.left=`${re}px`,T.style.top=`${oe}px`,T.style.bottom="";try{T.focus({preventScroll:!0})}catch{try{T.focus()}catch{}}},[]),P=l.useCallback(()=>{x.current="",w.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(w.current),w.current=null,S.current=!1,k.current=null},[]),$=l.useCallback(()=>{const F=h.current,B=p.current,T=m.current;if(!F||!B||!T)return;const V=T.getBoundingClientRect();if(!(V.width<24||V.height<24))try{F.fit();const X={cols:B.cols,rows:B.rows},fe=y.current;(!fe||fe.cols!==X.cols||fe.rows!==X.rows)&&(y.current=X,g.current(X.cols,X.rows))}catch{}},[]),R=l.useCallback(()=>{if(S.current)return;const F=p.current;if(!F){P();return}if(!x.current)return;const B=x.current;x.current="",S.current=!0,F.write(B,()=>{S.current=!1,x.current&&(typeof window<"u"?w.current=window.requestAnimationFrame(()=>{w.current=null,R()}):R())})},[P]),H=l.useCallback(()=>{w.current===null&&(typeof window<"u"?w.current=window.requestAnimationFrame(()=>{w.current=null,R()}):R())},[R]),U=l.useCallback(F=>{F&&(x.current+=F,H())},[H]),Y=l.useCallback(()=>{if(j.current?.(),j.current=null,N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),!d){L.current=0;return}const F=m.current;if(!F)return;const B=p.current;if(!B)return;L.current=0;const T=2.2,V=2.8,X=25,fe=.25,ae=8,xe=.05,Me=.015,Q={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},re=()=>typeof performance<"u"?performance.now():Date.now(),oe=Math.max(12,Math.round(i*1.35));let W=0;const me=J=>{if(!J)return!1;const E=B.getViewportY(),z=W+J,q=Math.trunc(z/oe);return W=z-q*oe,q!==0&&B.scrollLines(q),B.getViewportY()!==E},ye=()=>{Q.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(Q.rafId),Q.rafId=null},ce={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const J=Object.assign(Q,{pointerId:null,startX:null,startY:null,moved:!1}),E=6,z=he=>{if(he.pointerType==="touch"){ye(),J.pointerId=he.pointerId,J.startX=he.clientX,J.startY=he.clientY,J.moved=!1,J.lastY=he.clientY,J.lastTime=re(),J.velocity=0;try{F.setPointerCapture(he.pointerId)}catch{}}},q=he=>{if(he.pointerType!=="touch"||J.pointerId!==he.pointerId)return;if(J.startX!==null&&J.startY!==null&&!J.moved){const yt=he.clientX-J.startX,vt=he.clientY-J.startY;Math.hypot(yt,vt)>=E&&(J.moved=!0)}if(J.lastY===null){J.lastY=he.clientY,J.lastTime=re();return}const He=J.lastY,We=J.lastTime??re(),Be=re();J.lastY=he.clientY,J.lastTime=Be;const Ze=He-he.clientY;if(Math.abs(Ze)<1)return;const lt=Math.max(Be-We,8),ct=T+Math.min(V,Math.abs(Ze)/X),dt=Ze*ct,mt=dt/lt;J.velocity=J.velocity*(1-fe)+mt*fe,J.velocity>ae?J.velocity=ae:J.velocity<-ae&&(J.velocity=-ae),J.moved&&(he.cancelable&&he.preventDefault(),he.stopPropagation()),me(dt)},be=he=>{if(he.pointerType!=="touch"||J.pointerId!==he.pointerId)return;const He=!J.moved;J.pointerId=null,J.startX=null,J.startY=null,J.moved=!1,J.lastY=null,J.lastTime=null;try{F.releasePointerCapture(he.pointerId)}catch{}if(He){A(he.clientX,he.clientY);return}if(typeof window>"u")return;if(Math.abs(J.velocity)<xe){J.velocity=0;return}let We=re();const Be=()=>{const Ze=re(),lt=Math.max(Ze-We,8);We=Ze;const ct=me(J.velocity*lt)??!1,dt=Math.sign(J.velocity),mt=Math.max(0,Math.abs(J.velocity)-Me*lt);if(J.velocity=mt*dt,!ct||mt<=xe){ye(),J.velocity=0;return}J.rafId=window.requestAnimationFrame(Be)};J.rafId=window.requestAnimationFrame(Be)};F.addEventListener("pointerdown",z,ce),F.addEventListener("pointermove",q,ce),F.addEventListener("pointerup",be,ce),F.addEventListener("pointercancel",be,ce);const ee=F.style.touchAction;F.style.touchAction="manipulation",j.current=()=>{ye(),N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),L.current=0,F.removeEventListener("pointerdown",z,ce),F.removeEventListener("pointermove",q,ce),F.removeEventListener("pointerup",be,ce),F.removeEventListener("pointercancel",be,ce),F.style.touchAction=ee};return}const Ee=6,Pe=J=>{J.touches.length===1&&(ye(),Q.lastY=J.touches[0].clientY,Q.lastTime=re(),Q.velocity=0,Q.startX=J.touches[0].clientX,Q.startY=J.touches[0].clientY,Q.didMove=!1)},G=J=>{if(J.touches.length!==1){Q.lastY=null,Q.lastTime=null,Q.velocity=0,Q.startX=null,Q.startY=null,Q.didMove=!1,ye();return}const E=J.touches[0].clientX,z=J.touches[0].clientY;if(Q.startX!==null&&Q.startY!==null&&!Q.didMove){const lt=E-Q.startX,ct=z-Q.startY;Math.hypot(lt,ct)>=Ee&&(Q.didMove=!0)}if(Q.lastY===null){Q.lastY=z,Q.lastTime=re();return}const q=Q.lastY,be=Q.lastTime??re(),ee=re();Q.lastY=z,Q.lastTime=ee;const he=q-z;if(Math.abs(he)<1)return;const He=Math.max(ee-be,8),We=T+Math.min(V,Math.abs(he)/X),Be=he*We,Ze=Be/He;Q.velocity=Q.velocity*(1-fe)+Ze*fe,Q.velocity>ae?Q.velocity=ae:Q.velocity<-ae&&(Q.velocity=-ae),Q.didMove&&(J.preventDefault(),J.stopPropagation()),me(Be)},K=J=>{const E=!Q.didMove;Q.lastY=null,Q.lastTime=null;const z=Q.velocity;if(Q.startX=null,Q.startY=null,Q.didMove=!1,E){const ee=J.changedTouches?.[0];A(ee?.clientX,ee?.clientY);return}if(typeof window>"u")return;if(Math.abs(z)<xe){Q.velocity=0;return}let q=re();const be=()=>{const ee=re(),he=Math.max(ee-q,8);q=ee;const He=me(Q.velocity*he)??!1,We=Math.sign(Q.velocity),Be=Math.max(0,Math.abs(Q.velocity)-Me*he);if(Q.velocity=Be*We,!He||Be<=xe){ye(),Q.velocity=0;return}Q.rafId=window.requestAnimationFrame(be)};Q.rafId=window.requestAnimationFrame(be)};F.addEventListener("touchstart",Pe,ce),F.addEventListener("touchmove",G,ce),F.addEventListener("touchend",K,ce),F.addEventListener("touchcancel",K,ce);const I=F.style.touchAction;F.style.touchAction="manipulation",j.current=()=>{ye(),N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),L.current=0,F.removeEventListener("touchstart",Pe,ce),F.removeEventListener("touchmove",G,ce),F.removeEventListener("touchend",K,ce),F.removeEventListener("touchcancel",K,ce),F.style.touchAction=I}},[d,A,i]);return l.useEffect(()=>{let F=!1,B=null,T=null,V=[];const X=m.current;return X?(X.tabIndex=0,(async()=>{try{const ae=await Jb();if(F)return;const xe=Qb(a,i,o,ae),Me=new Ff(xe),Q=new Pf;B=Me,p.current=Me,h.current=Q,Me.loadAddon(Q),Me.open(X),C();const re=Zb(X);re?(re.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=re,M()):f.current=null,$(),Y(),Me.focus(),V=[Me.onData(oe=>{b.current(oe)})],T=new ResizeObserver(()=>{$()}),T.observe(X),typeof window<"u"&&window.setTimeout(()=>{$()},0)}catch{}})(),()=>{F=!0,j.current?.(),j.current=null,V.forEach(ae=>ae.dispose()),T?.disconnect(),B?.dispose(),p.current=null,h.current=null,f.current=null,y.current=null,P()}):void 0},[$,a,i,Y,o,P]),l.useEffect(()=>{const F=p.current;F&&(F.reset(),P(),y.current=null,$(),F.focus())},[s,v,$,P]),l.useEffect(()=>(Y(),()=>{j.current?.(),j.current=null}),[Y,s]),l.useEffect(()=>{const F=p.current;if(!F)return;if(r.length===0){k.current!==null&&(F.reset(),P(),$());return}const B=k.current;let T;if(B===null)T=r;else{const V=r.findIndex(X=>X.id===B);T=V>=0?r.slice(V+1):r}T.length>0&&U(T.map(V=>V.data).join("")),k.current=r[r.length-1].id},[r,v,U,$,P]),l.useImperativeHandle(u,()=>({focus:()=>{if(d){A();return}p.current?.focus()},clear:()=>{const F=p.current;F&&(F.reset(),P(),$())},fit:()=>{$()}}),[d,A,$,P]),e.jsxs("div",{ref:m,className:O("relative h-full w-full",c),style:{backgroundColor:o.background},onClick:F=>{d?A(F.clientX,F.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:D,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:F=>{const B=String(F.currentTarget.value||"");if(!B)return;const T=B.replace(/\r\n|\r|\n/g,"\r");b.current(T),F.currentTarget.value=""},onKeyDown:F=>{F.key==="Backspace"&&(F.currentTarget.value||b.current(""))}}):null,f.current&&!d?e.jsx(gi,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});Ja.displayName="TerminalViewport";const jc=13,ew={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Jn={ctrl:"5",cmd:"3"},tw={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},sw=(s,r)=>{if(r)switch(s){case"arrow-up":return`\x1B[1;${Jn[r]}A`;case"arrow-down":return`\x1B[1;${Jn[r]}B`;case"arrow-right":return`\x1B[1;${Jn[r]}C`;case"arrow-left":return`\x1B[1;${Jn[r]}D`}return ew[s]??null},rw=()=>{const{terminal:s}=Tr(),{currentTheme:r}=Fr(),{monoFont:t}=Ou(),{isMobile:n,hasTouchInput:o}=Ct(),{currentSessionId:a,sessions:i,worktreeMetadata:c}=pe(),d=a?c.get(a)??void 0:void 0,u=l.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const E=i.find(q=>q.id===a),z=typeof E?.directory=="string"?E.directory:null;return z&&z.length>0?z:null},[a,i,d]),{currentDirectory:m,homeDirectory:f}=ht(),p=u||m||null,h=l.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),b=wc(),g=b.sessions,y=b.setTerminalSession,x=b.setConnecting,w=b.appendToBuffer,S=b.clearTerminalSession,k=b.removeTerminalSession,j=b.clearBuffer,N=l.useMemo(()=>{if(p)return g.get(p)},[g,p]),L=N?.terminalSessionId??null,D=N?.bufferChunks??[],M=N?.bufferLength??0,v=N?.isConnecting??!1,C=L,[A,P]=l.useState(null),[$,R]=l.useState(!1),[H,U]=l.useState(null),[Y,F]=l.useState(!1),B=l.useRef(null),T=l.useRef(null),V=l.useRef(C),X=l.useRef(p),fe=l.useRef(null),xe=Fe(E=>E.activeMainTab)==="terminal";l.useEffect(()=>{V.current=C},[C]),l.useEffect(()=>{X.current=p},[p]),l.useEffect(()=>{!n&&H!==null&&U(null)},[n,H,U]),l.useEffect(()=>{!C&&H!==null&&U(null)},[C,H,U]);const Me=l.useCallback(()=>{B.current?.(),B.current=null,T.current=null},[]);l.useEffect(()=>()=>{Me(),V.current=null},[Me]);const Q=l.useCallback(E=>{if(T.current===E)return;Me();const z=s.connect(E,{onEvent:q=>{const be=X.current;if(be)switch(q.type){case"connected":{(q.runtime||q.ptyBackend)&&console.log(`[Terminal] connected runtime=${q.runtime??"unknown"} pty=${q.ptyBackend??"unknown"}`),x(be,!1),P(null),R(!1),fe.current?.focus();break}case"reconnecting":{const ee=q.attempt??0,he=q.maxAttempts??3;P(`Reconnecting (${ee}/${he})...`),R(!1);break}case"data":{q.data&&w(be,q.data);break}case"exit":{const ee=typeof q.exitCode=="number"?q.exitCode:null,he=typeof q.signal=="number"?q.signal:null;w(be,`\r
|
|
95
|
-
[Process exited${ee!==null?` with code ${ee}`:""}${he!==null?` (signal ${he})`:""}]\r
|
|
96
|
-
`),S(be),x(be,!1),P("Terminal session ended"),R(!1),Me();break}}},onError:(q,be)=>{const ee=X.current;if(!ee)return;const he=be?`Connection failed: ${q.message}`:q.message||"Terminal stream connection error";P(he),R(!!be),be&&(x(ee,!1),Me(),k(ee))}},tw);B.current=()=>{z.close(),T.current=null},T.current=E},[w,S,Me,k,x,s,P]);l.useEffect(()=>{let E=!1;if(!p){P(a?"No working directory available for terminal.":"Select a session to open the terminal."),Me();return}return(async()=>{const q=p;if(!X.current||X.current!==q)return;let ee=wc.getState().getTerminalSession(q)?.terminalSessionId??null;if(!ee){P(null),R(!1),x(q,!0);try{const he=await s.createSession({cwd:q});if(E){try{await s.close(he.sessionId)}catch{}return}y(q,he),ee=he.sessionId}catch(he){E||(P(he instanceof Error?he.message:"Failed to start terminal session"),R(!0),x(q,!1));return}}!ee||E||(V.current=ee,Q(ee))})(),()=>{E=!0,V.current=null,Me()}},[a,p,C,k,x,y,Q,Me,s]);const re=l.useCallback(async()=>{if(!p||Y)return;F(!0),P(null),R(!1),Me();const E=V.current;try{if(s.restartSession&&E){const z=await s.restartSession(E,{cwd:p});y(p,z),V.current=z.sessionId,Q(z.sessionId)}else{if(E)try{await s.close(E)}catch{}k(p)}}catch(z){P(z instanceof Error?z.message:"Failed to restart terminal"),R(!0)}finally{F(!1)}},[p,Y,Me,s,y,Q,k]),oe=l.useCallback(async()=>{if(p&&!Y){F(!0),P(null),R(!1),Me();try{s.forceKill&&await s.forceKill({cwd:p})}catch{}k(p),j(p),fe.current?.clear(),await new Promise(E=>setTimeout(E,100));try{x(p,!0);const E=await s.createSession({cwd:p});y(p,E),V.current=E.sessionId,Q(E.sessionId)}catch(E){P(E instanceof Error?E.message:"Failed to create terminal"),R(!0),x(p,!1)}finally{F(!1)}}},[p,Y,Me,s,k,j,x,y,Q]),W=l.useCallback(()=>{if(!p)return;j(p),fe.current?.clear(),fe.current?.focus();const E=V.current;E&&s.sendInput(E,"\f").catch(z=>{P(z instanceof Error?z.message:"Failed to refresh prompt")})},[j,p,P,s]),me=l.useCallback(E=>{if(!E)return;let z=E,q=!1;if(H&&E.length>0){const ee=E[0];if(ee.length===1&&/[a-zA-Z]/.test(ee)){const he=ee.toUpperCase();(H==="ctrl"||H==="cmd")&&(z=String.fromCharCode(he.charCodeAt(0)&31),q=!0)}q||(q=!0)}const be=V.current;be&&(s.sendInput(be,z).catch(ee=>{P(ee instanceof Error?ee.message:"Failed to send input")}),q&&(U(null),fe.current?.focus()))},[H,U,s]),ye=l.useCallback((E,z)=>{const q=V.current;q&&s.resize({sessionId:q,cols:E,rows:z}).catch(()=>{})},[s]),ce=l.useCallback(E=>{U(z=>z===E?null:E),fe.current?.focus()},[U]),Ce=l.useCallback(E=>{const z=sw(E,H);z&&(me(z),U(null),fe.current?.focus())},[H,me,U]);l.useEffect(()=>{if(!n||!H||!C)return;const E=z=>{if(z.repeat)return;const q=z.key;if(!q||q==="Control"||q==="Meta"||q==="Alt"||q==="Shift")return;const be=q.length===1?q.toLowerCase():q,ee=z.code??"",he=ee.startsWith("Key")&&ee.length===4?ee.slice(3).toUpperCase():null,He=q.length===1&&/[a-zA-Z]/.test(q)?q.toUpperCase():he,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){z.preventDefault(),z.stopPropagation(),Ce(We[be]);return}if(H==="ctrl"&&He&&He.length===1&&He>="A"&&He<="Z"){const Be=String.fromCharCode(He.charCodeAt(0)&31);z.preventDefault(),z.stopPropagation(),me(Be),U(null),fe.current?.focus()}};return window.addEventListener("keydown",E),()=>{window.removeEventListener("keydown",E)}},[H,Ce,me,n,U,C]);const Ee=l.useMemo(()=>{const E=wr[co].stack;if(typeof window>"u")return(wr[t]??wr[co]).stack;const q=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return q&&q.trim().length>0?q.trim():(wr[t]??wr[co]).stack??E},[t]),Pe=l.useMemo(()=>Xb(r),[r]),G=l.useMemo(()=>`${p??"no-dir"}::${C??"pending"}`,[p,C]);l.useEffect(()=>{if(!xe)return;const E=fe.current;if(!E)return;const z=()=>{E.fit()};if(typeof window<"u"){const q=window.requestAnimationFrame(()=>{z(),E.focus()}),be=[220,400].map(ee=>window.setTimeout(z,ee));return()=>{window.cancelAnimationFrame(q),be.forEach(ee=>window.clearTimeout(ee))}}z()},[xe,G,C]);const K=A?.includes("Reconnecting"),I=A?K?e.jsx(Lf,{size:20,className:"text-amber-400"}):e.jsx(Vt,{size:20,className:"text-destructive"}):C&&!v&&!Y?e.jsx(to,{size:20,className:"text-emerald-400"}):v||Y?e.jsx(Ui,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Ui,{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:re,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const J=!C||v||Y;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:[I,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:re,disabled:Y,title:"Restart terminal session",type:"button",children:[e.jsx(xs,{size:16,className:O((v||Y)&&"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:()=>Ce("esc"),disabled:J,children:"Esc"}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ce("tab"),disabled:J,children:[e.jsx(Hi,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:H==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ce("ctrl"),disabled:J,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:H==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ce("cmd"),disabled:J,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:()=>Ce("arrow-up"),disabled:J,children:[e.jsx(In,{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:()=>Ce("arrow-left"),disabled:J,children:[e.jsx(id,{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:()=>Ce("arrow-down"),disabled:J,children:[e.jsx(en,{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:()=>Ce("arrow-right"),disabled:J,children:[e.jsx(Hi,{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:()=>Ce("enter"),disabled:J,children:[e.jsx(vn,{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:xe?n?e.jsx(Ja,{ref:E=>{fe.current=E},sessionKey:G,chunks:D,onInput:me,onResize:ye,theme:Pe,fontFamily:Ee,fontSize:jc,enableTouchScroll:o},G):e.jsx(tt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Ja,{ref:E=>{fe.current=E},sessionKey:G,chunks:D,onInput:me,onResize:ye,theme:Pe,fontFamily:Ee,fontSize:jc,enableTouchScroll:o},G)}):null}),A&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2",children:[e.jsx("span",{children:A}),$&&e.jsx(ve,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:oe,disabled:Y,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},Bu=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:si},{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:od},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:Sn},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Ft},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:Cr}],nw={},ow={},aw={};Bu.forEach(s=>{nw[s.id]=s.label,ow[s.id]=s.description,aw[s.id]=s});const iw=({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}=sn(),{setSidebarOpen:p}=Fe(),{isMobile:h}=Ct(),[b,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=b?"bg-transparent":y?"bg-background":"bg-sidebar",w=()=>{const A="new-agent";let P=A,$=1;for(;i.some(R=>R.name===P);)P=`${A}-${$}`,$++;d({name:P,scope:"user"}),c(P),s?.(),h&&p(!1)},S=async A=>{if(_r(A)){se.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${A.name}"?`)&&(await m(A.name)?se.success(`Agent "${A.name}" deleted successfully`):se.error("Failed to delete agent"))},k=async A=>{_r(A)&&window.confirm(`Are you sure you want to reset agent "${A.name}" to its default configuration?`)&&(await m(A.name)?se.success(`Agent "${A.name}" reset to default`):se.error("Failed to reset agent"))},j=A=>{const P=A.name;let $=1,R=`${P}-copy`;for(;i.some(F=>F.name===R);)$++,R=`${P}-copy-${$}`;const H=A,U=typeof A.model=="string"?A.model:A.model?.providerID&&A.model?.modelID?`${A.model.providerID}/${A.model.modelID}`:void 0,Y=A;d({name:R,scope:H.scope||"user",description:A.description,model:U,temperature:A.temperature,top_p:A.topP,prompt:A.prompt,mode:A.mode,tools:A.tools,permission:A.permission,disable:Y.disable}),c(R),h&&p(!1)},N=A=>{o(A.name),t(A)},L=async()=>{if(!r)return;const A=n.trim().replace(/\s+/g,"-");if(!A){se.error("Agent name is required");return}if(A===r.name){t(null);return}if(i.some(H=>H.name===A)){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;await u({name:A,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:$.disable,scope:$.scope})?await m(r.name)?(se.success(`Agent renamed to "${A}"`),c(A)):se.error("Failed to remove old agent after rename"):se.error("Failed to rename agent"),t(null)},D=A=>{switch(A){case"primary":return e.jsx(jn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(cd,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(ld,{className:"h-3 w-3 text-primary"});default:return null}},M=i.filter(A=>!gd(A)),v=M.filter(_r),C=M.filter(A=>!_r(A));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:w,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(Nn,{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:[v.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"}),v.map(A=>e.jsx(Sc,{agent:A,isSelected:a===A.name,onSelect:()=>{c(A.name),s?.(),h&&p(!1)},onReset:()=>k(A),onDuplicate:()=>j(A),getAgentModeIcon:D},A.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(A=>e.jsx(Sc,{agent:A,isSelected:a===A.name,onSelect:()=>{c(A.name),s?.(),h&&p(!1)},onRename:()=>N(A),onDelete:()=>S(A),onDuplicate:()=>j(A),getAgentModeIcon:D},A.name))]})]})}),e.jsx(as,{open:r!==null,onOpenChange:A=>!A&&t(null),children:e.jsxs(is,{children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Rename Agent"}),e.jsxs(Ss,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(it,{value:n,onChange:A=>o(A.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:A=>{A.key==="Enter"&&L()}}),e.jsxs(Ks,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Mr,{onClick:L,children:"Rename"})]})]})})]})},Sc=({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(qt,{children:[e.jsx(Kt,{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(Zr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(St,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(ci,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(St,{onClick:u=>{u.stopPropagation(),i()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(St,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(xs,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(St,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Ms({className:s,variant:r,...t}){return e.jsx(ve,{variant:r,size:"sm",className:O("h-6 px-2 text-xs",s),...t})}const lw=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),cw=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=lw.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Ii=({providerId:s,modelId:r,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=ut(),i=Fe(T=>T.isMobile),{toggleFavoriteModel:c,isFavoriteModel:d,addRecentModel:u}=Fe(),{favoriteModelsList:m,recentModelsList:f}=Ci(),{isMobile:p}=Ct(),h=i||p,[b,g]=l.useState(!1),[y,x]=l.useState(new Set),[w,S]=l.useState(!1),[k,j]=l.useState(""),[N,L]=l.useState(0),D=l.useRef([]),M=()=>g(!1),v=T=>{x(V=>{const X=new Set(V);return X.has(T)?X.delete(T):X.add(T),X})};l.useEffect(()=>{w||(j(""),L(0))},[w]),l.useEffect(()=>{L(0)},[k]);const C=T=>{const V=T?.name||T?.id||"",X=String(V);return X.length>40?X.substring(0,37)+"...":X},A=(T,V)=>{const X=`${T}/${V}`;return a.get(X)},P=(T,V)=>{t(T,V),T&&V&&u(T,V),S(!1)},$=(T,V)=>{if(!k.trim())return!0;const X=k.toLowerCase();return T.toLowerCase().includes(X)||V.toLowerCase().includes(X)},R=(T,V,X,fe,ae,xe)=>{const Me=A(V,X),Q=cw(Me?.limit?.context),re=s===V&&r===X,oe=d(V,X);return e.jsxs("div",{ref:W=>{D.current[ae]=W},className:O("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",xe?"bg-accent":"hover:bg-accent/50"),onClick:()=>P(V,X),onMouseEnter:()=>L(ae),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:C(T)}),Q?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:Q}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[re&&e.jsx(Dt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:W=>{W.preventDefault(),W.stopPropagation(),c(V,X)},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(er,{className:"h-3.5 w-3.5"}):e.jsx(Hr,{className:"h-3.5 w-3.5"})})]})]},`${fe}-${V}-${X}`)},H=m.filter(({model:T,providerID:V})=>{const fe=o.find(xe=>xe.id===V)?.name||V,ae=C(T);return $(ae,fe)}),U=f.filter(({model:T,providerID:V})=>{const fe=o.find(xe=>xe.id===V)?.name||V,ae=C(T);return $(ae,fe)}),Y=o.map(T=>{const X=(Array.isArray(T.models)?T.models:[]).filter(fe=>{const ae=C(fe);return $(ae,T.name||T.id||"")});return{...T,models:X}}).filter(T=>T.models.length>0),F=H.length>0||U.length>0||Y.length>0,B=()=>h?e.jsx(ps,{open:b,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:T,providerID:V,modelID:X})=>{const fe=V===s&&X===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(V,X),M()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{providerId:V,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:C(T)})]})}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),c(V,X)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-yellow-500 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Unfavorite",children:e.jsx(er,{className:"h-4 w-4"})})]},`fav-mobile-${V}-${X}`)})})]}),f.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Recents"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:T,providerID:V,modelID:X})=>{const fe=V===s&&X===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(V,X),M()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{providerId:V,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:C(T)})]})}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),c(V,X)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Favorite",children:e.jsx(Hr,{className:"h-4 w-4"})})]},`recent-mobile-${V}-${X}`)})})]}),o.map(T=>{const V=Array.isArray(T.models)?T.models:[];if(V.length===0)return null;const X=T.id===s,fe=y.has(T.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:()=>v(T.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{providerId:T.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:T.name}),X&&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(Es,{className:"h-3 w-3 text-muted-foreground"})]}),fe&&e.jsx("div",{className:"border-t border-border/20",children:V.map(ae=>{const xe=T.id===s&&ae.id===r;return e.jsxs("div",{className:O("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",xe?"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(T.id,ae.id),M()},children:e.jsx("span",{className:"font-medium truncate",children:C(ae)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:Me=>{Me.preventDefault(),Me.stopPropagation(),c(T.id,ae.id)},className:O("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(T.id,ae.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(T.id,ae.id)?"Unfavorite":"Favorite",children:d(T.id,ae.id)?e.jsx(er,{className:"h-4 w-4"}):e.jsx(Hr,{className:"h-4 w-4"})}),xe&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},ae.id)})})]},T.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(zt,{providerId:s,className:"h-3.5 w-3.5"}):e.jsx(Zs,{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(qt,{open:w,onOpenChange:S,children:[e.jsx(Kt,{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(zt,{providerId:s,className:"h-3 w-3 flex-shrink-0"}),e.jsx(Zs,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Zs,{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(Yt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const T=[];H.forEach(({model:ae,providerID:xe,modelID:Me})=>{T.push({model:ae,providerID:xe,modelID:Me,section:"fav"})}),U.forEach(({model:ae,providerID:xe,modelID:Me})=>{T.push({model:ae,providerID:xe,modelID:Me,section:"recent"})}),Y.forEach(ae=>{ae.models.forEach(xe=>{T.push({model:xe,providerID:ae.id,modelID:xe.id,section:"provider"})})});const V=T.length,X=ae=>{if(ae.key==="ArrowDown"){ae.preventDefault(),ae.stopPropagation();const xe=(N+1)%Math.max(1,V);L(xe),setTimeout(()=>{D.current[xe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(ae.key==="ArrowUp"){ae.preventDefault(),ae.stopPropagation();const xe=(N-1+Math.max(1,V))%Math.max(1,V);L(xe),setTimeout(()=>{D.current[xe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(ae.key==="Enter"){ae.preventDefault(),ae.stopPropagation();const xe=T[N];xe&&P(xe.providerID,xe.modelID)}else ae.key==="Escape"&&(ae.preventDefault(),ae.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(sr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(it,{type:"text",placeholder:"Search models",value:k,onChange:ae=>j(ae.target.value),onKeyDown:X,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(Vt,{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,{}),!F&&k&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),H.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(er,{className:"h-4 w-4 text-primary"}),"Favorites"]}),H.map(({model:ae,providerID:xe,modelID:Me})=>{const Q=fe++;return R(ae,xe,Me,"fav",Q,N===Q)})]}),U.length>0&&e.jsxs(e.Fragment,{children:[H.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(qs,{className:"h-4 w-4"}),"Recent"]}),U.map(({model:ae,providerID:xe,modelID:Me})=>{const Q=fe++;return R(ae,xe,Me,"recent",Q,N===Q)})]}),(H.length>0||U.length>0)&&Y.length>0&&e.jsx(Us,{}),Y.map((ae,xe)=>e.jsxs(l.Fragment,{children:[xe>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(zt,{providerId:ae.id,className:"h-4 w-4 flex-shrink-0"}),ae.name]}),ae.models.map(Me=>{const Q=fe++;return R(Me,ae.id,Me.id,"provider",Q,N===Q)})]},ae.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"})]})})()})]}),B()]})},dw=()=>{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}},uw=()=>{const{selectedAgentName:s,getAgentByName:r,createAgent:t,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:i}=sn();ut();const{tools:c}=dw(),d=s?r(s):null,u=!!(a&&a.name===s&&!d),[m,f]=l.useState(""),[p,h]=l.useState("user"),[b,g]=l.useState(""),[y,x]=l.useState("subagent"),[w,S]=l.useState(""),[k,j]=l.useState(void 0),[N,L]=l.useState(void 0),[D,M]=l.useState(""),[v,C]=l.useState({}),[A,P]=l.useState("allow"),[$,R]=l.useState("allow"),[H,U]=l.useState("allow"),[Y,F]=l.useState("allow"),[B,T]=l.useState("ask"),[V,X]=l.useState("ask"),[fe,ae]=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),L(a.top_p),M(a.prompt||"");const re=a.tools||{};C(re);const oe=(ce,Ce,Ee)=>ce==="allow"||ce==="ask"||ce==="deny"?ce:Ce?"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 Ce=ce["*"];if(Ce==="allow"||Ce==="ask"||Ce==="deny")return Ce}},ye=re.edit===!1||re.write===!1||re.patch===!1;P(oe(me(W.edit),ye,"allow")),U(oe(me(W.bash),re.bash===!1,"allow")),R(oe(me(W.webfetch),re.webfetch===!1,"allow")),F(oe(me(W.skill),re.skill===!1,"allow")),T(oe(me(W.doom_loop),!1,"ask")),X(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),L(d.topP),M(d.prompt||"");const re=d.tools||{};C(re);const oe=(ce,Ce,Ee)=>ce==="allow"||ce==="ask"||ce==="deny"?ce:Ce?"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 Ce=ce["*"];if(Ce==="allow"||Ce==="ask"||Ce==="deny")return Ce}},ye=re.edit===!1||re.write===!1||re.patch===!1;P(oe(me(W.edit),ye,"allow")),U(oe(me(W.bash),re.bash===!1,"allow")),R(oe(me(W.webfetch),re.webfetch===!1,"allow")),F(oe(me(W.skill),re.skill===!1,"allow")),T(oe(me(W.doom_loop),!1,"ask")),X(oe(me(W.external_directory),!1,"ask"))}},[d,u,s,o,a]);const xe=async()=>{const re=u?m.trim().replace(/\s+/g,"-"):s?.trim();if(!re){se.error("Agent name is required");return}if(u&&o.some(oe=>oe.name===re)){se.error("An agent with this name already exists");return}ae(!0);try{const oe=w.trim(),W={name:re,description:b.trim()||void 0,mode:y,model:oe===""?null:oe,temperature:k,top_p:N,prompt:D.trim()||void 0,tools:Object.keys(v).length>0?v:void 0,permission:{edit:A,webfetch:$,bash:H,skill:Y,doom_loop:B,external_directory:V},scope:u?p:void 0};let me;u?(me=await t(W),me&&i(null)):me=await n(re,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{ae(!1)}},Me=re=>{C(oe=>({...oe,[re]:!oe[re]}))},Q=re=>{const oe={};c.forEach(W=>{oe[W]=re}),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(it,{value:m,onChange:re=>f(re.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Fs,{value:p,onValueChange:re=>h(re),children:[e.jsxs(Ps,{className:"!h-9 w-auto gap-1.5",children:[p==="user"?e.jsx(ws,{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(ws,{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(bs,{value:b,onChange:re=>g(re.target.value),placeholder:"What does this agent do?",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Mode"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsxs(Ms,{variant:y==="primary"?"default":"outline",onClick:()=>x("primary"),className:O("gap-2",y==="primary"?void 0:"text-foreground"),children:[e.jsx(jn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Ms,{variant:y==="subagent"?"default":"outline",onClick:()=>x("subagent"),className:O("gap-2",y==="subagent"?void 0:"text-foreground"),children:[e.jsx(ld,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Ms,{variant:y==="all"?"default":"outline",onClick:()=>x("all"),className:O("gap-2",y==="all"?void 0:"text-foreground"),children:[e.jsx(cd,{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(Ii,{providerId:w?w.split("/")[0]:"",modelId:w?w.split("/")[1]:"",onChange:(re,oe)=>{S(re&&oe?`${re}/${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(Ut,{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,(k!==void 0?k:.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(Wi,{className:"h-3.5 w-3.5"})}),e.jsx(it,{type:"text",inputMode:"decimal",value:k!==void 0?k:"",onChange:re=>{const oe=re.target.value;if(oe===""){j(void 0);return}const W=parseFloat(oe);!isNaN(W)&&W>=0&&W<=2&&j(W)},onBlur:re=>{const oe=re.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,(k!==void 0?k:.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(Ut,{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,(N!==void 0?N:.9)-.1);L(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(Wi,{className:"h-3.5 w-3.5"})}),e.jsx(it,{type:"text",inputMode:"decimal",value:N!==void 0?N:"",onChange:re=>{const oe=re.target.value;if(oe===""){L(void 0);return}const W=parseFloat(oe);!isNaN(W)&&W>=0&&W<=1&&L(W)},onBlur:re=>{const oe=re.target.value;if(oe!==""){const W=parseFloat(oe);if(!isNaN(W)){const me=Math.max(0,Math.min(1,W));L(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,(N!==void 0?N:.9)+.1);L(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(bs,{value:D,onChange:re=>M(re.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:()=>Q(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>Q(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:c.map(re=>e.jsx("button",{type:"button",onClick:()=>Me(re),className:O("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",v[re]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:re},re))})]}),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:A==="allow"?"default":"outline",onClick:()=>P("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:A==="ask"?"default":"outline",onClick:()=>P("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:A==="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(Ut,{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:H==="allow"?"default":"outline",onClick:()=>U("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:H==="ask"?"default":"outline",onClick:()=>U("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:H==="deny"?"default":"outline",onClick:()=>U("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(Ut,{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:$==="allow"?"default":"outline",onClick:()=>R("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:$==="ask"?"default":"outline",onClick:()=>R("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:$==="deny"?"default":"outline",onClick:()=>R("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(Ut,{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:Y==="allow"?"default":"outline",onClick:()=>F("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:Y==="ask"?"default":"outline",onClick:()=>F("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:Y==="deny"?"default":"outline",onClick:()=>F("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(Ut,{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:B==="allow"?"default":"outline",onClick:()=>T("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:B==="ask"?"default":"outline",onClick:()=>T("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:B==="deny"?"default":"outline",onClick:()=>T("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(Ut,{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:V==="allow"?"default":"outline",onClick:()=>X("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:V==="ask"?"default":"outline",onClick:()=>X("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:V==="deny"?"default":"outline",onClick:()=>X("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(Ut,{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:xe,disabled:fe,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Lo,{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(Nn,{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"})]})})},mw=({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}=nn(),{setSidebarOpen:p}=Fe(),{isMobile:h}=Ct(),[b,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=b?"bg-transparent":y?"bg-background":"bg-sidebar",w=()=>{const v="new-command";let C=v,A=1;for(;i.some(P=>P.name===C);)C=`${v}-${A}`,A++;d({name:C,scope:"user"}),c(C),s?.(),h&&p(!1)},S=async v=>{if(Br(v)){se.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${v.name}"?`)&&(await m(v.name)?se.success(`Command "${v.name}" deleted successfully`):se.error("Failed to delete command"))},k=async v=>{Br(v)&&window.confirm(`Are you sure you want to reset command "${v.name}" to its default configuration?`)&&(await m(v.name)?se.success(`Command "${v.name}" reset to default`):se.error("Failed to reset command"))},j=v=>{const C=v.name;let A=1,P=`${C}-copy`;for(;i.some($=>$.name===P);)A++,P=`${C}-copy-${A}`;d({name:P,scope:v.scope||"user",description:v.description,template:v.template,agent:v.agent,model:v.model,subtask:v.subtask}),c(P),h&&p(!1)},N=v=>{o(v.name),t(v)},L=async()=>{if(!r)return;const v=n.trim().replace(/\s+/g,"-");if(!v){se.error("Command name is required");return}if(v===r.name){t(null);return}if(i.some(A=>A.name===v)){se.error("A command with this name already exists");return}await u({name:v,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(se.success(`Command renamed to "${v}"`),c(v)):se.error("Failed to remove old command after rename"):se.error("Failed to rename command"),t(null)},D=i.filter(Br),M=i.filter(v=>!Br(v));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:w,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:[D.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"}),[...D].sort((v,C)=>v.name.localeCompare(C.name)).map(v=>e.jsx(Nc,{command:v,isSelected:a===v.name,onSelect:()=>{c(v.name),s?.(),h&&p(!1)},onReset:()=>k(v),onDuplicate:()=>j(v)},v.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((v,C)=>v.name.localeCompare(C.name)).map(v=>e.jsx(Nc,{command:v,isSelected:a===v.name,onSelect:()=>{c(v.name),s?.(),h&&p(!1)},onRename:()=>N(v),onDelete:()=>S(v),onDuplicate:()=>j(v)},v.name))]})]})}),e.jsx(as,{open:r!==null,onOpenChange:v=>!v&&t(null),children:e.jsxs(is,{children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Rename Command"}),e.jsxs(Ss,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(it,{value:n,onChange:v=>o(v.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:v=>{v.key==="Enter"&&L()}}),e.jsxs(Ks,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Mr,{onClick:L,children:"Rename"})]})]})})]})},Nc=({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(qt,{children:[e.jsx(Kt,{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(Zr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(St,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(ci,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(St,{onClick:c=>{c.stopPropagation(),i()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(St,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(xs,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(St,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),zu=({agentName:s,onChange:r,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=sn(),a=o(),i=Fe(b=>b.isMobile),{isMobile:c}=Ct(),d=i||c,[u,m]=l.useState(!1);l.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=b=>{r(b)},h=()=>d?e.jsx(ps,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(b=>{const g=b.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(b.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:b.name}),b.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:b.description})]}),g&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},b.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(Nn,{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(qt,{children:[e.jsx(Kt,{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(Nn,{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(Yt,{className:"max-w-[300px]",children:[a.map(b=>e.jsx(St,{className:"typography-meta",onSelect:()=>p(b.name),children:e.jsx("span",{className:"font-medium",children:b.name})},b.name)),e.jsx(St,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},fw=()=>{const{selectedCommandName:s,getCommandByName:r,createCommand:t,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:i}=nn(),c=s?r(s):null,d=!!(a&&a.name===s&&!c),[u,m]=l.useState(""),[f,p]=l.useState("user"),[h,b]=l.useState(""),[g,y]=l.useState(""),[x,w]=l.useState(""),[S,k]=l.useState(""),[j,N]=l.useState(!1),[L,D]=l.useState(!1);l.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),b(a.description||""),y(a.agent||""),w(a.model||""),k(a.template||""),N(a.subtask||!1)):c&&(b(c.description||""),y(c.agent||""),w(c.model||""),k(c.template||""),N(c.subtask||!1))},[c,d,s,o,a]);const M=async()=>{const v=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!v){se.error("Command name is required");return}if(!S.trim()){se.error("Command template is required");return}if(d&&o.some(C=>C.name===v)){se.error("A command with this name already exists");return}D(!0);try{const C=g.trim(),A=x.trim(),P=S.trim(),$={name:v,description:h.trim()||void 0,agent:C===""?null:C,model:A===""?null:A,template:P,subtask:j,scope:d?f:void 0};let R;d?(R=await t($),R&&i(null)):R=await n(v,$),R?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{D(!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(it,{value:u,onChange:v=>m(v.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Fs,{value:f,onValueChange:v=>p(v),children:[e.jsxs(Ps,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(ws,{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(ws,{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(bs,{value:h,onChange:v=>b(v.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(zu,{agentName:g,onChange:v=>y(v)}),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(Ii,{providerId:x?x.split("/")[0]:"",modelId:x?x.split("/")[1]:"",onChange:(v,C)=>{w(v&&C?`${v}/${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:v=>N(v.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(Ut,{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(bs,{value:S,onChange:v=>k(v.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(Ut,{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(Ut,{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(Ut,{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:L,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Lo,{className:"h-3 w-3"}),L?"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"})]})})},ar=()=>{try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},uo="useSkillsStore",cr=Tt()(_t(vs((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=ar(),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=ar(),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=>{Is("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=ar(),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:uo}),d}catch{return!1}finally{os()}},updateSkill:async(t,n)=>{Is("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=ar(),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:uo}),u}catch{return!1}finally{os()}},deleteSkill:async t=>{Is("Deleting skill...");try{const n=ar(),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:uo}),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=ar(),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=ar(),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=ar(),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:js(()=>ls()),partialize:s=>({selectedSkillName:s.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=cr);let kc=null;kc||(kc=Oo(s=>{if(s.source!==uo&&kn(s,"skills")){const{loadSkills:r}=cr.getState();r()}}));const pw=({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}=cr(),{setSidebarOpen:h}=Fe(),{isMobile:b}=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 w=g?"bg-transparent":x?"bg-background":"bg-sidebar",S=()=>{const v="new-skill";let C=v,A=1;for(;i.some(P=>P.name===C);)C=`${v}-${A}`,A++;d({name:C,scope:"user",description:""}),c(C),s?.(),b&&h(!1)},k=async v=>{window.confirm(`Are you sure you want to delete skill "${v.name}"?`)&&(await m(v.name)?se.success(`Skill "${v.name}" deleted successfully`):se.error("Failed to delete skill"))},j=async v=>{const C=v.name;let A=1,P=`${C}-copy`;for(;i.some(R=>R.name===P);)A++,P=`${C}-copy-${A}`;const $=await p(v.name);if(!$){se.error("Failed to load skill details for duplication");return}d({name:P,scope:v.scope||"user",description:($.sources.md.fields.includes("description"),""),instructions:""}),c(P),b&&h(!1)},N=v=>{o(v.name),t(v)},L=async()=>{if(!r)return;const v=n.trim().replace(/\s+/g,"-").toLowerCase();if(!v){se.error("Skill name is required");return}if(v===r.name){t(null);return}if(i.some(P=>P.name===v)){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:v,description:"Renamed skill",scope:r.scope})?await m(r.name)?(se.success(`Skill renamed to "${v}"`),c(v)):se.error("Failed to remove old skill after rename"):se.error("Failed to rename skill"),t(null)},D=i.filter(v=>v.scope==="project"),M=i.filter(v=>v.scope==="user");return e.jsxs("div",{className:O("flex h-full flex-col",w),children:[e.jsx("div",{className:O("border-b px-3",b?"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(dd,{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:[D.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"}),D.map(v=>e.jsx(Cc,{skill:v,isSelected:a===v.name,onSelect:()=>{c(v.name),s?.(),b&&h(!1)},onRename:()=>N(v),onDelete:()=>k(v),onDuplicate:()=>j(v)},v.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(v=>e.jsx(Cc,{skill:v,isSelected:a===v.name,onSelect:()=>{c(v.name),s?.(),b&&h(!1)},onRename:()=>N(v),onDelete:()=>k(v),onDuplicate:()=>j(v)},v.name))]})]})}),e.jsx(as,{open:r!==null,onOpenChange:v=>!v&&t(null),children:e.jsxs(is,{children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Rename Skill"}),e.jsxs(Ss,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(it,{value:n,onChange:v=>o(v.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:v=>{v.key==="Enter"&&L()}}),e.jsxs(Ks,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Mr,{onClick:L,children:"Rename"})]})]})})]})},Cc=({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(qt,{children:[e.jsx(Kt,{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(Zr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(St,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(ci,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(St,{onClick:i=>{i.stopPropagation(),a()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(St,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),va=()=>{try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},Ti=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=va(),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,b=h&&f.some(g=>g.id===h)?h:f[0]?.id??null;return s({sources:f,itemsBySource:p,selectedSourceId:b}),!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=va(),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=va(),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 cr.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"})),hw=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,gw=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},xw=async()=>{try{if(Xt())return await tn();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}},yw=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=Ti(),[a,i]=l.useState(""),[c,d]=l.useState(""),[u,m]=l.useState(""),[f,p]=l.useState([]),[h,b]=l.useState(null),[g,y]=l.useState(!1),[x,w]=l.useState([]),[S,k]=l.useState(null);l.useEffect(()=>{s&&(i(""),d(""),m(""),b(null),y(!1),w([]),k(null),(async()=>{const D=await xw(),M=Array.isArray(D?.skillCatalogs)?D?.skillCatalogs:[];p(M||[])})())},[s]);const j=l.useMemo(()=>{const D=c.trim(),M=u.trim();return f.some(v=>{const C=(v.source||"").trim(),A=(v.subpath||"").trim();return C===D&&A===M})},[f,c,u]),N=async()=>{const D=c.trim();if(!D){se.error("Repository source is required");return}a.trim()||i(gw(D)),y(!1),b(null);const M=await t({source:D,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||[];w(C),!S&&C.length>0&&k(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 v=M.items?.length||0;if(b(v),v===0){se.error("No skills found in this repository"),y(!1);return}w([]),y(!0),se.success(`Found ${v} skill(s)`)},L=async()=>{const D=a.trim(),M=c.trim(),v=u.trim();if(!D){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:hw(),label:D,source:M,...v?{subpath:v}:{},...S?{gitIdentityId:S}:{}},A=[...f,C];try{await ns({skillCatalogs:A}),p(A),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(Ss,{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(it,{value:a,onChange:D=>i(D.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(it,{value:c,onChange:D=>{d(D.target.value),y(!1),b(null)},placeholder:"owner/repo or git@github.com:owner/repo.git"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Public repos work everywhere. Private repos require SSH identity (Desktop/Web only)."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Optional subpath"}),e.jsx(it,{value:u,onChange:D=>{m(D.target.value),y(!1),b(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:D=>k(D),children:[e.jsx(Ps,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:x.find(D=>D.id===S)?.name||"Choose identity"})}),e.jsx(Rs,{align:"start",children:x.map(D=>e.jsx(Ot,{value:D.id,className:"pr-2 [&>span:first-child]:hidden",children:D.name},D.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(Ks,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(ve,{variant:"outline",onClick:()=>{N()},disabled:o||!c.trim(),className:"gap-2",children:[e.jsx(ed,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(ve,{variant:"default",onClick:()=>{L()},disabled:!g||j||!a.trim()||!c.trim(),children:"Add catalog"})]})]})})},bw=({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(Ss,{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(Ks,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Mr,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},ww=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=Ti(),[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 b=>{const g=await n({source:b.source,subpath:b.subpath,gitIdentityId:t?.gitIdentityId,scope:b.scope,selections:[{skillDir:b.skillDir}],conflictPolicy:"prompt",conflictDecisions:b.conflictDecisions});if(g.ok){se.success("Skill installed successfully"),r(!1);return}if(g.error?.kind==="conflicts"){p({source:b.source,subpath:b.subpath,scope:b.scope,skillDir:b.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(Ss,{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(b=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:b},b))})]}):null}),e.jsxs(Ks,{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:b=>i(b),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(ws,{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(ws,{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(bw,{open:c,onOpenChange:d,conflicts:u,onConfirm:b=>{f&&(h({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:b}),d(!1))}})]}):null},vw=async()=>{try{if(Xt())return await tn();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}},jw=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:i,isLoadingCatalog:c,lastCatalogError:d}=Ti(),[u,m]=l.useState(""),[f,p]=l.useState(!1),[h,b]=l.useState(!1),[g,y]=l.useState(null),[x,w]=l.useState(!1);l.useEffect(()=>{i()},[i]);const S=l.useMemo(()=>o?n[o]||[]:[],[n,o]),k=l.useMemo(()=>{const D=u.trim().toLowerCase();return D?S.filter(M=>{const v=M.skillName.toLowerCase(),C=(M.description||"").toLowerCase(),A=(M.frontmatterName||"").toLowerCase();return v.includes(D)||C.includes(D)||A.includes(D)}):S},[S,u]),j=l.useMemo(()=>t.find(D=>D.id===o)||null,[t,o]),N=!!(o&&o.startsWith("custom:")),L=async()=>{if(!(!o||!N)&&window.confirm("Remove this catalog?")){w(!0);try{const D=await vw(),v=(Array.isArray(D?.skillCatalogs)?D?.skillCatalogs:[]).filter(C=>C.id!==o);await ns({skillCatalogs:v}),await i({refresh:!0})}finally{w(!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(ki,{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:D=>a(D),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(D=>e.jsx(Ot,{value:D.id,className:"pr-2 [&>span:first-child]:hidden",children:D.label},D.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(Tn,{className:"h-4 w-4"}),"Refresh"]}),N?e.jsxs(ve,{type:"button",variant:"outline",onClick:()=>{L()},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(it,{value:u,onChange:D=>m(D.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:c?"Loading…":`${k.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:k.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"})]}):k.map(D=>{const M=D.installed?.isInstalled,v=D.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:D.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 (",v||"unknown",")"]}):null,D.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"})]}),D.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:D.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),D.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:D.warnings.join(" · ")}):null]}),e.jsx(ve,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!D.installable,onClick:()=>{y(D),b(!0)},children:"Install"})]})},`${D.sourceId}:${D.skillDir}`)})}),e.jsx(yw,{open:f,onOpenChange:p}),e.jsx(ww,{open:h,onOpenChange:b,item:g})]})})},Sw=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:i,setSkillDraft:c,setSelectedSkill:d}=cr(),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 b=m?e.jsx(ki,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[g,y]=l.useState(""),[x,w]=l.useState("user"),[S,k]=l.useState(""),[j,N]=l.useState(""),[L,D]=l.useState([]),[M,v]=l.useState([]),[C,A]=l.useState(!1),[P,$]=l.useState(!1),[R,H]=l.useState(""),[U,Y]=l.useState(""),[F,B]=l.useState(!1),[T,V]=l.useState(""),[X,fe]=l.useState(""),[ae,xe]=l.useState(null),[Me,Q]=l.useState(!1),[re,oe]=l.useState(""),W=m?g.trim()!==""||S.trim()!==""||j.trim()!==""||M.length>0:S!==R||j!==U,me=ae?X!==re:T.trim()!=="";l.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&i)y(i.name||""),w(i.scope||"user"),k(i.description||""),N(i.instructions||""),H(""),Y(""),D([]),v(i.pendingFiles||[]);else if(s&&u){$(!0);try{const K=await t(s);if(K){const I=K.sources.md;k(I.description||""),N(I.instructions||""),H(I.description||""),Y(I.instructions||""),D(I.supportingFiles||[])}}catch(K){console.error("Failed to load skill details:",K)}finally{$(!1)}}})()},[u,m,s,a,i,t,p]);const ye=async()=>{const G=m?g.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!G){se.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(G)||G.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===G)){se.error("A skill with this name already exists");return}A(!0);try{const K={name:G,description:S.trim(),instructions:j.trim()||void 0,scope:m?x:void 0,supportingFiles:m&&M.length>0?M:void 0};let I;m?(I=await n(K),I&&(c(null),v([]),d(G))):(I=await o(G,K),I&&(H(S.trim()),Y(j.trim()))),I?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{A(!1)}},ce=()=>{xe(null),V(""),fe(""),oe(""),B(!0)},Ce=async G=>{if(xe(G),V(G),m){const I=M.find(J=>J.path===G)?.content||"";fe(I),oe(I),B(!0);return}if(s){Q(!0),B(!0);try{const{readSupportingFile:K}=cr.getState(),I=await K(s,G);fe(I||""),oe(I||"")}catch{se.error("Failed to load file content"),fe(""),oe("")}finally{Q(!1)}}},Ee=async()=>{if(!T.trim()){se.error("File name is required");return}const G=T.trim(),K=ae!==null;if(m){if(K)v(E=>E.map(z=>z.path===ae?{path:G,content:X}:z)),se.success(`File "${G}" updated`);else{if(M.some(E=>E.path===G)){se.error("A file with this name already exists");return}v(E=>[...E,{path:G,content:X}]),se.success(`File "${G}" added`)}B(!1),xe(null);return}if(!s){se.error("No skill selected");return}const{writeSupportingFile:I}=cr.getState();if(await I(s,G,X)){se.success(K?`File "${G}" updated`:`File "${G}" created`),B(!1),xe(null);const E=await t(s);E&&D(E.sources.md.supportingFiles||[])}else se.error(K?"Failed to update file":"Failed to create file")},Pe=async G=>{if(m){v(K=>K.filter(I=>I.path!==G)),se.success(`File "${G}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${G}"?`)){const{deleteSupportingFile:K}=cr.getState();if(await K(s,G)){se.success(`File "${G}" deleted`);const J=await t(s);J&&D(J.sources.md.supportingFiles||[])}else se.error("Failed to delete file")}};return m&&p==="external"?e.jsx(jw,{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(dd,{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?b: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(it,{value:g,onChange:G=>y(G.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(Fs,{value:x,onValueChange:G=>w(G),children:[e.jsxs(Ps,{className:"!h-9 w-auto gap-1.5",children:[x==="user"?e.jsx(ws,{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(ws,{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(bs,{value:S,onChange:G=>k(G.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(bs,{value:j,onChange:G=>N(G.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 G=m?M:L;return G.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:G.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:()=>Ce(K.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ws,{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:I=>{I.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(Lo,{className:"h-3 w-3"}),C?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(as,{open:F,onOpenChange:G=>{B(G),G||xe(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:ae?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ss,{children:ae?"Modify the file content":"Create a new file in the skill directory"})]}),Me?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(it,{value:T,onChange:G=>V(G.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:ae!==null}),!ae&&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(bs,{value:X,onChange:G=>fe(G.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Ks,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>{B(!1),xe(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Mr,{onClick:Ee,disabled:Me||!me,children:ae?"Save Changes":"Create File"})]})]})})]})})},Nw="__add_provider__",kw=({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(Nw),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(Sn,{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(zt,{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)})})]})},Cw=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Mc=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=Cw.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Dc="__add_provider__",Xr=s=>typeof s=="object"&&s!==null,Ac=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()},Mw=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},Dw=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}},Aw=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=>Dw(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},Ew=()=>{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,b]=l.useState(""),[g,y]=l.useState(null),[x,w]=l.useState({}),[S,k]=l.useState({}),[j,N]=l.useState([]),[L,D]=l.useState(!1),[M,v]=l.useState(null),[C,A]=l.useState(""),[P,$]=l.useState(""),[R,H]=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(Mw(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()=>{D(!0),v(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;N(Aw(ce))}catch(ye){if(!W)return;console.error("Failed to load available providers:",ye),v("Unable to load provider list")}finally{W&&D(!1)}})(),()=>{W=!1}},[]);const U=l.useMemo(()=>new Set(s.map(W=>W.id)),[s]),Y=l.useMemo(()=>j.filter(W=>!U.has(W.id)),[j,U]);l.useEffect(()=>{if(r===Dc){if(!C&&Y.length>0){A(Y[0].id);return}C&&!Y.some(W=>W.id===C)&&A(Y[0]?.id??"")}},[r,C,Y]);const F=s.find(W=>W.id===r),B=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})}),Ce=await ce.json().catch(()=>null);if(!ce.ok){const Ee=Ce?.error||"Failed to save API key";throw new Error(Ee)}se.success("API key saved"),m(Ee=>({...Ee,[W]:""})),await gn(),await n(),t(W)}catch(ce){console.error("Failed to save API key:",ce),se.error("Failed to save API key")}finally{p(null)}},T=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})}),Ce=await ce.json().catch(()=>null);if(!ce.ok){const E=Ce?.error||"Failed to start OAuth flow";throw new Error(E)}const Ee=Xr(Ce)?Ce:{},Pe=Xr(Ee.data)?Ee.data:Ee,G=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,I=typeof Pe.user_code=="string"&&Pe.user_code||typeof Pe.code=="string"&&Pe.code||typeof Pe.userCode=="string"&&Pe.userCode||void 0;if(!G&&!K&&!I)throw new Error("No OAuth details returned");const J=`${W}:${me}`;k(E=>({...E,[J]:{url:G,instructions:K,userCode:I}})),G&&window.open(G,"_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)}},V=async(W,me)=>{const ye=`${W}:${me}`,ce=x[ye]?.trim(),Ce=`oauth-complete:${W}:${me}`;p(Ce);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)}),G=await Pe.json().catch(()=>null);if(!Pe.ok){const K=G?.error||"Failed to complete OAuth flow";throw new Error(K)}se.success("OAuth connection completed"),w(K=>({...K,[ye]:""})),y(null),await gn(),await n(),t(W)}catch(Ee){console.error("Failed to complete OAuth flow:",Ee),se.error("Failed to complete OAuth flow")}finally{p(null)}},X=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")}},ae=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 Ce=ce?.error||"Failed to disconnect provider";throw new Error(Ce)}se.success("Provider disconnected"),await gn(),await n()}catch(ye){console.error("Failed to disconnect provider:",ye),se.error("Failed to disconnect provider")}finally{p(null)}},xe=r===Dc;if(!xe&&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(Sn,{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(xe)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."})]}),L?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):M?e.jsx("p",{className:"typography-meta text-muted-foreground",children:M}):Y.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(qt,{open:R,onOpenChange:W=>{H(W),W||$("")},children:[e.jsx(Kt,{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?Y.find(W=>W.id===C)?.name||C:"Select provider"}),e.jsx(Nt,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(Yt,{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(sr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:P,onChange:W=>$(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=Y.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(St,{onSelect:()=>{A(me.id),H(!1),$("")},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(it,{type:"password",value:u[C]??"",onChange:W=>m(me=>({...me,[C]:W.target.value})),placeholder:"sk-..."}),e.jsx(ve,{size:"sm",onClick:()=>B(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=>Ac(ye)==="oauth");return me.length===0?null:e.jsx("div",{className:"space-y-3",children:me.map((ye,ce)=>{const Ce=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:Ce}),(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:()=>T(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(it,{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(it,{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:()=>X(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(it,{value:x[Ee]??"",onChange:G=>w(K=>({...K,[Ee]:G.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(ve,{size:"sm",onClick:()=>V(C,ce),disabled:f===`oauth-complete:${C}:${ce}`,className:"h-8",children:f===`oauth-complete:${C}:${ce}`?"Saving…":"Complete"})]})]},`${C}-${Ce}`)})})})()]})]})]})});if(!F)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(Sn,{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 Me=Array.isArray(F.models)?F.models:[],re=(a[F.id]??[]).filter(W=>Ac(W)==="oauth"),oe=Me.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(zt,{providerId:F.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:F.name||F.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",F.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(it,{type:"password",value:u[F.id]??"",onChange:W=>m(me=>({...me,[F.id]:W.target.value})),placeholder:"sk-..."}),e.jsx(ve,{size:"sm",onClick:()=>B(F.id),disabled:f===`api:${F.id}`,className:"h-8",children:f===`api:${F.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:()=>ae(F.id),disabled:f===`disconnect:${F.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:f===`disconnect:${F.id}`?"Disconnecting…":"Disconnect provider"})}),re.length>0&&e.jsx("div",{className:"space-y-3",children:re.map((W,me)=>{const ye=W.label||W.name||`OAuth method ${me+1}`,ce=`${F.id}:${me}`,Ce=g?.providerId===F.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:()=>T(F.id,me),disabled:f===`oauth:${F.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(it,{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(it,{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:()=>X(S[ce]?.url??""),className:"h-8",children:"Copy link"})]})]}),Ce&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(it,{value:x[ce]??"",onChange:Ee=>w(Pe=>({...Pe,[ce]:Ee.target.value})),placeholder:"Paste authorization code"}),e.jsx(ve,{size:"sm",onClick:()=>V(F.id,me),disabled:f===`oauth-complete:${F.id}:${me}`,className:"h-8",children:f===`oauth-complete:${F.id}:${me}`?"Saving…":"Complete"})]})]},`${F.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(it,{value:h,onChange:W=>b(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(F.id,me):void 0,Ce=Mc(ce?.limit?.context),Ee=Mc(ce?.limit?.output),Pe=[];return ce?.tool_call&&Pe.push({key:"tools",icon:Ro,label:"Tool calling"}),ce?.reasoning&&Pe.push({key:"reasoning",icon:Jr,label:"Reasoning"}),ce?.attachment&&Pe.push({key:"image",icon:rr,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}),(Ce||Ee)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[Ce?`${Ce} ctx`:"",Ce&&Ee?" · ":"",Ee?`${Ee} out`:""]}),Pe.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:Pe.map(({key:G,icon:K,label:I})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:I,"aria-label":I,children:e.jsx(K,{className:"h-3 w-3"})},G))})]},me)})})]})]})})},Iw={branch:Ft,briefcase:li,house:ii,graduation:ai,code:Gs,heart:ad},Tw={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Fw=({onItemSelect:s})=>{const{selectedProfileId:r,profiles:t,globalIdentity:n,setSelectedProfile:o,deleteProfile:a,loadProfiles:i,loadGlobalIdentity:c}=Bo(),{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",b=()=>{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:b,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(Ec,{profile:n,isSelected:r==="global",onSelect:()=>{o("global"),s?.(),u&&d(!1)},onDelete:void 0,isReadOnly:!0})]}),t.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),t.length===0&&!n?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ft,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:t.map(y=>e.jsx(Ec,{profile:y,isSelected:r===y.id,onSelect:()=>{o(y.id),s?.(),u&&d(!1)},onDelete:()=>g(y)},y.id))})]})]})},Ec=({profile:s,isSelected:r,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=Iw[s.icon||"branch"]||Ft,i=Tw[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(qt,{children:[e.jsx(Kt,{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(Zr,{className:"h-3.5 w-3.5"})})}),e.jsx(Yt,{align:"end",className:"w-fit min-w-20",children:e.jsxs(St,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})},Ic=[{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)"}],Pw=[{key:"branch",Icon:Ft,label:"Branch"},{key:"briefcase",Icon:li,label:"Work"},{key:"house",Icon:ii,label:"Personal"},{key:"graduation",Icon:ai,label:"School"},{key:"code",Icon:Gs,label:"Code"}],Rw=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=Bo(),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(""),[b,g]=l.useState(""),[y,x]=l.useState("keyword"),[w,S]=l.useState("branch"),[k,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 N=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:b.trim()||null,color:y,icon:w};let v;if(i)v=await t(M);else if(s)v=await n(s,M);else return;v?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)}},L=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")}},D=l.useMemo(()=>Ic.find(v=>v.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(it,{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:Ic.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:Pw.map(M=>{const v=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",w===M.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:M.label,children:e.jsx(v,{className:"w-4 h-4",style:{color:D}})},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(Ut,{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(it,{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(Ut,{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(it,{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(Ut,{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(it,{value:b,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:L,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:N,disabled:k,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Lo,{className:"h-3 w-3"}),k?"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(ws,{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 ja(s,r,t){return Math.min(t,Math.max(r,s))}const Ao=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,b]=Ne.useState(()=>String(s));Ne.useEffect(()=>{document.activeElement!==p.current&&b(String(s))},[s]);const g=Ne.useCallback(()=>{p.current?.focus()},[]),y=Ne.useCallback(v=>{const C=ja(v,t,n);r(C),b(String(C))},[n,t,r]),x=Ne.useCallback(()=>{const v=Number(h);return Number.isFinite(v)?v:s},[h,s]),w=Ne.useCallback(()=>{y(x()+o),g()},[y,x,g,o]),S=Ne.useCallback(()=>{y(x()-o),g()},[y,x,g,o]),k=v=>{const C=v.target.value;b(C);const A=Number(C);Number.isFinite(A)&&r(ja(A,t,n))},j=v=>{const C=Number(h);if(!Number.isFinite(C))b(String(s));else{const A=ja(C,t,n);A!==C&&r(A),b(String(A))}c?.(v)},N=v=>{if(v.key==="ArrowUp"){v.preventDefault(),w();return}if(v.key==="ArrowDown"){v.preventDefault(),S();return}d?.(v)},L=x(),D=u||L<=t,M=u||L>=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:k,onBlur:j,onKeyDown:N,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:w,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(Fo,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:D,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"})})]})]})});Ao.displayName="NumberInput";const Lw=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Tc=[{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"}],Fc=[{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."}],Fi=({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),b=zs(S=>S.queueModeEnabled),g=zs(S=>S.setQueueMode),{themeMode:y,setThemeMode:x}=Fr(),w=S=>s?s.includes(S):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[w("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:Lw.map(S=>e.jsx(Ms,{variant:y===S.value?"default":"outline",className:O(y===S.value?void 0:"text-foreground"),onClick:()=>x(S.value),children:S.label},S.value))})]}),w("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(Ao,{value:i,onValueChange:c,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Ms,{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"})})]})]}),w("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(Ms,{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(Ao,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Ms,{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"})})]})]}),w("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(Ms,{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"})})]})]}),w("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:Tc.find(S=>S.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Tc.map(S=>e.jsx(Ms,{variant:o===S.value?"default":"outline",className:O(o===S.value?void 0:"text-foreground"),onClick:()=>a(S.value),children:S.label},S.value))})]}),w("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:Fc.map(S=>e.jsx(Ms,{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:Fc.find(S=>S.id===p)?.description})]})]}),w("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"})]}),w("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:b,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:b?`Enter queues messages, ${ss()}+Enter sends immediately.`:`Enter sends immediately, ${ss()}+Enter queues messages.`})]})]})},Pc="https://github.com/btriapitsyn/openchamber",$w=800,Hu=()=>{const[s,r]=l.useState(!1),[t,n]=l.useState(!1),o=$o(),{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)},$w);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:()=>gn(),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:Pc,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ra,{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(ud,{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(La,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Ha,{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(eo,{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:Pc,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(Ra,{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(La,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Ha,{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})]})},Ow=1440*60*1e3,Uu=5,Rc=1440*60*1e3,Sa=s=>s.time?.updated??s.time?.created??0,Lc=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=Uu,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*Ow,i=[...s].sort((d,u)=>Sa(u)-Sa(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=Sa(d);return u?u<a:!1}).map(d=>d.id)},Wu=s=>{const r=s?.autoRun!==!1,t=pe(g=>g.sessions),n=pe(g=>g.currentSessionId),o=pe(g=>g.isLoading),a=pe(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?[]:Lc({sessions:t,currentSessionId:n,cutoffDays:c}),[c,n,t]),b=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<Rc)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const x=Lc({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<Rc||b()},[c,i,d,r,o,t.length,b]),{candidates:h,isRunning:m,runCleanup:b,keepRecentCount:Uu}},Na=1,ka=365,Vu=()=>{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}=Wu({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(Ut,{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 b=Number(h);if(!Number.isFinite(b))return;const g=Math.min(ka,Math.max(Na,Math.round(b)));o(g)},onBlur:()=>{if(a.trim()===""){i(String(t));return}const p=Number(a);if(!Number.isFinite(p)){i(String(t));return}const h=Math.min(ka,Math.max(Na,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(Ao,{value:t,onValueChange:o,min:Na,max:ka,step:1,"aria-label":"Retention period in days"}),e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"days since last activity"})]}),e.jsx(Ms,{type:"button",variant:"outline",onClick:f,disabled:d,children:d?"Cleaning up...":"Run cleanup now"})]}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Eligible for deletion right now: ",m]})]})},Gu=()=>{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(Xt())y=await tn();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 w=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});w.ok&&(y=await w.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(w){console.warn("Failed to save default model:",w)}},[a,s,r,n]),b=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(Ut,{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(Ii,{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(zu,{agentName:d||"",onChange:b})]})]}),(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})]})]})},_w=({section:s})=>{const{isMobile:r}=Ct(),t=r&&di();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(Fi,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Gu,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Vu,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Hu,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(Bw,{});case"chat":return e.jsx(zw,{});case"sessions":return e.jsx(Hw,{});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()})},Bw=()=>e.jsx(Fi,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),zw=()=>e.jsx(Fi,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),Hw=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Gu,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Vu,{})})]}),Uw=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]}],Ww=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=Ct(),n=t&&di(),[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:Uw.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(Hu,{})})]})},Vw=(()=>{const s=Bu.filter(n=>n.id!=="sessions"),r=s.find(n=>n.id==="settings"),t=s.filter(n=>n.id!=="settings");return r?[r,...t]:s})(),Ca=200,Ma=500,Gw=264,qw=700,Za=({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(Ma,Math.max(Ca,Math.floor(window.innerWidth*.2))):Gw),[p,h]=l.useState(!1),[b,g]=l.useState(!1),[y,x]=l.useState(0),w=l.useRef(null),S=l.useRef(0),k=l.useRef(m),[j,N]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),L=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),D=l.useMemo(()=>Et(),[]);l.useEffect(()=>{typeof window>"u"||N(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{const B=w.current;if(!B)return;const T=new ResizeObserver(V=>{for(const X of V)x(X.contentRect.width)});return T.observe(B),x(B.clientWidth),()=>T.disconnect()},[]);const M=y===0||y>=qw;l.useEffect(()=>{if(typeof window>"u")return;const B=()=>{if(!p){const T=Math.min(Ma,Math.max(Ca,Math.floor(window.innerWidth*.2)));f(T)}};return window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[p]),l.useEffect(()=>{if(!b)return;const B=V=>{const X=V.clientX-S.current,fe=Math.min(Ma,Math.max(Ca,k.current+X));f(fe),h(!0)},T=()=>g(!1);return window.addEventListener("pointermove",B),window.addEventListener("pointerup",T,{once:!0}),()=>{window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",T)}},[b]);const v=B=>{g(!0),S.current=B.clientX,k.current=m,B.preventDefault()},C=l.useCallback(async B=>{if(!B.target.closest("button, a, input, select, textarea")&&B.button===0&&j)try{const{getCurrentWindow:T}=await Jt(async()=>{const{getCurrentWindow:X}=await import("./vendor-.bun-B7CnnRlj.js").then(fe=>fe.cb);return{getCurrentWindow:X}},__vite__mapDeps([0,1]));await T().startDragging()}catch(T){console.error("Failed to start window dragging:",T)}},[j]),A=l.useCallback(async B=>{if(B.button===0&&j)try{const{getCurrentWindow:T}=await Jt(async()=>{const{getCurrentWindow:X}=await import("./vendor-.bun-B7CnnRlj.js").then(fe=>fe.cb);return{getCurrentWindow:X}},__vite__mapDeps([0,1]));await T().startDragging()}catch(T){console.error("Failed to start window dragging:",T)}},[j]),P=l.useCallback(B=>{a(B),u(!1)},[]),$=l.useCallback(()=>{n&&u(!0)},[n]),R=()=>{switch(o){case"settings":return e.jsx(Ww,{selectedSection:i,onSelectSection:B=>{c(B),$()}});case"agents":return e.jsx(iw,{onItemSelect:$});case"commands":return e.jsx(mw,{onItemSelect:$});case"skills":return e.jsx(pw,{onItemSelect:$});case"providers":return e.jsx(kw,{onItemSelect:$});case"git-identities":return e.jsx(Fw,{onItemSelect:$});default:return null}},H=()=>{switch(o){case"agents":return e.jsx(uw,{});case"commands":return e.jsx(fw,{});case"skills":return e.jsx(Sw,{});case"providers":return e.jsx(Ew,{});case"git-identities":return e.jsx(Rw,{});case"settings":return e.jsx(_w,{section:i});default:return null}},U=ss(),Y=l.useMemo(()=>j&&L?"pl-[5.75rem]":"",[j,L]),F=j&&L;return e.jsxs("div",{ref:w,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&&Y,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($f,{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&&F&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),Vw.map(({id:B,label:T,icon:V})=>{const X=o===B,fe=V;return n?e.jsxs(Xe,{delayDuration:500,children:[e.jsx(Qe,{asChild:!0,children:e.jsx("button",{onClick:()=>P(B),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",X?"text-foreground":"text-muted-foreground"),"aria-pressed":X,"aria-label":T,children:e.jsx(fe,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(Ye,{children:e.jsx("p",{children:T})})]},B):e.jsxs(l.Fragment,{children:[e.jsxs("button",{onClick:()=>P(B),onMouseDown:X?A:void 0,className:O("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",X?"app-region-drag":"app-region-no-drag","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",X?"text-foreground":"text-muted-foreground"),"aria-pressed":X,"aria-label":T,children:[e.jsx(fe,{className:"h-4 w-4",weight:"regular"}),M&&e.jsx("span",{children:T})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},B)})]}),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(Vt,{className:"h-5 w-5"})})}),e.jsx(Ye,{children:e.jsxs("p",{children:["Close Settings (",U,"+,)"]})})]})})]}),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(Wt,{children:H()})}):e.jsx("div",{className:O("flex-1 overflow-hidden",D?"bg-background":"bg-sidebar"),children:e.jsx(Wt,{children:R()})}):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)]":D?"bg-background":"bg-sidebar",b?"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",b?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:v,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(Wt,{children:R()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(Wt,{children:H()})})]})})]})},Kw=()=>{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")},[]),xx({enabled:!0});const h=$o(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 w=()=>{x!==void 0&&window.clearTimeout(x),x=window.setTimeout(()=>{Fe.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",w),()=>{window.removeEventListener("resize",w),x!==void 0&&window.clearTimeout(x)}},[]),l.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const x=document.documentElement;let w=0,S=!1,k=0,j=null;const N=Fe.getState().setKeyboardOpen,L=()=>{j&&(j.style.setProperty("--oc-keyboard-avoid-offset","0px"),j.removeAttribute("data-keyboard-avoid-active"),j=null)},D=$=>{if(!$)return null;const R=$.closest("[data-keyboard-avoid]");if(R)return R;if($.classList.contains("overlay-scrollbar-container")){const H=$.parentElement;if(H instanceof HTMLElement)return H}return $},M=()=>{w=0,S=!0,x.style.setProperty("--oc-keyboard-inset","0px"),N(!1)},v=()=>{const $=window.visualViewport,R=$?Math.round($.height):window.innerHeight,H=$?Math.max(0,Math.round($.offsetTop)):0;x.style.setProperty("--oc-visual-viewport-offset-top",`${H}px`);const U=document.activeElement,Y=U?.tagName,B=Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||!!U?.isContentEditable,T=Math.round(x.clientHeight||window.innerHeight),V=R+H,X=Math.max(0,T-V),ae=X>=(B?120:180)?X:0;if(S)ae===0&&(S=!1),w=0;else if(w===0)ae>0&&B&&(w=ae);else{const Me=!B&&R>k+6;ae===0?(w=0,N(!1)):Me?M():(ae>0&&B||ae>w)&&(w=ae,N(!0))}x.style.setProperty("--oc-keyboard-inset",`${w}px`),k=R;const xe=B?D(U):null;if(!m||!xe||!U)L();else{xe!==j&&(L(),j=xe);const Me=H+R,re=U.getBoundingClientRect().bottom-Me,oe=8,W=Math.max(w,ae),me=re>oe&&W>0?Math.min(re,W):0,ye=j;ye&&(ye.style.setProperty("--oc-keyboard-avoid-offset",`${me}px`),ye.setAttribute("data-keyboard-avoid-active","true"))}if(m&&B){const Me=document.scrollingElement;Me&&Me.scrollTop!==0&&(Me.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};v();const C=window.visualViewport;C?.addEventListener("resize",v),C?.addEventListener("scroll",v),window.addEventListener("resize",v),window.addEventListener("orientationchange",v);const A=$=>{const R=$.target;if(!R)return;const H=R.tagName;(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||R.isContentEditable)&&(S=!1),v()};document.addEventListener("focusin",A,!0);const P=$=>{const R=$.target;if(!R)return;const H=R.tagName;if(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||R.isContentEditable){const Y=$.relatedTarget,F=Y?.tagName;if(F==="INPUT"||F==="TEXTAREA"||F==="SELECT"||Y?.isContentEditable)return;M()}};return document.addEventListener("focusout",P,!0),()=>{C?.removeEventListener("resize",v),C?.removeEventListener("scroll",v),window.removeEventListener("resize",v),window.removeEventListener("orientationchange",v),document.removeEventListener("focusin",A,!0),document.removeEventListener("focusout",P,!0),L()}},[m]);const b=l.useMemo(()=>{switch(r){case"git":return e.jsx(Vb,{});case"diff":return e.jsx(_g,{});case"terminal":return e.jsx(rw,{});default:return null}},[r]),g=r==="chat",y=a&&!m;return e.jsx(ix,{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(Kg,{}),e.jsx(Qg,{}),e.jsx(sx,{}),m?e.jsxs(e.Fragment,{children:[!(a||c)&&e.jsx(Dl,{}),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(Wt,{children:e.jsx(Qa,{})})}),b&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Wt,{children:b})})]})}),e.jsx(ps,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(Ua,{mobileVariant:!0})}),c&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(Wt,{children:e.jsx(Hl,{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(Wt,{children:e.jsx(Za,{onClose:()=>i(!1)})})})]}):e.jsxs(e.Fragment,{children:[!y&&e.jsx(Gg,{isOpen:s,isMobile:m,children:e.jsx(Ua,{})}),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(Dl,{}),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(Wt,{children:e.jsx(Qa,{})})}),b&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Wt,{children:b})})]})})]}),c&&e.jsx("div",{className:O("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(Wt,{children:e.jsx(Hl,{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(Wt,{children:e.jsx(Za,{onClose:()=>i(!1)})})})]}),!y&&e.jsx(zg,{})]})})},Yw=550,Xw=()=>{const[s,r]=l.useState("chat"),[t,n]=l.useState(0),o=l.useRef(null),a=pe(N=>N.currentSessionId),i=pe(N=>N.sessions),c=pe(N=>!!N.newSessionDraft?.open),d=pe(N=>N.openNewSessionDraft),[u,m]=l.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),f=ut(N=>N.isInitialized),p=ut(N=>N.initializeApp),h=pe(N=>N.loadSessions),b=pe(N=>N.loadMessages),g=pe(N=>N.messages),[y,x]=l.useState(()=>f),[w,S]=l.useState(!1);l.useEffect(()=>{a&&r("chat")},[a]),l.useEffect(()=>{!a&&!c&&d()},[a,c,d]);const k=l.useCallback(()=>{r("sessions")},[]);l.useEffect(()=>{const N=L=>{const M=L.detail?.status;(M==="connected"||M==="connecting"||M==="error"||M==="disconnected")&&m(M)};return window.addEventListener("openchamber:connection-status",N),()=>window.removeEventListener("openchamber:connection-status",N)},[]),l.useEffect(()=>{const N=L=>{const M=L.detail?.view;M==="settings"?r("settings"):M==="chat"?r("chat"):M==="sessions"&&r("sessions")};return window.addEventListener("openchamber:navigate",N),()=>window.removeEventListener("openchamber:navigate",N)},[]),l.useEffect(()=>{(async()=>{if(!(w||y||u!=="connected")){S(!0);try{f||await p(),await h(),x(!0)}catch{}finally{S(!1)}}})()},[u,f,y,p,w,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 b(a)}catch{}})()},[u,a,s,y,b,g,c]),l.useEffect(()=>{const N=o.current;if(!N)return;const L=new ResizeObserver(D=>{for(const M of D)n(M.contentRect.width)});return L.observe(N),n(N.clientWidth),()=>L.disconnect()},[]);const j=t>0&&t<Yw;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($c,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ua,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>r("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):s==="settings"?e.jsx(Za,{onClose:()=>r("sessions"),forceMobile:j}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx($c,{title:c&&!a?"New session":i.find(N=>N.id===a)?.title||"Chat",showBack:!0,onBack:k,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Wt,{children:e.jsx(Qa,{})})})]})})},$c=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,onAgentManager:a,showContextUsage:i})=>{const{getCurrentModel:c}=ut(),d=pe(b=>b.getContextUsage),u=c(),m=u?.limit&&typeof u.limit=="object"?u.limit:null,f=typeof m?.context=="number"?m.context:0,p=typeof m?.output=="number"?m.output:0,h=d(f,p);return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border bg-background shrink-0",children:[r&&t&&e.jsx("button",{onClick:t,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:e.jsx(id,{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"})}),a&&e.jsx("button",{onClick:a,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Agent Manager",children:e.jsx(Nn,{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"})}),i&&h&&h.totalTokens>0&&e.jsx(za,{totalTokens:h.totalTokens,percentage:h.percentage,contextLimit:h.contextLimit,outputLimit:h.outputLimit??0,size:"compact"})]})},Oc=".openchamber",fn=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")};function Qw(s){if(!s)return null;const r=s.split("/");if(r.length<3)return null;const t=r[0];if(!t||t.includes(" "))return null;const n=r[1];if(!n)return null;const o=r[r.length-1],a=parseInt(o,10),i=r.length>=4&&!isNaN(a)&&String(a)===o,c=i?r.slice(2,-1):r.slice(2);if(c.length===0)return null;const d=c.join("/");return{groupSlug:t,provider:n,model:d,index:i?a:1}}const Pi=Tt()(_t((s,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const t=ht.getState().currentDirectory;if(!t){s({groups:[],isLoading:!1,error:"No project directory selected"});return}const n=fn(t);if(n.includes(`/${Oc}/`)){s({isLoading:!1});return}const o=r().groups;s({isLoading:!0,error:null});try{const a=Re.getApiClient();let i=new Map,c=[];try{c=await Mn(n),i=new Map(c.map(h=>[fn(h.worktree),h]))}catch{console.debug("Failed to list git worktrees")}const d=c.filter(h=>fn(h.worktree).includes(`/${Oc}/`)),u=new Map;await Promise.all(d.map(async h=>{try{const b=await a.session.list({directory:fn(h.worktree)}),g=Array.isArray(b.data)?b.data:[];for(const y of g)u.set(y.id,y)}catch(b){console.debug("Failed to fetch sessions from worktree:",h.worktree,b)}}));const m=Array.from(u.values()),f=new Map;for(const h of m){const b=Qw(h.title);if(!b)continue;const g=fn(h.directory),y=i.get(g),x={id:h.id,path:g,providerId:b.provider,modelId:b.model,instanceNumber:b.index,branch:y?.branch??"",displayLabel:`${b.provider}/${b.model}`,worktreeMetadata:y?Dn(n,y):void 0},w=f.get(b.groupSlug);w?w.push(x):f.set(b.groupSlug,[x])}const p=Array.from(f.entries()).map(([h,b])=>{const g=b.reduce((y,x)=>{const S=m.find(k=>k.id===x.id)?.time?.updated??0;return Math.max(y,S)},0);return{name:h,sessions:b.sort((y,x)=>{const w=y.providerId.localeCompare(x.providerId);if(w!==0)return w;const S=y.modelId.localeCompare(x.modelId);return S!==0?S:y.instanceNumber-x.instanceNumber}),lastActive:g||Date.now(),sessionCount:b.length}});p.sort((h,b)=>h.name.localeCompare(b.name)),s({groups:p,isLoading:!1,error:null})}catch(a){console.error("Failed to load agent groups:",a),s({groups:o.length>0?o:[],isLoading:!1,error:a instanceof Error?a.message:"Failed to load agent groups"})}},selectGroup:t=>{const{groups:n}=r(),o=n.find(a=>a.name===t);s({selectedGroupName:t,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:t=>{s({selectedSessionId:t})},getSelectedGroup:()=>{const{groups:t,selectedGroupName:n}=r();return n?t.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:t}=r(),n=r().getSelectedGroup();return!n||!t?null:n.sessions.find(o=>o.id===t)??null},clearError:()=>{s({error:null})}}),{name:"agent-groups-store"})),Jw=s=>{const t=Date.now()-s,n=Math.floor(t/(60*1e3)),o=Math.floor(t/(3600*1e3)),a=Math.floor(t/(1440*60*1e3));return n<1?"now":n<60?`${n}m`:o<24?`${o}h`:`${a}d`},Zw=({group:s,isSelected:r,onSelect:t})=>{const[n,o]=l.useState(!1);return e.jsx("div",{className:O("group relative flex items-center rounded-md px-1.5 py-1.5 cursor-pointer",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),onClick:t,children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col gap-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:s.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-micro text-muted-foreground/60 flex items-center gap-1",children:[e.jsx(Ft,{className:"h-3 w-3"}),s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:Jw(s.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(qt,{open:n,onOpenChange:o,children:[e.jsx(Kt,{asChild:!0,children:e.jsx("button",{type:"button",className: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","opacity-0 group-hover:opacity-100",n&&"opacity-100"),"aria-label":"Group menu",onClick:a=>a.stopPropagation(),children:e.jsx(Zr,{className:"h-3.5 w-3.5"})})}),e.jsx(Yt,{align:"end",className:"min-w-[140px]",children:e.jsx(St,{className:"text-destructive focus:text-destructive",children:"Delete"})})]})})]})})},ev=({className:s,selectedGroupName:r,onGroupSelect:t,onNewAgent:n})=>{const[o,a]=l.useState(""),[i,c]=l.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Pi(),f=ht(y=>y.currentDirectory);l.useEffect(()=>{f&&m()},[f,m]);const p=5,h=l.useMemo(()=>{if(!o.trim())return d;const y=o.toLowerCase();return d.filter(x=>x.name.toLowerCase().includes(y))},[o,d]),b=i?h:h.slice(0,p),g=h.length-p;return e.jsxs("div",{className:O("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",s),children:[e.jsx("div",{className:"px-2.5 pt-3 pb-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(sr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(it,{value:o,onChange:y=>a(y.target.value),placeholder:"Search Agent Groups...",className:"pl-8 h-8 rounded-lg border-border/40 bg-background/50 typography-meta"})]})}),e.jsx("div",{className:"px-2.5 pb-2",children:e.jsxs(ve,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(Gt,{className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label",children:"New Agent Group"})]})}),e.jsxs("div",{className:"px-2.5 py-1.5 flex items-center gap-1",children:[e.jsx(Nt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium text-muted-foreground uppercase tracking-wider",children:"Agent Groups"}),u&&e.jsx("span",{className:"typography-micro text-muted-foreground/50 ml-auto",children:"Loading..."})]}),e.jsxs(tt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[b.map(y=>e.jsx(Zw,{group:y,isSelected:r===y.name,onSelect:()=>t?.(y.name)},y.name)),!i&&g>0&&e.jsxs("button",{type:"button",onClick:()=>c(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",g,")"]}),i&&h.length>p&&e.jsx("button",{type:"button",onClick:()=>c(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&h.length===0&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:o.trim()?"No groups found":"No agent groups yet"}),!o.trim()&&e.jsx("p",{className:"typography-micro text-muted-foreground/60 mt-1",children:"Create a new agent group to get started"})]})]})]})},tv=10*1024*1024,sv=5,rv=({className:s,onCreateGroup:r,isCreating:t=!1})=>{const[n,o]=l.useState(""),[a,i]=l.useState(""),[c,d]=l.useState([]),[u,m]=l.useState("HEAD"),[f,p]=l.useState([]),[h,b]=l.useState(!1),g=l.useRef(null),y=l.useRef(null),x=ht(C=>C.currentDirectory??null),{isGitRepository:w,isLoading:S}=Mi(x),k=l.useCallback(C=>{c.length>=sv||d(A=>[...A,C])},[c.length]),j=l.useCallback(C=>{d(A=>A.filter((P,$)=>$!==C))},[]),N=async C=>{const A=C.target.files;if(!A)return;let P=0;for(let $=0;$<A.length;$++){const R=A[$];if(R.size>tv){se.error(`File "${R.name}" is too large (max 10MB)`);continue}try{const H=await new Promise((Y,F)=>{const B=new FileReader;B.onload=()=>Y(B.result),B.onerror=F,B.readAsDataURL(R)}),U={id:Do(),filename:R.name,mimeType:R.type||"application/octet-stream",size:R.size,dataUrl:H};p(Y=>[...Y,U]),P++}catch(H){console.error("File attach failed",H),se.error(`Failed to attach "${R.name}"`)}}P>0&&se.success(`Attached ${P} file${P>1?"s":""}`),g.current&&(g.current.value="")},L=C=>{p(A=>A.filter(P=>P.id!==C))},D=h||t,M=!!(n.trim()&&a.trim()&&c.length>=1&&w&&!S),v=async C=>{if(C.preventDefault(),!(!M||D)){b(!0);try{const A=c.map(({providerID:$,modelID:R,displayName:H})=>({providerID:$,modelID:R,displayName:H})),P=f.length>0?f.map($=>({mime:$.mimeType,filename:$.filename,url:$.dataUrl})):void 0;await r?.({name:n.trim(),prompt:a.trim(),models:A,worktreeBaseBranch:u,files:P}),o(""),i(""),d([]),p([]),m("HEAD")}catch(A){console.error("Failed to create agent group:",A),se.error("Failed to create agent group")}finally{b(!1)}}};return e.jsx("div",{className:O("flex flex-col items-center justify-center h-full w-full p-4",s),children:e.jsxs("form",{onSubmit:v,className:"w-full max-w-2xl space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:"Group Name"}),e.jsx(it,{id:"group-name",value:n,onChange:C=>o(C.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch naming"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-1.5",children:[e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(au,{directory:x,value:u,onChange:m}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from ",e.jsx("code",{className:"font-mono text-xs",children:u})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Models"}),e.jsx(ou,{selectedModels:c,onAdd:k,onRemove:j,minModels:1,addButtonLabel:"Add model",maxModels:5})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:"Prompt"}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-input/10 dark:bg-input/30 overflow-hidden",children:[e.jsx(bs,{ref:y,id:"prompt",value:a,onChange:C=>i(C.target.value),placeholder:"Ask anything...",className:"min-h-[100px] max-h-[300px] resize-none border-0 bg-transparent px-4 py-3 typography-markdown focus-visible:ring-0 focus-visible:ring-offset-0"}),f.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:f.map(C=>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:[C.mimeType.startsWith("image/")?e.jsx(rr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Ws,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:C.filename,children:C.filename}),e.jsx("button",{type:"button",onClick:()=>L(C.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Vt,{className:"h-3.5 w-3.5"})})]},C.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:g,type:"file",multiple:!0,className:"hidden",onChange:N,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>g.current?.click(),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors","aria-label":"Add attachment",children:e.jsx(sd,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[c.length," model",c.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!M||D,className:O("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",M?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:D?e.jsx(Of,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(td,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},nv=({group:s,className:r})=>{const{selectedSessionId:t,selectSession:n}=Pi(),{setCurrentSession:o,currentSessionId:a}=pe(),i=l.useMemo(()=>t?s.sessions.find(u=>u.id===t)??s.sessions[0]??null:s.sessions[0]??null,[s.sessions,t]),c=l.useCallback(u=>{n(u.id),o(u.id)},[n,o]);l.useEffect(()=>{if(s.sessions.length>0){const u=t?s.sessions.find(m=>m.id===t)??s.sessions[0]:s.sessions[0];u&&(u.id!==a&&o(u.id),t||n(u.id))}},[s.name,s.sessions,t,a,n,o]);const d=i?.id===a;return e.jsxs("div",{className:O("flex h-full flex-col bg-background",r),children:[e.jsxs("div",{className:"flex-shrink-0 border-b border-border/30 px-4 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"typography-heading-lg text-foreground truncate",children:s.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{children:"·"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ft,{className:"h-3.5 w-3.5"}),i?.worktreeMetadata?.label||i?.branch||"No branch"]})]})]})}),s.sessions.length>0&&e.jsx("div",{className:"mt-3",children:e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsxs(ve,{variant:"outline",className:"w-full justify-between h-10 px-3",children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:i&&e.jsxs(e.Fragment,{children:[e.jsx(zt,{providerId:i.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsx("span",{className:"truncate typography-body",children:i.modelId}),i.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",i.instanceNumber]})]})}),e.jsx(Nt,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Yt,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:s.sessions.map(u=>e.jsxs(St,{onClick:()=>c(u),className:"flex items-center gap-2 py-2",children:[e.jsx(zt,{providerId:u.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate typography-body",children:u.modelId}),u.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",u.instanceNumber]})]}),u.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(Ft,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:u.worktreeMetadata?.label||u.branch})]})]}),i?.id===u.id&&e.jsx(Dt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},u.id))})]})})]}),e.jsx("div",{className:"flex-1 min-h-0",children:i?d?e.jsx(Tu,{sessionId:i.id,children:e.jsx(Iu,{})}):e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx("div",{className:"px-4 py-2 bg-muted/30 border-b border-border/30",children:e.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx(zt,{providerId:i.providerId,className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:i.displayLabel}),e.jsx("span",{children:"·"}),e.jsx("span",{className:"font-mono text-xs truncate",children:i.path})]})}),e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center p-8",children:[e.jsxs("p",{className:"typography-body text-muted-foreground mb-2",children:["Loading session for ",e.jsx("span",{className:"font-medium text-foreground",children:i.displayLabel})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground/60",children:["Session ID: ",i.id]})]})})]}):e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx("p",{className:"typography-body text-muted-foreground",children:"No sessions in this group"})})})]})},ov=({className:s})=>{const{selectedGroupName:r,selectGroup:t,getSelectedGroup:n,loadGroups:o}=Pi(),{createMultiRun:a,isLoading:i}=wn(),c=l.useCallback(f=>{t(f)},[t]),d=l.useCallback(()=>{t(null)},[t]),u=l.useCallback(async f=>{se.info(`Creating agent group "${f.name}" with ${f.models.length} model(s)...`);const p=await a(f);if(p)se.success(`Agent group "${f.name}" created with ${p.sessionIds.length} session(s)`),await o(),t(f.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50));else{const h=wn.getState().error;se.error(h||"Failed to create agent group")}},[a,o,t]),m=n();return e.jsxs("div",{className:O("flex h-full w-full bg-background",s),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(ev,{selectedGroupName:r,onGroupSelect:c,onNewAgent:d})}),e.jsx("div",{className:"flex-1 min-w-0",children:m?e.jsx(nv,{group:m}):e.jsx(rv,{onCreateGroup:u,isCreating:i})})]})},Da=({...s})=>{const{theme:r="system"}=_f();return e.jsx(Bf,{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})},av=(s=5e3)=>{const[r,t]=Ne.useState(null);return Ne.useEffect(()=>{if(!Xt())return;let n=!1,o=null;const a=async()=>{const i=await ap();n||(t(i),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},iv=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=pe(),c=av(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(Ni,{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(zf,{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(Vt,{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," / ",Zt.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:[Zt.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:[Zt.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:[Zt.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(Hf,{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>Zt.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"})]})]})]})]})},lv="openchamber-message-cursors",Qr="cursors",cv=1,qu="openchamber.messageCursors",Ri=()=>typeof window<"u",Li=()=>Ri()&&typeof indexedDB<"u",Ku=()=>Li()?new Promise((s,r)=>{const t=indexedDB.open(lv,cv);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")),Yu=()=>{if(!Ri())return{};try{const s=window.localStorage.getItem(qu);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},dv=s=>{if(Ri())try{window.localStorage.setItem(qu,JSON.stringify(s))}catch{}},uv=async(s,r,t)=>{if(!s||!r)return;if(Li())try{const o=await Ku();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=Yu();n[s]={messageId:r,completedAt:t},dv(n)},mv=async s=>{if(!s)return null;if(Li())try{const t=await Ku(),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 Yu()[s]??null},fv=50,pv=750,_c=new WeakMap,Bc=s=>{if(!s||!Array.isArray(s))return 0;const r=_c.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 _c.set(s,t),t},hv=10,zc=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<hv?null:n},Hc=(s,r)=>{const t=zc(s),n=zc(r);return!t||!n||t.length!==n.length?!0:t>n},ei=new Map,Uc=(s,r)=>{const t=`${s}:${r}`,n=ei.get(t);if(n&&n.sessionId===s)return n.message;const i=(pe.getState().messages.get(s)||[]).find(c=>c.info.id===r)||null;return ei.set(t,{sessionId:s,message:i}),i},gv=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:c,getWorktreeMetadata:d,loadMessages:u,loadSessions:m}=pe(),{checkConnection:f}=ut(),p=ht(K=>K.currentDirectory),h=l.useMemo(()=>{if(!a)return;try{const I=d?.(a);if(I?.path)return I.path}catch(I){console.warn("Failed to inspect worktree metadata for session directory:",I)}const K=c.find(I=>I.id===a);if(K&&typeof K.directory=="string"&&K.directory.trim().length>0)return K.directory.trim()},[a,d,c]),b=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,I)=>{const J=I??null,E=y.current;if(!(E&&E.status===K&&E.hint===J)){if(y.current={status:K,hint:J},Ht()){const q={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[K]??"[INFO]",be=J?`${q} SSE ${K}: ${J}`:`${q} SSE ${K}`;console.info(be)}g(K,J)}},[g]),w=l.useCallback((K,I)=>{if(!K)return Promise.resolve();const J=Date.now();if(A.current)return A.current;if(J-P.current<pv)return Promise.resolve();const E=u(K).catch(z=>{console.warn(`[useEventStream] Failed to resync messages (${I}):`,z)}).finally(()=>{A.current=null,P.current=Date.now()});return A.current=E,E},[u]),S=l.useCallback(async K=>{Ht()&&console.info("[useEventStream] Bootstrapping state:",K);try{await Promise.all([m(),a?w(a,K):Promise.resolve()])}catch(I){console.warn("[useEventStream] Bootstrap failed:",K,I)}},[a,m,w]),k=l.useCallback((K,I,J)=>{Ht()&&console.debug(`[MessageTracker] ${K}: ${I}`,J)},[]),j=l.useCallback(K=>{Ht()&&console.debug(`[MessageTracker] ${K}: reported`)},[]),N=l.useRef(null),L=l.useRef(null),D=l.useRef(0);l.useRef(new Set);const M=l.useRef(new Map),v=l.useRef(null),C=l.useRef(!1),A=l.useRef(null),P=l.useRef(0),$=l.useCallback(()=>{if(typeof document>"u")return"visible";const K=document.visibilityState;return K==="hidden"&&document.hasFocus()?"visible":K},[]),R=l.useRef($()),H=l.useRef(typeof navigator>"u"?!0:navigator.onLine),U=l.useRef(!1),Y=l.useRef(null),F=l.useRef(null),B=l.useRef(Date.now()),T=l.useRef(!1),V=l.useCallback(K=>{const I=Date.now();I-B.current>25e3&&(S(K),B.current=I)},[S]);l.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(T.current=!0)},[]);const X=l.useRef(new Map),fe=l.useRef(new Map),ae=l.useRef(0),xe=l.useRef(null),Me=l.useRef(a);l.useEffect(()=>{Me.current=a},[a]);const Q=l.useCallback(K=>{if(!K)return;const I=Date.now(),J=M.current,E=J.get(K);E&&I-E<3e3||(J.set(K,I),setTimeout(async()=>{try{const z=await Re.getSession(K);if(z){const q={};typeof z.title=="string"&&z.title.length>0&&(q.title=z.title),z.summary!==void 0&&(q.summary=z.summary),Object.keys(q).length>0&&i(K,q)}}catch(z){console.warn("Failed to refresh session metadata:",z)}},100))},[i]),re=l.useCallback(()=>{v.current||(v.current=setTimeout(()=>{v.current=null;try{m()}catch(K){console.warn("Failed to refresh sessions after stream completion:",K)}},500))},[m]),oe=l.useCallback((K,I)=>{if(pe.getState().sessionActivityPhase?.get(K)===I){fe.current=new Map(pe.getState().sessionActivityPhase??new Map);return}const E=X.current.get(K);E&&(clearTimeout(E),X.current.delete(K));const z=new Map(pe.getState().sessionActivityPhase??new Map);if(z.set(K,I),fe.current=z,pe.setState({sessionActivityPhase:z}),I==="cooldown"){const q=setTimeout(()=>{if(X.current.delete(K),pe.getState().sessionActivityPhase?.get(K)==="cooldown"){const ee=new Map(pe.getState().sessionActivityPhase??new Map);ee.set(K,"idle"),fe.current=ee,pe.setState({sessionActivityPhase:ee})}},2e3);X.current.set(K,q)}},[]),W=l.useCallback(async()=>{const K=Date.now();if(xe.current)return xe.current;if(K-ae.current<1500)return;ae.current=K;const I=q=>{if(typeof q!="string")return null;const be=q.trim();if(!be)return null;const ee=be.replace(/\\/g,"/");return ee.length>1?ee.replace(/\/+$/,""):ee},J=q=>{try{const he=d?.(q),He=I(he?.path??null);if(He)return He}catch{}const be=c.find(he=>he.id===q);return I(be?.directory??null)},E=q=>{Object.entries(q).forEach(([be,ee])=>{if(!be||!ee)return;const he=ee.type==="busy"||ee.type==="retry"?"busy":"idle";oe(be,he)})},z=(async()=>{try{const q=await Re.getGlobalSessionStatus();if(q&&Object.keys(q).length>0){E(q);return}const be=new Set;c.forEach(Be=>{const Ze=J(Be.id);Ze&&be.add(Ze)});const ee=I(b??null);ee&&be.add(ee);const he=Array.from(be);if(he.length===0){const Be=await Re.getSessionStatus();Be&&E(Be);return}const He=await Promise.allSettled(he.map(Be=>Re.getSessionStatusForDirectory(Be))),We={};He.forEach(Be=>{Be.status!=="fulfilled"||!Be.value||Object.assign(We,Be.value)}),E(We)}catch{}})().finally(()=>{xe.current=null});return xe.current=z,z},[b,d,c,oe]),me=l.useCallback(K=>{if(B.current=Date.now(),Ht()&&console.debug("[useEventStream] Received event:",K.type,K.properties),!K.properties)return;const I=K.properties;if(!new Set(["session.abort","session.error"]).has(K.type)){const E=(typeof I.session=="object"&&I.session!==null?I.session:null)||(typeof I.sessionInfo=="object"&&I.sessionInfo!==null?I.sessionInfo:null);if(E){const z=E,q=typeof z.id=="string"&&z.id.length>0?z.id:typeof z.sessionID=="string"&&z.sessionID.length>0?z.sessionID:typeof I.sessionID=="string"&&I.sessionID.length>0?I.sessionID:typeof I.id=="string"&&I.id.length>0?I.id:void 0;if(q){const be=typeof z.title=="string"?z.title:typeof I.title=="string"?I.title:void 0,ee=typeof z.summary=="object"&&z.summary!==null?z.summary:typeof I.summary=="object"&&I.summary!==null?I.summary:void 0;if(be!==void 0||ee!==void 0){const he={};be!==void 0&&(he.title=be),ee!==void 0&&(he.summary=ee),i(q,he)}}}}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 E=typeof I.sessionId=="string"?I.sessionId:null,z=typeof I.phase=="string"?I.phase:null;E&&(z==="idle"||z==="busy"||z==="cooldown")&&(oe(E,z),re());break}case"session.status":if(T.current)break;{const E=typeof I.sessionID=="string"?I.sessionID:null,z=typeof I.status=="object"&&I.status!==null?I.status:null,q=typeof z?.type=="string"?z.type:null;E&&q&&(oe(E,q==="busy"||q==="retry"?"busy":"idle"),re())}break;case"message.part.updated":{const E=typeof I.part=="object"&&I.part!==null?I.part:null;if(!E)break;const z=E,q=typeof I.info=="object"&&I.info!==null?I.info:I,be=typeof q.sessionID=="string"?q.sessionID:null,ee=typeof z.sessionID=="string"&&z.sessionID.length>0?z.sessionID:typeof be=="string"&&be.length>0?be:typeof I.sessionID=="string"&&I.sessionID.length>0?I.sessionID:null,he=typeof q.id=="string"?q.id:null,He=typeof z.messageID=="string"&&z.messageID.length>0?z.messageID:typeof he=="string"&&he.length>0?he:typeof I.messageID=="string"&&I.messageID.length>0?I.messageID:null;if(!ee||!He){Ht()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:z.sessionID??be??I.sessionID,messageID:z.messageID??he??I.messageID});break}const We=ee,Be=He,Ze=pe.getState().sessionMemoryState.get(We)?.trimmedHeadMaxId;if(Ze&&!Hc(Be,Ze)){Ht()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:We,messageId:Be,trimmedHeadMaxId:Ze});break}let lt="assistant";if(q&&typeof q.role=="string")lt=q.role;else{const dt=Uc(We,Be);if(dt){const mt=dt.info.role;typeof mt=="string"&&(lt=mt)}}if(k(Be,"part_received",{role:lt}),lt==="user"&&z.synthetic===!0){k(Be,"skipped_synthetic_user_part");break}const ct={...E,type:E.type||"text"};k(Be,"addStreamingPart_called"),s(We,Be,ct,lt);break}case"message.updated":{const E=typeof I.info=="object"&&I.info!==null?I.info:I,z=E,q=typeof z.sessionID=="string"&&z.sessionID.length>0?z.sessionID:typeof I.sessionID=="string"&&I.sessionID.length>0?I.sessionID:null,be=typeof z.id=="string"&&z.id.length>0?z.id:typeof I.messageID=="string"&&I.messageID.length>0?I.messageID:null;if(!q||!be){Ht()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:z.sessionID??I.sessionID,messageID:z.id??I.messageID});break}const ee=q,he=be,He=pe.getState().sessionMemoryState.get(ee)?.trimmedHeadMaxId;if(He&&!Hc(he,He)){Ht()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:ee,messageId:he,trimmedHeadMaxId:He});break}if(T.current&&Ht())try{const _e=I.parts||z.parts||[],Ge=(Array.isArray(_e)?_e.filter(rt=>rt?.type==="text"):[]).map(rt=>{const le=rt;return typeof le?.text=="string"?le.text:typeof le?.content=="string"?le.content:""}).join(`
|
|
101
|
-
`);console.info("[STREAM-TRACE] message.updated",{messageId:he,role:z.role,status:z.status,textLen:Ge.length,textPreview:Ge.slice(0,120),partsCount:Array.isArray(_e)?_e.length:0})}catch{}if(k(he,"message_updated",{role:z.role}),z.role==="user"){const _e=I.parts||z.parts,ze=Array.isArray(_e)?_e:[],Ge={...E,userMessageMarker:!0,clientRole:"user"};if(t(ee,he,Ge),ze.length>0)for(let rt=0;rt<ze.length;rt++){const le=ze[rt];if(le.synthetic===!0)continue;const ue={...le,type:le?.type||"text",sessionID:le?.sessionID||ee,messageID:le?.messageID||he};s(ee,he,ue,"user")}k(he,"user_message_created_from_event",{partsCount:ze.length});break}const We=Uc(ee,he),Be=Bc(We?.parts||[]),Ze=We?.info?.finish==="stop",lt=I.parts||z.parts,ct=Array.isArray(lt)?lt:[],dt=ct.length>0,yt=typeof(z.time||{})?.completed=="number";if(!dt&&!yt)break;const vt=E.finish,gt=typeof vt=="string"?vt:null,bt=gt==="stop";if(z.role==="assistant"&&dt){const _e=Bc(ct);if(Be>0&&_e+fv<Be&&!bt){k(he,"skipped_shrinking_update",{incomingLen:_e,existingLen:Be});break}if(T.current){const Ge=Be>0&&_e<Be,rt=ct.some(ue=>{if(!ue||ue.type!=="text")return!1;const je=ue;return typeof je.text=="string"&&je.text.length>0});if(Ge&&!(bt&&rt)){k(he,"desktop_shrinking_update_suppressed",{incomingLen:_e,existingLen:Be});break}}}if(t(ee,he,E),dt&&z.role!=="user"){const Ge=(pe.getState().messages.get(ee)||[]).find(ue=>ue.info.id===he),rt=!Ge||Ge.parts.length===0;k(he,rt?"server_parts_injected":"server_parts_refreshed",{count:ct.length});const le=T.current&&z.role==="assistant"?ct.filter(ue=>ue?.type!=="text"):ct;for(let ue=0;ue<le.length;ue++){const je=le[ue],ke={...je,type:je?.type||"text",sessionID:je?.sessionID||ee,messageID:je?.messageID||he};s(ee,he,ke,z.role),k(he,`server_part_${ue}`)}}const Z=E.time,De=Z?.completed,ne=typeof De=="number"&&Number.isFinite(De),ie=gt==="stop"||Ze;if(E.role==="assistant"&&(ne||ie)&&E.role==="assistant"){const ze=pe.getState().messages.get(ee)||[];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(he!==Ge)break;if(!ie&&T.current){k(he,"desktop_completion_without_stop");break}const le=ne?De:Date.now();ne||t(ee,he,{...E,time:{...Z??{},completed:le}}),k(he,"completed",{timeCompleted:le}),j(he),uv(ee,he,le),r(ee,he),T.current||gt==="stop"&&pe.getState().sessionActivityPhase?.get(ee)==="busy"&&oe(ee,"cooldown");const ue=E.sessionID,je=typeof ue=="string"&&ue.length>0?ue:ee;Q(je),E.summary&&typeof je=="string"&&n(je,null)}break}case"session.updated":{const E=typeof I.info=="object"&&I.info!==null?I.info:typeof I.sessionInfo=="object"&&I.sessionInfo!==null?I.sessionInfo:typeof I.session=="object"&&I.session!==null?I.session:I,z=typeof E.id=="string"&&E.id.length>0?E.id:typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:typeof I.sessionID=="string"&&I.sessionID.length>0?I.sessionID:typeof I.id=="string"&&I.id.length>0?I.id:void 0;if(z){const q=typeof E.time=="object"&&E.time!==null?E.time:typeof I.time=="object"&&I.time!==null?I.time:null,be=q&&typeof q.compacting=="number"?q.compacting:null;n(z,be)}break}case"session.abort":{const E=typeof I.sessionID=="string"&&I.sessionID.length>0?I.sessionID:null,z=typeof I.messageID=="string"&&I.messageID.length>0?I.messageID:null;E&&z&&r(E,z);break}case"permission.updated":a===I.sessionID&&o(I);break;case"permission.asked":if("sessionID"in I&&I.sessionID===a){const E=I,z={id:E.id,type:E.permission,pattern:E.patterns,sessionID:E.sessionID,messageID:E.tool?.messageID||E.sessionID,callID:E.tool?.callID,title:`${E.permission} permission required`,metadata:{...E.metadata,always:E.always,patterns:E.patterns},time:{created:Date.now()}};o(z)}break;case"permission.replied":break;case"todo.updated":{const E=typeof I.sessionID=="string"?I.sessionID:null,z=Array.isArray(I.todos)?I.todos:[];E&&z.length>0&&Px(E,z);break}}},[a,s,r,t,o,f,Q,re,n,i,k,j,oe,S]),ye=l.useCallback(()=>{const K=$();return R.current=K,K==="visible"&&H.current},[$]),ce=l.useCallback(()=>{Ht()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:T.current,hasUnsubscribe:!!N.current,currentSessionId:Me.current,effectiveDirectory:b,onlineStatus:H.current,visibilityState:R.current,lastEventTimestamp:B.current,reconnectAttempts:D.current})},[b]),Ce=l.useCallback(async()=>!0,[]),Ee=l.useCallback(()=>{if(C.current){Ht()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(C.current=!0,L.current&&(clearTimeout(L.current),L.current=null),N.current){const K=N.current;N.current=null;try{K()}catch(I){console.warn("[useEventStream] Error during unsubscribe:",I)}}C.current=!1},[]),Pe=l.useCallback(async K=>{if(ce(),!ye()){U.current=!0,H.current?x("paused","Paused while hidden"):x("offline","Waiting for network");return}T.current&&(await Ce()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),K?.resetAttempts&&(D.current=0),Ee(),B.current=Date.now(),x("connecting",null),Ht()&&console.info("[useEventStream] Starting event stream...");const I=E=>{console.warn("Event stream error:",E)},J=()=>{const E=U.current;if(D.current=0,U.current=!1,B.current=Date.now(),x("connected",null),f(),Array.from(pe.getState().sessionActivityPhase?.values?.()??[]).some(q=>q==="busy")&&W(),E)S("sse_reconnected");else{const q=Me.current;q&&setTimeout(()=>{w(q,"sse_reconnected").then(()=>Q(q)).catch(be=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",be)})},0)}};if(Ht()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:b,isCleaningUp:C.current}),C.current){Ht()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const E=Re.subscribeToEvents(me,I,J,b),z=()=>{try{E()}catch(q){console.warn("[useEventStream] Error during unsubscribe:",q)}};C.current?z():N.current=z}catch(E){console.error("[useEventStream] Error during subscription:",E),I(E)}},[ye,Ee,x,f,w,Q,me,b,W,Ce,ce,S]),G=l.useCallback(K=>{if(!ye()){U.current=!0,Ee(),H.current?x("paused","Paused while hidden"):x("offline","Waiting for network");return}const I=D.current+1;D.current=I;const J=K??`Retrying (${I})`;x("reconnecting",J);const E=I<=3?Math.min(1e3*Math.pow(2,I-1),8e3):Math.min(2e3*Math.pow(2,I-3),32e3),z=Math.floor(Math.random()*250),q=E+z;L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{Pe({resetAttempts:!1})},q)},[ye,Ee,x,Pe]);l.useEffect(()=>{const K=X.current;typeof window<"u"&&(window.__messageTracker=k);let I=null;T.current&&typeof window<"u"&&(I=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),re())},window.addEventListener("openchamber:session-activity",I));const J=()=>{Y.current&&(clearTimeout(Y.current),Y.current=null)},E=()=>{Y.current||(Y.current=setTimeout(()=>{const He=$();R.current=He,He!=="visible"?(Ee(),U.current=!0,x("paused","Paused while hidden")):J()},5e3))},z=()=>{if(R.current=$(),R.current==="visible"){if(J(),V("visibility_restore"),U.current||!N.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const He=Me.current;He&&(w(He,"visibility_restore").catch(()=>{}),Q(He)),m(),W(),x("connecting","Resuming stream"),Pe({resetAttempts:!0})}}else x("paused","Paused while hidden"),E()},q=()=>{if(R.current=$(),R.current==="visible"&&(J(),V("window_focus"),U.current||!N.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const He=Me.current;He&&(Q(He),w(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=()=>{H.current=!0,V("network_restored"),(U.current||!N.current)&&(x("connecting","Network restored"),Pe({resetAttempts:!0}))},ee=()=>{H.current=!1,U.current=!0,x("offline","Waiting for network"),Ee()};typeof document<"u"&&document.addEventListener("visibilitychange",z),typeof window<"u"&&(window.addEventListener("online",be),window.addEventListener("offline",ee),window.addEventListener("focus",q));const he=setTimeout(()=>{Pe({resetAttempts:!0})},100);return F.current&&clearInterval(F.current),F.current=setInterval(()=>{if(!ye())return;const He=Date.now();Array.from(pe.getState().sessionActivityPhase?.values?.()??[]).some(Be=>Be==="busy")&&W(),He-B.current>25e3&&Promise.resolve().then(async()=>{try{await Re.checkHealth()?B.current=Date.now():G("Refreshing stalled stream")}catch(Be){console.warn("Health check after stale stream failed:",Be),G("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(he),I&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",I),typeof document<"u"&&document.removeEventListener("visibilitychange",z),typeof window<"u"&&(window.removeEventListener("online",be),window.removeEventListener("offline",ee),window.removeEventListener("focus",q)),J(),F.current&&(clearInterval(F.current),F.current=null),K.forEach(He=>clearTimeout(He)),K.clear(),ei.clear(),U.current=!1,R.current=$(),H.current=typeof navigator>"u"?!0:navigator.onLine,Ee(),v.current&&(clearTimeout(v.current),v.current=null),x("idle",null)}},[b,k,$,Ee,x,Pe,G,u,Q,re,oe,W,ye,m,V,w])},xv=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=pe(),{toggleCommandPalette:a,toggleHelpDialog:i,toggleSidebar:c,setSessionSwitcherOpen:d,setSessionCreateDialogOpen:u,setActiveMainTab:m,setSettingsDialogOpen:f,setModelSelectorOpen:p}=Fe(),{themeMode:h,setThemeMode:b}=Fr(),{working:g}=xu(),y=l.useRef(null),x=l.useRef(null),w=l.useRef(!1),S=l.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null),y.current=null,n()},[n]);l.useEffect(()=>{const k=j=>{if(hs(j)&&j.key==="k"&&(j.preventDefault(),a()),hs(j)&&j.shiftKey&&j.key.toLowerCase()==="l"){const L=Er()?.diagnostics;if(!L||(j.preventDefault(),w.current))return;w.current=!0,L.downloadLogs().then(({fileName:D,content:M})=>{const v=D||"openchamber.log",C=new Blob([M],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(C),P=document.createElement("a");P.href=A,P.download=v,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(A)}).finally(()=>{w.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 N=["light","dark","system"],D=(N.indexOf(h)+1)%N.length;b(N[D])}if(hs(j)&&!j.shiftKey&&j.key.toLowerCase()==="t"){j.preventDefault();const{isTimelineDialogOpen:N,setTimelineDialogOpen:L}=Fe.getState();L(!N);return}if(hs(j)&&!j.shiftKey&&j.key===","){j.preventDefault();const{isSettingsDialogOpen:N}=Fe.getState();f(!N);return}if(hs(j)&&!j.shiftKey&&j.key.toLowerCase()==="l"){j.preventDefault();const{isMobile:N,isSessionSwitcherOpen:L}=Fe.getState();N?d(!L):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:N,isCommandPaletteOpen:L,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isSessionCreateDialogOpen:v,isAboutDialogOpen:C,activeMainTab:A,isModelSelectorOpen:P}=Fe.getState();if(N||L||D||M||v||C||!(A==="chat"))return;j.preventDefault(),p(!P);return}if(j.key==="Escape"){const{isSettingsDialogOpen:N,isCommandPaletteOpen:L,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isSessionCreateDialogOpen:v,isAboutDialogOpen:C,activeMainTab:A}=Fe.getState();if(N){j.preventDefault(),f(!1),S();return}if(L||D||M||v||C||!(A==="chat")){S();return}const R=o;if(!(g.canAbort&&!!R)){S();return}const U=Date.now(),Y=y.current;if(Y&&U<Y){j.preventDefault(),S(),r();return}j.preventDefault();const F=t(3e3)??U+3e3;y.current=F,x.current&&clearTimeout(x.current);const B=Math.max(F-U,0);x.current=setTimeout(()=>{y.current&&Date.now()>=y.current&&S()},B||0);return}};return window.addEventListener("keydown",k),()=>{window.removeEventListener("keydown",k)}},[s,r,a,i,c,d,u,m,f,p,b,h,g,t,S,o]),l.useEffect(()=>()=>{S()},[S])},Wc="openchamber:menu-action",yv=s=>{const{openNewSessionDraft:r}=pe(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setSessionCreateDialogOpen:i,setActiveMainTab:c,setSettingsDialogOpen:d,setAboutDialogOpen:u}=Fe(),{setDirectory:m}=ht(),{setThemeMode:f}=Fr(),p=l.useRef(!1),h=l.useCallback(()=>{Xt()&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(b=>{b.success&&b.path?m(b.path,{showOverlay:!0}):b.error&&b.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:b.error})}).catch(b=>{console.error("Desktop: Error selecting directory:",b),se.error("Failed to select directory")}):vr.requestDirectoryDialog()},[m]);l.useEffect(()=>{const b=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 w=Er()?.diagnostics;if(!w||p.current)break;p.current=!0,w.downloadLogs().then(({fileName:S,content:k})=>{const j=S||"openchamber.log",N=new Blob([k],{type:"text/plain;charset=utf-8"}),L=URL.createObjectURL(N),D=document.createElement("a");D.href=L,D.download=j,document.body.appendChild(D),D.click(),document.body.removeChild(D),URL.revokeObjectURL(L),se.success("Logs saved",{description:`Downloaded to ~/Downloads/${j}`})}).catch(()=>{se.error("Failed to download logs")}).finally(()=>{p.current=!1});break}}};return window.addEventListener(Wc,b),()=>window.removeEventListener(Wc,b)},[r,t,n,o,a,i,c,d,u,f,s,h])},bv=s=>s.role==="assistant",Vc=s=>{const r=s.info;if(!bv(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},mo=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},Gc=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>yn(n)).join(" ").replace(/\s+/g," ").trim(),wv=(s,r)=>{if(!s||!mo(s.info))return-1;const t=Gc(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(!mo(i.info))return;const d=Gc(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(!mo(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},vv=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=pe(),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 mv(s);if(!u)return;const f=d[d.length-1];if(f){const p=u.findIndex(g=>g.info.id===f.info.id),b=p===-1?wv(f,u):p;if(b!==-1)if(b<u.length-1){const g=u.slice(b+1);console.log(`[SYNC] Found ${g.length} new messages to append`);const y=[...d,...g],{syncMessages:x}=pe.getState();x(s,y)}else{const g=u[b],y=d[d.length-1],x=Vc(g),w=Vc(y);if(x&&!w){console.log("[SYNC] Last message completed on server");const S=[...d.slice(0,-1),g],{syncMessages:k}=pe.getState();k(s,S)}}else if(mo(f.info)){const g=u.slice(-Zt.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:y}=pe.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 b=u.slice(p+1).slice(-Zt.VIEWPORT_MESSAGES);if(b.length>0){console.log(`[SYNC] Restoring ${b.length} messages after cursor`);const{syncMessages:g}=pe.getState();g(s,b)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const h=u.slice(-Zt.VIEWPORT_MESSAGES),{syncMessages:b}=pe.getState();b(s,h)}}else if(u.length>0){const p=u.slice(-Zt.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:h}=pe.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])},jv=()=>{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&&pe.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function Sv(){const{git:s}=Tr(),r=ht(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=pe(),{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 Nv({children:s}){return Sv(),e.jsx(e.Fragment,{children:s})}const kv=()=>{const[{isUpdating:s,message:r},t]=l.useState(()=>Cp());return l.useEffect(()=>kp(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(Ai,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Cv=({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 Jt(async()=>{const{getVersion:u}=await import("./vendor-.bun-B7CnnRlj.js").then(m=>m.cc);return{getVersion:u}},__vite__mapDeps([0,1])),d=await c();n(d)}catch{n("1.4.3")}})():n("1.4.3")},[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(Ai,{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(Ra,{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(ud,{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(La,{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 Aa({apis:s,children:r}){return e.jsx(yi.Provider,{value:s,children:r})}const Mv="curl -fsSL https://opencode.ai/install | bash",Dv=3e3;function Av({onCopy:s}){return e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsxs("code",{children:[e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),e.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),e.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),e.jsx("span",{className:"text-muted-foreground",children:" | "}),e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e.jsx("button",{onClick:s,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Ys,{className:"h-4 w-4"})})]})}const Ev=3e4;function Iv({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),Ev);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 Jt(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-B7CnnRlj.js").then(b=>b.cb);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,Dv);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(fo,{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(Av,{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(fo,{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 Tv=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=Fe();return e.jsx(Cv,{open:s,onOpenChange:r})};function Fv({apis:s}){const{initializeApp:r,isInitialized:t}=ut(),{error:n,clearError:o,loadSessions:a}=pe(),i=ht(k=>k.currentDirectory),c=ht(k=>k.isSwitchingDirectory),[d,u]=l.useState(!1),{uiFont:m,monoFont:f}=Ou(),[p,h]=l.useState(()=>s.runtime.isDesktop),[b,g]=l.useState(()=>s.runtime.isVSCode),[y,x]=l.useState(()=>s.runtime.isDesktop?ip():!0);l.useEffect(()=>{h(s.runtime.isDesktop),g(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),l.useEffect(()=>(Qi(s),()=>Qi(null)),[s]),l.useEffect(()=>{if(typeof document>"u")return;const k=document.documentElement,j=vc[m]?.stack??vc[Yb].stack,N=wr[f]?.stack??wr[co].stack;k.style.setProperty("--font-sans",j),k.style.setProperty("--font-heading",j),k.style.setProperty("--font-family-sans",j),k.style.setProperty("--font-mono",N),k.style.setProperty("--font-family-mono",N),k.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=j)},[m,f]),l.useEffect(()=>{if(t){const j=setTimeout(()=>{const N=document.getElementById("initial-loading");N&&(N.classList.add("fade-out"),setTimeout(()=>{N.remove()},300))},150);return()=>clearTimeout(j)}},[t]),l.useEffect(()=>{const k=setTimeout(()=>{const j=document.getElementById("initial-loading");j&&!t&&(j.classList.add("fade-out"),setTimeout(()=>{j.remove()},300))},5e3);return()=>clearTimeout(k)},[t]),l.useEffect(()=>{(async()=>await r())()},[r]),l.useEffect(()=>{if(c)return;(async()=>(Re.setDirectory(i),await a()))()},[i,c,a]),gv(),xv();const w=l.useCallback(()=>{u(k=>!k)},[]);yv(w),vv(),jv(),Wu(),l.useEffect(()=>{const k=j=>{hs(j)&&j.shiftKey&&j.key==="D"&&(j.preventDefault(),u(N=>!N))};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[]),l.useEffect(()=>{n&&setTimeout(()=>o(),5e3)},[n,o]);const S=l.useCallback(()=>{x(!0),window.location.reload()},[]);return p&&!y?e.jsx(Wt,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(Iv,{onCliAvailable:S})})}):b?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(Wt,{children:e.jsx(Aa,{apis:s,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(ov,{}),e.jsx(Da,{})]})})}):e.jsx(Wt,{children:e.jsx(Aa,{apis:s,children:e.jsx(gc,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Xw,{}),e.jsx(Da,{})]})})})}):e.jsx(Wt,{children:e.jsx(Aa,{apis:s,children:e.jsx(Nv,{children:e.jsx(gc,{children:e.jsxs("div",{className:`h-full text-foreground ${p?"bg-transparent":"bg-background"}`,children:[e.jsx(Kw,{}),e.jsx(Da,{}),e.jsx(kv,{}),e.jsx(Tv,{}),d&&e.jsx(iv,{onClose:()=>u(!1)})]})})})})})}const Xu=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=ht.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&t.setDirectory(r,{showOverlay:!1})},Qu="/auth/session",Pv=async()=>fetch(Qu,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Rv=async s=>fetch(Qu,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),$i=({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})]}),Lv=({message:s="Preparing workspace…"})=>e.jsx($i,{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})})}),$v=({onRetry:s})=>e.jsx($i,{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"})]})}),Ov=({children:s})=>{const r=l.useMemo(()=>Xt(),[]),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),b=l.useCallback(async()=>{if(n){a("authenticated");return}a(y=>y==="authenticated"?y:"pending");try{const y=await Pv();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||b()},[b,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 vd(),await jd(),await Xu()))())},[n,o]);const g=async y=>{if(y.preventDefault(),!(!i||d)){u(!0),f("");try{const x=await Rv(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(Lv,{}):o==="error"?e.jsx($v,{onRetry:()=>{b()}}):o==="locked"?e.jsx($i,{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(Uf,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(it,{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(es,{className:"h-4 w-4 animate-spin"}):e.jsx(Wf,{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})},Ea=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 _v{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=Ea(r.colors.surface.muted),o=Ea(r.colors.surface.subtle),a=Ea(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()?xp:ui;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 Oi={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"}}},_i={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"}}},En=[Oi,_i];function Eo(s){return En.find(r=>r.metadata.id===s)}const Ju=Oi.metadata.id,Zu=_i.metadata.id,Bv=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,em=s=>s==="dark"?_i:Oi,zv=s=>(En.find(t=>t.metadata.variant===s)??em(s)).metadata.id,Zn=(s,r)=>{const t=Eo(s);return t&&t.metadata.variant===r?t:En.find(o=>o.metadata.variant===r)??em(r)},Hv=typeof window<"u"?l.useLayoutEffect:l.useEffect,Io=(s,r)=>{if(!s)return r==="light"?Ju:Zu;const t=Eo(s);return t&&t.metadata.variant===r?t.metadata.id:zv(r)},Uv=s=>{let r=Ju,t=Zu,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=Eo(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=Io(a,"light"),t=Io(i,"dark")}if(s){const o=Eo(s);o&&(o.metadata.variant==="light"?r=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:t}};function Wv({children:s,defaultThemeId:r}){const t=Ne.useMemo(()=>new _v,[]),[n,o]=Ne.useState(()=>Uv(r)),[a,i]=Ne.useState(()=>Bv()),[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"?Zn(n.lightThemeId,"light"):n.themeMode==="dark"||a?Zn(n.darkThemeId,"dark"):Zn(n.lightThemeId,"light"),[u,n,a,c]),f=Ne.useMemo(()=>u&&c?[c,...En]:En,[u,c]);Ne.useEffect(()=>{if(!u)return;const k=L=>{d(L);const D=L.metadata.variant==="dark"?"dark":"light",M=Fe.getState();M.theme!==D&&M.setTheme(D)},j=L=>{const D=L.detail;D?.theme&&k(D.theme)},N=window.__OPENCHAMBER_VSCODE_THEME__;return N&&k(N),window.addEventListener("openchamber:vscode-theme",j),()=>window.removeEventListener("openchamber:vscode-theme",j)},[u]);const p=Ne.useCallback(k=>{if(typeof document>"u")return;const j=k.colors.surface.background;Xt()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=j;let N=document.querySelector('meta[name="theme-color"]');N||(N=document.createElement("meta"),N.setAttribute("name","theme-color"),document.head.appendChild(N)),N.setAttribute("content",j);const L=k.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let D=document.querySelector(`meta[name="theme-color"][media="${L}"]`);D||(D=document.createElement("meta"),D.setAttribute("name","theme-color"),D.setAttribute("media",L),document.head.appendChild(D)),D.setAttribute("content",j)},[]),h=Ne.useCallback(k=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",k)},[]);Hv(()=>{if(typeof window>"u")return;t.apply(m),h(u),p(m);const k=document.documentElement;k.classList.remove("light","dark"),k.classList.add(m.metadata.variant)},[h,t,m,u,p]),Ne.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const k=window.matchMedia("(prefers-color-scheme: dark)"),j=N=>{i(N.matches)};return i(k.matches),k.addEventListener("change",j),()=>k.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 k=j=>{const N=j.detail;N&&o(L=>{let D=L.themeMode;N.useSystemTheme===!0?D="system":N.useSystemTheme===!1&&(N.themeVariant==="dark"||N.themeVariant==="light")&&(D=N.themeVariant);let M=L.lightThemeId;typeof N.lightThemeId=="string"&&N.lightThemeId.length>0&&(M=Io(N.lightThemeId,"light"));let v=L.darkThemeId;return typeof N.darkThemeId=="string"&&N.darkThemeId.length>0&&(v=Io(N.darkThemeId,"dark")),D===L.themeMode&&M===L.lightThemeId&&v===L.darkThemeId?L:{themeMode:D,lightThemeId:M,darkThemeId:v}})};return window.addEventListener("openchamber:settings-synced",k),()=>window.removeEventListener("openchamber:settings-synced",k)},[]);const b=Ne.useCallback(k=>{const j=f.find(N=>N.metadata.id===k);j&&o(N=>j.metadata.variant==="dark"?N.darkThemeId===j.metadata.id&&N.themeMode==="dark"?N:{...N,darkThemeId:j.metadata.id,themeMode:"dark"}:N.lightThemeId===j.metadata.id&&N.themeMode==="light"?N:{...N,lightThemeId:j.metadata.id,themeMode:"light"})},[f]),g=Ne.useCallback(k=>{o(j=>j.themeMode===k?j:{...j,themeMode:k})},[]),y=Ne.useCallback(k=>{if(k){o(N=>N.themeMode==="system"?N:{...N,themeMode:"system"});return}const j=m.metadata.variant==="dark"?"dark":"light";o(N=>N.themeMode===j?N:{...N,themeMode:j})},[m.metadata.variant]),x=Ne.useCallback(k=>{const j=f.find(N=>N.metadata.id===k&&N.metadata.variant==="light");j&&o(N=>N.lightThemeId===j.metadata.id?N:{...N,lightThemeId:j.metadata.id})},[f]),w=Ne.useCallback(k=>{const j=f.find(N=>N.metadata.id===k&&N.metadata.variant==="dark");j&&o(N=>N.darkThemeId===j.metadata.id?N:{...N,darkThemeId:j.metadata.id})},[f]),S={currentTheme:m,availableThemes:f,setTheme:b,isSystemPreference:n.themeMode==="system",setSystemPreference:y,themeMode:n.themeMode,setThemeMode:g,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:x,setDarkThemePreference:w};return e.jsx(bi.Provider,{value:S,children:s})}const Vv=({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})},Gv={getLastAssistantMessage(){const s=pe.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=pe.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=ht.getState(),r=pe.getState(),t=s.currentDirectory||null,n=Re.getDirectory()??null,o=r.sessions||[],a=new Set,i={};o.forEach(N=>{const L=N.directory;typeof L=="string"&&L.trim().length>0?(a.add(L),i[L]=(i[L]??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(N){return{available:!1,error:N instanceof Error?N.message:String(N)}}})(),d=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,u=typeof window<"u"?window.__OPENCHAMBER_DESKTOP_SERVER__:null,m=!!(d?.runtime?.isDesktop||typeof window<"u"&&window.opencodeDesktop),f=async N=>{try{return await N.json()}catch{return null}},p=async N=>{try{return await N.text()}catch{return null}},h=async N=>{try{const L=await fetch(N);return L.ok?await f(L):{status:L.status}}catch(L){return{error:L instanceof Error?L.message:String(L)}}};let b=null,g=null,y=null,x=null;const w=t?`/api/path?directory=${encodeURIComponent(t)}`:"/api/path";b=await h(w);const S=t?`/api/project/current?directory=${encodeURIComponent(t)}`:"/api/project/current";g=await h(S),y=await h("/api/config/settings");try{const N=await fetch("/api/health"),L=N.headers.get("content-type")||"",D=await p(N);x={status:N.status,ok:N.ok,contentType:L,type:L.includes("application/json")?"json":"html",preview:D?D.slice(0,120):null}}catch(N){x={error:N instanceof Error?N.message:String(N)}}let k={isGitRepo:null};if(t)try{k.isGitRepo=await rn(t)}catch(N){k={isGitRepo:null,error:N instanceof Error?N.message:String(N)}}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:b?.directory||b?.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:k,localStorage:c,opencode:{pathInfo:b,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=pe.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=pe.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=pe.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(b=>typeof b=="number");return h.length>0?Math.max(...h):null},f=c.map((p,h)=>{const b=p.info??{},g=Array.isArray(p.parts)?p.parts:[],y=b.time??{},x=u(y.completed),w=x!==null,S=g.filter(A=>A.type==="tool"),k=g.filter(A=>A.type==="reasoning"),j=m(S.map(A=>u(A.state?.time?.end??A.state?.time?.start))),N=m(k.map(A=>u(A.time?.end??A.time?.start))),L=m([j,N].filter(A=>A!==null)),D=S.some(A=>["pending","running","started"].includes(A.state?.status)),M=k.some(A=>typeof A.time?.end!="number");S.length>0&&(d.withTools+=1),k.length>0&&(d.withReasoning+=1),w||(d.completedMissing+=1);const v=!!(w&&typeof j=="number"&&x<j);v&&(d.completedBeforeTool+=1);const C=!!(w&&typeof N=="number"&&x<N);return C&&(d.completedBeforeReasoning+=1),w&&D&&(d.runningToolsWhenCompleted+=1),w&&M&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:b.id,role:b.role,completedAt:x,latestToolTimestamp:j,latestReasoningTimestamp:N,latestPartTimestamp:L,completed_missing:!w,completed_before_tool:v,completed_before_reasoning:C,running_tools_when_completed:!!(w&&D),reasoning_open_when_completed:!!(w&&M),has_tools:S.length>0,has_reasoning:k.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=pe.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,b=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:",b?.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=Gv,Ht()&&(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 qc=!1;const qv=()=>{if(qc||typeof window>"u")return;qc=!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 Kc=!1;const Yc="openchamber-typography-base",Kv=()=>{if(typeof document>"u")return;const r=`:root {
|
|
119
|
-
${Object.entries(ui).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
|
|
120
|
-
`)}
|
|
121
|
-
}
|
|
122
|
-
`,t=document.getElementById(Yc);if(t){t.textContent=r;return}const n=document.createElement("style");n.id=Yc,n.textContent=r,document.head.appendChild(n)},Yv=()=>{Kc||typeof window>"u"||(Kc=!0,Kv())},Xv=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await vd();await jd();qv();Yv();await Xu();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 tm=document.getElementById("root");if(!tm)throw new Error("Root element not found");Vf.createRoot(tm).render(e.jsx(Ne.StrictMode,{children:e.jsx(Wv,{children:e.jsx(Vv,{children:e.jsx(Ov,{children:e.jsx(Fv,{apis:Xv})})})})}));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 Zv=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{as as D,kr as S,is as a,xg as b,O as c,xy as d,yy as e,ac as f,Ir as g,by as h,vy as i,Zv as m,Cu as p,wy as r,so as t};
|