@openchamber/web 1.5.8 → 1.5.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{ToolOutputDialog-DtvujDp_.js → ToolOutputDialog-Dz-mXTUL.js} +2 -2
- package/dist/assets/{index-BsjSeUw1.js → index-6-7dM4cm.js} +2 -2
- package/dist/assets/index-BlYLID2P.css +1 -0
- package/dist/assets/main-C3SPutdi.js +265 -0
- package/dist/assets/{vendor-.bun-koHRsLHN.js → vendor-.bun-Bui932eM.js} +86 -86
- package/dist/index.html +3 -3
- package/package.json +2 -2
- package/server/index.js +39 -14
- package/server/lib/git-service.js +1 -0
- package/dist/assets/index-CDs3bEu_.css +0 -1
- package/dist/assets/main-2dYN2XA4.js +0 -254
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-Bui932eM.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-Dz-mXTUL.js","assets/index-6-7dM4cm.js","assets/index-BlYLID2P.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as Ih,c as Ph,F as Th,j as e,R as Fh,T as Rh,P as Lh,C as Oh,A as _h,a as $h,b as Bh,d as zh,e as Hh,f as Wh,L as Uh,g as Vh,i as Gh,I as qh,s as Pt,S as Kh,k as Yh,l as is,m as hs,p as qs,n as Ks,o as qc,_ as js,q as i,r as _m,u as ss,v as Qh,w as $m,x as Jh,y as Xh,z as Zh,B as eg,D as tg,E as sg,G as Ae,H as Kc,J as rg,K as ng,M as Qs,N as Sl,O as Yc,Q as Uo,U as Ut,V as er,W as Ct,X as oc,Y as Nl,Z as Bm,$ as og,a0 as Xr,a1 as ag,a2 as Qn,a3 as tr,a4 as lr,a5 as tn,a6 as Vt,a7 as ac,a8 as ig,a9 as wn,aa as ic,ab as Dn,ac as vn,ad as Kr,ae as kl,af as Ls,ag as zm,ah as lg,ai as cg,aj as dg,ak as ug,al as mg,am as fg,an as pg,ao as Na,ap as hg,aq as za,ar as Xs,as as Zr,at as Ms,au as An,av as Vs,aw as Jn,ax as us,ay as kr,az as gg,aA as xg,aB as Hm,aC as lc,aD as jn,aE as cc,aF as Cr,aG as Wm,aH as Xn,aI as yg,aJ as di,aK as Um,aL as zs,aM as Vm,aN as Sn,aO as Nn,aP as Ha,aQ as Ti,aR as bg,aS as sn,aT as Tr,aU as rr,aV as wg,aW as vg,aX as Qc,aY as Cl,aZ as jg,a_ as Sg,a$ as Ng,b0 as kg,b1 as Cg,b2 as Mg,b3 as Dg,b4 as Ag,b5 as Eg,b6 as Gm,b7 as Fi,b8 as Ig,b9 as Mr,ba as Pg,bb as Tg,bc as Fg,bd as Rg,be as Lg,bf as Og,bg as _g,bh as $g,bi as Bg,bj as zg,bk as Hg,bl as Wg,bm as Ug,bn as Vg,bo as Gg,bp as qg,bq as Fr,br as Wa,bs as Dr,bt as vr,bu as Kg,bv as ui,bw as Yg,bx as zn,by as Qg,bz as Jg,bA as Xg,bB as Zn,bC as Zg,bD as ex,bE as tx,bF as sx,bG as rx,bH as ka,bI as mi,bJ as nx,bK as ox,bL as Gn,bM as Bn,bN as qm,bO as ax,bP as ix,bQ as sr,bR as lx,bS as Or,bT as Km,bU as cx,bV as dx,bW as Ml,bX as Ym,bY as Qm,bZ as ux,b_ as mx,b$ as fx,c0 as eo,c1 as px,c2 as Jc,c3 as hx,c4 as Dl,c5 as mo,c6 as fo,c7 as gx,c8 as xx,c9 as yx,ca as fi,cb as bx,cc as wx,cd as vx,ce as fn,cf as Xc,cg as jx,ch as Sx,ci as Nx,cj as kx,ck as Cx,cl as Mx,cm as Dx,cn as Ax,co as Jm,cp as Qe,cq as Xm,cr as po,cs as Ex,ct as Ix,cu as Px,cv as Tx,cw as Fx,cx as Rx,cy as Zm,cz as ef,cA as tf,cB as sf,cC as rf,cD as Lx,cE as nf,cF as of,cG as af,cH as Hn,cI as Ox,cJ as _x,cK as Al,cL as $x,cM as lf,cN as dc,cO as uc,cP as mc,cQ as Bx,cR as zx,cS as Hx,cT as Wx,cU as Zc,cV as cf,cW as Ux,cX as Vx,cY as Gx,cZ as qx,c_ as ed,c$ as td,d0 as sd,d1 as Kx,d2 as To,d3 as df,d4 as uf,d5 as xo,d6 as pi,d7 as mf,d8 as Yx,d9 as Qx,da as ff,db as El,dc as Jx,dd as Xx,de as Zx,df as ey,dg as ty,dh as sy}from"./vendor-.bun-Bui932eM.js";import{c as ry,g as ny,d as oy,a as ay,r as iy,l as ly,b as cy,u as dy,e as uy,f as my,h as fy,i as py,j as hy,k as gy,m as xy,n as yy}from"./index-6-7dM4cm.js";const ms=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",zt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,ur=()=>typeof window>"u"?!1:!ms()&&!zt(),rn=()=>ms()?window.opencodeDesktop??null:null,pf=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const t=window.opencodeDesktop;return t?.getSettings&&t?.updateSettings?{getSettings:t.getSettings.bind(t),updateSettings:t.updateSettings.bind(t)}:null},fc=async()=>{const t=rn();if(typeof window<"u"){const r=window.__OPENCHAMBER_HOME__;if(r&&r.length>0)return r}if(!t)return null;if(typeof t.homeDirectory=="string"&&t.homeDirectory.length>0)return t.homeDirectory;try{if(!t.getHomeDirectory)return null;const r=await t.getHomeDirectory();if(r?.success&&typeof r.path=="string"&&r.path.length>0)return r.path}catch(r){console.warn("Failed to obtain desktop home directory:",r)}return null},by=async()=>{const t=rn();if(!t)return null;try{return await t.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},wy=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Br=async()=>{const t=pf();if(!t)return null;try{return await t.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},vy=async t=>{const r=pf();if(!r)return null;try{return await r.updateSettings(t)}catch(s){return console.warn("[desktop] Failed to update desktop settings",s),null}},jy=async t=>{const r=rn();if(!r||!r.requestDirectoryAccess)return{success:!0,path:t};try{return await r.requestDirectoryAccess(t)}catch(s){return console.warn("Failed to request directory access",s),{success:!1,error:s instanceof Error?s.message:String(s)}}},Sy=async t=>{const r=rn();if(!r||!r.startAccessingDirectory)return{success:!0};try{return await r.startAccessingDirectory(t)}catch(s){return console.warn("Failed to start accessing directory",s),{success:!1,error:s instanceof Error?s.message:String(s)}}},Ny=async t=>{const r=rn();if(!r||!r.stopAccessingDirectory)return{success:!0};try{return await r.stopAccessingDirectory(t)}catch(s){return console.warn("Failed to stop accessing directory",s),{success:!1,error:s instanceof Error?s.message:String(s)}}},ky=async()=>{const t=rn();if(!t||!t.checkForUpdates)return null;try{return await t.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},Cy=async t=>{const r=rn();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(t),!0}catch(s){return console.warn("Failed to download update",s),!1}},My=async()=>{const t=rn();if(!t||!t.restartToUpdate)return!1;try{return await t.restartToUpdate(),!0}catch(r){return console.warn("Failed to restart for update",r),!1}};function L(...t){return Ih(Ph(t))}const hf=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),$s=t=>hf()&&ms()?t.metaKey:t.ctrlKey,Xt=()=>hf()&&ms()?"⌘":"Ctrl",gf=(t,r)=>{const s=t??"",n=Math.max(16,r?.maxLength??45);if(s.length<=n)return s;const o=s.split("/");if(o.length<=1)return s;const a=o.pop()??"";if(!a)return s;const l=Math.max(0,n-(a.length+2));if(l<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const u=c?`${c}/${d}`:d;if(u.length>l)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,l):""}return c?`${c}…/${a}`:`…/${a}`},Ua=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function Yr(t,r){if(!t)return"";const s=Ua(t);if(s==="/")return"/";const n=r?Ua(r):void 0;if(n&&n!=="/"){if(s===n)return"~";if(s.startsWith(`${n}/`)){const o=s.slice(n.length+1);return o?`~/${o}`:"~"}}return s}function rd(t,r){if(!t)return"/";const s=Ua(t);if(!s||s==="/")return"/";const n=r?Ua(r):void 0;return n&&n!=="/"&&s===n?"~":s.split("/").pop()||s||"/"}function Js(t,r){return r?t?t.toLowerCase().includes(r.toLowerCase())?!0:new Th([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function Dy({delayDuration:t=0,...r}){return e.jsx($h,{"data-slot":"tooltip-provider",delayDuration:t,...r})}function dt({delayDuration:t=0,...r}){return e.jsx(Dy,{delayDuration:t,children:e.jsx(Fh,{"data-slot":"tooltip",...r})})}function ut({...t}){return e.jsx(Rh,{"data-slot":"tooltip-trigger",...t})}function ct({className:t,sideOffset:r=0,children:s,...n}){return e.jsx(Lh,{children:e.jsxs(Oh,{"data-slot":"tooltip-content",sideOffset:r,className:L("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",t),...n,children:[s,e.jsx(_h,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}function rs({...t}){return e.jsx(Bh,{"data-slot":"dropdown-menu",...t})}function ns({...t}){return e.jsx(zh,{"data-slot":"dropdown-menu-trigger",...t})}function os({className:t,sideOffset:r=4,...s}){return e.jsx(Hh,{children:e.jsx(Wh,{"data-slot":"dropdown-menu-content",sideOffset:r,className:L("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",t),...s})})}function Nt({className:t,inset:r,variant:s="default",...n}){return e.jsx(Yh,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":s,className:L("hover:bg-muted data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",t),...n})}function Va({...t}){return e.jsx(Vh,{"data-slot":"dropdown-menu-radio-group",...t})}function Ga({className:t,children:r,...s}){return e.jsxs(Gh,{"data-slot":"dropdown-menu-radio-item",className:L("relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-muted [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",t),...s,children:[e.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:e.jsx(qh,{children:e.jsx(Pt,{className:"size-3"})})}),r]})}function Rr({className:t,inset:r,...s}){return e.jsx(Uh,{"data-slot":"dropdown-menu-label","data-inset":r,className:L("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",t),...s})}function Ds({className:t,...r}){return e.jsx(Kh,{"data-slot":"dropdown-menu-separator",className:L("bg-border -mx-1 my-0.5 h-px",t),...r})}let Ri=null;const nd=()=>{const t=new Map;return{getItem:r=>t.get(r)??null,setItem:(r,s)=>{t.set(r,s)},removeItem:r=>{t.delete(r)},clear:()=>{t.clear()},key:r=>Array.from(t.keys())[r]??null,get length(){return t.size}}},Ay=()=>{if(typeof window>"u"||!window.localStorage)return nd();const t=window.localStorage,r=nd();let s=!0;const n=()=>{s=!1};return{getItem:u=>{if(s)try{const m=t.getItem(u);if(m!==null)return m}catch{n()}return r.getItem(u)},setItem:(u,m)=>{if(s)try{t.setItem(u,m),r.removeItem(u);return}catch{n()}r.setItem(u,m)},removeItem:u=>{if(s)try{t.removeItem(u)}catch{n()}r.removeItem(u)},clear:()=>{if(s)try{t.clear()}catch{n()}r.clear()},key:u=>{if(s)try{return t.key(u)}catch{n()}return r.key(u)},get length(){if(s)try{return t.length+r.length}catch{n()}return r.length}}},Ss=()=>(Ri||(Ri=Ay()),Ri),pc={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Ey={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function od(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Lr={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)"}}},Ca={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Lr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ca.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Lr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ca.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Lr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ca.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Lr.tool.inline})},Me=is()(hs(qs((t,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",mainTabGuard:null,pendingDiffFile:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,showTextJustificationActivity:!1,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,memoryLimitHistorical:90,memoryLimitViewport:120,memoryLimitActiveSession:180,toolCallExpansion:"collapsed",fontSize:100,padding:100,cornerRadius:12,inputBarOffset:0,favoriteModels:[],recentModels:[],diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"stacked",isTimelineDialogOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",setTheme:s=>{t({theme:s}),r().applyTheme()},toggleSidebar:()=>{t(s=>{const n=!s.isSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:n,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:n}})},setSidebarOpen:s=>{t(()=>{if(s&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:s,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:s}})},setSidebarWidth:s=>{t({sidebarWidth:s,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:s=>{t({isSessionSwitcherOpen:s})},setMainTabGuard:s=>{t({mainTabGuard:s})},setActiveMainTab:s=>{const n=r().mainTabGuard;n&&!n(s)||t({activeMainTab:s})},setPendingDiffFile:s=>{t({pendingDiffFile:s})},navigateToDiff:s=>{const n=r().mainTabGuard;n&&!n("diff")||t({pendingDiffFile:s,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:s}=r();return s&&t({pendingDiffFile:null}),s},setIsMobile:s=>{t({isMobile:s})},toggleCommandPalette:()=>{t(s=>({isCommandPaletteOpen:!s.isCommandPaletteOpen}))},setCommandPaletteOpen:s=>{t({isCommandPaletteOpen:s})},toggleHelpDialog:()=>{t(s=>({isHelpDialogOpen:!s.isHelpDialogOpen}))},setHelpDialogOpen:s=>{t({isHelpDialogOpen:s})},setAboutDialogOpen:s=>{t({isAboutDialogOpen:s})},setSessionCreateDialogOpen:s=>{t({isSessionCreateDialogOpen:s})},setSettingsDialogOpen:s=>{t({isSettingsDialogOpen:s})},setModelSelectorOpen:s=>{t({isModelSelectorOpen:s})},setSidebarSection:s=>{t({sidebarSection:s})},setEventStreamStatus:(s,n)=>{t({eventStreamStatus:s,eventStreamHint:n??null})},setShowReasoningTraces:s=>{t({showReasoningTraces:s})},setShowTextJustificationActivity:s=>{t({showTextJustificationActivity:s})},setAutoDeleteEnabled:s=>{t({autoDeleteEnabled:s})},setAutoDeleteAfterDays:s=>{const n=Math.max(1,Math.min(365,s));t({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:s=>{t({autoDeleteLastRunAt:s})},setMemoryLimitHistorical:s=>{const n=Math.max(10,Math.min(500,Math.round(s)));t({memoryLimitHistorical:n})},setMemoryLimitViewport:s=>{const n=Math.max(20,Math.min(500,Math.round(s)));t({memoryLimitViewport:n})},setMemoryLimitActiveSession:s=>{const n=Math.max(30,Math.min(1e3,Math.round(s)));t({memoryLimitActiveSession:n})},setToolCallExpansion:s=>{t({toolCallExpansion:s})},setFontSize:s=>{const n=Math.max(50,Math.min(200,s));t({fontSize:n}),r().applyTypography()},setPadding:s=>{const n=Math.max(50,Math.min(200,s));t({padding:n}),r().applyPadding()},setCornerRadius:s=>{t({cornerRadius:s})},applyTypography:()=>{const{fontSize:s}=r(),n=document.documentElement,o=s/100,a=Object.entries(pc);if(o===1){for(const[l]of a)n.style.removeProperty(od(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(od(l),`${d*o}rem`)}},applyPadding:()=>{const{padding:s}=r(),n=document.documentElement,o=s/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);n.style.setProperty("--padding-scale",a.toString());const l=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*l).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*l).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*l).toFixed(3)),n.style.setProperty("--line-height-loose",(2*l).toFixed(3))},setDiffLayoutPreference:s=>{t({diffLayoutPreference:s})},setDiffFileLayout:(s,n)=>{t(o=>({diffFileLayout:{...o.diffFileLayout,[s]:n}}))},setDiffWrapLines:s=>{t({diffWrapLines:s})},setDiffViewMode:s=>{t({diffViewMode:s})},setInputBarOffset:s=>{t({inputBarOffset:s})},setKeyboardOpen:s=>{t({isKeyboardOpen:s})},toggleFavoriteModel:(s,n)=>{t(o=>o.favoriteModels.some(l=>l.providerID===s&&l.modelID===n)?{favoriteModels:o.favoriteModels.filter(l=>!(l.providerID===s&&l.modelID===n))}:{favoriteModels:[{providerID:s,modelID:n},...o.favoriteModels]})},isFavoriteModel:(s,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===s&&a.modelID===n)},addRecentModel:(s,n)=>{t(o=>{const a=o.recentModels.filter(l=>!(l.providerID===s&&l.modelID===n));return{recentModels:[{providerID:s,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||t(s=>{const n={};return s.isSidebarOpen&&!s.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:s}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),s==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(s)},setMultiRunLauncherOpen:s=>{t(n=>({isMultiRunLauncherOpen:s,multiRunLauncherPrefillPrompt:s?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:s=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:s,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:s=>{t({isTimelineDialogOpen:s})},setNativeNotificationsEnabled:s=>{t({nativeNotificationsEnabled:s})},setNotificationMode:s=>{t({notificationMode:s})}}),{name:"ui-store",storage:Ks(()=>Ss()),partialize:t=>({theme:t.theme,isSidebarOpen:t.isSidebarOpen,sidebarWidth:t.sidebarWidth,isSessionSwitcherOpen:t.isSessionSwitcherOpen,activeMainTab:t.activeMainTab,sidebarSection:t.sidebarSection,isSessionCreateDialogOpen:t.isSessionCreateDialogOpen,isSettingsDialogOpen:t.isSettingsDialogOpen,showReasoningTraces:t.showReasoningTraces,showTextJustificationActivity:t.showTextJustificationActivity,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,autoDeleteLastRunAt:t.autoDeleteLastRunAt,memoryLimitHistorical:t.memoryLimitHistorical,memoryLimitViewport:t.memoryLimitViewport,memoryLimitActiveSession:t.memoryLimitActiveSession,toolCallExpansion:t.toolCallExpansion,fontSize:t.fontSize,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,recentModels:t.recentModels,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,diffViewMode:t.diffViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode})}),{name:"ui-store"}));async function Iy(){try{const t=await fetch("/api/openchamber/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Server responded with ${t.status}`);const r=await t.json();return{available:r.available??!1,version:r.version,currentVersion:r.currentVersion??"unknown",body:r.body,packageManager:r.packageManager,updateCommand:r.updateCommand}}catch(t){return console.warn("Failed to check for web updates:",t),null}}function Py(){return ms()?"desktop":ur()?"web":null}const ad={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},hi=is()((t,r)=>({...ad,checkForUpdates:async()=>{const s=Py();if(s){t({checking:!0,error:null,runtimeType:s});try{let n=null;s==="desktop"?n=await ky():s==="web"&&(n=await Iy()),t({checking:!1,available:n?.available??!1,info:n,lastChecked:Date.now()})}catch(n){t({checking:!1,error:n instanceof Error?n.message:"Failed to check for updates"})}}},downloadUpdate:async()=>{const{available:s,runtimeType:n}=r();if(!(n!=="desktop"||!s)){t({downloading:!0,error:null,progress:null});try{await Cy(o=>{t({progress:o})}),t({downloading:!1,downloaded:!0})}catch(o){t({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:s,runtimeType:n}=r();if(!(n!=="desktop"||!s))try{await My()}catch(o){t({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{t({available:!1,downloaded:!1,info:null})},reset:()=>{t(ad)}})),Ty="/api",Fy=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Ry=t=>{const r=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(Fy.test(r)||typeof window>"u")return r;const s=window.location?.href||window.location?.origin;if(!s)return r;try{return new URL(r,s).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),r}},Ly=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_DESKTOP_SERVER__,r=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!t||!r)return null;const s=typeof t.origin=="string"&&t.origin.length>0?t.origin:null;return s?`${s}/api`:null},Zo=t=>t.replace(/\\/g,"/"),Li=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class Oy{client;baseUrl;scopedClients=new Map;sseAbortControllers=new Map;currentDirectory=void 0;globalSseAbortController=null;globalSseTask=null;globalSseLastEventId;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;constructor(r=Ty){const n=Ly()||r;this.baseUrl=Ry(n),this.client=qc({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}getScopedApiClient(r){const s=this.normalizeCandidatePath(r)??r,n=s||"",o=this.scopedClients.get(n);if(o)return o;const a=qc({baseUrl:this.baseUrl,directory:s});return this.scopedClients.set(n,a),a}normalizeCandidatePath(r){if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const n=s.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const s=r.match(/^([A-Za-z]:)(?:\/|$)/);if(s){const a=s[1],c=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,s){if(r==null)return s();const n=this.currentDirectory;this.currentDirectory=r;try{return await s()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,s=o=>{const a=this.normalizeCandidatePath(o);a&&r.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(s(a.directory),s(a.worktree),s(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!r.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);s(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>s(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(s(this.currentDirectory),typeof window<"u")try{s(window.localStorage.getItem("lastDirectory")),s(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&s(process.cwd()),!r.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(r);return this.deriveHomeDirectory(n)}async probeDirectory(r){const s=this.normalizeCandidatePath(r);if(!s)return!1;try{const o=(await this.client.path.get({directory:s})).data,a=typeof o?.directory=="string"?o.directory:null;return!!(a&&a.trim().length>0)}catch{return!1}}async listSessions(){const r=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(r.data)?r.data:[]}async createSession(r){const s=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!s.data)throw new Error("Failed to create session");return s.data}async getSession(r){const s=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!s.data)throw new Error("Session not found");return s.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,s){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:s});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r,s){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof s=="number"?{limit:s}:{}})).data||[]}async getSessionTodos(r){try{const s=this.baseUrl.replace(/\/$/,""),n=new URL(`${s}/session/${encodeURIComponent(r)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(r){if(!r)return!1;const s=r.toLowerCase();return s.startsWith("text/")&&s!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript"].includes(s)}isHeicMime(r){if(!r)return!1;const s=r.toLowerCase();return s==="image/heic"||s==="image/heif"}async compressImage(r,s,n=.8,o=2048){return typeof document>"u"?r:new Promise(a=>{const l=new Image;l.onload=()=>{let c=l.width,d=l.height;(c>o||d>o)&&(c>d?(d=Math.round(d*(o/c)),c=o):(c=Math.round(c*(o/d)),d=o));const u=document.createElement("canvas");u.width=c,u.height=d;const m=u.getContext("2d");if(!m){a(r);return}m.drawImage(l,0,0,c,d);let f=s;s==="image/png"&&r.length>2.5*1024*1024&&(f="image/jpeg");try{a(u.toDataURL(f,n))}catch{a(r)}},l.onerror=()=>a(r),l.src=r})}async convertHeicToJpeg(r){try{const s=(await js(async()=>{const{default:f}=await import("./vendor-.bun-Bui932eM.js").then(p=>p.h);return{default:f}},__vite__mapDeps([0,1]))).default,n=r.url.indexOf(",");if(n===-1)return r;const o=r.url.substring(n+1),a=atob(o),l=new Uint8Array(a.length);for(let f=0;f<a.length;f++)l[f]=a.charCodeAt(f);const c=new Blob([l],{type:r.mime}),d=await s({blob:c,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const h=new FileReader;h.onload=()=>f(h.result),h.onerror=p,h.readAsDataURL(d)});let m=r.filename;return m&&(m=m.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:m,url:u}}catch(s){return console.warn("Failed to convert HEIC to JPEG:",s),r}}async normalizeFilePart(r){if(this.isHeicMime(r.mime))return this.convertHeicToJpeg(r);if(r.mime.startsWith("image/")&&(r.mime==="image/jpeg"||r.mime==="image/png"||r.mime==="image/webp")&&r.url.length>1.33*1024*1024){const n=await this.compressImage(r.url,r.mime),o=n.startsWith("data:image/jpeg")?"image/jpeg":r.mime;return{...r,mime:o,url:n}}if(!this.shouldNormalizeToTextPlain(r.mime))return r;let s=r.url;if(r.url.startsWith("data:")){const n=r.url.indexOf(",");if(n!==-1){const o=r.url.substring(5,n),a=r.url.substring(n);s=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:s}}async sendMessage(r){const s=Date.now(),n=r.messageId??`temp_${s}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.prefaceText&&r.prefaceText.trim()&&o.push({type:"text",text:r.prefaceText,synthetic:r.prefaceTextSynthetic!==!1}),r.text&&r.text.trim()){const a={type:"text",text:r.text};o.push(a)}if(r.files&&r.files.length>0)for(const a of r.files){const l=await this.normalizeFilePart(a),c={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(c)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text,...a.synthetic?{synthetic:!0}:{}}),a.files&&a.files.length>0)for(const l of a.files){const c=await this.normalizeFilePart(l),d={type:"file",mime:c.mime,filename:c.filename,url:c.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,variant:r.variant,parts:o}),n}async abortSession(r){return!!(await this.client.session.abort({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(r,s,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:s,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const s=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!s.data)throw new Error("Failed to unrevert session");return s.data}async forkSession(r,s){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:s});if(!n.data)throw new Error("Failed to fork session");return n.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(r){try{const s=this.baseUrl.replace(/\/$/,""),n=new URL(`${s}/session/status`),o=typeof r=="string"?r.trim():"";o.length>0&&n.searchParams.set("directory",o);const a=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const l=await a.json().catch(()=>null);return!l||typeof l!="object"?{}:l}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async getWebServerSessionActivity(){try{const r=await fetch("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return null;const s=await r.json().catch(()=>null);return!s||typeof s!="object"?null:s}catch{return null}}async listToolIds(r){try{const s=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(s?{directory:s}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(r,s,n){return(await this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:s,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async replyToQuestion(r,s){const n=!Array.isArray(s)||s.length===0?[]:Array.isArray(s[0])?s:[s];return(await this.client.question.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},answers:n})).data||!1}async rejectQuestion(r){return(await this.client.question.reject({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async listPendingQuestions(r){const s=[],n=async d=>{try{const u=typeof d=="string"?d.trim():"";return(await this.client.question.list(u?{directory:u}:void 0)).data||[]}catch{return[]}};s.push(n(null));const o=new Set;for(const d of r?.directories??[]){const u=this.normalizeCandidatePath(d??null);u&&o.add(u)}for(const d of o)s.push(n(d));const a=await Promise.all(s),l=[],c=new Set;for(const d of a)for(const u of d){if(!u||typeof u!="object")continue;const m=u.id;typeof m!="string"||m.length===0||c.has(m)||(c.add(m),l.push(u))}return l}async getConfig(){const r=await this.client.config.get();if(!r.data)throw new Error("Failed to get config");return r.data}async updateConfig(r){const s=`${this.baseUrl}/config`,n=await fetch(s,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(r){const s=await this.getConfig(),n=r(s);return await this.updateConfig(n)}async getProviders(){const r=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!r.data)throw new Error("Failed to get providers");return r.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]}catch{return[]}}parseSseBlock(r){if(!r)return null;const s=r.split(`
|
|
3
|
+
`),n=[];let o;for(const l of s)if(l.startsWith("data:"))n.push(l.slice(5).replace(/^\s/,""));else if(l.startsWith("id:")){const c=l.slice(3).trim();c&&(o=c)}if(n.length===0)return null;const a=n.join(`
|
|
4
|
+
`).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const s=r,n=typeof s.directory=="string"?s.directory:typeof s.properties=="object"&&s.properties!==null?s.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof s.type=="string")return{directory:o&&o.length>0?o:"global",payload:s};const a=s.payload;if(a&&typeof a=="object"){const l=a;if(typeof l.type=="string")return{directory:o&&o.length>0?o:"global",payload:l}}return null}emitGlobalSseEvent(r){for(const s of this.globalSseListeners)try{s(r)}catch(n){console.warn("[OpencodeClient] Global SSE listener error:",n)}}notifyGlobalSseOpen(){for(const r of this.globalSseOpenListeners)try{r()}catch(s){console.warn("[OpencodeClient] Global SSE open handler error:",s)}}notifyGlobalSseError(r){for(const s of this.globalSseErrorListeners)try{s(r)}catch(n){console.warn("[OpencodeClient] Global SSE error handler failed:",n)}}ensureGlobalSseStarted(){if(this.globalSseTask)return;const r=new AbortController;this.globalSseAbortController=r,this.globalSseTask=this.runGlobalSseLoop(r).catch(s=>{s?.name==="AbortError"||r.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",s)}).finally(()=>{this.globalSseAbortController===r&&(this.globalSseAbortController=null),this.globalSseTask=null,this.globalSseIsConnected=!1})}maybeStopGlobalSse(){this.globalSseListeners.size>0||(this.globalSseAbortController&&!this.globalSseAbortController.signal.aborted&&this.globalSseAbortController.abort(),this.globalSseAbortController=null)}async runGlobalSseLoop(r){const s=`${this.baseUrl.replace(/\/+$/,"")}/global/event`;let n=0;for(;!r.signal.aborted;){try{const a={Accept:"text/event-stream","Cache-Control":"no-cache"};this.globalSseLastEventId&&(a["Last-Event-ID"]=this.globalSseLastEventId);const l=await fetch(s,{method:"GET",headers:a,signal:r.signal});if(!l.ok||!l.body)throw new Error(`Global SSE connect failed with status ${l.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const c=l.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await c.read();if(f||r.signal.aborted)break;if(!p||p.length===0)continue;u+=d.decode(p,{stream:!0}).replace(/\r\n/g,`
|
|
5
|
+
`);const h=u.split(`
|
|
6
|
+
|
|
7
|
+
`);u=h.pop()??"";for(const g of h){const x=this.parseSseBlock(g);if(!x)continue;x.id&&(this.globalSseLastEventId=x.id);const b=this.normalizeRoutedSsePayload(x.data);b&&this.emitGlobalSseEvent(b)}}const m=u.trim();if(m&&!r.signal.aborted){const f=this.parseSseBlock(m);f?.id&&(this.globalSseLastEventId=f.id);const p=f?this.normalizeRoutedSsePayload(f.data):null;p&&this.emitGlobalSseEvent(p)}this.globalSseIsConnected=!1}catch(a){if(this.globalSseIsConnected=!1,a?.name==="AbortError"||r.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",a),this.notifyGlobalSseError(a)}if(r.signal.aborted)break;n+=1;const o=Math.min(3e3*Math.pow(2,n),3e4);await new Promise(a=>setTimeout(a,o))}}subscribeToGlobalEvents(r,s,n,o){const a=this.normalizeCandidatePath(o?.directory??null),l=c=>{a&&c.directory!==a||r(c)};return this.globalSseListeners.add(l),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(c){console.warn("[OpencodeClient] Global SSE open handler error:",c)}},0)),s&&this.globalSseErrorListeners.add(s),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(l),n&&this.globalSseOpenListeners.delete(n),s&&this.globalSseErrorListeners.delete(s),this.maybeStopGlobalSse()}}subscribeToEvents(r,s,n,o,a){const l=a?.key??"default",c=a?.scope??"directory",d=this.sseAbortControllers.get(l);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(l,u);let m;if(c==="global"){let p=null;const h=x=>{if(x.directory==="global")return x.payload;const b=x.payload,y=typeof b.properties=="object"&&b.properties!==null?b.properties:{};return y.directory===x.directory?x.payload:{...b,properties:{...y,directory:x.directory}}},g=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)};return u.signal.addEventListener("abort",g,{once:!0}),p=this.subscribeToGlobalEvents(x=>{u.signal.aborted||r(h(x))},s?x=>{u.signal.aborted||s(x)}:void 0,n?()=>{u.signal.aborted||n()}:void 0),()=>{g(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const h=p;if(typeof h.type=="string")return h;const g=h.payload;if(g&&typeof g=="object"){const x=g;if(typeof x.type=="string"){if(typeof h.directory=="string"&&h.directory.length>0){const y={...(typeof x.properties=="object"&&x.properties!==null?x.properties:null)??{},directory:h.directory};return{...x,properties:y}}return x}}return null};return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const p=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",p??"default");const h=async g=>{try{const x=p?{directory:p}:void 0,b={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:w=>{w instanceof Error&&w.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",w),s&&!u.signal.aborted&&s(w))},onSseEvent:w=>{if(u.signal.aborted)return;w.id&&typeof w.id=="string"&&(m=w.id);const S=w.data,M=f(S);M&&r(M)}};m&&(b.headers={...b.headers||{},"Last-Event-ID":m});const y=await this.client.event.subscribe(x,b);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const w of y.stream)if(u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(x){if(x?.name==="AbortError"||u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",x),s&&s(x);const b=Math.min(3e3*Math.pow(2,g),3e4);await new Promise(y=>setTimeout(y,b)),u.signal.aborted||await h(g+1);return}if(!u.signal.aborted){const x=Math.min(3e3*Math.pow(2,g),3e4);await new Promise(b=>setTimeout(b,x)),await h(g+1)}};try{await h(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)}})(),()=>{this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l),u.abort()}}async readFile(r){try{const s=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,directory:this.currentDirectory})});if(!s.ok)throw new Error(`Failed to read file: ${s.statusText}`);return await s.text()}catch{return`// Content of ${r}
|
|
8
|
+
// This would be loaded from the server`}}async listFiles(r){try{const s=r||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:s})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(s=>({name:s.name,description:s.description,agent:s.agent,model:s.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(s=>({name:s.name,description:s.description,agent:s.agent,model:s.model,template:s.template,subtask:s.subtask}))}catch{return[]}}async getCommandDetails(r){try{const s=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(s.data){const n=s.data.find(o=>o.name===r);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{let r;const s=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;s==="/api"?r="/health":s.endsWith("/api")?r=`${s.slice(0,-4)}/health`:r=`${s}/health`;const n=await fetch(r);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(r){const s=Li();if(s?.createDirectory)try{return await s.createDirectory(r)}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(l||"Failed to create directory")}const n=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!n.ok){const a=await n.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await n.json()}async listLocalDirectory(r,s){const n=Li();if(n)try{const o=await n.listDirectory(r||"",s);return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:Zo(a.path),isDirectory:!!a.isDirectory,isFile:!a.isDirectory,isSymbolicLink:!1}))}catch(o){throw console.error("Failed to list directory contents:",o),o}try{const o=new URLSearchParams;r&&r.trim().length>0&&o.set("path",r),s?.respectGitignore&&o.set("respectGitignore","true");const a=o.toString(),l=await fetch(`${this.baseUrl}/fs/list${a?`?${a}`:""}`);if(!l.ok){const d=await l.json().catch(()=>({})),u=typeof d.error=="string"?d.error:"Failed to list directory";throw new Error(u)}const c=await l.json();return!c||!Array.isArray(c.entries)?[]:c.entries}catch(o){throw console.error("Failed to list directory contents:",o),o}}async searchFiles(r,s){const n=Li(),o=typeof s?.directory=="string"&&s.directory.trim().length>0?s.directory.trim():this.currentDirectory,a=o?Zo(o):null;if(n)try{const m=await n.search({directory:o||"",query:r,maxResults:s?.limit,includeHidden:s?.includeHidden,respectGitignore:s?.respectGitignore});return Array.isArray(m)?m.map(f=>{const p=Zo(f.path),h=p.split("/").filter(Boolean).pop()||p,g=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?Zo(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:g,extension:h.includes(".")?h.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const l=new URLSearchParams;o&&o.length>0&&l.set("directory",o),typeof r=="string"&&l.set("q",r),typeof s?.limit=="number"&&Number.isFinite(s.limit)&&l.set("limit",String(s.limit)),s?.includeHidden&&l.set("includeHidden","true"),s?.respectGitignore===!1&&l.set("respectGitignore","false");const c=`${this.baseUrl}/fs/search${l.toString()?`?${l.toString()}`:""}`,d=await fetch(c,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await fc();if(r)return r;try{const s=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!s.ok){const o=await s.json().catch(()=>({})),a=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(a)}const n=await s.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(s){return console.warn("Failed to resolve filesystem home directory:",s),null}}async setOpenCodeWorkingDirectory(r){if(!r||typeof r!="string"||!r.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",r),null;const s=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",s,"with path:",r);try{const n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})}),o=await n.json().catch(()=>null);if(!n.ok){const a=o??{},l=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(l)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:r}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const Oe=new Oy,_y=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:Oe},Symbol.toStringTag,{value:"Module"})),Il=new Set;function gi(t){return Il.add(t),()=>{Il.delete(t)}}function jr(t,r){const s=Array.isArray(t)?t:[t],n=Array.from(new Set(s));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:r?.source,timestamp:Date.now()};for(const a of Il)try{const l=a(o);l instanceof Promise&&l.catch(c=>{console.error("[ConfigSync] Async listener failed:",c)})}catch(l){console.error("[ConfigSync] Listener threw:",l)}}function Fo(t,r){return t.scopes.includes("all")||t.scopes.includes(r)}const hc="Updating OpenCode configuration...";let Sr=0,en=hc;const Pl=new Set;function qa(){const t={isUpdating:Sr>0,message:en};Pl.forEach(r=>r(t))}function Us(t){Sr+=1,Sr===1?(en=t||hc,qa()):t&&(en=t,qa())}function _s(){Sr!==0&&(Sr-=1,Sr===0&&(en=hc,qa()))}function _r(t){en===t&&Sr>0||(en=t,Sr>0&&qa())}function $y(t){return Pl.add(t),t({isUpdating:Sr>0,message:en}),()=>{Pl.delete(t)}}function By(){return{isUpdating:Sr>0,message:en}}const wr=is()(hs(qs((t,r)=>({queuedMessages:{},queueModeEnabled:!0,addToQueue:(s,n)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};t(l=>{const c=l.queuedMessages[s]??[];return{queuedMessages:{...l.queuedMessages,[s]:[...c,a]}}})},removeFromQueue:(s,n)=>{t(o=>{const l=(o.queuedMessages[s]??[]).filter(c=>c.id!==n);if(l.length===0){const{[s]:c,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[s]:l}}})},popToInput:(s,n)=>{const l=(r().queuedMessages[s]??[]).find(c=>c.id===n);return l?(t(c=>{const u=(c.queuedMessages[s]??[]).filter(m=>m.id!==n);if(u.length===0){const{[s]:m,...f}=c.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...c.queuedMessages,[s]:u}}}),l):null},clearQueue:s=>{t(n=>{const{[s]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:s=>{t({queueModeEnabled:s}),cs({queueModeEnabled:s})},getQueueForSession:s=>r().queuedMessages[s]??[]}),{name:"message-queue-store",storage:Ks(()=>Ss()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),xf="directoryTreeShowHidden",Tl="directory-show-hidden-change",id=()=>{if(typeof window>"u")return!0;try{const t=Ss().getItem(xf);return t===null?!0:t==="true"}catch{return!0}},zy=()=>{typeof window>"u"||window.dispatchEvent(new Event(Tl))},gc=(t,r={})=>{if(!(typeof window>"u")){try{Ss().setItem(xf,t?"true":"false"),zy()}catch{}r.persist!==!1&&cs({directoryShowHidden:t})}},Vo=()=>{const[t,r]=i.useState(id);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(id())};return window.addEventListener("storage",s),window.addEventListener(Tl,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Tl,s)}},[]),t},yf="filesViewShowGitignored",Fl="files-view-show-gitignored-change",ld=()=>{if(typeof window>"u")return!1;try{return Ss().getItem(yf)==="true"}catch{return!1}},Hy=()=>{typeof window>"u"||window.dispatchEvent(new Event(Fl))},bf=(t,r={})=>{if(!(typeof window>"u")){try{Ss().setItem(yf,t?"true":"false"),Hy()}catch{}r.persist!==!1&&cs({filesViewShowGitignored:t})}},xi=()=>{const[t,r]=i.useState(ld);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(ld())};return window.addEventListener("storage",s),window.addEventListener(Fl,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Fl,s)}},[]),t},cd=t=>{if(!t||typeof t!="object")return null;const r={};return typeof t.showReasoningTraces=="boolean"&&(r.showReasoningTraces=t.showReasoningTraces),Object.keys(r).length>0?r:null},Wy=t=>!t||typeof t!="object"?null:{showReasoningTraces:t.showReasoningTraces},Uy=t=>{const r=Me.getState();typeof t.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(t.showReasoningTraces)},Vy=async()=>{if(typeof window>"u")return null;if(ms()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const s=await r.load();return cd(typeof s=="object"&&s!==null?s:null)}catch(s){return console.warn("Failed to load appearance preferences from desktop storage:",s),null}}const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const r=JSON.parse(t),s=Wy(r);return cd(s)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let wf=null;const dd=t=>{wf=t},Ps=()=>wf,Ma=t=>{typeof window>"u"||(t.themeId&&localStorage.setItem("selectedThemeId",t.themeId),t.themeVariant&&localStorage.setItem("selectedThemeVariant",t.themeVariant),t.lightThemeId&&localStorage.setItem("lightThemeId",t.lightThemeId),t.darkThemeId&&localStorage.setItem("darkThemeId",t.darkThemeId),typeof t.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(t.useSystemTheme)),t.lastDirectory&&localStorage.setItem("lastDirectory",t.lastDirectory),t.homeDirectory&&(localStorage.setItem("homeDirectory",t.homeDirectory),window.__OPENCHAMBER_HOME__=t.homeDirectory),Array.isArray(t.projects)&&t.projects.length>0?localStorage.setItem("projects",JSON.stringify(t.projects)):localStorage.removeItem("projects"),t.activeProjectId?localStorage.setItem("activeProjectId",t.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(t.pinnedDirectories)&&t.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(t.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),typeof t.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(t.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof t.directoryShowHidden=="boolean"&&localStorage.setItem("directoryTreeShowHidden",t.directoryShowHidden?"true":"false"),typeof t.filesViewShowGitignored=="boolean"&&localStorage.setItem("filesViewShowGitignored",t.filesViewShowGitignored?"true":"false"))},Gy=t=>{if(!Array.isArray(t))return;const r=[],s=new Set;for(const n of t){if(!n||typeof n!="object")continue;const o=n,a=typeof o.id=="string"?o.id.trim():"",l=typeof o.label=="string"?o.label.trim():"",c=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!l||!c||s.has(a)||(s.add(a),r.push({id:a,label:l,source:c,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},qy=t=>{if(!Array.isArray(t))return;const r=[],s=new Set,n=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=c==="/"?c:c.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||s.has(l)||n.has(d))continue;s.add(l),n.add(d);const u={id:l,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.baseBranch=="string"&&m.baseBranch.trim()&&(f.baseBranch=m.baseBranch.trim()),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r.length>0?r:void 0},vf=()=>{const t=Me.persist;if(t&&typeof t=="object")return t},jf=()=>Ps()?.settings??null,Da=t=>{const r=Me.getState(),s=wr.getState();if(typeof t.showReasoningTraces=="boolean"&&t.showReasoningTraces!==r.showReasoningTraces&&r.setShowReasoningTraces(t.showReasoningTraces),typeof t.autoDeleteEnabled=="boolean"&&t.autoDeleteEnabled!==r.autoDeleteEnabled&&r.setAutoDeleteEnabled(t.autoDeleteEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)){const n=Math.max(1,Math.min(365,t.autoDeleteAfterDays));n!==r.autoDeleteAfterDays&&r.setAutoDeleteAfterDays(n)}typeof t.memoryLimitHistorical=="number"&&Number.isFinite(t.memoryLimitHistorical)&&r.setMemoryLimitHistorical(t.memoryLimitHistorical),typeof t.memoryLimitViewport=="number"&&Number.isFinite(t.memoryLimitViewport)&&r.setMemoryLimitViewport(t.memoryLimitViewport),typeof t.memoryLimitActiveSession=="number"&&Number.isFinite(t.memoryLimitActiveSession)&&r.setMemoryLimitActiveSession(t.memoryLimitActiveSession),typeof t.queueModeEnabled=="boolean"&&t.queueModeEnabled!==s.queueModeEnabled&&s.setQueueMode(t.queueModeEnabled),typeof t.showTextJustificationActivity=="boolean"&&t.showTextJustificationActivity!==r.showTextJustificationActivity&&r.setShowTextJustificationActivity(t.showTextJustificationActivity),typeof t.nativeNotificationsEnabled=="boolean"&&t.nativeNotificationsEnabled!==r.nativeNotificationsEnabled&&r.setNativeNotificationsEnabled(t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&t.notificationMode!==r.notificationMode&&r.setNotificationMode(t.notificationMode),typeof t.toolCallExpansion=="string"&&(t.toolCallExpansion==="collapsed"||t.toolCallExpansion==="activity"||t.toolCallExpansion==="detailed")&&t.toolCallExpansion!==r.toolCallExpansion&&r.setToolCallExpansion(t.toolCallExpansion),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&t.fontSize!==r.fontSize&&r.setFontSize(t.fontSize),typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding!==r.padding&&r.setPadding(t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&t.cornerRadius!==r.cornerRadius&&r.setCornerRadius(t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&t.inputBarOffset!==r.inputBarOffset&&r.setInputBarOffset(t.inputBarOffset),typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&t.diffLayoutPreference!==r.diffLayoutPreference&&r.setDiffLayoutPreference(t.diffLayoutPreference),typeof t.diffViewMode=="string"&&(t.diffViewMode==="single"||t.diffViewMode==="stacked")&&t.diffViewMode!==r.diffViewMode&&r.setDiffViewMode(t.diffViewMode),typeof t.directoryShowHidden=="boolean"&&gc(t.directoryShowHidden,{persist:!1}),typeof t.filesViewShowGitignored=="boolean"&&bf(t.filesViewShowGitignored,{persist:!1})},ud=t=>{if(!t||typeof t!="object")return null;const r=t,s={};typeof r.themeId=="string"&&r.themeId.length>0&&(s.themeId=r.themeId),(r.useSystemTheme===!0||r.useSystemTheme===!1)&&(s.useSystemTheme=r.useSystemTheme),typeof r.themeVariant=="string"&&(r.themeVariant==="light"||r.themeVariant==="dark")&&(s.themeVariant=r.themeVariant),typeof r.lightThemeId=="string"&&r.lightThemeId.length>0&&(s.lightThemeId=r.lightThemeId),typeof r.darkThemeId=="string"&&r.darkThemeId.length>0&&(s.darkThemeId=r.darkThemeId),typeof r.lastDirectory=="string"&&r.lastDirectory.length>0&&(s.lastDirectory=r.lastDirectory),typeof r.homeDirectory=="string"&&r.homeDirectory.length>0&&(s.homeDirectory=r.homeDirectory);const n=qy(r.projects);n&&(s.projects=n),typeof r.activeProjectId=="string"&&r.activeProjectId.length>0&&(s.activeProjectId=r.activeProjectId),Array.isArray(r.approvedDirectories)&&(s.approvedDirectories=r.approvedDirectories.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.securityScopedBookmarks)&&(s.securityScopedBookmarks=r.securityScopedBookmarks.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.pinnedDirectories)&&(s.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(a=>typeof a=="string"&&a.length>0)))),typeof r.showReasoningTraces=="boolean"&&(s.showReasoningTraces=r.showReasoningTraces),typeof r.autoDeleteEnabled=="boolean"&&(s.autoDeleteEnabled=r.autoDeleteEnabled),typeof r.autoDeleteAfterDays=="number"&&Number.isFinite(r.autoDeleteAfterDays)&&(s.autoDeleteAfterDays=r.autoDeleteAfterDays),typeof r.defaultModel=="string"&&r.defaultModel.length>0&&(s.defaultModel=r.defaultModel),typeof r.defaultVariant=="string"&&r.defaultVariant.length>0&&(s.defaultVariant=r.defaultVariant),typeof r.defaultAgent=="string"&&r.defaultAgent.length>0&&(s.defaultAgent=r.defaultAgent),typeof r.autoCreateWorktree=="boolean"&&(s.autoCreateWorktree=r.autoCreateWorktree),typeof r.gitmojiEnabled=="boolean"&&(s.gitmojiEnabled=r.gitmojiEnabled),typeof r.queueModeEnabled=="boolean"&&(s.queueModeEnabled=r.queueModeEnabled),typeof r.showTextJustificationActivity=="boolean"&&(s.showTextJustificationActivity=r.showTextJustificationActivity),typeof r.nativeNotificationsEnabled=="boolean"&&(s.nativeNotificationsEnabled=r.nativeNotificationsEnabled),typeof r.notificationMode=="string"&&(r.notificationMode==="always"||r.notificationMode==="hidden-only")&&(s.notificationMode=r.notificationMode),typeof r.toolCallExpansion=="string"&&(r.toolCallExpansion==="collapsed"||r.toolCallExpansion==="activity"||r.toolCallExpansion==="detailed")&&(s.toolCallExpansion=r.toolCallExpansion),typeof r.fontSize=="number"&&Number.isFinite(r.fontSize)&&(s.fontSize=r.fontSize),typeof r.padding=="number"&&Number.isFinite(r.padding)&&(s.padding=r.padding),typeof r.cornerRadius=="number"&&Number.isFinite(r.cornerRadius)&&(s.cornerRadius=r.cornerRadius),typeof r.inputBarOffset=="number"&&Number.isFinite(r.inputBarOffset)&&(s.inputBarOffset=r.inputBarOffset),typeof r.diffLayoutPreference=="string"&&(r.diffLayoutPreference==="dynamic"||r.diffLayoutPreference==="inline"||r.diffLayoutPreference==="side-by-side")&&(s.diffLayoutPreference=r.diffLayoutPreference),typeof r.diffViewMode=="string"&&(r.diffViewMode==="single"||r.diffViewMode==="stacked")&&(s.diffViewMode=r.diffViewMode),typeof r.directoryShowHidden=="boolean"&&(s.directoryShowHidden=r.directoryShowHidden),typeof r.filesViewShowGitignored=="boolean"&&(s.filesViewShowGitignored=r.filesViewShowGitignored),typeof r.memoryLimitHistorical=="number"&&Number.isFinite(r.memoryLimitHistorical)&&(s.memoryLimitHistorical=r.memoryLimitHistorical),typeof r.memoryLimitViewport=="number"&&Number.isFinite(r.memoryLimitViewport)&&(s.memoryLimitViewport=r.memoryLimitViewport),typeof r.memoryLimitActiveSession=="number"&&Number.isFinite(r.memoryLimitActiveSession)&&(s.memoryLimitActiveSession=r.memoryLimitActiveSession);const o=Gy(r.skillCatalogs);return o&&(s.skillCatalogs=o),s},Ky=async()=>{const t=jf();if(t)try{const r=await t.load();return ud(r.settings)}catch(r){console.warn("Failed to load shared settings from runtime settings API:",r)}try{const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return null;const s=await r.json().catch(()=>null);return ud(s)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},Sf=async()=>{if(typeof window>"u")return;const t=vf(),r=s=>{Ma(s);const n=()=>Da(s);if(t?.hasHydrated?.())n();else if(n(),t?.onFinishHydration){const o=t.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:s}))};try{const s=ms()?await Br():await Ky();s&&r(s)}catch(s){console.warn("Failed to synchronise settings:",s)}},cs=async t=>{if(typeof window>"u")return;if(ms()){try{const s=await vy(t);s&&(Ma(s),Da(s))}catch(s){console.warn("Failed to update desktop settings:",s)}return}const r=jf();if(r)try{const s=await r.save(t);s&&(Ma(s),Da(s));return}catch(s){console.warn("Failed to update settings via runtime settings API:",s)}try{const s=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!s.ok){console.warn("Failed to update shared settings via API:",s.status,s.statusText);return}const n=await s.json().catch(()=>null);n&&(Ma(n),Da(n))}catch(s){console.warn("Failed to update shared settings via API:",s)}},Nf=async()=>{if(typeof window>"u")return;const t=vf();try{const r=await Vy();if(!r)return;const s=()=>Uy(r);if(t?.hasHydrated?.()){s();return}if(s(),t?.onFinishHydration){const n=t.onFinishHydration(()=>{n?.(),s()})}}catch(r){console.warn("Failed to load appearance preferences:",r)}},Yy=3e4,Qy=40,Jy=60,Xy=(t,r,s,n,o)=>{const a=t.trim(),l=r.trim().toLowerCase();return`${a}::${l}::${s}::${n?"1":"0"}::${o?"1":"0"}`},yi=is()(hs((t,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,n,o=Jy,a){if(!s||s.trim().length===0)return[];const l=s.trim(),c=typeof n=="string"?n.trim():"",d=!!a?.includeHidden,u=a?.respectGitignore??!0,m=Xy(l,c,o,d,u),f=Date.now(),p=r().cache[m];if(p&&f-p.timestamp<Yy)return p.files;const h=r().inFlight[m];if(h)return h;const g=Oe.searchFiles(c,{directory:l,limit:o,includeHidden:d,respectGitignore:u}).then(x=>(t(b=>{const y={...b.cache,[m]:{files:x,timestamp:Date.now()}},w=b.cacheKeys.filter(S=>S!==m);for(w.push(m);w.length>Qy;){const S=w.shift();S&&delete y[S]}return{cache:y,cacheKeys:w}}),x)).finally(()=>{t(x=>{const b={...x.inFlight};return delete b[m],{inFlight:b}})});return t(x=>({inFlight:{...x.inFlight,[m]:g}})),g},invalidateDirectory(s){if(!s||s.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${s.trim()}::`;t(a=>{const l={...a.cache},c=a.cacheKeys.filter(m=>m.startsWith(o)?(delete l[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:l,cacheKeys:c,inFlight:u}})}}),{name:"file-search-store"})),xs=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var Zy={};let dr=null;const cr=Ss(),md=cr.getItem("lastDirectory"),eb=typeof md=="string"&&md.length>0,ea=t=>{try{yi.getState().invalidateDirectory(t)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},kf=t=>{const r=t.trim();if(!r)return r;const s=r.replace(/\\/g,"/");return s.length>1?s.replace(/\/+$/,""):s},tb=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},Aa=(t,r)=>{const s=tb(t,r);return kf(s)},Ka=()=>{if(typeof window<"u"){const r=cr.getItem("homeDirectory")||dr||null,s=cr.getItem("lastDirectory");if(s&&!zt())return Aa(s,r);if(dr)return dr;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 dr=n,cr.setItem("homeDirectory",n),n;if(r&&!zt())return dr=r,r}const t=typeof process<"u"&&Zy?.HOME;return t||process?.cwd?.()||"/"},sb=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");if(s.length>1){const n=s.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return s==="/"||s.length===0?null:s},rb=t=>(dr=t,typeof window<"u"&&cr.setItem("homeDirectory",t),cs({homeDirectory:t}),t),Cf=async()=>{const t=n=>{const o=sb(n);return o?rb(o):null};try{const n=await Oe.getFilesystemHome(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Oe.getSystemInfo(),o=t(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await fc(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=Ka(),s=t(r);return s||r},nb=()=>{if(!zt())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const r=kf(t);return r.length>0?r:null},xn=nb()||Ka();xn&&Oe.setDirectory(xn);const ob=!!(xn&&xn!=="/"),xt=is()(hs((t,r)=>({currentDirectory:xn,directoryHistory:[xn],historyIndex:0,homeDirectory:xn,hasPersistedDirectory:eb,isHomeReady:ob,isSwitchingDirectory:!1,setDirectory:(s,n)=>{const o=dr||r().homeDirectory||cr.getItem("homeDirectory"),a=Aa(s,o);xs()&&console.log("[DirectoryStore] setDirectory called with path:",a),Oe.setDirectory(a),ea(),t(l=>{const c=[...l.directoryHistory.slice(0,l.historyIndex+1),a];return cr.setItem("lastDirectory",a),cs({lastDirectory:a}),{currentDirectory:a,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const s=r();if(s.historyIndex>0){const n=s.historyIndex-1,o=s.directoryHistory[n];Oe.setDirectory(o),ea(),cr.setItem("lastDirectory",o),cs({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const s=r();if(s.historyIndex<s.directoryHistory.length-1){const n=s.historyIndex+1,o=s.directoryHistory[n];Oe.setDirectory(o),ea(),cr.setItem("lastDirectory",o),cs({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:s,setDirectory:n}=r(),o=dr||r().homeDirectory||Ka();if(s===o||s==="/")return;const a=s.endsWith("/")?s.slice(0,-1):s,l=a.lastIndexOf("/");if(l===-1){const c=dr||Ka();n(c)}else n(l===0?"/":a.substring(0,l))},goHome:async()=>{const s=dr||r().homeDirectory||await Cf();r().setDirectory(s)},synchronizeHomeDirectory:s=>{const n=r(),o=s;dr=o;const a=n.homeDirectory!==o,l=cr.getItem("lastDirectory"),c=typeof l=="string"&&l.length>0,d=!c&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||t({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",m=n.currentDirectory?Aa(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(x=>Aa(x,o)),p=f.some((x,b)=>x!==n.directoryHistory[b]),h=!!(m&&m!==n.currentDirectory),g={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d?(g.currentDirectory=o,g.directoryHistory=[o],g.historyIndex=0,g.isSwitchingDirectory=!1):(h||p)&&(g.currentDirectory=m,g.directoryHistory=f,g.historyIndex=Math.min(n.historyIndex,f.length-1),g.isSwitchingDirectory=!1),t(()=>g),(d||h)&&u){const x=d?o:m;Oe.setDirectory(x),ea(),cr.setItem("lastDirectory",x),cs({lastDirectory:x})}cs({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Cf().then(t=>{xt.getState().synchronizeHomeDirectory(t)});const qn=Ss(),Mf="projects",Rl="activeProjectId",ab=(t,r)=>{const s=t.trim();return!s.startsWith("~")||!r?s:s==="~"?r:s.startsWith("~/")||s.startsWith("~\\")?`${r}${s.slice(1)}`:s},bi=t=>{const r=t.trim();if(!r)return"";const s=qn.getItem("homeDirectory")||xt.getState().homeDirectory||"",o=ab(r,s).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},Df=t=>{const r=bi(t);if(!r||r==="/")return"Root";const s=r.split("/").filter(Boolean);return s[s.length-1]||r},ib=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Af=t=>{if(!Array.isArray(t))return[];const r=[],s=new Set,n=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=bi(c);if(!d||s.has(l)||n.has(d))continue;s.add(l),n.add(d);const u={id:l,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.baseBranch=="string"&&(f.baseBranch=m.baseBranch),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r},lb=()=>{try{const t=qn.getItem(Mf);return t?Af(JSON.parse(t)):[]}catch{return[]}},cb=()=>{try{const t=qn.getItem(Rl);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},xc=(t,r)=>{try{qn.setItem(Mf,JSON.stringify(t))}catch{}try{r?qn.setItem(Rl,r):qn.removeItem(Rl)}catch{}},Pn=(t,r)=>{xc(t,r),cs({projects:t,activeProjectId:r??void 0})},db=lb(),ub=()=>{if(typeof window>"u"||!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode)return null;const r=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof r!="string"||r.trim().length===0)return null;const s=bi(r);if(!s)return null;const n=`vscode:${s}`,o={id:n,path:s,label:Df(s),addedAt:Date.now(),lastOpenedAt:Date.now()};return xs()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},ir=ub(),yc=ir?.projects??db,Ef=ir?.activeProjectId??cb()??yc[0]?.id??null;ir&&xc(yc,Ef);const Ft=is()(hs((t,r)=>({projects:yc,activeProjectId:Ef,validateProjectPath:s=>{if(typeof s!="string"||s.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=bi(s);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(s,n)=>{if(ir)return null;const{validateProjectPath:o}=r(),a=o(s);if(!a.ok||!a.normalizedPath)return null;const l=a.normalizedPath,c=r().projects.find(g=>g.path===l);if(c)return r().setActiveProject(c.id),c;const d=Date.now(),u=n?.label?.trim()||Df(l),m=n?.id?.trim(),p={id:m&&!r().projects.some(g=>g.id===m)?m:ib(),path:l,label:u,addedAt:d,lastOpenedAt:d},h=[...r().projects,p];return t({projects:h}),xs()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:s=>{if(ir)return;const n=r(),o=n.projects.filter(l=>l.id!==s);let a=n.activeProjectId;if(n.activeProjectId===s&&(a=o[0]?.id??null),t({projects:o,activeProjectId:a}),Pn(o,a),a){const l=o.find(c=>c.id===a);l&&(Oe.setDirectory(l.path),xt.getState().setDirectory(l.path,{showOverlay:!1}))}else xt.getState().goHome()},setActiveProject:s=>{if(ir)return;const{projects:n,activeProjectId:o}=r();if(o===s)return;const a=n.find(d=>d.id===s);if(!a)return;const l=Date.now(),c=n.map(d=>d.id===s?{...d,lastOpenedAt:l}:d);t({projects:c,activeProjectId:s}),Pn(c,s),Oe.setDirectory(a.path),xt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:s=>{if(ir)return;const{projects:n,activeProjectId:o}=r();if(o===s||!n.find(d=>d.id===s))return;const l=Date.now(),c=n.map(d=>d.id===s?{...d,lastOpenedAt:l}:d);t({projects:c,activeProjectId:s}),Pn(c,s)},renameProject:(s,n)=>{if(ir)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:l}=r(),c=a.map(d=>d.id===s?{...d,label:o}:d);t({projects:c}),Pn(c,l)},reorderProjects:(s,n)=>{if(ir)return;const{projects:o,activeProjectId:a}=r();if(s<0||s>=o.length||n<0||n>=o.length||s===n)return;const l=[...o],[c]=l.splice(s,1);l.splice(n,0,c),t({projects:l}),Pn(l,a)},synchronizeFromSettings:s=>{if(ir)return;const n=Af(s.projects??[]),o=typeof s.activeProjectId=="string"&&s.activeProjectId.trim()?s.activeProjectId.trim():null,a=r(),l=JSON.stringify(a.projects)!==JSON.stringify(n),c=a.activeProjectId!==o;if(!(!l&&!c)&&(t({projects:n,activeProjectId:o}),xc(n,o),o)){const d=n.find(u=>u.id===o);d&&(Oe.setDirectory(d.path),xt.getState().setDirectory(d.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:s,activeProjectId:n}=r();return n?s.find(o=>o.id===n)??null:null},updateWorktreeDefaults:(s,n)=>{if(ir)return;const{projects:o,activeProjectId:a}=r(),l=o.find(u=>u.id===s);if(!l)return;const c={...l.worktreeDefaults};n.baseBranch!==void 0&&(n.baseBranch.trim()?c.baseBranch=n.baseBranch.trim():delete c.baseBranch),n.autoCreateWorktree!==void 0&&(c.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===s?{...u,worktreeDefaults:Object.keys(c).length>0?c:void 0}:u);t({projects:d}),Pn(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",t=>{const r=t.detail;r&&typeof r=="object"&&Ft.getState().synchronizeFromSettings(r)});const mb=new Set(["init","review"]),Wn=t=>mb.has(t.name),Co="useCommandsStore",Ll=t=>new Promise(r=>setTimeout(r,t)),ta=()=>{try{const r=Ft.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const s=Oe.getDirectory();if(s?.trim())return s.trim()}catch(t){console.warn("[CommandsStore] Error resolving config directory:",t)}return null},fb=2e4,fd=300,pd=4,pb=800,hb=200,gb=2e3,nn=is()(hs(qs((t,r)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:s=>{t({selectedCommandName:s})},setCommandDraft:s=>{t({commandDraft:s})},loadCommands:async()=>{t({isLoading:!0});const s=r().commands;let n=null;for(let o=0;o<3;o++)try{const a=ta(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await Oe.withDirectory(a,()=>Oe.listCommandsWithDetails()),d=await Promise.all(c.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${l}`,{headers:{"Cache-Control":"no-cache",...a?{"x-opencode-directory":a}:{}}});if(m.ok){const f=await m.json();let p=f.scope;if(!p&&f.sources){const h=f.sources;p=(h.md?.exists?h.md.scope:void 0)??(h.json?.exists?h.json.scope:void 0)??h.md?.scope??h.json?.scope}return p==="project"||p==="user"?{...u,scope:p}:{...u,scope:void 0}}}catch(m){console.warn(`[CommandsStore] Failed to fetch config for command ${u.name}:`,m)}return u}));return JSON.stringify(s)!==JSON.stringify(d)?t({commands:d,isLoading:!1}):t({isLoading:!1}),!0}catch(a){n=a;const l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load commands:",n),t({commands:s,isLoading:!1}),!1},createCommand:async s=>{Us("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",s.name);const o={template:s.template||""};s.description&&(o.description=s.description),s.agent&&(o.agent=s.agent),s.model&&(o.model=s.model),s.subtask!==void 0&&(o.subtask=s.subtask),s.scope&&(o.scope=s.scope),console.log("[CommandsStore] Command config to save:",o);const a=ta(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(s.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await Oi({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&jr("commands",{source:Co}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||_s()}},updateCommand:async(s,n)=>{Us("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",s),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const l=ta(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(s)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),u?.requiresReload??!0)return o=!0,await Oi({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&jr("commands",{source:Co}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||_s()}},deleteCommand:async s=>{Us("Deleting command configuration…");let n=!1;try{const o=ta(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),c?.requiresReload??!0)return n=!0,await Oi({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&jr("commands",{source:Co}),r().selectedCommandName===s&&t({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||_s()}},getCommandByName:s=>{const{commands:n}=r();return n.find(o=>o.name===s)}}),{name:"commands-store",storage:Ks(()=>Ss()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=nn);async function xb(t){const r=typeof t=="number"&&t>0?Math.min(t,fd):0;r>0&&await Ll(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<fb;){n+=1,_r(`Waiting for OpenCode… (attempt ${n})`);try{if(await Oe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-s,l=n<=pd&&a<1200?fd:Math.min(pb+Math.max(0,n-pd)*hb,gb);await Ll(l)}throw o||new Error("OpenCode did not become ready in time")}async function Oi(t={}){const{message:r,delayMs:s}=t;try{_r(r||"Refreshing commands…")}catch{}try{await xb(s),_r("Refreshing commands…"),await nn.getState().loadCommands(),jr("commands",{source:Co})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),_r("OpenCode refresh failed. Please retry refreshing configuration manually."),await Ll(1500)}finally{_s()}}let hd=null;hd||(hd=gi(t=>{if(t.source!==Co&&Fo(t,"commands")){const{loadCommands:r}=nn.getState();r()}}));const Ur=()=>{const t=Oe.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Ea="useSkillsStore",mr=is()(hs(qs((t,r)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:s=>{t({selectedSkillName:s})},setSkillDraft:s=>{t({skillDraft:s})},loadSkills:async()=>{t({isLoading:!0});const s=r().skills;let n=null;for(let o=0;o<3;o++)try{const a=Ur(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills${l}`);if(!c.ok)throw new Error(`Failed to list skills: ${c.status}`);const m=((await c.json()).skills||[]).map(f=>({name:f.name,path:f.path,scope:f.scope??"user",source:f.source??"opencode",description:f.sources?.md?.description||""}));return t({skills:m,isLoading:!1}),!0}catch(a){n=a;const l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load skills:",n),t({skills:s,isLoading:!1}),!1},getSkillDetail:async s=>{try{const n=Ur(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(s)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async s=>{Us("Creating skill...");try{const n={name:s.name,description:s.description};s.instructions&&(n.instructions=s.instructions),s.scope&&(n.scope=s.scope),s.supportingFiles&&(n.supportingFiles=s.supportingFiles);const o=Ur(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(s.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),c=await l.json().catch(()=>null);if(!l.ok){const u=c?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&jr("skills",{source:Ea}),d}catch{return!1}finally{_s()}},updateSkill:async(s,n)=>{Us("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=Ur(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(s)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&jr("skills",{source:Ea}),u}catch{return!1}finally{_s()}},deleteSkill:async s=>{Us("Deleting skill...");try{const n=Ur(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(s)}${o}`,{method:"DELETE"}),l=await a.json().catch(()=>null);if(!a.ok){const d=l?.error||"Failed to delete skill";throw new Error(d)}const c=await r().loadSkills();return c&&jr("skills",{source:Ea}),r().selectedSkillName===s&&t({selectedSkillName:null}),c}catch{return!1}finally{_s()}},getSkillByName:s=>{const{skills:n}=r();return n.find(o=>o.name===s)},readSupportingFile:async(s,n)=>{try{const o=Ur(),a=o?`&directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return l.ok?(await l.json()).content??null:null}catch{return null}},writeSupportingFile:async(s,n,o)=>{try{const a=Ur(),l=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}${l}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(s,n)=>{try{const o=Ur(),a=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}${a}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:Ks(()=>Ss()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=mr);let gd=null;gd||(gd=gi(t=>{if(t.source!==Ea&&Fo(t,"skills")){const{loadSkills:r}=mr.getState();r()}}));const xd=[{id:"anthropic",label:"Anthropic",description:"Anthropic's public skills repository",source:"anthropics/skills",defaultSubpath:"skills",sourceType:"github"},{id:"clawdhub",label:"ClawdHub",description:"Community skill registry with vector search",source:"clawdhub:registry",sourceType:"clawdhub"}],sa=()=>{const t=Oe.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Go=is()(hs((t,r)=>({sources:xd,itemsBySource:{},selectedSourceId:xd[0]?.id??null,pageInfoBySource:{},loadedSourceIds:{},clawdhubHasMoreBySource:{},isLoadingCatalog:!1,isLoadingSource:!1,isLoadingMore:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:s=>t({selectedSourceId:s}),loadCatalog:async s=>{t({isLoadingCatalog:!0,lastCatalogError:null});const n={sources:r().sources,itemsBySource:r().itemsBySource,pageInfoBySource:r().pageInfoBySource,loadedSourceIds:r().loadedSourceIds,clawdhubHasMoreBySource:r().clawdhubHasMoreBySource};let o=null;try{const a=s?.refresh?"?refresh=true":"",l=new AbortController,c=window.setTimeout(()=>l.abort(),3e3);try{const d=await fetch(`/api/config/skills/catalog${a}`,{method:"GET",headers:{Accept:"application/json"},signal:l.signal}),u=await d.json().catch(()=>null);if(!d.ok||!u?.ok)throw o=u?.error||{kind:"unknown",message:`Failed to load catalog (${d.status})`},new Error(o.message);const m=u.sources&&u.sources.length>0?u.sources:n.sources,f=s?.refresh?{}:r().itemsBySource||{},p=s?.refresh?{}:r().pageInfoBySource||{},h=s?.refresh?{}:r().loadedSourceIds||{},g=s?.refresh?{}:r().clawdhubHasMoreBySource||{},x=r().selectedSourceId,b=x&&m.some(y=>y.id===x)?x:m[0]?.id??null;return t({sources:m,itemsBySource:f,pageInfoBySource:p,loadedSourceIds:h,clawdhubHasMoreBySource:g,selectedSourceId:b}),!0}finally{window.clearTimeout(c)}}catch(a){return o=o||{kind:"unknown",message:a instanceof Error?a.message:String(a)},t({sources:n.sources,itemsBySource:n.itemsBySource,pageInfoBySource:n.pageInfoBySource,loadedSourceIds:n.loadedSourceIds,clawdhubHasMoreBySource:n.clawdhubHasMoreBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{t({isLoadingCatalog:!1})}},loadSource:async(s,n)=>{if(!s)return!1;t({isLoadingSource:!0,lastCatalogError:null});try{const o=sa(),a=n?.refresh?"&refresh=true":"",l=o?`?directory=${encodeURIComponent(o)}&sourceId=${encodeURIComponent(s)}${a}`:`?sourceId=${encodeURIComponent(s)}${a}`,c=await fetch(`/api/config/skills/catalog/source${l}`,{method:"GET",headers:{Accept:"application/json"}}),d=await c.json().catch(()=>null),u=Array.isArray(d?.items);if(!c.ok||!d?.ok&&!u){const p=await fetch(`/api/config/skills/catalog${l}`,{method:"GET",headers:{Accept:"application/json"}}),h=await p.json().catch(()=>null),g=h?.itemsBySource?.[s];return p.ok&&h?.ok&&Array.isArray(g)?(t(x=>({itemsBySource:{...x.itemsBySource,[s]:g},pageInfoBySource:{...x.pageInfoBySource,[s]:{nextCursor:null}},loadedSourceIds:{...x.loadedSourceIds,[s]:!0},clawdhubHasMoreBySource:{...x.clawdhubHasMoreBySource,[s]:!1}})),!0):(t({lastCatalogError:d?.error||{kind:"unknown",message:`Failed to load source (${c.status})`}}),!1)}const m=d?.items||[],f=d?.nextCursor??null;return t(p=>({itemsBySource:{...p.itemsBySource,[s]:m},pageInfoBySource:{...p.pageInfoBySource,[s]:{nextCursor:f}},loadedSourceIds:{...p.loadedSourceIds,[s]:!0},clawdhubHasMoreBySource:{...p.clawdhubHasMoreBySource,[s]:m.length>0}})),!0}catch(o){return t({lastCatalogError:{kind:"unknown",message:o instanceof Error?o.message:String(o)}}),!1}finally{t({isLoadingSource:!1})}},loadMoreClawdHub:async()=>{const s=r().selectedSourceId;if(!s)return!1;const o=r().pageInfoBySource[s]?.nextCursor||null;t({isLoadingMore:!0});try{const a=sa(),l=[`sourceId=${encodeURIComponent(s)}`];a&&l.push(`directory=${encodeURIComponent(a)}`),o&&l.push(`cursor=${encodeURIComponent(o)}`);const c=`?${l.join("&")}`,d=await fetch(`/api/config/skills/catalog/source${c}`,{method:"GET",headers:{Accept:"application/json"}}),u=await d.json().catch(()=>null);if(!d.ok||!u?.ok)return!1;const m=u.nextCursor??null,f=r().itemsBySource[s]||[],p=u.items||[],h=new Map(f.map(b=>[`${b.sourceId}:${b.skillDir}`,b]));let g=0;for(const b of p){const y=`${b.sourceId}:${b.skillDir}`;h.has(y)||(g+=1),h.set(y,b)}const x=p.length===0||g===0;return t(b=>({itemsBySource:{...b.itemsBySource,[s]:Array.from(h.values())},pageInfoBySource:{...b.pageInfoBySource,[s]:{nextCursor:m}},clawdhubHasMoreBySource:{...b.clawdhubHasMoreBySource,[s]:!x}})),!0}catch{return!1}finally{t({isLoadingMore:!1})}},scanRepo:async s=>{t({isScanning:!0,lastScanError:null,scanResults:null});try{const n=sa(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s)}),l=await a.json().catch(()=>null);if(!a.ok||!l){const c=l?.error||{kind:"unknown",message:"Failed to scan repository"};return t({lastScanError:c}),{ok:!1,error:c}}return l.ok?(t({scanResults:l.items||[]}),l):(t({lastScanError:l.error||{kind:"unknown",message:"Failed to scan repository"}}),l)}finally{t({isScanning:!1})}},installSkills:async s=>{t({isInstalling:!0,lastInstallError:null});try{const n=sa(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/install${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s)}),l=await a.json().catch(()=>null);if(!l){const c={kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:c}),{ok:!1,error:c}}if(!a.ok||!l.ok){const c=l.error||{kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:c}),{ok:!1,error:c}}return mr.getState().loadSkills(),l}catch(n){const o={kind:"unknown",message:n instanceof Error?n.message:String(n)};return t({lastInstallError:o}),{ok:!1,error:o}}finally{t({isInstalling:!1})}}}),{name:"skills-catalog-store"})),yb=()=>{const t=Oe.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},ra=()=>{try{const r=Ft.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const s=Oe.getDirectory();if(s?.trim())return s.trim()}catch(t){console.warn("[AgentsStore] Error resolving config directory:",t)}return null},pn=t=>{const r=t;return r.native===!0||r.builtIn===!0},If=t=>{const r=t;return r.hidden===!0||r.options?.hidden===!0},Pf=t=>t.filter(r=>!If(r)),Ia="useAgentsStore",Ya=t=>new Promise(r=>setTimeout(r,t)),bb=2e4,yd=300,bd=4,wb=800,vb=200,jb=2e3,on=is()(hs(qs((t,r)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:s=>{t({selectedAgentName:s})},setAgentDraft:s=>{t({agentDraft:s})},loadAgents:async()=>{t({isLoading:!0});const s=r().agents;for(let n=0;n<3;n++)try{const o=ra(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await Oe.withDirectory(o,()=>Oe.listAgents()),c=await Promise.all(l.map(async d=>{try{const u=await fetch(`/api/config/agents/${encodeURIComponent(d.name)}${a}`,{headers:{"Cache-Control":"no-cache",...o?{"x-opencode-directory":o}:{}}});if(u.ok){const m=await u.json();let f=m.scope;if(!f&&m.sources){const p=m.sources;f=(p.md?.exists?p.md.scope:void 0)??(p.json?.exists?p.json.scope:void 0)??p.md?.scope??p.json?.scope}return f==="project"||f==="user"?{...d,scope:f}:{...d,scope:void 0}}}catch(u){console.warn(`[AgentsStore] Failed to fetch config for agent ${d.name}:`,u)}return d}));return JSON.stringify(s)!==JSON.stringify(c)?t({agents:c,isLoading:!1}):t({isLoading:!1}),!0}catch{}return t({isLoading:!1}),!1},createAgent:async s=>{Us("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",s.name);const o={mode:s.mode||"subagent"};s.description&&(o.description=s.description),s.model&&(o.model=s.model),s.temperature!==void 0&&(o.temperature=s.temperature),s.top_p!==void 0&&(o.top_p=s.top_p),s.prompt&&(o.prompt=s.prompt),s.permission&&(o.permission=s.permission),s.disable!==void 0&&(o.disable=s.disable),s.scope&&(o.scope=s.scope),console.log("[AgentsStore] Agent config to save:",o);const a=ra(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(s.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await Mo({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&jr("agents",{source:Ia}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||_s()}},updateAgent:async(s,n)=>{Us("Updating agent configuration…");let o=!1;try{const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const l=ra(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(s)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update agent";throw new Error(p)}if(u?.requiresReload??!0)return o=!0,await Mo({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&jr("agents",{source:Ia}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||_s()}},deleteAgent:async s=>{Us("Deleting agent configuration…");let n=!1;try{const o=ra(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete agent";throw new Error(m)}if(c?.requiresReload??!0)return n=!0,await Mo({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&jr("agents",{source:Ia}),r().selectedAgentName===s&&t({selectedAgentName:null}),u}catch{return!1}finally{n||_s()}},getAgentByName:s=>{const{agents:n}=r();return n.find(o=>o.name===s)},getVisibleAgents:()=>{const{agents:s}=r();return Pf(s)}}),{name:"agents-store",storage:Ks(()=>Ss()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=on);async function Sb(t){const r=typeof t=="number"&&t>0?Math.min(t,yd):0;r>0&&await Ya(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<bb;){n+=1,_r(`Waiting for OpenCode… (attempt ${n})`);try{if(await Oe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-s,l=n<=bd&&a<1200?yd:Math.min(wb+Math.max(0,n-bd)*vb,jb);await Ya(l)}throw o||new Error("OpenCode did not become ready in time")}const Nb=t=>{if(!t||t.length===0)return["all"];const r=Array.from(new Set(t));return r.includes("all")?["all"]:r};async function kb(t={}){const{message:r,delayMs:s}=t,n=Nb(t.scopes),o=t.mode??(n.includes("all")?"projects":"active");try{_r(r||"Refreshing configuration…")}catch{}try{await Sb(s);const a=Ze.getState(),l=on.getState(),c=nn.getState(),d=mr.getState(),u=Go.getState(),m=n.includes("all")||n.includes("providers"),f=n.includes("all")||n.includes("agents"),p=n.includes("all")||n.includes("agents"),h=n.includes("all")||n.includes("commands"),g=n.includes("all")||n.includes("skills"),x=yb(),b=o==="projects"?Ft.getState().projects:[],y=Array.from(new Set([...x?[x]:[],...b.map(M=>M.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&Ze.setState({directoryScoped:{}});const w=[];for(const M of y)m&&w.push(a.loadProviders({directory:M}).then(()=>{})),f&&w.push(a.loadAgents({directory:M}).then(()=>{}));const S=[];p&&S.push(l.loadAgents().then(()=>{})),h&&S.push(c.loadCommands().then(()=>{})),g&&(S.push(d.loadSkills().then(()=>{})),S.push(u.loadCatalog().then(()=>{}))),_r("Refreshing configuration…"),await Promise.all([...w,...S])}catch{_r("OpenCode refresh failed. Please retry."),await Ya(1500)}finally{_s()}}async function Mo(t){await kb(t)}async function Do(t){Us(t?.message||"Reloading OpenCode configuration…");try{const r=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),s=await r.json().catch(()=>null);if(!r.ok){const o=s?.error||"Failed to reload configuration";throw new Error(o)}const n={...t,scopes:t?.scopes??["all"],mode:t?.mode??"projects"};s?.requiresReload?await Mo({...n,message:s.message,delayMs:s.reloadDelayMs}):await Mo(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),_r("Failed to reload configuration. Please try again."),await Ya(2e3),_s(),r}}let wd=null;wd||(wd=gi(t=>{if(t.source!==Ia&&Fo(t,"agents")){const{loadAgents:r}=on.getState();r()}}));const Cb="https://models.dev/api.json",Mb="/api/openchamber/models-metadata",vd="opencode",jd="big-pickle",Db=async()=>{try{if(ms()){const c=await Br();return{defaultModel:c?.defaultModel,defaultVariant:c?.defaultVariant,defaultAgent:c?.defaultAgent,autoCreateWorktree:c?.autoCreateWorktree,gitmojiEnabled:c?.gitmojiEnabled}}const t=Ps()?.settings;if(t)try{const d=(await t.load())?.settings;if(d){const u=typeof d?.defaultModel=="string"?d.defaultModel.trim():"",m=typeof d?.defaultVariant=="string"?d.defaultVariant.trim():"",f=typeof d?.defaultAgent=="string"?d.defaultAgent.trim():"",p=typeof d?.gitmojiEnabled=="boolean"?d.gitmojiEnabled:void 0;return{defaultModel:u.length>0?u:void 0,defaultVariant:m.length>0?m:void 0,defaultAgent:f.length>0?f:void 0,autoCreateWorktree:typeof d?.autoCreateWorktree=="boolean"?d.autoCreateWorktree:void 0,gitmojiEnabled:p}}}catch{}const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const s=await r.json(),n=typeof s?.defaultModel=="string"?s.defaultModel.trim():"",o=typeof s?.defaultVariant=="string"?s.defaultVariant.trim():"",a=typeof s?.defaultAgent=="string"?s.defaultAgent.trim():"",l=typeof s?.gitmojiEnabled=="boolean"?s.gitmojiEnabled:void 0;return{defaultModel:n.length>0?n:void 0,defaultVariant:o.length>0?o:void 0,defaultAgent:a.length>0?a:void 0,autoCreateWorktree:typeof s?.autoCreateWorktree=="boolean"?s.autoCreateWorktree:void 0,gitmojiEnabled:l}}catch{return{}}},na=t=>{if(!t||typeof t!="string")return null;const r=t.split("/");return r.length!==2||!r[0]||!r[1]?null:{providerId:r[0],modelId:r[1]}},Ab=t=>t?.toLowerCase?.()??"",Eb=t=>t==="primary"||t==="all"||t===void 0||t===null,Ro=t=>typeof t=="object"&&t!==null,Qa=t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),Ib=t=>{if(!Ro(t))return!1;const r=t;if(r.modalities){const{input:s,output:n}=r.modalities;if(s&&!Qa(s)||n&&!Qa(n))return!1}return!0},Pb=t=>{if(!Ro(t))return!1;const r=t;return r.models===void 0||Ro(r.models)},Tf=(t,r)=>{const s=Ab(t);return!s||!r?"":`${s}/${r}`},Tb=t=>{const r=new Map;if(!Ro(t))return r;for(const[s,n]of Object.entries(t)){if(!Pb(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:s,a=n.models;if(!(!a||!Ro(a)))for(const[l,c]of Object.entries(a)){if(!Ib(c))continue;const d=typeof l=="string"&&l.length>0?l:c.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof c.id=="string"&&c.id.length>0?c.id:d,providerId:o,name:typeof c.name=="string"?c.name:void 0,tool_call:typeof c.tool_call=="boolean"?c.tool_call:void 0,reasoning:typeof c.reasoning=="boolean"?c.reasoning:void 0,temperature:typeof c.temperature=="boolean"?c.temperature:void 0,attachment:typeof c.attachment=="boolean"?c.attachment:void 0,modalities:c.modalities?{input:Qa(c.modalities.input)?c.modalities.input:void 0,output:Qa(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=Tf(o,d);m&&r.set(m,u)}}return r},Fb=async()=>{if(typeof fetch!="function")return new Map;const t=[Mb,Cb];for(const r of t){const s=typeof AbortController<"u"?new AbortController:void 0,n=s?setTimeout(()=>s.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),a={signal:s?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const l=await fetch(r,a);if(!l.ok)throw new Error(`Metadata request to ${r} returned status ${l.status}`);const c=await l.json();return Tb(c)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let _i=null;const Rb=(t,r)=>{t().size>0||_i||(_i=Fb().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{_i=null}))},Lb=t=>new Promise(r=>setTimeout(r,t)),bc="__global__",Kn=t=>{const r=typeof t=="string"?t.trim():"";return r.length>0?r:bc},Tn=t=>t===bc?null:t,Ob=()=>{if(typeof window>"u")return bc;const t=Oe.getDirectory()??xt.getState().currentDirectory;return Kn(t)},Ze=is()(hs(qs((t,r)=>({activeDirectoryKey:Ob(),directoryScoped:{},providers:[],agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultAgent:void 0,settingsAutoCreateWorktree:!1,settingsGitmojiEnabled:!1,activateDirectory:async s=>{const n=Kn(s);t(o=>{const a=o.directoryScoped[n];return a?{activeDirectoryKey:n,providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders}:{activeDirectoryKey:n,providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}}}),r().isConnected&&(await r().loadProviders({directory:Tn(n)}),await r().loadAgents({directory:Tn(n)}))},loadProviders:async s=>{const n=Kn(s?.directory??Tn(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),l=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let c=null;for(let d=0;d<3;d++)try{Rb(()=>r().modelsMetadata,h=>t({modelsMetadata:h}));const u=await Oe.withDirectory(Tn(n),()=>Oe.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(h=>{const g=h.models??{},x=Object.keys(g).map(b=>g[b]);return{...h,models:x}});t(h=>{const x={...h.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:p,defaultProviders:f},b={directoryScoped:{...h.directoryScoped,[n]:x}};if(h.activeDirectoryKey===n&&(b.providers=p,b.defaultProviders=f,!h.currentProviderId&&!h.currentModelId&&h.settingsDefaultModel)){const y=na(h.settingsDefaultModel);if(y){const w=p.find(S=>S.id===y.providerId);if(w?.models.some(S=>S.id===y.modelId)){const S=w.models.find(N=>N.id===y.modelId),M=h.settingsDefaultVariant&&S?.variants?.[h.settingsDefaultVariant]?h.settingsDefaultVariant:void 0;b.currentProviderId=y.providerId,b.currentModelId=y.modelId,b.currentVariant=M,b.selectedProviderId=y.providerId,x.currentProviderId=y.providerId,x.currentModelId=y.modelId,x.currentVariant=M,x.selectedProviderId=y.providerId}}}return b});return}catch(u){c=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",c),t(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:l},f={directoryScoped:{...d.directoryScoped,[n]:m}};if(d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=l,!d.currentProviderId&&!d.currentModelId&&d.settingsDefaultModel)){const p=na(d.settingsDefaultModel);if(p){const h=a.find(g=>g.id===p.providerId);if(h?.models.some(g=>g.id===p.modelId)){const g=h.models.find(b=>b.id===p.modelId),x=d.settingsDefaultVariant&&g?.variants?.[d.settingsDefaultVariant]?d.settingsDefaultVariant:void 0;f.currentProviderId=p.providerId,f.currentModelId=p.modelId,f.currentVariant=x,f.selectedProviderId=p.providerId,m.currentProviderId=p.providerId,m.currentModelId=p.modelId,m.currentVariant=x,m.selectedProviderId=p.providerId}}}return f})},setProvider:s=>{const{providers:n}=r(),o=n.find(c=>c.id===s);if(!o)return;const l=o.models[0]?.id||"";t(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentVariant:c.currentVariant,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentProviderId:s,currentModelId:l,selectedProviderId:s};return{currentProviderId:s,currentModelId:l,selectedProviderId:s,directoryScoped:{...c.directoryScoped,[d]:m}}})},setModel:s=>{t(n=>{const o=n.activeDirectoryKey,l={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentModelId:s};return{currentModelId:s,directoryScoped:{...n.directoryScoped,[o]:l}}})},setCurrentVariant:s=>{t(n=>{if(n.currentVariant===s)return n;const o=n.activeDirectoryKey,l={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentVariant:s};return{currentVariant:s,directoryScoped:{...n.directoryScoped,[o]:l}}})},getCurrentModelVariants:()=>{const n=r().getCurrentModel()?.variants;return n?Object.keys(n):[]},cycleCurrentVariant:()=>{const s=r().getCurrentModelVariants();if(s.length===0)return;const n=r().currentVariant;if(!n){r().setCurrentVariant(s[0]);return}const o=s.indexOf(n);if(o===-1||o===s.length-1){r().setCurrentVariant(void 0);return}r().setCurrentVariant(s[o+1])},setSelectedProvider:s=>{t(n=>{const o=n.activeDirectoryKey,l={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},selectedProviderId:s};return{selectedProviderId:s,directoryScoped:{...n.directoryScoped,[o]:l}}})},saveAgentModelSelection:(s,n,o)=>{t(a=>{const l=a.activeDirectoryKey,c={...a.agentModelSelections,[s]:{providerId:n,modelId:o}},u={...a.directoryScoped[l]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:c};return{agentModelSelections:c,directoryScoped:{...a.directoryScoped,[l]:u}}})},getAgentModelSelection:s=>{const{agentModelSelections:n}=r();return n[s]||null},loadAgents:async s=>{const n=Kn(s?.directory??Tn(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let l=null;for(let c=0;c<3;c++)try{const[d,u]=await Promise.all([Oe.withDirectory(Tn(n),()=>Oe.listAgents()),Db()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(t(N=>{const A={...N.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},k={settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsGitmojiEnabled:u.gitmojiEnabled??!1,directoryScoped:{...N.directoryScoped,[n]:A}};return N.activeDirectoryKey===n&&(k.agents=m),k}),m.length===0)return t(N=>{const A={...N.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},k={directoryScoped:{...N.directoryScoped,[n]:A}};return N.activeDirectoryKey===n&&(k.currentAgentName=void 0),k}),!0;const p=(N,v)=>{const A=f.find(k=>k.id===N);return A?A.models.some(k=>k.id===v):!1},h=m.filter(N=>Eb(N.mode));let b=h.find(N=>N.name==="build")||h[0]||m[0];const y={};if(u.defaultAgent){const N=m.find(v=>v.name===u.defaultAgent);N?b=N:y.defaultAgent=""}let w,S,M;if(u.defaultModel){const N=na(u.defaultModel);if(N&&p(N.providerId,N.modelId)){if(w=N.providerId,S=N.modelId,u.defaultVariant){const k=f.find(C=>C.id===N.providerId)?.models.find(C=>C.id===N.modelId)?.variants;k&&Object.prototype.hasOwnProperty.call(k,u.defaultVariant)?M=u.defaultVariant:y.defaultVariant=""}}else y.defaultModel=""}if(!w&&b?.model?.providerID&&b?.model?.modelID){const{providerID:N,modelID:v}=b.model;p(N,v)&&(w=N,S=v)}if(!w)if(p(vd,jd))w=vd,S=jd;else{const N=f[0],v=N?.models[0];N&&v&&(w=N.id,S=v.id)}return t(N=>{const v=N.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},A={...v,providers:f,agents:m,currentAgentName:b.name,currentProviderId:w??v.currentProviderId,currentModelId:S??v.currentModelId,currentVariant:M},k={directoryScoped:{...N.directoryScoped,[n]:A}};return N.activeDirectoryKey===n&&(k.currentAgentName=b.name,w&&S&&(k.currentProviderId=w,k.currentModelId=S,k.currentVariant=M)),k}),Object.keys(y).length>0&&(t({settingsDefaultModel:y.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultVariant:y.defaultVariant!==void 0?void 0:r().settingsDefaultVariant,settingsDefaultAgent:y.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),cs(y).catch(()=>{})),!0}catch(d){l=d;const u=200*(c+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",l),t(c=>{const d=c.activeDirectoryKey===n?c.providers:c.directoryScoped[n]?.providers??[],m={...c.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...c.directoryScoped,[n]:m}};return c.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:s=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:l}=r();if(t(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentAgentName:s};return{currentAgentName:s,directoryScoped:{...c.directoryScoped,[d]:m}}}),s&&typeof window<"u"){const c=window.__zustand_session_store__;if(c){const d=c.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&c.setState(h=>{const g=new Map(h.currentAgentContext);return g.set(u,s),{currentAgentContext:g}}),u&&m(u)&&(p(u,s)||f(u,n))}}if(s&&typeof window<"u"){const c=window.__zustand_session_store__;if(c?.getState){const{currentSessionId:m,getAgentModelForSession:f}=c.getState();if(m&&f(m,s))return}if(a){const m=na(a);if(m&&o.find(p=>p.id===m.providerId)?.models.some(p=>p.id===m.modelId)){t(p=>{const h=p.activeDirectoryKey,g=p.directoryScoped[h]??{providers:p.providers,agents:p.agents,currentProviderId:p.currentProviderId,currentModelId:p.currentModelId,currentVariant:p.currentVariant,currentAgentName:p.currentAgentName,selectedProviderId:p.selectedProviderId,agentModelSelections:p.agentModelSelections,defaultProviders:p.defaultProviders};let x;if(l){const S=o.find(M=>M.id===m.providerId)?.models.find(M=>M.id===m.modelId)?.variants;S&&Object.prototype.hasOwnProperty.call(S,l)&&(x=l)}const b={...g,currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:x};return{currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:x,directoryScoped:{...p.directoryScoped,[h]:b}}});return}}const u=n.find(m=>m.name===s)?.model;if(u?.providerID&&u?.modelID){const{providerID:m,modelID:f}=u;o.find(g=>g.id===m)?.models.find(g=>g.id===f)&&t(g=>{const x=g.activeDirectoryKey,y={...g.directoryScoped[x]??{providers:g.providers,agents:g.agents,currentProviderId:g.currentProviderId,currentModelId:g.currentModelId,currentAgentName:g.currentAgentName,selectedProviderId:g.selectedProviderId,agentModelSelections:g.agentModelSelections,defaultProviders:g.defaultProviders},currentProviderId:m,currentModelId:f,selectedProviderId:m};return{currentProviderId:m,currentModelId:f,selectedProviderId:m,directoryScoped:{...g.directoryScoped,[x]:y}}})}}},setSettingsDefaultModel:s=>{t({settingsDefaultModel:s})},setSettingsDefaultVariant:s=>{t({settingsDefaultVariant:s})},setSettingsDefaultAgent:s=>{t({settingsDefaultAgent:s})},setSettingsAutoCreateWorktree:s=>{t({settingsAutoCreateWorktree:s})},setSettingsGitmojiEnabled:s=>{t({settingsGitmojiEnabled:s})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Oe.checkHealth();return t({isConnected:a}),a}catch(a){o=a,n+=1;const l=400*n;await Lb(l)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),t({isConnected:!1}),!1},initializeApp:async()=>{try{const s=xs();s&&console.log("Starting app initialization...");const n=await r().checkConnection();if(s&&console.log("Connection check result:",n),!n){s&&console.log("Server not connected"),t({isConnected:!1});return}s&&console.log("Initializing app..."),await Oe.initApp(),s&&console.log("Loading providers..."),await r().loadProviders(),s&&console.log("Loading agents..."),await r().loadAgents(),t({isInitialized:!0,isConnected:!0}),s&&console.log("App initialized successfully")}catch(s){console.error("Failed to initialize app:",s),t({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:s,currentProviderId:n}=r();return s.find(o=>o.id===n)},getCurrentModel:()=>{const s=r().getCurrentProvider(),{currentModelId:n}=r();if(s)return s.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:s,currentAgentName:n}=r();if(n)return s.find(o=>o.name===n)},getModelMetadata:(s,n)=>{const o=Tf(s,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:s}=r();return Pf(s)}}),{name:"config-store",storage:Ks(()=>Ss()),partialize:t=>({activeDirectoryKey:t.activeDirectoryKey,directoryScoped:t.directoryScoped,currentProviderId:t.currentProviderId,currentModelId:t.currentModelId,currentVariant:t.currentVariant,currentAgentName:t.currentAgentName,selectedProviderId:t.selectedProviderId,agentModelSelections:t.agentModelSelections,defaultProviders:t.defaultProviders,settingsDefaultModel:t.settingsDefaultModel,settingsDefaultVariant:t.settingsDefaultVariant,settingsDefaultAgent:t.settingsDefaultAgent,settingsAutoCreateWorktree:t.settingsAutoCreateWorktree,settingsGitmojiEnabled:t.settingsGitmojiEnabled})})));typeof window<"u"&&(window.__zustand_config_store__=Ze);let Sd=null;Sd||(Sd=gi(async t=>{const r=[];if(Fo(t,"agents")){const{loadAgents:s}=Ze.getState();r.push(s().then(()=>{}))}if(Fo(t,"providers")){const{loadProviders:s}=Ze.getState();r.push(s())}r.length>0&&await Promise.all(r)}));let Nd=null;typeof window<"u"&&!Nd&&(Nd=xt.subscribe((t,r)=>{const s=Kn(t.currentDirectory),n=Kn(r.currentDirectory);s!==n&&Ze.getState().activateDirectory(t.currentDirectory)}));const hn={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,HISTORICAL_MESSAGES:90,FETCH_BUFFER:20,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Ol=180,Ja=()=>{const t=Me.getState?.();return t?{...hn,HISTORICAL_MESSAGES:t.memoryLimitHistorical??hn.HISTORICAL_MESSAGES,VIEWPORT_MESSAGES:t.memoryLimitViewport??hn.VIEWPORT_MESSAGES}:hn},_l=()=>{const t=Me.getState?.();return t?t.memoryLimitActiveSession??Ol:Ol},Pr=hn,Rs=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function zr(t){const r=Rs();return r?r.checkIsGitRepository(t):ry(t)}async function _b(t){const r=Rs();return r?r.getGitStatus(t):ny(t)}async function wc(t){const r=Rs();return r?r.getGitBranches(t):hy(t)}async function $l(t,r){const s=Rs();return s?s.deleteGitBranch(t,r):oy(t,r)}async function kd(t,r){const s=Rs();return s?s.deleteRemoteBranch(t,r):ay(t,r)}async function $b(t,r){const s=Rs();return s?.generatePullRequestDescription?s.generatePullRequestDescription(t,r):yy(t,r)}async function Ff(t){const r=Rs();return r?r.listGitWorktrees(t):ly(t)}async function Rf(t,r){const s=Rs();return s?s.removeGitWorktree(t,r):iy(t,r)}async function Bb(t,r={}){const s=Rs();return s?s.gitFetch(t,r):xy(t,r)}async function zb(t,r,s){const n=Rs();return n?n.renameBranch(t,r,s):gy(t,r,s)}async function Hb(){const t=Rs();return t?t.getGitIdentities():py()}async function Wb(t){const r=Rs();return r?r.createGitIdentity(t):uy(t)}async function Ub(t,r){const s=Rs();return s?s.updateGitIdentity(t,r):dy(t,r)}async function Vb(t){const r=Rs();return r?r.deleteGitIdentity(t):cy(t)}async function Gb(){const t=Rs();return t?.discoverGitCredentials?t.discoverGitCredentials():my()}async function qb(){const t=Rs();return t?.getGlobalGitIdentity?t.getGlobalGitIdentity():fy()}const Kb="openchamber.json",Yb=".openchamber",Qb=[".config","openchamber"],Jb=[".config","openchamber","projects"],Xb="settings.json",$i=new Map,Cd=t=>/^[A-Za-z0-9._-]+$/.test(t),Zb=t=>{let r="";for(const s of t)r+=s.toString(16).padStart(2,"0");return r},ew=async t=>{try{if(typeof crypto>"u"||!crypto.subtle)return null;const s=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-1",s);return Zb(new Uint8Array(n))}catch{return null}};function wi(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Lo=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},to=(t,r)=>{const s=Lo(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},Lf=t=>to(to(t,Yb),Kb),qo=()=>{const t="/api";return t.startsWith("/"),t},vc=async(t,r)=>{try{const s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return s.ok?{ok:!0,data:await s.json().catch(()=>null)}:{ok:!1,data:null}}catch{return{ok:!1,data:null}}},tw=async t=>{const r=wi();if(r?.createDirectory)try{if((await r.createDirectory(t))?.success)return!0}catch{}return!!(await vc(`${qo()}/fs/mkdir`,{path:t})).ok},Of=async t=>{const r=wi();if(r?.readFile)try{const s=await r.readFile(t);return typeof s?.content=="string"?s.content:""}catch{return null}try{const s=await fetch(`${qo()}/fs/read?path=${encodeURIComponent(t)}`);return s.ok?await s.text():null}catch{return null}},sw=async(t,r)=>{const s=wi();if(s?.writeFile)try{if((await s.writeFile(t,r))?.success)return!0}catch{}return!!(await vc(`${qo()}/fs/write`,{path:t,content:r})).ok},_f=async()=>{if(!zt()){const t=await fc().catch(()=>null);if(t&&t.trim().length>0)return Lo(t)}try{const t=await fetch(`${qo()}/fs/home`);if(!t.ok)return null;const r=await t.json().catch(()=>null),s=typeof r?.home=="string"?r.home.trim():"";return s?Lo(s):null}catch{return null}},rw=async()=>{const t=await _f();return t?Qb.reduce((r,s)=>to(r,s),t):null},$f=async()=>{const t=await _f();return t?Jb.reduce((r,s)=>to(r,s),t):null},nw=async()=>{const t=await rw();return t?to(t,Xb):null},ow=async t=>{const r=typeof t?.path=="string"?t.path.trim():"",s=r?Lo(r):"",n=typeof t?.id=="string"?t.id.trim():"";if(n&&Cd(n))return n;if(s){const a=$i.get(s);if(a)return a}const o=await nw();if(o&&s){const a=await Of(o);if(a)try{const l=JSON.parse(a),c=Array.isArray(l?.projects)?l.projects:[];for(const d of c){if(!d||typeof d!="object")continue;const u=d,m=typeof u.id=="string"?u.id.trim():"",f=typeof u.path=="string"?Lo(u.path.trim()):"";if(m&&Cd(m)&&f&&f===s)return $i.set(s,m),m}}catch{}}if(s){const a=await ew(s),l=a?`path_${a}`:`path_${s.replace(/[^A-Za-z0-9._-]+/g,"_")}`;return $i.set(s,l),l}return null},Bf=async t=>{const r=await $f();if(!r)return null;const s=await ow(t);return s?to(r,`${s}.json`):null};async function zf(t){const r=typeof t?.path=="string"?t.path.trim():"";if(!r)return null;const s=await Bf(t),n=async c=>{const d=await Of(c);return d===null?null:d},o=c=>{if(typeof c!="string")return null;const d=c.trim();if(!d)return null;try{const u=JSON.parse(d);return!u||typeof u!="object"?null:u}catch{return null}};if(s){const c=o(await n(s));if(c)return c}const a=Lf(r),l=o(await n(a));if(!l)return null;try{await Hf(t,l)&&await lw(r)}catch{}return l}async function Hf(t,r){if(!(typeof t?.path=="string"?t.path.trim():""))return!1;const n=await $f(),o=await Bf(t);if(!n||!o)return!1;try{if(!await tw(n))return!1;const l=JSON.stringify(r,null,2);return await sw(o,l)}catch(a){return console.error("Failed to write openchamber config:",a),!1}}async function aw(t,r){const n={...await zf(t)||{},...r};return Hf(t,n)}async function ho(t){return(await zf(t))?.["setup-worktree"]??[]}async function Wf(t,r){const s=r.filter(n=>n.trim().length>0);return aw(t,{"setup-worktree":s})}function iw(t,r){return t.replace(/\$ROOT_PROJECT_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_PROJECT_PATH\}/g,r.rootWorktreePath).replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}async function lw(t){const r=Lf(t),s=wi();if(s?.delete)try{await s.delete(r);return}catch{}try{await vc(`${qo()}/fs/delete`,{path:r})}catch{}}const cw=".openchamber",Oo=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},dw=t=>t?t.startsWith("refs/heads/")?t.substring(11):t.startsWith("heads/")?t.substring(6):t.startsWith("refs/")?t.substring(5):t:"";async function uw(t){const{projectDirectory:r,path:s,force:n}=t,o=Oo(r);await Rf(o,{path:s,force:n})}async function vi(t){const r=Oo(t);return Ff(r)}async function Ko(t){const r=Oo(t),s=await _b(r);return{isDirty:!s.isClean,ahead:s.ahead,behind:s.behind,upstream:s.tracking}}function ji(t,r){const s=Oo(t),n=Oo(r.worktree),o=`${s}/${cw}/`;return{source:n.startsWith(o)?"legacy":"sdk",path:n,branch:r.branch??"",label:dw(r.branch??""),projectDirectory:s,relativePath:n.startsWith(`${s}/`)?n.slice(s.length+1):n}}const mw=".openchamber",so=t=>{const r=t.replace(/\\/g,"/");return r==="/"?"/":r.length>1?r.replace(/\/+$/,""):r},fw=(t,r)=>{const s=so(t),n=so(r),o=`${s}/${mw}/`;return n.startsWith(o)},pw=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80),hw=t=>{const r=t.trim();return r?`'${r.replace(/'/g,"'\\''")}'`:"''"},Uf=t=>{if(!t||typeof t!="object")return t;const r=t;return"data"in r?r.data:t},gw=t=>{const r=so(t),s=r.split("/").filter(Boolean);return s[s.length-1]??r},xw=t=>{const r=[],s=typeof t.startPoint=="string"?t.startPoint.trim():"";s&&s!=="HEAD"&&r.push(`git reset --hard ${hw(s)}`);for(const o of t.setupCommands){const a=o.trim();a&&r.push(iw(a,{rootWorktreePath:t.projectDirectory}))}const n=r.filter(Boolean).join(" && ");return n.trim().length>0?n:void 0};async function _o(t){const r=t.path,s=Oe.getScopedApiClient(r),n=[];try{const a=await s.worktree.list(),l=Uf(a),c=Array.isArray(l)?l:[];for(const d of c){if(typeof d!="string"||d.trim().length===0)continue;const u=so(d),m=gw(u);n.push({source:"sdk",name:m,path:u,projectDirectory:r,branch:`opencode/${m}`,label:m})}}catch{}try{const l=(await vi(r)).map(c=>ji(r,c)).filter(c=>fw(r,c.path)).map(c=>({...c,source:"legacy"}));n.push(...l)}catch{}const o=new Map;for(const a of n){const l=so(a.path),c=o.get(l);if(!c){o.set(l,a);continue}c.source!=="sdk"&&a.source==="sdk"&&o.set(l,a)}return Array.from(o.values()).sort((a,l)=>{const c=(a.label||a.branch||a.path).toLowerCase(),d=(l.label||l.branch||l.path).toLowerCase();return c.localeCompare(d)})}async function Si(t,r){const s=t.path,n=Oe.getScopedApiClient(s),a=(typeof r.preferredName=="string"?pw(r.preferredName):"")||void 0,l=Array.isArray(r.setupCommands)?r.setupCommands:[],c=xw({projectDirectory:s,setupCommands:l,startPoint:r.startPoint});let d=null;const u=r.allowSuffix!==!1,m=a&&u?6:1;for(let p=0;p<m;p+=1){const h=a?p===0?a:`${a}-${p+1}`:void 0;try{const g=await n.worktree.create({worktreeCreateInput:{...h?{name:h}:{},...c?{startCommand:c}:{}}}),x=Uf(g);if(!x||typeof x!="object")throw new Error("Invalid worktree.create response");const b=x,y=typeof b.name=="string"?b.name:h,w=typeof b.branch=="string"?b.branch:y?`opencode/${y}`:"",S=typeof b.directory=="string"?b.directory:"";if(!y||!S)throw new Error("Worktree create missing name/directory");return{source:"sdk",name:y,path:so(S),projectDirectory:s,branch:w,label:y}}catch(g){d=g}}const f=d instanceof Error?d.message:"Failed to create worktree";throw new Error(f)}async function Yo(t,r,s){const n=t.path,o=!!s?.deleteRemoteBranch,a=s?.remoteName;if(r.source==="sdk"){await Oe.getScopedApiClient(n).worktree.remove({worktreeRemoveInput:{directory:r.path}});const m=(r.branch||"").replace(/^refs\/heads\//,"").trim();m&&await $l(n,{branch:m,force:!0}).catch(()=>{}),o&&m&&await kd(n,{branch:m,remote:a}).catch(()=>{});return}const l=!!r.status?.isDirty,c=!!(s?.force??l);await Rf(n,{path:r.path,force:c}).catch(async()=>{await uw({projectDirectory:n,path:r.path,force:!0})});const d=(r.branch||"").replace(/^refs\/heads\//,"").trim();d&&await $l(n,{branch:d,force:!0}).catch(()=>{}),o&&d&&await kd(n,{branch:d,remote:a}).catch(()=>{})}const Vf=Ss(),Gf="oc.sessionSelectionByDirectory",Md=".openchamber",yw=()=>{try{const t=Vf.getItem(Gf);if(!t)return{};const r=JSON.parse(t);return!r||typeof r!="object"?{}:Object.entries(r).reduce((s,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(s[n]=o),s),{})}catch{return{}}};let Pa=null;const jc=()=>(Pa||(Pa=yw()),Pa),qf=t=>{Pa=t;try{Vf.setItem(Gf,JSON.stringify(t))}catch{}},Kf=t=>{if(!t)return null;const s=jc()[t];return typeof s=="string"?s:null},Er=(t,r)=>{if(!t)return;const s={...jc()};r?s[t]=r:delete s[t],qf(s)},bw=(t,r)=>{if(!t)return;const s=Kf(t);if(!s)return;if(!new Set(r).has(s)){const o={...jc()};delete o[t],qf(o)}},Dd=async(t,r)=>{const s=t.status??await Ko(t.path).catch(()=>{}),n=Ft.getState().projects,o=At(t.projectDirectory)??t.projectDirectory,l={id:n.find(c=>At(c.path)===o)?.id??`path:${o}`,path:o};await Yo(l,s?{...t,status:s}:t,{deleteRemoteBranch:r?.deleteRemoteBranch,remoteName:r?.remoteName,force:!!s?.isDirty})},At=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},Ad=()=>{if(typeof window>"u")return null;const t=window.__VSCODE_CONFIG__,r=typeof t?.workspaceFolder=="string"?t.workspaceFolder:null;return At(r)},ww=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,oa=(...t)=>{xs()&&ww()&&console.log("[OpenChamber][VSCode][sessions]",...t)},Vr=t=>{const r=new Map;return t.forEach(s=>{if(!s||typeof s.id!="string"||s.id.length===0)return;const n=r.get(s.id);if(!n){r.set(s.id,s);return}const o=n.time?.updated??0;(s.time?.updated??0)>o&&r.set(s.id,s)}),Array.from(r.values())},nr=t=>{const r=new Map;t.forEach(s=>{const n=At(s.directory??null);if(!n)return;const o=r.get(n);o?o.push(s):r.set(n,[s])});for(const[s,n]of r.entries())r.set(s,Vr(n));return r},Fn=(t,r)=>{const s=t.find(n=>n.id===r);return s?At(s.directory??null):null},vw=async(t,r,s)=>{const n=At(r);if(!n||t.length===0)return null;const o=t.map(u=>({id:u.id,directory:At(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await vi(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const m=new Map(s);return o.forEach(({id:f})=>{m.delete(f)&&(u=!0)}),u?m:null}const l=new Map;a.forEach(u=>{const m=ji(n,u),f=At(m.path)??m.path;f!==n&&l.set(f,m)});let c=!1;const d=new Map(s);return o.forEach(({id:u,directory:m})=>{const f=l.get(m);if(!f){d.delete(u)&&(c=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),c=!0)}),c?d:null},ht=is()(hs(qs((t,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,loadSessions:async()=>{t({isLoading:!0,error:null});try{const s=xt.getState(),n=Ft.getState(),o=Oe.getApiClient(),a=Ad(),l=!!a;oa("loadSessions:start",{workspace:a,currentDirectory:s.currentDirectory,clientDirectory:Oe.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const c=new Map,d=async F=>{const B=At(F)??F,V=B,ne=c.get(V);if(ne)return ne;try{const O=await o.path.get({directory:F}),K=At(O.data?.directory??null)??B;return c.set(V,K),K}catch{return c.set(V,B),B}},u=(F,B,V)=>{const ne=At(B);if(!ne)return F;const G=V?.includeDescendants===!0?`${ne}/`:null,K=V?.includeMissingDirectory===!0;return F.filter(q=>{const $=At(q.directory??null);return $?!!($===ne||G&&$.startsWith(G)):K})},m=(F,B,V)=>{const ne=At(B);if(!ne)return F;const O=At(V??null);if(!O||O===ne)return F.map(q=>At(q.directory??null)?q:{...q,directory:ne});const G=O==="/"?"/":`${O}/`,K=ne==="/"?"/":`${ne}/`;return F.map(q=>{const $=At(q.directory??null);if(!$)return{...q,directory:ne};if($===O)return{...q,directory:ne};if(G!=="/"&&$.startsWith(G)){const W=$.slice(G.length);return{...q,directory:`${K}${W}`}}return q})},f=async F=>{const B=At(F);if(!B)try{const $=await o.session.list(void 0);return Array.isArray($.data)?$.data:[]}catch($){throw console.debug("Failed to list sessions (global):",$),$}const V=await d(B),ne=async()=>{const $=await o.session.list({directory:B});return Array.isArray($.data)?$.data:[]};let O=[],G=null,K=!1;try{O=await ne()}catch($){console.debug("Failed to list sessions for directory:",B,$),G=$,O=[]}if(O.length===0){K=!0;try{const $=await o.session.list(void 0),W=Array.isArray($.data)?$.data:[];O=u(W,V,{includeDescendants:l,includeMissingDirectory:!1})}catch($){throw console.debug("Failed to list sessions (global fallback):",$),G||$}}const q=u(O,V,{includeDescendants:l,includeMissingDirectory:!K});return oa("fetchSessionsForDirectory",{requestedDirectory:B,canonicalDirectory:V,fetched:O.length,filtered:q.length}),m(q,B,V)},p=At(s.currentDirectory??Oe.getDirectory()??null),h=n.projects.find(F=>F.id===n.activeProjectId)??null,g=At(h?.path??null),x=g??p??null,b=n.projects.length>0?n.projects:x?[{id:"legacy",path:x}]:[];if(b.length===0){t({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}const y=await Promise.all(b.map(async F=>{const B=At(F.path);if(!B)return{projectId:F.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const V=await zr(B).catch(()=>!1),ne=await f(B||null);oa("projectSessions",{projectId:F.id,projectPath:B,isGitRepo:V,parentSessions:ne.length});const O=[];let G=[];const K=new Set;if(K.add(B),V){const $=`${B}/${Md}`;try{const W=new Set,Y=await _o({id:F.id,path:B}).catch(()=>[]);G=Y,Y.forEach(z=>{z?.path&&W.add(At(z.path)??z.path)}),(await Oe.listLocalDirectory(B)).some(z=>z.isDirectory&&z.name===Md)&&(await Oe.listLocalDirectory($)).filter(R=>R.isDirectory).forEach(R=>{const we=/^([A-Za-z]:)?\//.test(R.path)?R.path:`${$}/${R.name}`,xe=At(we)??we;W.add(xe)}),W.forEach(z=>{const R=At(z)??z;K.add(R)}),W.size>0&&(await Promise.allSettled(Array.from(W).map(R=>f(R)))).forEach(R=>{R.status==="fulfilled"&&Array.isArray(R.value)&&O.push(...R.value)})}catch{G=[]}}const q=Vr([...ne,...O]);return{projectId:F.id,projectPath:B,sessions:q,discoveredWorktrees:G,validPaths:K}})),w=new Map;y.forEach(F=>{F.projectPath&&F.validPaths.forEach(B=>{const V=At(B)??B,ne=F.sessions.filter(O=>(At(O.directory??null)??V)===V);w.set(V,Vr(ne))})});const S=Vr(Array.from(w.values()).flat()),M=r();let N=M.worktreeMetadata;for(const F of y)if(F.projectPath)try{const B=await vw(F.sessions,F.projectPath,N);B&&(N=B)}catch(B){console.debug("Failed to refresh worktree metadata during session load:",B)}const v=new Map;y.forEach(F=>{F.projectPath&&v.set(F.projectPath,F.discoveredWorktrees)});const A=new Set;y.forEach(F=>{F.validPaths.forEach(B=>{const V=At(B)??B;V&&A.add(V)})});const k=p??g??null,C=k&&A.has(k)?k:g??k,j=C?w.get(C)??[]:S,T=new Set(S.map(F=>F.id));for(const[F,B]of w.entries())bw(F,B.map(V=>V.id));const I=(C??null)!==(M.lastLoadedDirectory??null);let P=M.currentSessionId;if((!P||!T.has(P)||I)&&(P=j[0]?.id??S[0]?.id??null),C){const F=Kf(C);F&&T.has(F)&&(P=F)}const D=(()=>{if(!P)return C??null;const F=N.get(P)?.path;if(F)return At(F)??F;const B=Fn(S,P);return B||(C??null)})();try{Oe.setDirectory(D??void 0)}catch(F){console.warn("Failed to sync OpenCode directory after session load:",F)}const E=g?y.find(F=>F.projectPath===g)?.discoveredWorktrees??[]:[];t({sessions:S,sessionsByDirectory:w,currentSessionId:P,lastLoadedDirectory:C??null,isLoading:!1,worktreeMetadata:N,availableWorktrees:E,availableWorktreesByProject:v}),C&&Er(C,P),D&&D!==C&&Er(D,P)}catch(s){t({error:s instanceof Error?s.message:"Failed to load sessions",isLoading:!1})}},createSession:async(s,n,o)=>{t({error:null});const a=xt.getState(),l=At(a.currentDirectory),c=Ad(),d=c??At(n??Oe.getDirectory()??l);oa("createSession:start",{title:s,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:c});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(x=>x.id)),p={id:u,title:s||"New session",parentID:o??void 0,directory:d??null,projectID:m.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(t(x=>{const b=[p,...x.sessions],y=new Map(x.sessionsByDirectory);if(d){const w=y.get(d)??[];y.set(d,Vr([p,...w]))}return{sessions:b,sessionsByDirectory:y,currentSessionId:u,webUICreatedSessions:new Set([...x.webUICreatedSessions,u]),isLoading:!1}}),d)try{Oe.setDirectory(d)}catch(x){console.warn("Failed to sync OpenCode directory after session creation:",x)}const h=x=>{const b=d??null,y=b?{...x,directory:b}:x;t(w=>{const S=w.sessions.map(N=>N.id===u?y:N),M=new Map(w.sessionsByDirectory);if(d){const v=(M.get(d)??[]).map(A=>A.id===u?y:A);M.set(d,Vr(v))}return{sessions:S,sessionsByDirectory:nr(S),currentSessionId:y.id,webUICreatedSessions:new Set([...Array.from(w.webUICreatedSessions).filter(N=>N!==u),y.id])}}),Er(d??null,y.id)},g=async()=>{const x=Oe.getApiClient(),b=20;for(let y=0;y<b;y+=1){try{const w=await x.session.list(d?{directory:d}:void 0),M=(Array.isArray(w.data)?w.data:[]).find(N=>!(f.has(N.id)||s&&N.title&&N.title!==s));if(M)return M}catch(w){console.debug("Session poll attempt failed:",w)}await new Promise(w=>setTimeout(w,2e3))}return null};try{const x=()=>Oe.createSession({title:s,parentID:o??void 0});let b=null;try{b=d?await Oe.withDirectory(d,x):await x()}catch(y){console.warn("Direct session create failed or timed out, falling back to polling:",y)}return b||(b=await g()),b?(h(b),b):(t(y=>({sessions:y.sessions.filter(w=>w.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(w=>w!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(x){return t(b=>({sessions:b.sessions.filter(y=>y.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(b.webUICreatedSessions).filter(y=>y!==u)),isLoading:!1,error:x instanceof Error?x.message:"Failed to create session"})),null}},deleteSession:async(s,n)=>{t({isLoading:!0,error:null});const o=r().worktreeMetadata.get(s),a=Fn(r().sessions,s),l=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await Dd(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Oe.deleteSession(s);if(!(l?await Oe.withDirectory(l,d):await d()))return t(p=>{const h={isLoading:!1,error:"Failed to delete session"};if(c){const g=new Map(p.worktreeMetadata);g.delete(s),h.worktreeMetadata=g}return h}),!1;let m=null;t(p=>{const h=p.sessions.filter(y=>y.id!==s);m=p.currentSessionId===s?null:p.currentSessionId;const g=new Map(p.worktreeMetadata);g.delete(s);const x=n?.archiveWorktree&&o?p.availableWorktrees.filter(y=>At(y.path)!==At(o.path)):p.availableWorktrees,b=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const y=At(o.projectDirectory)??o.projectDirectory,w=b.get(y)??[];b.set(y,w.filter(S=>At(S.path)!==At(o.path)))}return{sessions:h,sessionsByDirectory:nr(h),currentSessionId:m,isLoading:!1,worktreeMetadata:g,availableWorktrees:x,availableWorktreesByProject:b}});const f=l??Oe.getDirectory()??null;return Er(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return t(c?m=>{const f=new Map(m.worktreeMetadata);return f.delete(s),{worktreeMetadata:f,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(s,n)=>{const o=Array.from(new Set(s.filter(b=>typeof b=="string"&&b.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||t({isLoading:!0,error:null});const l=[],c=[],d=new Set,u=[],m=new Set;for(const b of o)try{const y=r().worktreeMetadata.get(b),w=Fn(r().sessions,b),S=y?.path??w;y&&n?.archiveWorktree&&!m.has(y.path)&&(await Dd(y,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(b),u.push({path:y.path,projectDirectory:y.projectDirectory}),m.add(y.path));const M=()=>Oe.deleteSession(b);(S?await Oe.withDirectory(S,M):await M())?(l.push(b),y?.path&&!u.some(v=>v.path===y.path)&&u.push({path:y.path,projectDirectory:y.projectDirectory})):c.push(b)}catch{c.push(b)}const f=xt.getState();u.forEach(({path:b,projectDirectory:y})=>{f.currentDirectory===b&&f.setDirectory(y,{showOverlay:!1})});const p=new Set(l),h=c.length>0?c.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let g=null;t(b=>{const y=b.sessions.filter(v=>!p.has(v.id));b.currentSessionId&&p.has(b.currentSessionId)?g=null:g=b.currentSessionId;const w=new Map(b.worktreeMetadata);for(const v of p)w.delete(v);for(const v of d)w.delete(v);const S=new Set(u.map(v=>At(v.path)).filter(v=>!!v)),M=S.size>0?b.availableWorktrees.filter(v=>!S.has(At(v.path)??v.path)):b.availableWorktrees,N=new Map(b.availableWorktreesByProject);return u.length>0&&u.reduce((A,k)=>{const C=At(k.projectDirectory)??k.projectDirectory,j=At(k.path)??k.path;return A.has(C)||A.set(C,new Set),A.get(C)?.add(j),A},new Map).forEach((A,k)=>{const j=(N.get(k)??[]).filter(T=>!A.has(At(T.path)??T.path));N.set(k,j)}),{sessions:y,sessionsByDirectory:nr(y),currentSessionId:g,...a?{}:{isLoading:!1,error:h},worktreeMetadata:w,availableWorktrees:M,availableWorktreesByProject:N}});const x=Oe.getDirectory()??null;return Er(x,g),{deletedIds:l,failedIds:c}},updateSessionTitle:async(s,n)=>{try{const o=Fn(r().sessions,s),a=r().worktreeMetadata.get(s),l=()=>Oe.updateSession(s,n),c=a?.path??o,d=c?await Oe.withDirectory(c,l):await l();t(u=>{const m=u.sessions.map(f=>f.id===s?d:f);return{sessions:m,sessionsByDirectory:nr(m)}})}catch(o){t({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async s=>{try{const n=Fn(r().sessions,s),o=Oe.getApiClient(),l=r().worktreeMetadata.get(s)?.path??n,c=async()=>{const u=n??Oe.getDirectory();return o.session.share({sessionID:s,...u?{directory:u}:{}})},d=l?await Oe.withDirectory(l,c):await c();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:nr(m)}}),d.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async s=>{try{const n=Fn(r().sessions,s),o=Oe.getApiClient(),l=r().worktreeMetadata.get(s)?.path??n,c=async()=>{const u=n??Oe.getDirectory();return o.session.unshare({sessionID:s,...u?{directory:u}:{}})},d=l?await Oe.withDirectory(l,c):await c();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:nr(m)}}),d.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:s=>{t({currentSessionId:s,error:null});const n=Oe.getDirectory()??null;Er(n,s)},clearError:()=>{t({error:null})},getSessionsByDirectory:s=>{const n=At(s)??s,{sessionsByDirectory:o,sessions:a}=r(),l=o.get(n);return l||a.filter(c=>(At(c.directory??null)??n)===n)},getDirectoryForSession:s=>{if(!s)return null;const n=r().worktreeMetadata.get(s);if(n?.path)return At(n.path)??n.path;const o=r().sessions.find(l=>l.id===s);return At(o?.directory??null)},applySessionMetadata:(s,n)=>{!s||!n||t(o=>{const a=o.sessions.findIndex(h=>h.id===s);if(a===-1)return o;const l=o.sessions[a],c=n.time?{...l.time,...n.time}:l.time,d=n.summary===void 0?l.summary:n.summary||void 0,u=n.share===void 0?l.share:n.share||void 0,m={...l,...n,time:c,summary:d,share:u},f=m.title!==l.title||m.parentID!==l.parentID||m.directory!==l.directory||m.version!==l.version||m.projectID!==l.projectID||JSON.stringify(m.time)!==JSON.stringify(l.time)||JSON.stringify(m.summary??null)!==JSON.stringify(l.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(l.share??null),p=[...o.sessions];return p[a]=f?m:l,{sessions:p,sessionsByDirectory:nr(p)}})},isOpenChamberCreatedSession:s=>{const{webUICreatedSessions:n}=r();return n.has(s)},markSessionAsOpenChamberCreated:s=>{t(n=>{const o=new Set(n.webUICreatedSessions);return o.add(s),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:s=>{const{markSessionAsOpenChamberCreated:n}=r();n(s)},setWorktreeMetadata:(s,n)=>{s&&t(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(s,n):a.delete(s),{worktreeMetadata:a}})},getWorktreeMetadata:s=>{if(s)return r().worktreeMetadata.get(s)},setSessionDirectory:(s,n)=>{if(!s)return;const o=r().sessions,a=o.findIndex(u=>u.id===s);if(a===-1)return;const c=o[a].directory??null,d=n??void 0;c!==(d??null)&&(t(u=>{const m=[...u.sessions],f={...m[a]};return d!==void 0?f.directory=d:delete f.directory,m[a]=f,{sessions:m,sessionsByDirectory:nr(m)}}),c&&Er(c,null),n&&Er(n,s))},updateSession:s=>{t(n=>{const a=n.sessions.findIndex(c=>c.id===s.id)===-1?[s,...n.sessions]:n.sessions.map(c=>c.id===s.id?s:c),l=Vr(a);return{sessions:l,sessionsByDirectory:nr(l)}})},removeSessionFromStore:s=>{s&&t(n=>{const o=n.sessions.find(u=>u.id===s),a=At(o?.directory??null),l=n.sessions.filter(u=>u.id!==s);if(l.length===n.sessions.length)return n;const c=new Map(n.worktreeMetadata);c.delete(s);const d=n.currentSessionId===s?null:n.currentSessionId;return a&&Er(a,null),{sessions:l,sessionsByDirectory:nr(l),currentSessionId:d,worktreeMetadata:c}})}}),{name:"session-store",storage:Ks(()=>Ss()),partialize:t=>({currentSessionId:t.currentSessionId,sessions:t.sessions,lastLoadedDirectory:t.lastLoadedDirectory,webUICreatedSessions:Array.from(t.webUICreatedSessions),worktreeMetadata:Array.from(t.worktreeMetadata.entries()),availableWorktrees:t.availableWorktrees,availableWorktreesByProject:Array.from(t.availableWorktreesByProject.entries())}),merge:(t,r)=>{if(!(p=>typeof p=="object"&&p!==null)(t))return r;const n=Array.isArray(t.sessions)?t.sessions:r.sessions,o=typeof t.currentSessionId=="string"||t.currentSessionId===null?t.currentSessionId:r.currentSessionId,a=Array.isArray(t.webUICreatedSessions)?t.webUICreatedSessions:[],l=Array.isArray(t.worktreeMetadata)?t.worktreeMetadata:[],c=Array.isArray(t.availableWorktrees)?t.availableWorktrees:r.availableWorktrees,d=Array.isArray(t.availableWorktreesByProject)?t.availableWorktreesByProject:[],u=new Map(d),m=typeof t.lastLoadedDirectory=="string"?t.lastLoadedDirectory:r.lastLoadedDirectory??null,f=Vr(n);return{...r,...t,sessions:f,sessionsByDirectory:nr(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(l),availableWorktrees:c,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),Yf="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.",jw="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: ",Bi=t=>typeof t=="string"&&t.trim()===Yf.trim(),zi=(t,r)=>{const s=Date.now(),n=t.get(r),o=new Map(t);return o.set(r,{phase:"streaming",startedAt:n?.startedAt??s,lastUpdateAt:s}),o},yo=(t,r)=>{const s=Array.from(r);if(!s.some(a=>t.has(a)))return t;const o=new Map(t);return s.forEach(a=>{o.delete(a)}),o},Ed=new Map,Qf=t=>{const r=Ed.get(t);r&&(clearTimeout(r),Ed.delete(t))},an=t=>{for(const r of t)Qf(r)},$o=t=>{if(!t)return"";if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>$o(r)).join("");if(typeof t=="object"){if(typeof t.text=="string")return t.text;if(Array.isArray(t.content))return t.content.map(r=>$o(r)).join("")}return""},dn=t=>{if(!t)return"";const r=t;if(typeof r.text=="string")return r.text;if(Array.isArray(r.text))return r.text.map(n=>typeof n=="string"?n:dn(n)).join("");const s=$o(r.delta);return s||(typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||$o(o.delta)||""}return""}).join(""):"")},bo=(t,r)=>{const s={...t};if(s.type=s.type||"text",s.type==="text"){const n=r&&typeof r.text=="string"?r.text:"",o=typeof s.text=="string"?s.text:"",a=$o(t.delta);o?s.text=o:a?s.text=n?`${n}${a}`:a:n?s.text=n:s.text="",delete s.delta}return s},Id=50*1024*1024,Sw=t=>{const r=(t||"").toLowerCase();switch(r.includes(".")&&r.split(".").pop()||""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";case"bmp":return"image/bmp";case"ico":return"image/x-icon";case"pdf":return"application/pdf";default:return"text/plain"}},Nw=t=>{if(t.type&&t.type.trim().length>0)return t.type;const r=(t.name||"").toLowerCase(),s=r.includes(".")&&r.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying"]).has(r))return"text/plain";switch(s){case"md":case"markdown":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"yaml":case"yml":return"application/x-yaml";case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"sh":case"bash":case"zsh":return"text/plain";default:return"application/octet-stream"}},kw=t=>{const r=t.replace(/\s+/g,"");if(!r)return 0;const s=r.endsWith("==")?2:r.endsWith("=")?1:0;return Math.floor(r.length*3/4)-s},Cw=t=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let s="";for(let n=0;n<t.length;n+=3){const o=t[n]??0,a=t[n+1],l=t[n+2],c=o<<16|(a??0)<<8|(l??0);s+=r[c>>18&63],s+=r[c>>12&63],s+=typeof a=="number"?r[c>>6&63]:"=",s+=typeof l=="number"?r[c&63]:"="}return s},fr=is()(hs(qs((t,r)=>({attachedFiles:[],addAttachedFile:async s=>{const{attachedFiles:n}=r();if(n.some(g=>g.filename===s.name&&g.size===s.size)){console.log(`File "${s.name}" is already attached`);return}const a=Id;if(s.size>a)throw new Error(`File "${s.name}" is too large. Maximum size is 50MB.`);const l=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],c=Nw(s);!l.some(g=>c.startsWith(g)||c===g||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const u=new FileReader,m=await new Promise((g,x)=>{u.onload=()=>g(u.result),u.onerror=x,u.readAsDataURL(s)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${c}`):m,p=g=>{const x=g.replace(/\\/g,"/").split("/");return x[x.length-1]||g},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:s,dataUrl:f,mimeType:c,filename:p(s.name),size:s.size,source:"local"};t(g=>({attachedFiles:[...g.attachedFiles,h]}))},addServerFile:async(s,n,o)=>{const{attachedFiles:a}=r();if(a.some(y=>y.serverPath===s&&y.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o,d,u;if(!c)try{const y=Oe.getApiClient(),w=s.lastIndexOf("/"),S=w>0?s.substring(0,w):"/",M=w>0?s.substring(w+1):s,N=await y.file.read({path:M,directory:S});N.data&&"content"in N.data?(c=N.data.content,d=N.data.encoding??void 0,u=N.data.mimeType??void 0):c=""}catch(y){console.error("Failed to read server file:",y),c=`[File: ${n}]`}const m=u||Sw(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const w=new TextEncoder().encode(c||"");return Cw(w)})(),h=d==="base64"?kw(p):new TextEncoder().encode(c||"").length;if(h>Id)throw new Error(`File "${n}" is too large. Maximum size is 50MB.`);const g=new File([],n,{type:f}),x=`data:${f};base64,${p}`,b={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:g,dataUrl:x,mimeType:f,filename:n,size:h,source:"server",serverPath:s};t(y=>({attachedFiles:[...y.attachedFiles,b]}))},removeAttachedFile:s=>{t(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==s)}))},clearAttachedFiles:()=>{t({attachedFiles:[]})}}),{name:"file-store",storage:Ks(()=>Ss()),partialize:t=>({attachedFiles:t.attachedFiles})}),{name:"file-store"})),Mw=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Dw=t=>t?Mw.has(t.toLowerCase()):!1,Aw=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Ew=t=>{if(t)try{const r=Aw();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===t)}catch{}},Iw=(t,r)=>{if(!t||t.length===0)return"ask";for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.permission===r&&n.pattern==="*")return n.action}for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.permission==="*"&&n.pattern==="*")return n.action}return"ask"},Ta=t=>{const r=Ew(t);return r?Iw(r.permission,"edit"):"ask"},Pd=t=>{if(!t||typeof t!="object")return 0;const r=t.input??0,s=t.output??0,n=t.reasoning??0,o=t.cache&&typeof t.cache=="object"?t.cache.read??0:0,a=t.cache&&typeof t.cache=="object"?t.cache.write??0:0;return r+s+n+o+a},Hi=t=>{const r=t.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return Pd(r);const s=t.parts.find(n=>typeof n.tokens<"u");return!s||typeof s.tokens>"u"?0:typeof s.tokens=="number"?s.tokens:Pd(s.tokens)},Wi=(t,r,s)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(s)&&s>0,a=o?Math.max(s,0):0,l=Math.min(o?a:32e3,32e3),c=Math.min(l,n),d=n>0?Math.max(n-c,1):0,u=d>0?t/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},wo=["ask","allow","full"],Td="__global__",tt=is()(hs(qs((t,r)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(s,n,o)=>{t(a=>{const l=new Map(a.sessionModelSelections);return l.set(s,{providerId:n,modelId:o}),{sessionModelSelections:l}})},getSessionModelSelection:s=>{const{sessionModelSelections:n}=r();return n.get(s)||null},saveSessionAgentSelection:(s,n)=>{t(o=>{const a=new Map(o.sessionAgentSelections);a.set(s,n);const l=new Map(o.currentAgentContext);return l.set(s,n),{sessionAgentSelections:a,currentAgentContext:l}})},getSessionAgentSelection:s=>{const{sessionAgentSelections:n}=r();return n.get(s)||null},saveAgentModelForSession:(s,n,o,a)=>{t(l=>{const c=new Map(l.sessionAgentModelSelections);let d=c.get(s);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(s,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(s,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(s);return a&&a.get(n)||null},saveAgentModelVariantForSession:(s,n,o,a,l)=>{t(c=>{const d=new Map(c.sessionAgentModelVariantSelections);let u=d.get(s);u?u=new Map(u):u=new Map;let m=u.get(n);m?m=new Map(m):m=new Map;const f=`${o}/${a}`;return l===void 0?(m.delete(f),m.size===0?(u.delete(n),u.size===0?d.delete(s):d.set(s,u)):(u.set(n,m),d.set(s,u))):(m.set(f,l),u.set(n,m),d.set(s,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(s,n,o,a)=>{const{sessionAgentModelVariantSelections:l}=r(),c=l.get(s);if(!c)return;const d=c.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(s,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:l}=r(),c=new Map,d=(g,x)=>{if("mode"in g&&g.mode&&typeof g.mode=="string"&&n.find(S=>S.name===g.mode))return g.mode;if("agent"in g&&g.agent&&typeof g.agent=="string"&&n.find(S=>S.name===g.agent))return g.agent;if(g.providerID&&g.modelID){const w=n.find(S=>S.model?.providerID===g.providerID&&S.model?.modelID===g.modelID);if(w)return w.name}const{currentAgentContext:b}=r(),y=b.get(s);if(y&&n.find(w=>w.name===y))return y;if(x>0&&g.providerID&&g.modelID){const S=(o.get(s)||[]).filter(M=>M.info.role==="assistant").sort((M,N)=>M.info.time.created-N.info.time.created);for(let M=x-1;M>=0;M--){const v=S[M].info;if(v.providerID===g.providerID&&v.modelID===g.modelID){if(v.mode&&typeof v.mode=="string"&&n.find(C=>C.name===v.mode))return v.mode;const A=n.find(k=>k.model?.providerID===v.providerID&&k.model?.modelID===v.modelID);if(A)return A.name}}}return g.providerID&&g.modelID&&n.find(S=>S.name==="build")?"build":null},u=o.get(s)||[],m=u.filter(g=>g.info.role==="assistant"||g.info.role==="user").sort((g,x)=>g.info.time.created-x.info.time.created),f=u.filter(g=>g.info.role==="assistant").sort((g,x)=>g.info.time.created-x.info.time.created);let p,h;for(let g=0;g<m.length;g++){const x=m[g],{info:b}=x,y=b;if(y.role==="user"){const w=typeof y.mode=="string"&&y.mode.trim().length>0?y.mode:typeof y.agent=="string"&&y.agent.trim().length>0?y.agent:void 0,S=typeof y.model?.providerID=="string"&&y.model.providerID.trim().length>0?y.model.providerID:typeof y.providerID=="string"&&y.providerID.trim().length>0?y.providerID:void 0,M=typeof y.model?.modelID=="string"&&y.model.modelID.trim().length>0?y.model.modelID:typeof y.modelID=="string"&&y.modelID.trim().length>0?y.modelID:void 0;if(w&&S&&M&&n.find(N=>N.name===w)){const N={providerId:S,modelId:M,timestamp:b.time.created},v=c.get(w);(!v||N.timestamp>v.timestamp)&&c.set(w,N),typeof y.variant=="string"&&y.variant.trim().length>0&&l(s,w,S,M,y.variant)}p=typeof y.variant=="string"&&y.variant.trim().length>0?y.variant:void 0,h=y.model?.providerID&&y.model?.modelID?{providerID:y.model.providerID,modelID:y.model.modelID}:void 0;continue}if(y.providerID&&y.modelID){const w=d(y,f.indexOf(x));if(w&&n.find(S=>S.name===w)){p&&h&&h.providerID===y.providerID&&h.modelID===y.modelID&&l(s,w,y.providerID,y.modelID,p);const S={providerId:y.providerID,modelId:y.modelID,timestamp:b.time.created},M=c.get(w);(!M||S.timestamp>M.timestamp)&&c.set(w,S)}}p=void 0,h=void 0}for(const[g,x]of c)a(s,g,x.providerId,x.modelId);return c},getContextUsage:(s,n,o,a)=>{if(!s)return null;const l=Wi(0,n,o),c=l.contextLimit,d=l.normalizedOutput??0,u=l.thresholdLimit;if(c===0||u===0)return null;const f=(a.get(s)||[]).filter(S=>S.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],h=p.info.id,g=S=>{const M=()=>{t(N=>{const v=N.sessionContextUsage.get(s);if(v&&v.totalTokens===S.totalTokens&&v.percentage===S.percentage&&v.contextLimit===S.contextLimit&&(v.outputLimit??0)===(S.outputLimit??0)&&(v.normalizedOutput??0)===(S.normalizedOutput??0)&&v.thresholdLimit===S.thresholdLimit&&v.lastMessageId===S.lastMessageId)return N;const A=new Map(N.sessionContextUsage);return A.set(s,S),{sessionContextUsage:A}})};typeof queueMicrotask=="function"?queueMicrotask(M):typeof window<"u"?window.setTimeout(M,0):setTimeout(M,0)},x=r().sessionContextUsage.get(s);if(x&&x.lastMessageId===h){const S=x.normalizedOutput??x.outputLimit??0,M=x.contextLimit!==c||S!==d||x.thresholdLimit!==u;if(M&&x.totalTokens>0){const N=x.totalTokens/u*100,v={totalTokens:x.totalTokens,percentage:Math.min(N,100),contextLimit:c,outputLimit:l.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return g(v),v}if(!M&&x.totalTokens>0)return x}const b=Hi(p);if(b===0)return x||null;const y=Wi(b,n,o),w={totalTokens:b,percentage:y.percentage,contextLimit:y.contextLimit,outputLimit:y.outputLimit,normalizedOutput:y.normalizedOutput,thresholdLimit:y.thresholdLimit,lastMessageId:h};return g(w),w},updateSessionContextUsage:(s,n,o,a)=>{const c=(a.get(s)||[]).filter(f=>f.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=Hi(d);if(u===0)return;const m=Wi(u,n,o);t(f=>{const p=new Map(f.sessionContextUsage);return p.set(s,{totalTokens:u,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit,normalizedOutput:m.normalizedOutput,thresholdLimit:m.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(s,n,o,a)=>{const c=r().sessionContextUsage.get(s);(!c||c.totalTokens===0)&&r().updateSessionContextUsage(s,n,o,a)},pollForTokenUpdates:(s,n,o,a=10)=>{let l=0;const c=()=>{l++;const u=(o.get(s)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&Hi(u)>0){r().updateSessionContextUsage(s,0,0,o);return}l<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:s=>{const{currentAgentContext:n}=r();return n.get(s)},getSessionAgentEditMode:(s,n,o=Ta(n))=>{if(!s||!n)return o;const l=r().sessionAgentEditModes.get(s)?.get(n);if(l!==void 0)return l;if(s!==Td){const d=r().sessionAgentEditModes.get(Td)?.get(n);if(d!==void 0)return d}return o},setSessionAgentEditMode:(s,n,o,a=Ta(n))=>{if(!s||!n)return;const l=a??"ask";l==="deny"||o==="deny"||wo.includes(o)&&t(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(s)??new Map);return o===l?(u.delete(n),u.size===0?d.delete(s):d.set(s,u)):(u.set(n,o),d.set(s,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(s,n,o=Ta(n))=>{if(!s||!n)return;const a=o??"ask";if(a==="deny")return;const l=r().getSessionAgentEditMode(s,n,a),c=wo.indexOf(l),d=wo.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%wo.length,f=wo[m];r().setSessionAgentEditMode(s,n,f,a)}}),{name:"context-store",storage:Ks(()=>Ss()),partialize:t=>({sessionModelSelections:Array.from(t.sessionModelSelections.entries()),sessionAgentSelections:Array.from(t.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(t.sessionAgentModelSelections.entries()).map(([r,s])=>[r,Array.from(s.entries())]),sessionAgentModelVariantSelections:Array.from(t.sessionAgentModelVariantSelections.entries()).map(([r,s])=>[r,Array.from(s.entries()).map(([n,o])=>[n,Array.from(o.entries())])]),currentAgentContext:Array.from(t.currentAgentContext.entries()),sessionContextUsage:Array.from(t.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(t.sessionAgentEditModes.entries()).map(([r,s])=>[r,Array.from(s.entries())])}),merge:(t,r)=>{const s=new Map;t?.sessionAgentModelSelections&&t.sessionAgentModelSelections.forEach(([a,l])=>{s.set(a,new Map(l))});const n=new Map;t?.sessionAgentModelVariantSelections&&t.sessionAgentModelVariantSelections.forEach(([a,l])=>{const c=new Map;l.forEach(([d,u])=>{c.set(d,new Map(u))}),n.set(a,c)});const o=new Map;return t?.sessionAgentEditModes&&t.sessionAgentEditModes.forEach(([a,l])=>{o.set(a,new Map(l))}),{...r,...t,sessionModelSelections:new Map(t?.sessionModelSelections||[]),sessionAgentSelections:new Map(t?.sessionAgentSelections||[]),sessionAgentModelSelections:s,sessionAgentModelVariantSelections:n,currentAgentContext:new Map(t?.currentAgentContext||[]),sessionContextUsage:new Map(t?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),Fd=(t,r)=>{const s=new Map(t);return s.delete(r),s};let Ui=[],Vi=null;const Pw=50,Tw=3e4,ln=new Map,aa=new Map,Rn=new Map,Fw=10,Xa=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.indexOf("_"),n=s>=0?r.slice(s+1):r;return!n||n.length<Fw?null:n},ia=(t,r)=>{const s=Xa(t),n=Xa(r);return!s||!n||s.length!==n.length?!0:s>n},Rw=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Un=t=>!Array.isArray(t)||t.length===0?0:t.reduce((r,s)=>{if(!s||s.type!=="text")return r;const n=s.text??s.content;return typeof n=="string"?r+n.length:r},0),Za=t=>t?.finish==="stop",Rd=t=>{if(t){if(typeof t.id=="string"&&t.id.length>0)return t.id;if(t.type){const r=t.reason,s=t.callID;return`${t.type}-${r??""}-${s??""}`}}},Ld=new Set,ei=(t=[],r=[])=>{if(!r.length)return[...t];const s=[...t],n=new Set(t.map(Rd).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=Rd(o);a&&n.has(a)||(s.push(o),a&&n.add(a))}),s},Lw=(t,r)=>{const s=Array.isArray(t.parts)?t.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=Un(s),a=Un(n),l=Za(t.info),c=Za(r.info);let d=n;return l&&o>=a?d=ei(s,n):c&&a>=o?d=ei(n,s):o>=a&&(d=s),{...r,info:{...t.info,...r.info},parts:d}},la=t=>{const r=[],s=new Map;for(const n of t){const o=typeof n?.info?.id=="string"?n.info.id:null;if(!o){r.push(n);continue}const a=s.get(o);if(a===void 0){s.set(o,r.length),r.push(n);continue}r[a]=Lw(r[a],n)}return r},Ow=(t,r)=>{let s=r,n=r?Xa(r):null;for(const o of t){const a=o?.info?.id,l=Xa(a);!a||!l||(!n||l>n)&&(n=l,s=a)}return s},xr=(t,r,s)=>{if(t.get(r)===s)return t;const o=new Map(t);return s?o.set(r,s):o.delete(r),o},Ln=(t,r,s)=>{if(t.get(r)===s)return t;const o=new Map(t);return o.set(r,s),o},ca=(t,r)=>{const s=new Map(t);let n=!1;for(const o of r)s.delete(o)&&(n=!0);return n?s:t},_w=(t,r)=>{const s=new Set,n=t.streamingMessageIds.get(r);return n&&s.add(n),t.messageStreamStates.forEach((o,a)=>{t.messageSessionIndex.get(a)===r&&s.add(a)}),s},Od=(t,r,s)=>t.streamingMessageIds.get(r)===s?!0:t.messageSessionIndex.get(s)===r&&t.messageStreamStates.has(s),$w=async t=>{if(t)try{return ht.getState().getDirectoryForSession(t)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},_d=t=>{if(!t)return null;try{return ht.getState().sessions.find(n=>n.id===t)?.revert?.messageID??null}catch{return null}},$d=(t,r)=>{if(!r)return t;const s=t.findIndex(n=>n.info.id===r);return s===-1?t:t.slice(0,s)},Gi=async(t,r)=>{const s=await $w(t);return s?Oe.withDirectory(s,r):r()},St=is()(hs(qs((t,r)=>({messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,messageSessionIndex:new Map,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,pendingAssistantParts:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,pendingAssistantHeaderSessions:new Set,pendingUserMessageMetaBySession:new Map,loadMessages:async(s,n)=>{const o=Ja(),a=n===1/0,l=a?1/0:n??o.HISTORICAL_MESSAGES,c=r().sessionMemoryState.get(s)?.isStreaming,d=c?o.VIEWPORT_MESSAGES:l,u=c||a?void 0:d+o.FETCH_BUFFER,m=await Gi(s,()=>Oe.getSessionMessages(s,u)),f=_d(s),p=$d(m,f),h=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,x=(h?p.filter(b=>{const y=b?.info?.id;return y?ia(y,h):!0}):p).slice(-d);t(b=>{const y=new Map(b.messages),w=b.messages.get(s)||[],S=new Map(w.filter(E=>typeof E.info?.id=="string").map(E=>[E.info.id,E])),M=x.map(E=>{const F={...E.info,clientRole:E.info?.clientRole??E.info.role,userMessageMarker:E.info.role==="user"?!0:E.info?.userMessageMarker},B=(Array.isArray(E.parts)?E.parts:[]).map(ne=>{if(ne?.type==="text"){const O=ne.text??ne.content??"";if(Bi(O))return{...ne,synthetic:!0}}return ne}),V=F?.id?S.get(F.id):void 0;if(V&&V.info.role==="assistant"){const ne=Array.isArray(V.parts)?V.parts:[],O=Un(ne),G=Un(B);if(Za(V.info)&&O>G){const q=ei(ne,B);return{...E,info:F,parts:q}}}return{...E,info:F,parts:B}}),N=la(M),v=new Set(w.map(E=>E.info.id)),A=new Set(N.map(E=>E.info.id)),k=[];v.forEach(E=>{A.has(E)||k.push(E)}),y.set(s,N);const C=new Map(b.sessionMemoryState),j=b.sessionMemoryState.get(s);C.set(s,{...j,viewportAnchor:N.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:m.length,hasMoreAbove:m.length>x.length,trimmedHeadMaxId:j?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const T={messages:y,sessionMemoryState:C};an(k);const I=yo(b.messageStreamStates,k);if(I!==b.messageStreamStates&&(T.messageStreamStates=I),k.length>0){const E=b.streamingMessageIds.get(s);E&&k.includes(E)&&(T.streamingMessageIds=xr(T.streamingMessageIds??b.streamingMessageIds,s,null))}if(k.length>0){const E=ca(T.messageSessionIndex??b.messageSessionIndex,k);E!==(T.messageSessionIndex??b.messageSessionIndex)&&(T.messageSessionIndex=E)}if(k.length>0){const E=new Map(b.pendingAssistantParts);let F=!1;k.forEach(B=>{E.delete(B)&&(F=!0)}),F&&(T.pendingAssistantParts=E)}const P=T.messageSessionIndex??b.messageSessionIndex;let D=P;return N.forEach(E=>{const F=E?.info?.id;typeof F=="string"&&F.length>0&&(D=Ln(D,F,s))}),D!==P&&(T.messageSessionIndex=D),T})},sendMessage:async(s,n,o,a,l,c,d,u,m)=>{if(!l)throw new Error("No session selected");const f=l;r().sessionAbortFlags.has(f)&&t(p=>{const h=new Map(p.sessionAbortFlags);return h.delete(f),{sessionAbortFlags:h}}),await Gi(f,async()=>{try{let p=s;if(s.startsWith("/")){const g=s.indexOf(" "),x=g===-1?s.substring(1):s.substring(1,g),b=g===-1?"":s.substring(g+1).trim(),y=Oe.getApiClient(),w=Oe.getDirectory();if(x==="init"){const S=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await y.session.init({sessionID:f,...w?{directory:w}:{},messageID:S,providerID:n,modelID:o});return}if(x==="summarize"){await y.session.summarize({sessionID:f,...w?{directory:w}:{},providerID:n,modelID:o});return}try{const S=await Oe.getCommandDetails(x);S?.template?p=S.template.replace(/\$ARGUMENTS/g,b):p=s}catch(S){console.error("Command template resolution failed:",S),p=s}}t({lastUsedProvider:{providerID:n,modelID:o}}),t(g=>{const x=g.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},b=Rn.get(f);b&&(clearTimeout(b),Rn.delete(f));const y=new Map(g.sessionMemoryState);return y.set(f,{...x,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:y}});try{const g=new AbortController;t(y=>{const w=new Map(y.abortControllers);return w.set(f,g),{abortControllers:w}});const x=(c??[]).map(y=>({type:"file",mime:y.mimeType,filename:y.filename,url:y.dataUrl}));t(y=>{const w=new Set(y.pendingAssistantHeaderSessions);w.add(f);const S=new Map(y.pendingUserMessageMetaBySession);return S.set(f,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o,variant:typeof m=="string"&&m.trim().length>0?m:void 0}),{pendingAssistantHeaderSessions:w,pendingUserMessageMetaBySession:S}});const b=u?.map(y=>({text:y.text,synthetic:y.synthetic,files:y.attachments?.map(w=>({type:"file",mime:w.mimeType,filename:w.filename,url:w.dataUrl}))}));if(await Oe.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:x.length>0?x:void 0,additionalParts:b&&b.length>0?b:void 0,agentMentions:d?[{name:d}]:void 0}),x.length>0)try{fr.getState().clearAttachedFiles()}catch(y){console.error("Failed to clear attached files after send",y)}t(y=>{const w=new Map(y.abortControllers);return w.delete(f),{abortControllers:w}})}catch(g){let x="Network error while sending message. The message may still be processing.";if(g.name==="AbortError")x="Request timed out. The message may still be processing.";else if(g.message?.includes("504")||g.message?.includes("Gateway")){x="Gateway timeout - your message is being processed. Please wait for response.",t(b=>{const y=new Map(b.abortControllers);return y.delete(f),{abortControllers:y}});return}else g.message&&(x=g.message);throw t(b=>{const y=new Map(b.abortControllers);y.delete(f);const w=new Set(b.pendingAssistantHeaderSessions);w.delete(f);const S=new Map(b.pendingUserMessageMetaBySession);return S.delete(f),{abortControllers:y,pendingAssistantHeaderSessions:w,pendingUserMessageMetaBySession:S}}),new Error(x)}}catch(p){let h="Network error while sending message. The message may still be processing.";throw p.name==="AbortError"?h="Request timed out. The message may still be processing.":p.response?.status===401?h="Session not found or unauthorized. Please refresh the page.":p.response?.status===502?h="OpenCode is restarting. Please wait a moment and try again.":p.message?.includes("504")||p.message?.includes("Gateway")?h="Gateway timeout - your message is being processed. Please wait for response.":p.message&&(h=p.message),t(g=>{const x=new Map(g.abortControllers);x.delete(f);const b=new Set(g.pendingAssistantHeaderSessions);b.delete(f);const y=new Map(g.pendingUserMessageMetaBySession);return y.delete(f),{abortControllers:x,pendingAssistantHeaderSessions:b,pendingUserMessageMetaBySession:y}}),new Error(h)}})},abortCurrentOperation:async s=>{if(!s)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(s)?.abort();const c=_w(n,s);if(c.size===0){const u=s?a.get(s)??[]:[];let m=null;for(let f=u.length-1;f>=0;f-=1){const p=u[f];if(!p||p.info.role!=="assistant")continue;if(m||(m=p.info.id),(p.parts??[]).some(g=>g.type==="reasoning"||g.type==="tool"||g.type==="step-start")){c.add(p.info.id);break}}c.size===0&&m&&c.add(m)}for(const u of c){const m=ln.get(u);m&&(clearTimeout(m),ln.delete(u),aa.delete(u))}c.size>0&&an(c);const d=Date.now();t(u=>{const m=yo(u.messageStreamStates,c),f=u.messages.get(s)??[];let p=!1,h=u.messages;if(f.length>0&&c.size>0){const y=f.map(w=>{if(!c.has(w.info.id)&&c.size>0)return w;const S=(w.parts??[]).map(M=>{if(M.type==="reasoning"){const N=M,v={...N.time??{}};return typeof v.end!="number"&&(v.end=d),{...N,time:v}}if(M.type==="tool"){const N=M,v={...N.state??{}};return(v.status==="running"||v.status==="pending")&&(v.status="aborted"),{...N,state:v}}return M.type==="step-start"?{...M,type:"step-finish",aborted:!0}:M});return p=!0,{...w,info:{...w.info,abortedAt:d,streaming:!1,status:"aborted"},parts:S}});p&&(h=new Map(u.messages),h.set(s,y))}const g=u.sessionMemoryState.get(s);let x=u.sessionMemoryState;if(g){const y=new Map(u.sessionMemoryState);y.set(s,{...g,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),x=y}const b=new Map(u.sessionAbortFlags);return b.set(s,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:x,sessionAbortFlags:b,abortControllers:(()=>{const y=new Map(u.abortControllers);return y.delete(s),y})(),streamingMessageIds:xr(u.streamingMessageIds,s,null),...p?{messages:h}:{}}}),Oe.abortSession(s).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(s,n,o,a,l)=>{const c=r();if(Ld.has(n))return;const d=c.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!ia(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=c.messages.get(s)||[],m=u.find(h=>h.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",p=r().sessionMemoryState.get(s);if(p?.streamStartTime&&Date.now()-p.streamStartTime>Pr.ZOMBIE_TIMEOUT){p.isZombie||t(g=>{const x=new Map(g.sessionMemoryState);return x.set(s,{...p,isZombie:!0}),{sessionMemoryState:x}}),setTimeout(()=>{r().completeStreamingMessage(s,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}t(h=>{const x=[...h.messages.get(s)||[]],b={},y=Ln(h.messageSessionIndex,n,s);y!==h.messageSessionIndex&&(b.messageSessionIndex=y);const w=C=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(s)))return C;const T=new Map(h.sessionAbortFlags);return T.delete(s),{...C,sessionAbortFlags:T}},S=C=>{const j=C||"",T=aa.get(n);if(j&&T===j){const D=r();if(Od(D,s,n)){const E=ln.get(n);E&&(clearTimeout(E),ln.delete(n)),setTimeout(()=>{const F=r();typeof F.forceCompleteMessage=="function"&&F.forceCompleteMessage(s,n,"timeout"),F.completeStreamingMessage(s,n)},100)}}aa.set(n,j);const I=ln.get(n);I&&clearTimeout(I);const P=setTimeout(()=>{const D=r();typeof D.forceCompleteMessage=="function"&&D.forceCompleteMessage(s,n,"timeout"),Od(D,s,n)&&D.completeStreamingMessage(s,n),ln.delete(n),aa.delete(n)},8e3);ln.set(n,P)},M=s!==l,N=h.sessionMemoryState.get(s);if(M&&N?.isStreaming){x.length>=Pr.BACKGROUND_STREAMING_BUFFER&&x.shift();const C=new Map(h.sessionMemoryState);C.set(s,{...N,backgroundMessageCount:(N.backgroundMessageCount||0)+1}),h.sessionMemoryState=C}if(f==="assistant"){const C=h.sessionMemoryState.get(s);if(C){const j=Date.now(),T=new Map(h.sessionMemoryState);T.set(s,{...C,isStreaming:!0,streamStartTime:C.streamStartTime??j,lastAccessedAt:j,isZombie:!1}),h.sessionMemoryState=T}}const v=dn(o);if(Bi(v)&&(o.synthetic=!0),Rw()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:v.length,snapshotParts:u.length})}catch{}const A=b.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const C=xr(A,s,n);C!==A&&(b.streamingMessageIds=C,window.__messageTracker?.(n,"streamingId_set_latest"))}const k=x.findIndex(C=>C.info.id===n);if(k!==-1&&f==="user"){const C=x[k],j=C.parts.findIndex(E=>E.id===o.id);if(o.synthetic===!0){const E=dn(o).trim();if(!(E.startsWith("User has requested to enter plan mode")||E.startsWith("The plan at ")))return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h}const T=bo(o,j!==-1?C.parts[j]:void 0);window.__messageTracker?.(n,`user_part_type:${T.type||"unknown"}`);const I={...C};j!==-1?I.parts=I.parts.map((E,F)=>F===j?T:E):I.parts=[...I.parts,T];const P=[...x];P[k]=I;const D=new Map(h.messages);return D.set(s,P),w({messages:D})}if(f==="assistant"&&k!==-1){const C=x[k],j=C.parts.findIndex(F=>F.id===o.id),T=bo(o,j!==-1?C.parts[j]:void 0);window.__messageTracker?.(n,`part_type:${T.type||"unknown"}`);const I={...C};j!==-1?I.parts=I.parts.map((F,B)=>B===j?T:F):I.parts=[...I.parts,T];const P=[...x];P[k]=I;const D=new Map(h.messages);D.set(s,P),b.messageStreamStates=zi(h.messageStreamStates,n);const E=xr(b.streamingMessageIds??h.streamingMessageIds,s,n);return E!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=E,window.__messageTracker?.(n,"streamingId_set")),T.type==="text"?S(T.text||""):S(""),w({messages:D,...b})}if(k===-1){if(f==="user"){if(o.synthetic===!0){const ye=dn(o).trim();if(!(ye.startsWith("User has requested to enter plan mode")||ye.startsWith("The plan at ")))return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h}const Y=bo(o);window.__messageTracker?.(n,`new_user_part_type:${Y.type||"unknown"}`);const X=h.pendingUserMessageMetaBySession.get(s),Z=tt.getState(),z=X?.mode??Z.getSessionAgentSelection(s)??Z.getCurrentAgent(s),R=typeof z=="string"&&z.trim().length>0?z.trim():void 0,de=X?.providerID??(h.lastUsedProvider?.providerID||void 0),we=X?.modelID??(h.lastUsedProvider?.modelID||void 0);X&&(b.pendingUserMessageMetaBySession=Fd(h.pendingUserMessageMetaBySession,s));const xe={info:{id:n,sessionID:s,role:"user",clientRole:"user",userMessageMarker:!0,...R?{mode:R}:{},...de?{providerID:de}:{},...we?{modelID:we}:{},time:{created:Date.now()}},parts:[Y]},Pe=[...x,xe];Pe.sort((ye,J)=>{const ce=ye.info?.time?.created||0,ge=J.info?.time?.created||0;return ce-ge});const H=new Map(h.messages);return H.set(s,Pe),w({messages:H})}if(o?.type==="text"){const Y=dn(o).trim();if(Y.length>0){const X=[...x].reverse().find(Z=>Z.info.role==="user");if(X){const Z=X.parts.map(z=>dn(z)).join("").trim();if(Z.length>0&&Z===Y)return Ld.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const C=bo(o);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`),C.type==="text"?S(C.text||""):S("");const j=h.pendingAssistantParts.get(n),T=j?[...j.parts]:[],I=T.findIndex(Y=>Y.id===C.id);I!==-1?T[I]=C:T.push(C);const P=new Map(h.pendingAssistantParts);P.set(n,{sessionId:s,parts:T});const D=h.lastUsedProvider?.providerID||"",E=h.lastUsedProvider?.modelID||"",F=Date.now(),B=Oe.getDirectory()??"/",V=tt.getState(),ne=V.getSessionAgentSelection(s)??V.getCurrentAgent(s),O=typeof ne=="string"&&ne.trim().length>0?ne.trim():void 0,G=h.pendingAssistantHeaderSessions.has(s);if(G){const Y=new Set(h.pendingAssistantHeaderSessions);Y.delete(s),b.pendingAssistantHeaderSessions=Y}const q={info:f==="user"?{id:n,sessionID:s,role:"user",time:{created:F},agent:O||"default",model:{providerID:D,modelID:E},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:s,role:"assistant",time:{created:F},parentID:n,modelID:E,providerID:D,mode:O||"default",...G?{openchamberHeaderAnchor:!0}:{},path:{cwd:B,root:B},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:T},$=[...x,q],W=new Map(h.messages);if(W.set(s,$),f==="assistant"){b.messageStreamStates=zi(h.messageStreamStates,n);const Y=xr(b.streamingMessageIds??h.streamingMessageIds,s,n);Y!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=Y,window.__messageTracker?.(n,"streamingId_set"))}return w({messages:W,pendingAssistantParts:P,...b})}else{const C=x[k],j=C.parts.findIndex(E=>E.id===o.id),T=bo(o,j!==-1?C.parts[j]:void 0);window.__messageTracker?.(n,`part_type:${T.type||"unknown"}`);const I={...C};j!==-1?I.parts=I.parts.map((E,F)=>F===j?T:E):I.parts=[...I.parts,T];const P=[...x];P[k]=I;const D=new Map(h.messages);if(D.set(s,P),I.info.role==="assistant"){b.messageStreamStates=zi(h.messageStreamStates,n);const E=xr(b.streamingMessageIds??h.streamingMessageIds,s,n);E!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=E,window.__messageTracker?.(n,"streamingId_set"))}return T.type==="text"?S(T.text||""):S(""),w({messages:D,...b})}})},addStreamingPart:(s,n,o,a,l)=>{if(a!=="user"){r()._addStreamingPartImmediate(s,n,o,a,l);return}Ui.push({sessionId:s,messageId:n,part:o,role:a,currentSessionId:l}),Vi||(Vi=setTimeout(()=>{const c=[...Ui];Ui=[],Vi=null;const d=r();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Pw))},forceCompleteMessage:(s,n,o="timeout")=>{const a=l=>{if(s)return s;for(const[c,d]of l.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};t(l=>{const c=a(l);if(!c)return l;const d=l.messages.get(c)??[],u=d.findIndex(N=>N.info.id===n);if(u===-1)return l;const m=d[u];if(!m)return l;const f=Date.now(),p=m.info,h=typeof p?.time?.completed=="number"&&p.time.completed>0;let g=!1;const x={...p};h||(x.time={...p.time??{},completed:f},g=!0),x.status!=="completed"&&(x.status="completed",g=!0),x.streaming&&(x.streaming=!1,g=!0);let b=!1;const y=m.parts.map(N=>{if(!N)return N;if(N.type==="tool"){const v=N.state;if(!v)return N;const A=v.status,k=A==="running"||A==="pending"||A==="started",C=!v.time||typeof v.time?.end!="number";if(k||C){const j={...v};return k&&(j.status="completed"),C&&(j.time={...v.time??{},end:f}),b=!0,{...N,state:j}}return N}if(N.type==="reasoning"){const v=N.time;return!v||typeof v.end!="number"?(b=!0,{...N,time:{...v??{},end:f}}):N}if(N.type==="text"){const v=N.time;return v&&typeof v.end!="number"?(b=!0,{...N,time:{...v,end:f}}):N}return N});if(!g&&!b)return l;window.__messageTracker?.(n,`force_complete:${o}`);const w={...m,info:x,parts:b?y:m.parts},S=[...d];S[u]=w;const M=new Map(l.messages);return M.set(c,S),{messages:M}})},markMessageStreamSettled:s=>{t(n=>{Qf(s);const o=new Map(n.messageStreamStates);o.delete(s);let a=n.messages,l=!1;return n.messages.forEach((d,u)=>{if(l)return;const m=d.findIndex(x=>x.info.id===s);if(m===-1)return;const f=d[m];if(f.info?.animationSettled)return;const p={...f,info:{...f.info,animationSettled:!0}},h=[...d];h[m]=p;const g=new Map(n.messages);g.set(u,h),a=g,l=!0}),{messageStreamStates:o,...l?{messages:a}:{}}}),an([s])},updateMessageInfo:(s,n,o)=>{t(c=>{const d=c.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!ia(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(s)??[]],f=m.findIndex(k=>k.info.id===n),p=c.pendingAssistantParts.get(n),h=(k=[],C=[])=>{if(!C.length)return k;const j=[...k];return C.forEach(T=>{const I=j.findIndex(P=>P.id===T.id);I===-1?j.push(T):j[I]=T}),j},g=k=>{if(!k)return k;const C=k.clientRole??k.role,j=C==="user"?!0:k.userMessageMarker;return{...k,clientRole:C,...j?{userMessageMarker:!0}:{}}};if(f===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:s,messageId:n,messageInfo:o,existingCount:m.length}),m.length>0){const B=m[0]?.info,V=typeof B?.time?.created=="number"?B.time.created:null,ne=typeof B?.id=="string"?B.id:null,O=o,G=typeof O?.time?.created=="number"?O.time.created:null,K=typeof O?.id=="string"?O.id:n;let q=!1;if(G!==null&&V!==null&&(q=G<V),!q&&K&&ne&&(q=K.localeCompare(ne)<0),q)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const k=g(o);if(k&&k.role==="user"){const F=p?.parts??[],B=c.pendingUserMessageMetaBySession.get(s),V={info:{...k,userMessageMarker:!0,clientRole:"user",...B?.mode?{mode:B.mode}:{},...B?.providerID?{providerID:B.providerID}:{},...B?.modelID?{modelID:B.modelID}:{}},parts:F.length>0?[...F]:[]},ne=new Map(c.messages),O=[...m,V];O.sort((q,$)=>{const W=q.info?.time?.created||0,Y=$.info?.time?.created||0;return W-Y}),ne.set(s,O);const G={messages:ne,...B?{pendingUserMessageMetaBySession:Fd(c.pendingUserMessageMetaBySession,s)}:{}},K=Ln(G.messageSessionIndex??c.messageSessionIndex,n,s);if(K!==(G.messageSessionIndex??c.messageSessionIndex)&&(G.messageSessionIndex=K),p){const q=new Map(c.pendingAssistantParts);q.delete(n),G.pendingAssistantParts=q}return G}if(!k||k.role!=="assistant")return c;const C=p?.parts??[],j=c.pendingAssistantHeaderSessions.has(s),T={info:{...k,animationSettled:k?.animationSettled??!1,...j?{openchamberHeaderAnchor:!0}:{}},parts:C.length>0?[...C]:[]},I=new Map(c.messages),P=[...m,T];I.set(s,P);const D={messages:I,...j?{pendingAssistantHeaderSessions:(()=>{const F=new Set(c.pendingAssistantHeaderSessions);return F.delete(s),F})()}:{}},E=Ln(D.messageSessionIndex??c.messageSessionIndex,n,s);if(E!==(D.messageSessionIndex??c.messageSessionIndex)&&(D.messageSessionIndex=E),p){const F=new Map(c.pendingAssistantParts);F.delete(n),D.pendingAssistantParts=F}return D}const x=m[f],b=x.info;if(b.userMessageMarker===!0||b.clientRole==="user"||b.role==="user"){const k={...x.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:b.providerID||void 0,modelID:b.modelID||void 0},C=c.pendingUserMessageMetaBySession.get(s);C&&!k.mode&&C.mode&&(k.mode=C.mode);const j={...x,info:k},T=new Map(c.messages),I=[...m];if(I[f]=j,T.set(s,I),C){const P=new Map(c.pendingUserMessageMetaBySession);return P.delete(s),{messages:T,pendingUserMessageMetaBySession:P}}return{messages:T}}const w={...x.info,...o};o.role&&o.role!==x.info.role&&(w.role=x.info.role),w.clientRole=w.clientRole??x.info.clientRole??x.info.role,w.clientRole==="user"&&(w.userMessageMarker=!0);const S=p?.parts?h(x.parts,p.parts):x.parts,M={...x,info:w,parts:S},N=new Map(c.messages),v=[...m];v[f]=M,N.set(s,v);const A={messages:N};if(p){const k=new Map(c.pendingAssistantParts);k.delete(n),A.pendingAssistantParts=k}return A});const a=o?.finish,l=o?.role;typeof a=="string"&&l!=="user"&&setTimeout(()=>{r().completeStreamingMessage(s,n)},0)},completeStreamingMessage:(s,n)=>{const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(s)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(s,n,"cooldown");const a=o.streamingMessageIds.get(s)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const l={};if(a&&(l.streamingMessageIds=xr(o.streamingMessageIds,s,null),l.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(s),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),l.messageStreamStates=d}Object.keys(l).length>0&&t(l),o.pendingAssistantParts.has(n)&&t(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),an([n]);let c=!1;if(t(d=>{const u=d.sessionMemoryState.get(s);if(!u||!u.isStreaming)return d;const m=new Map(d.sessionMemoryState),f=Date.now(),p={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:f,streamingCooldownUntil:f+2e3};return m.set(s,p),c=!0,{sessionMemoryState:m}}),c){const d=Rn.get(s);d&&(clearTimeout(d),Rn.delete(s));const u=setTimeout(()=>{t(m=>{const f=m.sessionMemoryState.get(s);if(!f||f.isStreaming)return m;const p=new Map(m.sessionMemoryState),{streamingCooldownUntil:h,...g}=f;return p.set(s,g),{sessionMemoryState:p}}),Rn.delete(s)},2e3);Rn.set(s,u)}},syncMessages:(s,n)=>{const o=_d(s),a=$d(n,o),l=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,c=l?a.filter(d=>{const u=d?.info?.id;return u?ia(u,l):!0}):a;t(d=>{const u=new Map(d.messages),m=d.messages.get(s)||[],f=new Map(m.filter(N=>typeof N.info?.id=="string").map(N=>[N.info.id,N])),p=c.map(N=>{const v={...N.info,clientRole:N.info?.clientRole??N.info.role,userMessageMarker:N.info.role==="user"?!0:N.info?.userMessageMarker,animationSettled:N.info.role==="assistant"?N.info?.animationSettled??!0:N.info?.animationSettled},A=(Array.isArray(N.parts)?N.parts:[]).map(j=>{if(j?.type==="text"){const T=j.text??j.content??"";if(Bi(T))return{...j,synthetic:!0}}return j}),k=typeof v?.id=="string"?v.id:void 0,C=k?f.get(k):void 0;if(C&&C.info.role==="assistant"){const j=Array.isArray(C.parts)?C.parts:[],T=Un(j),I=Un(A);if(Za(C.info)&&T>I){const D=ei(j,A);return{...N,info:v,parts:D}}}return{...N,info:v,parts:A}}),h=la(p),g=new Set(m.map(N=>N.info.id)),x=new Set(h.map(N=>N.info.id)),b=[];g.forEach(N=>{x.has(N)||b.push(N)}),u.set(s,h);const y={messages:u,isSyncing:!0};an(b);const w=yo(d.messageStreamStates,b);if(w!==d.messageStreamStates&&(y.messageStreamStates=w),b.length>0){const N=d.streamingMessageIds.get(s);N&&b.includes(N)&&(y.streamingMessageIds=xr(y.streamingMessageIds??d.streamingMessageIds,s,null))}if(b.length>0){const N=ca(y.messageSessionIndex??d.messageSessionIndex,b);N!==(y.messageSessionIndex??d.messageSessionIndex)&&(y.messageSessionIndex=N)}if(b.length>0){const N=new Map(d.pendingAssistantParts);let v=!1;b.forEach(A=>{N.delete(A)&&(v=!0)}),v&&(y.pendingAssistantParts=N)}const S=y.messageSessionIndex??d.messageSessionIndex;let M=S;return h.forEach(N=>{const v=N?.info?.id;typeof v=="string"&&v.length>0&&(M=Ln(M,v,s))}),M!==S&&(y.messageSessionIndex=M),y}),setTimeout(()=>{t({isSyncing:!1})},100)},updateSessionCompaction:(s,n)=>{t(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(s)?(a.delete(s),{sessionCompactionUntil:a}):o;const l=n+Tw;return a.get(s)===l?o:(a.set(s,l),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:s=>{s&&t(n=>{const o=n.sessionAbortFlags.get(s);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(s,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(s,n)=>{t(o=>{const a=o.sessionMemoryState.get(s)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},l=new Map(o.sessionMemoryState);return l.set(s,{...a,viewportAnchor:n}),{sessionMemoryState:l}})},trimToViewportWindow:(s,n,o)=>{const a=n??Ja().VIEWPORT_MESSAGES,l=r(),c=l.messages.get(s);if(!c||c.length<=a)return;const d=l.sessionMemoryState.get(s)||{viewportAnchor:c.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(d.isStreaming&&s===o)return;const u=d.viewportAnchor||c.length-1;let m=Math.max(0,u-Math.floor(a/2));const f=Math.min(c.length,m+a);f===c.length&&f-m<a&&(m=Math.max(0,f-a));const p=c.slice(m,f),h=c.slice(0,m),g=new Set(p.map(b=>b.info.id)),x=c.filter(b=>!g.has(b.info.id)).map(b=>b.info.id);t(b=>{const y=new Map(b.messages);y.set(s,p);const w=new Map(b.sessionMemoryState),S={...d,viewportAnchor:u-m,trimmedHeadMaxId:Ow(h,d.trimmedHeadMaxId)};w.set(s,S);const M={messages:y,sessionMemoryState:w};an(x);const N=yo(b.messageStreamStates,x);if(N!==b.messageStreamStates&&(M.messageStreamStates=N),x.length>0){const k=b.streamingMessageIds.get(s);k&&x.includes(k)&&(M.streamingMessageIds=xr(M.streamingMessageIds??b.streamingMessageIds,s,null))}if(x.length>0){const k=ca(M.messageSessionIndex??b.messageSessionIndex,x);k!==(M.messageSessionIndex??b.messageSessionIndex)&&(M.messageSessionIndex=k)}const v=M.messageSessionIndex??b.messageSessionIndex;let A=v;return p.forEach(k=>{const C=k?.info?.id;typeof C=="string"&&C.length>0&&(A=Ln(A,C,s))}),A!==v&&(M.messageSessionIndex=A),M})},evictLeastRecentlyUsed:s=>{const n=r();if(n.messages.size<=Pr.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const m=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,m])});const l=a.filter(([d,u])=>d!==s&&!u.isStreaming);if(l.length===0)return;l.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const c=l[0][0];t(d=>{const m=(d.messages.get(c)||[]).map(M=>M.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(c);const h={messages:f,sessionMemoryState:p},g=new Map(d.pendingAssistantParts);let x=!1;g.forEach((M,N)=>{M.sessionId===c&&(g.delete(N),x=!0)}),x&&(h.pendingAssistantParts=g);const b=new Map(d.sessionCompactionUntil);b.delete(c)&&(h.sessionCompactionUntil=b),an(m);const y=yo(d.messageStreamStates,m);y!==d.messageStreamStates&&(h.messageStreamStates=y);const w=ca(h.messageSessionIndex??d.messageSessionIndex,m);w!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=w);const S=xr(d.streamingMessageIds,c,null);if(S!==d.streamingMessageIds&&(h.streamingMessageIds=S),d.abortControllers.has(c)){const M=new Map(d.abortControllers);M.delete(c),h.abortControllers=M}return h})},loadMoreMessages:async(s,n="up")=>{const o=r(),a=o.messages.get(s),l=o.sessionMemoryState.get(s);if(!a||!l||l.totalAvailableMessages&&a.length>=l.totalAvailableMessages)return;const c=await Gi(s,()=>Oe.getSessionMessages(s));if(n==="up"&&a.length>0){const d=la(c),u=a[0],m=d.findIndex(f=>f.info.id===u.info.id);if(m>0){const f=Math.min(Pr.VIEWPORT_MESSAGES,m),p=d.slice(m-f,m);t(h=>{const g=[...p,...a],x=la(g),b=Math.max(0,x.length-a.length),y=new Map(h.messages);y.set(s,x);const w=new Map(h.sessionMemoryState);return w.set(s,{...l,viewportAnchor:l.viewportAnchor+b,hasMoreAbove:m-f>0,totalAvailableMessages:d.length}),{messages:y,sessionMemoryState:w}})}else m===0&&t(f=>{const p=new Map(f.sessionMemoryState);return p.set(s,{...l,hasMoreAbove:!1,totalAvailableMessages:d.length}),{sessionMemoryState:p}})}},getLastMessageModel:s=>{const{messages:n}=r(),o=n.get(s);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const l=o[a];if(l.info.role==="assistant"&&"providerID"in l.info&&"modelID"in l.info)return{providerID:l.info.providerID,modelID:l.info.modelID}}return null}}),{name:"message-store",storage:Ks(()=>Ss()),partialize:t=>({lastUsedProvider:t.lastUsedProvider,sessionMemoryState:Array.from(t.sessionMemoryState.entries()).map(([r,s])=>[r,{viewportAnchor:s.viewportAnchor,isStreaming:s.isStreaming,lastAccessedAt:s.lastAccessedAt,backgroundMessageCount:s.backgroundMessageCount,totalAvailableMessages:s.totalAvailableMessages,hasMoreAbove:s.hasMoreAbove,trimmedHeadMaxId:s.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(t.sessionAbortFlags.entries()).map(([r,s])=>[r,{timestamp:s.timestamp,acknowledged:s.acknowledged}])}),merge:(t,r)=>{if(!t)return r;let s=r.sessionMemoryState;Array.isArray(t.sessionMemoryState)&&(s=new Map(t.sessionMemoryState.map(o=>o)));let n=r.sessionAbortFlags;return Array.isArray(t.sessionAbortFlags)&&(n=new Map(t.sessionAbortFlags)),{...r,lastUsedProvider:t.lastUsedProvider??r.lastUsedProvider,sessionMemoryState:s,sessionAbortFlags:n}}}),{name:"message-store"})),Bw=t=>typeof t=="object"&&t!==null,zw=t=>{if(!Array.isArray(t))return[];const r=[];return t.forEach(s=>{if(!Array.isArray(s)||s.length!==2)return;const[n,o]=s;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},Hw=async(t,r)=>{try{const n=ht.getState().getDirectoryForSession(t);if(n)return Oe.withDirectory(n,r)}catch(s){console.warn("Failed to resolve session directory for permission handling:",s)}return r()},Bo=is()(hs(qs((t,r)=>({permissions:new Map,addPermission:(s,n)=>{const o=s.sessionID;if(!o||r().permissions.get(o)?.some(f=>f.id===s.id))return;const l=s.permission?.toLowerCase?.()??null;let c=n?.currentAgentContext?.get(o);if(c||(c=n?.sessionAgentSelections?.get(o)??void 0),!c&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(c=f.getState().currentAgentName??void 0)}const d=Ta(c),u=n?.getSessionAgentEditMode?.(o,c)??d;if((u==="allow"||u==="full")&&Dw(l)){r().respondToPermission(o,s.id,"once").catch(()=>{});return}t(f=>{const p=f.permissions.get(o)||[],h=new Map(f.permissions);return h.set(o,[...p,s]),{permissions:h}})},respondToPermission:async(s,n,o)=>{await Hw(s,()=>Oe.replyToPermission(n,o)),o==="reject"&&await St.getState().abortCurrentOperation(s),t(a=>{const c=(a.permissions.get(s)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(s,c),{permissions:d}})}}),{name:"permission-store",storage:Ks(()=>Ss()),partialize:t=>({permissions:Array.from(t.permissions.entries())}),merge:(t,r)=>{if(!Bw(t))return r;const s=zw(t.permissions);return{...r,permissions:new Map(s)}}}),{name:"permission-store"})),Ww=t=>typeof t=="object"&&t!==null,Uw=t=>{if(!Array.isArray(t))return[];const r=[];return t.forEach(s=>{if(!Array.isArray(s)||s.length!==2)return;const[n,o]=s;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},Bd=async(t,r)=>{try{const n=ht.getState().getDirectoryForSession(t);if(n)return Oe.withDirectory(n,r)}catch(s){console.warn("Failed to resolve session directory for question handling:",s)}return r()},Vn=is()(hs(qs((t,r)=>({questions:new Map,addQuestion:s=>{const n=s.sessionID;!n||r().questions.get(n)?.some(a=>a.id===s.id)||t(a=>{const l=a.questions.get(n)||[],c=new Map(a.questions);return c.set(n,[...l,s]),{questions:c}})},dismissQuestion:(s,n)=>{!s||!n||t(o=>{const l=(o.questions.get(s)||[]).filter(d=>d.id!==n),c=new Map(o.questions);return c.set(s,l),{questions:c}})},respondToQuestion:async(s,n,o)=>{await Bd(s,()=>Oe.replyToQuestion(n,o)),r().dismissQuestion(s,n)},rejectQuestion:async(s,n)=>{await Bd(s,()=>Oe.rejectQuestion(n)),r().dismissQuestion(s,n)}}),{name:"question-store",storage:Ks(()=>Ss()),partialize:t=>({questions:Array.from(t.questions.entries())}),merge:(t,r)=>{if(!Ww(t))return r;const s=Uw(t.questions);return{...r,questions:new Map(s)}}}),{name:"question-store"})),Sc=t=>t.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
|
|
9
|
+
`).replace(/\n\s*\n+/g,`
|
|
10
|
+
`),Ao=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},zd=(t,r,s)=>{if(!r)return null;const n=s(r)?.path;if(typeof n=="string"&&n.trim().length>0)return Ao(n);const o=t.find(a=>a.id===r);return o?Ao(o.directory??null):null},be=is()(hs((t,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions:new Map,questions:new Map,attachedFiles:[],isLoading:!1,error:null,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,abortPromptSessionId:null,abortPromptExpiresAt:null,sessionActivityPhase:new Map,userSummaryTitles:new Map,pendingInputText:null,newSessionDraft:{open:!0,directoryOverride:null,parentID:null},getSessionAgentEditMode:(s,n,o)=>tt.getState().getSessionAgentEditMode(s,n,o),toggleSessionAgentEditMode:(s,n,o)=>tt.getState().toggleSessionAgentEditMode(s,n,o),setSessionAgentEditMode:(s,n,o,a)=>tt.getState().setSessionAgentEditMode(s,n,o,a),loadSessions:()=>ht.getState().loadSessions(),openNewSessionDraft:s=>{let n=null;s?.directoryOverride!==void 0?n=s.directoryOverride:n=Ft.getState().getActiveProject()?.path??null,t({newSessionDraft:{open:!0,directoryOverride:n,parentID:s?.parentID??null,title:s?.title},currentSessionId:null,error:null});try{const o=Ze.getState(),a=o.getVisibleAgents();let l;if(o.settingsDefaultAgent){const c=a.find(d=>d.name===o.settingsDefaultAgent);c&&(l=c.name)}l||(l=a.find(c=>c.name==="build")?.name||a[0]?.name),l&&o.setAgent(l)}catch{}},closeNewSessionDraft:()=>{const s=ht.getState().currentSessionId;t({newSessionDraft:{open:!1,directoryOverride:null,parentID:null,title:void 0},currentSessionId:s})},createSession:async(s,n,o)=>{r().closeNewSessionDraft();const a=await ht.getState().createSession(s,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async s=>{if(!s)return;const n=St.getState(),{messages:o,lastUsedProvider:a}=n;let l,c;if(o.forEach((y,w)=>{const S=y.find(M=>M.info?.id===s);S&&!l&&(l=S,c=w)}),!l||l.info.role!=="assistant")return;const d=Sc(l.parts);if(!d.trim())return;const u=ht.getState(),m=zd(u.sessions,c??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:g}=Ze.getState(),x=p||a?.providerID,b=h||a?.modelID;!x||!b||await Oe.sendMessage({id:f.id,providerID:x,modelID:b,text:d,prefaceText:Yf,agent:g??void 0})},deleteSession:(s,n)=>ht.getState().deleteSession(s,n),deleteSessions:(s,n)=>ht.getState().deleteSessions(s,n),updateSessionTitle:(s,n)=>ht.getState().updateSessionTitle(s,n),shareSession:s=>ht.getState().shareSession(s),unshareSession:s=>ht.getState().unshareSession(s),setCurrentSession:async s=>{s&&r().closeNewSessionDraft();const n=ht.getState().currentSessionId,o=zd(ht.getState().sessions,s,ht.getState().getWorktreeMetadata),a=Oe.getDirectory()??xt.getState().currentDirectory??null,l=o??a;try{Oe.setDirectory(l??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}if(n&&n!==s&&!r().sessionMemoryState.get(n)?.isStreaming){const d=r().messages.get(n)||[];d.length>0&&r().updateViewportAnchor(n,d.length-1),r().trimToViewportWindow(n,Ja().VIEWPORT_MESSAGES)}if(ht.getState().setCurrentSession(s),s){r().messages.get(s)||await r().loadMessages(s),r().trimToViewportWindow(s,_l());const d=r().messages.get(s);if(d&&d.length>0){const u=Ze.getState().agents;if(u.length>0)try{await tt.getState().analyzeAndSaveExternalSessionChoices(s,u,r().messages)}catch(m){console.warn("Failed to analyze session choices:",m)}}}r().evictLeastRecentlyUsed()},loadMessages:(s,n)=>St.getState().loadMessages(s,n),sendMessage:async(s,n,o,a,l,c,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=w=>{t(S=>{const M=new Map(S.sessionActivityPhase??new Map);return M.set(w,"busy"),{sessionActivityPhase:M}})},h=w=>{t(S=>{const M=new Map(S.sessionActivityPhase??new Map);return M.set(w,"idle"),{sessionActivityPhase:M}})};if(m?.open){const w=await ht.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!w?.id)throw new Error("Failed to create session");const S=Ze.getState(),M=S.currentAgentName,N=f??M,v=S.currentProviderId,A=S.currentModelId;if(v&&A)try{tt.getState().saveSessionModelSelection(w.id,v,A)}catch{}if(N){try{tt.getState().saveSessionAgentSelection(w.id,N)}catch{}if(v&&A){try{tt.getState().saveAgentModelForSession(w.id,N,v,A)}catch{}if(u!==void 0)try{tt.getState().saveAgentModelVariantForSession(w.id,N,v,A,u)}catch{}}}try{ht.getState().initializeNewOpenChamberSession(w.id,S.agents)}catch{}r().closeNewSessionDraft(),p(w.id);try{return await St.getState().sendMessage(s,n,o,N,w.id,l,c,d,u)}catch(k){throw h(w.id),k}}const g=ht.getState().currentSessionId,x=g?tt.getState().getSessionAgentSelection(g):null,b=Ze.getState().currentAgentName,y=f||x||b||void 0;if(g&&y){try{tt.getState().saveSessionAgentSelection(g,y)}catch{}if(u!==void 0)try{tt.getState().saveAgentModelVariantForSession(g,y,n,o,u)}catch{}}g&&p(g);try{return await St.getState().sendMessage(s,n,o,y,g||void 0,l,c,d,u)}catch(w){throw g&&h(g),w}},abortCurrentOperation:()=>{const s=ht.getState().currentSessionId;return St.getState().abortCurrentOperation(s||void 0)},armAbortPrompt:(s=3e3)=>{const n=ht.getState().currentSessionId;if(!n)return null;const o=Date.now()+s;return t({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{t({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:s=>{s&&St.getState().acknowledgeSessionAbort(s)},addStreamingPart:(s,n,o,a)=>{const c=ht.getState().currentSessionId||s;return St.getState().addStreamingPart(s,n,o,a,c)},completeStreamingMessage:(s,n)=>St.getState().completeStreamingMessage(s,n),markMessageStreamSettled:s=>St.getState().markMessageStreamSettled(s),updateMessageInfo:(s,n,o)=>St.getState().updateMessageInfo(s,n,o),updateSessionCompaction:(s,n)=>St.getState().updateSessionCompaction(s,n??null),addPermission:s=>{const n={currentAgentContext:tt.getState().currentAgentContext,sessionAgentSelections:tt.getState().sessionAgentSelections,getSessionAgentEditMode:tt.getState().getSessionAgentEditMode};return Bo.getState().addPermission(s,n)},respondToPermission:(s,n,o)=>Bo.getState().respondToPermission(s,n,o),addQuestion:s=>Vn.getState().addQuestion(s),dismissQuestion:(s,n)=>Vn.getState().dismissQuestion(s,n),respondToQuestion:(s,n,o)=>Vn.getState().respondToQuestion(s,n,o),rejectQuestion:(s,n)=>Vn.getState().rejectQuestion(s,n),clearError:()=>ht.getState().clearError(),getSessionsByDirectory:s=>ht.getState().getSessionsByDirectory(s),getDirectoryForSession:s=>ht.getState().getDirectoryForSession(s),getLastMessageModel:s=>St.getState().getLastMessageModel(s),getCurrentAgent:s=>tt.getState().getCurrentAgent(s),syncMessages:(s,n)=>St.getState().syncMessages(s,n),applySessionMetadata:(s,n)=>ht.getState().applySessionMetadata(s,n),addAttachedFile:s=>fr.getState().addAttachedFile(s),addServerFile:(s,n,o)=>fr.getState().addServerFile(s,n,o),removeAttachedFile:s=>fr.getState().removeAttachedFile(s),clearAttachedFiles:()=>fr.getState().clearAttachedFiles(),updateViewportAnchor:(s,n)=>St.getState().updateViewportAnchor(s,n),trimToViewportWindow:(s,n)=>{const o=ht.getState().currentSessionId,a=r().sessionActivityPhase?.get(s);if(!(a==="busy"||a==="cooldown"))return St.getState().trimToViewportWindow(s,n,o||void 0)},evictLeastRecentlyUsed:()=>{const s=ht.getState().currentSessionId;return St.getState().evictLeastRecentlyUsed(s||void 0)},loadMoreMessages:(s,n)=>St.getState().loadMoreMessages(s,n),saveSessionModelSelection:(s,n,o)=>tt.getState().saveSessionModelSelection(s,n,o),getSessionModelSelection:s=>tt.getState().getSessionModelSelection(s),saveSessionAgentSelection:(s,n)=>tt.getState().saveSessionAgentSelection(s,n),getSessionAgentSelection:s=>tt.getState().getSessionAgentSelection(s),saveAgentModelForSession:(s,n,o,a)=>tt.getState().saveAgentModelForSession(s,n,o,a),getAgentModelForSession:(s,n)=>tt.getState().getAgentModelForSession(s,n),saveAgentModelVariantForSession:(s,n,o,a,l)=>tt.getState().saveAgentModelVariantForSession(s,n,o,a,l),getAgentModelVariantForSession:(s,n,o,a)=>tt.getState().getAgentModelVariantForSession(s,n,o,a),analyzeAndSaveExternalSessionChoices:(s,n)=>{const o=St.getState().messages;return tt.getState().analyzeAndSaveExternalSessionChoices(s,n,o)},isOpenChamberCreatedSession:s=>ht.getState().isOpenChamberCreatedSession(s),markSessionAsOpenChamberCreated:s=>ht.getState().markSessionAsOpenChamberCreated(s),initializeNewOpenChamberSession:(s,n)=>ht.getState().initializeNewOpenChamberSession(s,n),setWorktreeMetadata:(s,n)=>ht.getState().setWorktreeMetadata(s,n),setSessionDirectory:(s,n)=>ht.getState().setSessionDirectory(s,n),getWorktreeMetadata:s=>ht.getState().getWorktreeMetadata(s),getContextUsage:(s,n)=>{if(r().newSessionDraft?.open)return null;const o=ht.getState().currentSessionId;if(!o)return null;const a=St.getState().messages;return tt.getState().getContextUsage(o,s,n,a)},updateSessionContextUsage:(s,n,o)=>{const a=St.getState().messages;return tt.getState().updateSessionContextUsage(s,n,o,a)},initializeSessionContextUsage:(s,n,o)=>{const a=St.getState().messages;return tt.getState().initializeSessionContextUsage(s,n,o,a)},debugSessionMessages:async s=>{const n=St.getState().messages.get(s)||[],o=ht.getState().sessions.find(a=>a.id===s);console.log(`Debug session ${s}:`,{session:o,messageCount:n.length,messages:n.map(a=>({id:a.info.id,role:a.info.role,parts:a.parts.length,tokens:a.info.tokens}))})},pollForTokenUpdates:(s,n,o)=>{const a=St.getState().messages;return tt.getState().pollForTokenUpdates(s,n,a,o)},updateSession:s=>ht.getState().updateSession(s),removeSessionFromStore:s=>ht.getState().removeSessionFromStore(s),revertToMessage:async(s,n)=>{const a=(St.getState().messages.get(s)||[]).find(m=>m.info.id===n);let l="";a&&a.info.role==="user"&&(l=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
|
|
11
|
+
`).trim());const c=await Oe.revertSession(s,n);ht.getState().updateSession(c);const d=St.getState().messages.get(s)||[],u=c.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);St.getState().syncMessages(s,f)}}l&&t({pendingInputText:l})},handleSlashUndo:async s=>{const o=(r().messages.get(s)||[]).filter(p=>p.info.role==="user"),l=r().sessions.find(p=>p.id===s);if(o.length===0)return;const c=l?.revert?.messageID;let d;if(c){const p=o.findIndex(h=>h.info.id===c);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(s,d.info.id);const{toast:f}=await js(async()=>{const{toast:p}=await import("./vendor-.bun-Bui932eM.js").then(h=>h.dj);return{toast:p}},__vite__mapDeps([0,1]));f.success(`Undid to: ${m}`)},handleSlashRedo:async s=>{const a=r().sessions.find(m=>m.id===s)?.revert?.messageID;if(!a)return;const c=(r().messages.get(s)||[]).filter(m=>m.info.role==="user"),d=c.findIndex(m=>m.info.id===a),u=c[d-1];if(u){const m=u.parts.find(h=>h.type==="text"),f=typeof m=="object"&&m&&"text"in m?String(m.text).slice(0,50)+(String(m.text).length>50?"...":""):"[No text]";await r().revertToMessage(s,u.info.id);const{toast:p}=await js(async()=>{const{toast:h}=await import("./vendor-.bun-Bui932eM.js").then(g=>g.dj);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await Oe.unrevertSession(s);await ht.getState().updateSession(m),await r().loadMessages(s);const{toast:f}=await js(async()=>{const{toast:p}=await import("./vendor-.bun-Bui932eM.js").then(h=>h.dj);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(s,n)=>{const a=r().sessions.find(l=>l.id===s);if(a)try{const l=await Oe.forkSession(s,n);if(!l||!l.id){const{toast:f}=await js(async()=>{const{toast:p}=await import("./vendor-.bun-Bui932eM.js").then(h=>h.dj);return{toast:p}},__vite__mapDeps([0,1]));f.error("Failed to fork session");return}const d=(r().messages.get(s)||[]).find(f=>f.info.id===n);if(!d){const{toast:f}=await js(async()=>{const{toast:p}=await import("./vendor-.bun-Bui932eM.js").then(h=>h.dj);return{toast:p}},__vite__mapDeps([0,1]));f.error("Message not found");return}let u="";for(const f of d.parts)f.type==="text"&&!f.synthetic&&!f.ignored&&(u+=f.text||"");r().setCurrentSession(l.id),u&&t({pendingInputText:u}),await r().loadMessages(l.id);const{toast:m}=await js(async()=>{const{toast:f}=await import("./vendor-.bun-Bui932eM.js").then(p=>p.dj);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(l){console.error("Failed to fork session:",l);const{toast:c}=await js(async()=>{const{toast:d}=await import("./vendor-.bun-Bui932eM.js").then(u=>u.dj);return{toast:d}},__vite__mapDeps([0,1]));c.error("Failed to fork session")}},setPendingInputText:s=>{t({pendingInputText:s})},consumePendingInputText:()=>{const s=r().pendingInputText;return s!==null&&t({pendingInputText:null}),s}}),{name:"composed-session-store"}));ht.subscribe((t,r)=>{if(t.sessions===r.sessions&&t.sessionsByDirectory===r.sessionsByDirectory&&t.currentSessionId===r.currentSessionId&&t.lastLoadedDirectory===r.lastLoadedDirectory&&t.isLoading===r.isLoading&&t.error===r.error&&t.webUICreatedSessions===r.webUICreatedSessions&&t.worktreeMetadata===r.worktreeMetadata&&t.availableWorktrees===r.availableWorktrees&&t.availableWorktreesByProject===r.availableWorktreesByProject)return;const s=be.getState().newSessionDraft?.open;be.setState({sessions:t.sessions,sessionsByDirectory:t.sessionsByDirectory,currentSessionId:s?null:t.currentSessionId,lastLoadedDirectory:t.lastLoadedDirectory,isLoading:t.isLoading,error:t.error,webUICreatedSessions:t.webUICreatedSessions,worktreeMetadata:t.worktreeMetadata,availableWorktrees:t.availableWorktrees,availableWorktreesByProject:t.availableWorktreesByProject})});St.subscribe((t,r)=>{if(t.messages===r.messages&&t.sessionMemoryState===r.sessionMemoryState&&t.messageStreamStates===r.messageStreamStates&&t.sessionCompactionUntil===r.sessionCompactionUntil&&t.sessionAbortFlags===r.sessionAbortFlags&&t.streamingMessageIds===r.streamingMessageIds&&t.abortControllers===r.abortControllers&&t.lastUsedProvider===r.lastUsedProvider&&t.isSyncing===r.isSyncing)return;const s=new Map;t.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const l=n[a];if(!l||!l.info)continue;const c=l.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=c.time&&typeof c.time.created=="number"?c.time.created:null;s.set(o,{title:u,createdAt:m});break}}}}}),be.setState({messages:t.messages,sessionMemoryState:t.sessionMemoryState,messageStreamStates:t.messageStreamStates,sessionCompactionUntil:t.sessionCompactionUntil,sessionAbortFlags:t.sessionAbortFlags,streamingMessageIds:t.streamingMessageIds,abortControllers:t.abortControllers,lastUsedProvider:t.lastUsedProvider,isSyncing:t.isSyncing,userSummaryTitles:s})});fr.subscribe((t,r)=>{t.attachedFiles!==r.attachedFiles&&be.setState({attachedFiles:t.attachedFiles})});tt.subscribe((t,r)=>{t.sessionModelSelections===r.sessionModelSelections&&t.sessionAgentSelections===r.sessionAgentSelections&&t.sessionAgentModelSelections===r.sessionAgentModelSelections&&t.currentAgentContext===r.currentAgentContext&&t.sessionContextUsage===r.sessionContextUsage&&t.sessionAgentEditModes===r.sessionAgentEditModes||be.setState({sessionModelSelections:t.sessionModelSelections,sessionAgentSelections:t.sessionAgentSelections,sessionAgentModelSelections:t.sessionAgentModelSelections,currentAgentContext:t.currentAgentContext,sessionContextUsage:t.sessionContextUsage,sessionAgentEditModes:t.sessionAgentEditModes})});Bo.subscribe((t,r)=>{t.permissions!==r.permissions&&be.setState({permissions:t.permissions})});Vn.subscribe((t,r)=>{t.questions!==r.questions&&be.setState({questions:t.questions})});xt.subscribe((t,r)=>{const s=Ao(t.currentDirectory??null),n=Ao(r.currentDirectory??null);if(s===n)return;const o=be.getState().newSessionDraft;if(!o?.open)return;const a=Ao(o.directoryOverride);a&&a!==n||be.setState(l=>({newSessionDraft:{...l.newSessionDraft,directoryOverride:s,parentID:null}}))});const Vw=be.getState().newSessionDraft?.open;be.setState({sessions:ht.getState().sessions,currentSessionId:Vw?null:ht.getState().currentSessionId,lastLoadedDirectory:ht.getState().lastLoadedDirectory,isLoading:ht.getState().isLoading,error:ht.getState().error,webUICreatedSessions:ht.getState().webUICreatedSessions,worktreeMetadata:ht.getState().worktreeMetadata,availableWorktrees:ht.getState().availableWorktrees,availableWorktreesByProject:ht.getState().availableWorktreesByProject,messages:St.getState().messages,sessionMemoryState:St.getState().sessionMemoryState,messageStreamStates:St.getState().messageStreamStates,sessionCompactionUntil:St.getState().sessionCompactionUntil,sessionAbortFlags:St.getState().sessionAbortFlags,streamingMessageIds:St.getState().streamingMessageIds,abortControllers:St.getState().abortControllers,lastUsedProvider:St.getState().lastUsedProvider,isSyncing:St.getState().isSyncing,permissions:Bo.getState().permissions,questions:Vn.getState().questions,attachedFiles:fr.getState().attachedFiles,sessionModelSelections:tt.getState().sessionModelSelections,sessionAgentSelections:tt.getState().sessionAgentSelections,sessionAgentModelSelections:tt.getState().sessionAgentModelSelections,currentAgentContext:tt.getState().currentAgentContext,sessionContextUsage:tt.getState().sessionContextUsage,sessionAgentEditModes:tt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=be);const Gw=async t=>{if(t)return await t.authStatus();const r=await fetch("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),s=await r.json().catch(()=>null);if(!r.ok||!s)throw new Error(s?.error||r.statusText||"Failed to load GitHub status");return s},Bs=is((t,r)=>({status:null,isLoading:!1,hasChecked:!1,setStatus:s=>t({status:s,hasChecked:!0}),refreshStatus:async(s,n)=>{const{hasChecked:o,status:a}=r();if(o&&!n?.force)return a;t({isLoading:!0});try{const l=await Gw(s);return t({status:l,isLoading:!1,hasChecked:!0}),l}catch(l){const c=l instanceof Error?l.message:String(l);return t({status:{connected:!1,error:c},isLoading:!1,hasChecked:!0}),null}}})),Nc=i.createContext(null),Hs=()=>{const t=i.useContext(Nc);if(!t)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return t},Jf=t=>{const r=Hs();return t(r)},qw=()=>Jf(t=>t.runtime.isDesktop),Xf=()=>Jf(t=>t.runtime.isVSCode),kc=({containerRef:t,minThumbSize:r=32,hideDelayMs:s=1e3,className:n,disableHorizontal:o=!1})=>{const[a,l]=i.useState(!1),[c,d]=i.useState({length:0,offset:0}),[u,m]=i.useState({length:0,offset:0}),f=i.useRef(null),p=i.useRef(null),h=i.useRef(!1),g=i.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),x=i.useRef(null),b=i.useCallback(()=>{const C=t.current;if(!C)return;const{scrollHeight:j,clientHeight:T,scrollTop:I,scrollWidth:P,clientWidth:D,scrollLeft:E}=C,F=8;if(j>T){const B=Math.max(T-F*2,0),V=T/j*B,ne=Math.max(r,Math.min(B,V)),O=Math.max(B-ne,0),G=Math.max(j-T,1),K=I/G*O;d({length:ne,offset:K})}else d({length:0,offset:0});if(!o&&P>D){const B=Math.max(D-F*2,0),V=D/P*B,ne=Math.max(r,Math.min(B,V)),O=Math.max(B-ne,0),G=Math.max(P-D,1),K=E/G*O;m({length:ne,offset:K})}else m({length:0,offset:0})},[t,r,o]),y=i.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),s)},[s]),w=i.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{b(),l(!0),y()})},[y,b]);i.useEffect(()=>{const C=t.current;if(!C)return;b(),l(!0),y(),C.addEventListener("scroll",w,{passive:!0});const j=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null;j?.observe(C);const T=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return T?.observe(C,{childList:!0,subtree:!0,characterData:!0}),()=>{C.removeEventListener("scroll",w),j?.disconnect(),T?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[t,w,y,b]);const S=(C,j)=>{const T=t.current;T&&(h.current=!0,g.current={pointerX:C.clientX,pointerY:C.clientY,scrollTop:T.scrollTop,scrollLeft:T.scrollLeft},x.current=j,l(!0),f.current&&clearTimeout(f.current),C.currentTarget.setPointerCapture(C.pointerId))},M=C=>{if(!h.current)return;const j=t.current;if(!j)return;const T=x.current;if(T==="vertical"){const{pointerY:I,scrollTop:P}=g.current,D=C.clientY-I,E=j.clientHeight,F=Math.max(E-c.length,1),B=Math.max(j.scrollHeight-j.clientHeight,1),V=D/F*B;j.scrollTop=P+V}else if(T==="horizontal"){const{pointerX:I,scrollLeft:P}=g.current,D=C.clientX-I,E=j.clientWidth,F=Math.max(E-u.length,1),B=Math.max(j.scrollWidth-j.clientWidth,1),V=D/F*B;j.scrollLeft=P+V}},N=C=>{h.current&&(h.current=!1,C.currentTarget.releasePointerCapture(C.pointerId),y())},v=c.length>0,A=u.length>0;if(!v&&!A)return null;const k=8;return e.jsxs("div",{className:L("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[v&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${k+c.offset}px`,right:`${k/2}px`},onPointerDown:C=>S(C,"vertical"),onPointerMove:M,onPointerUp:N,onPointerCancel:N}),A&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${k+u.offset}px`,bottom:`${k/2}px`},onPointerDown:C=>S(C,"horizontal"),onPointerMove:M,onPointerUp:N,onPointerCancel:N})]})},gt=i.forwardRef(({className:t,outerClassName:r,children:s,style:n,minThumbSize:o,hideDelayMs:a,as:l="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const h=i.useRef(null);return i.useImperativeHandle(p,()=>h.current,[]),e.jsxs("div",{className:L("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-auto",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(l,{ref:h,className:L("overlay-scrollbar-target overlay-scrollbar-container overscroll-auto",u?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",t),style:n,...f,children:s}),e.jsx(kc,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});gt.displayName="ScrollableOverlay";const Hd="mobile-overlay-root",Kw=()=>{if(typeof document>"u")return null;let t=document.getElementById(Hd);return t||(t=document.createElement("div"),t.id=Hd,document.body.appendChild(t)),t},Ws=({open:t,title:r,onClose:s,children:n,footer:o,className:a,contentMaxHeightClassName:l,renderHeader:c})=>{const d=i.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=Kw()),i.useEffect(()=>{if(!t)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const p=h=>{h.key==="Escape"&&s()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",p)}},[t,s]),!t||!d.current)return null;const u=l??"max-h-[min(70vh,520px)]",m=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:s,children:e.jsxs("div",{className:L("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),"data-keyboard-avoid":"true",onClick:f=>f.stopPropagation(),children:[(()=>{const f=e.jsx("button",{type:"button",onClick:s,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(ss,{className:"h-4 w-4"})});return c?c(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(gt,{outerClassName:u,className:"px-2 py-2 pwa-overlay-scroll",children:n}),o?e.jsx("div",{className:"border-t border-border/40 px-3 py-2",children:o}):null]})});return _m.createPortal(m,d.current)},Bl=({totalTokens:t,percentage:r,contextLimit:s,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[l,c]=i.useState(!1),d=i.useRef(void 0),u=b=>b>=1e6?`${(b/1e6).toFixed(1)}M`:b>=1e3?`${(b/1e3).toFixed(1)}K`:b.toFixed(1).replace(/\.0$/,""),m=b=>b>=90?"text-status-error":b>=75?"text-status-warning":"text-status-success",f=typeof n=="number"?Math.max(n,0):0,p=[`Used tokens: ${u(t)}`,`Context limit: ${u(s)}`,`Output limit: ${u(f)}`],h=i.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{c(!0)},500)},[]),g=i.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);i.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const x=e.jsxs("div",{className:L("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?g:void 0,children:[!a&&e.jsx(Qh,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:L(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[x,e.jsx(Ws,{open:l,onClose:()=>c(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(s)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(f)})]}),e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:L("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:x}),e.jsx(ct,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(b=>e.jsx("p",{className:"typography-micro leading-tight",children:b},b))})})]})},vo={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Zf=(t,r,s)=>{if(typeof window>"u")return;const n=document.documentElement,o=r==="mobile",a=r==="tablet";n.classList.remove("device-mobile","device-tablet","device-desktop"),n.classList.add(r==="mobile"?"device-mobile":r==="tablet"?"device-tablet":"device-desktop"),t?(n.classList.add("desktop-runtime"),n.style.setProperty("--is-mobile","0"),n.style.setProperty("--device-type","desktop"),n.style.setProperty("--font-scale","1"),n.style.setProperty("--has-coarse-pointer","0"),n.style.setProperty("--has-touch-input","0"),n.classList.remove("mobile-pointer")):(n.classList.remove("desktop-runtime"),n.style.setProperty("--is-mobile",o?"1":"0"),n.style.setProperty("--device-type",r),n.style.setProperty("--font-scale",o?"0.9":a?"0.95":"1"),n.style.setProperty("--has-coarse-pointer",s?"1":"0"),n.style.setProperty("--has-touch-input",s?"1":"0"),s?n.classList.add("mobile-pointer"):n.classList.remove("mobile-pointer"))};function qi(){const t=window.innerWidth,r=typeof window.matchMedia=="function",s=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=s?.matches??!1,a=n?.matches??!1,l=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||l>0,u=t>vo.md&&t<=vo.lg,m=t<=vo.md;let f=d&&m,p=d&&!f&&u,h=!d||t>vo.lg,g="desktop";c?(f=!1,p=!1,h=!0,g="desktop"):f?g="mobile":p?g="tablet":(h=!0,g="desktop"),Zf(c,g,d);let x="xs";for(const[b,y]of Object.entries(vo))t>=y&&(x=b);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:g,screenWidth:t,breakpoint:x,hasTouchInput:d}}function qt(){const[t,r]=i.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:qi());return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(qi())};return window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[]),i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const s=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(qi())},a=[],l=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return l(s),l(n),()=>{a.forEach(c=>c())}},[]),i.useEffect(()=>{if(typeof window>"u")return;const s=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,l=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=l||c||d>0;Zf(s,t.deviceType,u)},[t.deviceType,t.hasTouchInput]),t}const Qo=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s,newSessionDraft:n}=be(),{currentDirectory:o}=xt();if(t){const a=s.get(t);if(a?.path)return a.path;const c=r.find(d=>d.id===t)?.directory;if(c)return c}return n?.open&&n.directoryOverride?n.directoryOverride:o??void 0},da=5e3,Yw=1e4,Qw=5e3,Jw=1e4,Xw=25,Zw=4,Wd=15e3,yr=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),ev=(t,r)=>{if(!t&&!r)return!1;if(!t||!r)return!0;const s=new Set([...Object.keys(t),...Object.keys(r)]);for(const n of s){const o=t[n],a=r[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},tv=(t,r)=>{if(!t&&!r)return!1;if(!t||!r)return!0;const s=t.files??[],n=r.files??[];if(s.length!==n.length||t.ahead!==r.ahead||t.behind!==r.behind||t.current!==r.current||t.tracking!==r.tracking||t.isClean!==r.isClean)return!0;const o=new Set(s.map(a=>`${a.path}:${a.index}:${a.working_dir}`));for(const a of n)if(!o.has(`${a.path}:${a.index}:${a.working_dir}`))return!0;return!!ev(t.diffStats,r.diffStats)},sv=(t,r)=>{const s=new Set;if(!r)return s;const n=t?.files??[],o=r.files??[],a=new Map(n.map(f=>[f.path,f])),l=new Map(o.map(f=>[f.path,f])),c=new Set([...a.keys(),...l.keys()]);for(const f of c){const p=a.get(f),h=l.get(f);if(!p||!h){s.add(f);continue}if(p.index!==h.index||p.working_dir!==h.working_dir){s.add(f);continue}}const d=t?.diffStats??{},u=r.diffStats??{},m=new Set([...Object.keys(d),...Object.keys(u)]);for(const f of m){const p=d[f],h=u[f];if(!p||!h){s.add(f);continue}(p.insertions!==h.insertions||p.deletions!==h.deletions)&&s.add(f)}return s},ds=is()(hs((t,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:da,setActiveDirectory:s=>{const{activeDirectory:n,directories:o}=r();if(n!==s)if(s&&!o.has(s)){const a=new Map(o);a.set(s,yr()),t({activeDirectory:s,directories:a})}else t({activeDirectory:s})},getDirectoryState:s=>r().directories.get(s)??null,fetchStatus:async(s,n,o={})=>{const{silent:a=!1}=o,{directories:l}=r();let c=l.get(s);c||(c=yr()),a||t({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(s)){const f=new Map(l);return f.set(s,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),t({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(s);if(tv(c.status,m)){d=!0;const f=new Map(r().directories),p=f.get(s)??yr(),h=sv(p.status,m),g=new Set((p.status?.files??[]).map(w=>w.path)),x=new Set((m.files??[]).map(w=>w.path)),b=new Map(p.diffCache);for(const w of g)x.has(w)||b.delete(w);for(const w of h)b.delete(w);const y=h.size>0;f.set(s,{...p,isGitRepo:!0,status:m,diffCache:b,lastStatusFetch:Date.now(),lastStatusChange:y?Date.now():p.lastStatusChange}),t({directories:f})}else{const f=new Map(r().directories),p=f.get(s)??yr();f.set(s,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),t({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||t({isLoadingStatus:!1})}return d},fetchBranches:async(s,n)=>{t({isLoadingBranches:!0});try{const o=await n.getGitBranches(s),a=new Map(r().directories),l=a.get(s)??yr();a.set(s,{...l,branches:o}),t({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{t({isLoadingBranches:!1})}},fetchLog:async(s,n,o)=>{const{directories:a}=r(),l=a.get(s),c=o??l?.logMaxCount??25;t({isLoadingLog:!0});try{const d=await n.getGitLog(s,{maxCount:c}),u=new Map(r().directories),m=u.get(s)??yr();u.set(s,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:c}),t({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{t({isLoadingLog:!1})}},fetchIdentity:async(s,n)=>{t({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(s),a=new Map(r().directories),l=a.get(s)??yr();a.set(s,{...l,identity:o}),t({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{t({isLoadingIdentity:!1})}},fetchAll:async(s,n,o={})=>{const{directories:a}=r();let l=a.get(s);if(!l){l=yr();const f=new Map(a);f.set(s,l),t({directories:f})}const{force:c=!1}=o,d=Date.now();await r().fetchStatus(s,n);const u=r().directories.get(s);if(!u?.isGitRepo)return;await r().fetchBranches(s,n);const m=d-(u.lastLogFetch||0);(c||m>Jw||!u.log)&&await r().fetchLog(s,n),await r().fetchIdentity(s,n),r().fetchAllDiffs(s,n)},getDiff:(s,n)=>r().directories.get(s)?.diffCache.get(n)??null,setDiff:(s,n,o)=>{const a=new Map(r().directories),l=a.get(s)??yr(),c=new Map(l.diffCache);c.set(n,{...o,fetchedAt:Date.now()}),a.set(s,{...l,diffCache:c}),t({directories:a})},clearDiffCache:s=>{const n=new Map(r().directories),o=n.get(s);o&&(n.set(s,{...o,diffCache:new Map}),t({directories:n}))},fetchAllDiffs:async(s,n)=>{const o=r().directories.get(s);if(!o?.status?.files||o.status.files.length===0)return;const c=o.status.files.filter(w=>!o.diffCache.has(w.path)).slice(0,Xw);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(s,{path:w}),M=new Promise((v,A)=>{setTimeout(()=>A(new Error(`Timed out after ${Wd}ms`)),Wd)}),N=await Promise.race([S,M]);return{path:w,diff:{original:N.original??"",modified:N.modified??""}}},p=async()=>{for(;;){const w=m();if(!w)return;try{u.push(await f(w.path))}catch{}}},h=Math.min(Zw,c.length);await Promise.allSettled(Array.from({length:h},()=>p()));const g=new Map(r().directories),x=g.get(s);if(!x)return;const b=new Map(x.diffCache),y=Date.now();u.forEach(w=>{b.set(w.path,{...w.diff,fetchedAt:y})}),g.set(s,{...x,diffCache:b}),t({directories:g})},setLogMaxCount:(s,n)=>{const o=new Map(r().directories),a=o.get(s)??yr();o.set(s,{...a,logMaxCount:n}),t({directories:o})},startPolling:s=>{const{pollIntervalId:n}=r();if(n)return;const o=()=>{const{currentPollInterval:a}=r();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){t({pollIntervalId:o()});return}const{activeDirectory:c}=r();if(!c){t({pollIntervalId:o()});return}if(await r().fetchStatus(c,s,{silent:!0}))await r().fetchLog(c,s),r().fetchAllDiffs(c,s),t({currentPollInterval:da});else{const m=Math.min(a+Qw,Yw);t({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&t({pollIntervalId:o()})},a)};t({pollIntervalId:o(),currentPollInterval:da})},stopPolling:()=>{const{pollIntervalId:s}=r();s&&(clearTimeout(s),t({pollIntervalId:null,currentPollInterval:da}))},refresh:async(s,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,s,n)}}),{name:"git-store"})),ep=t=>ds(r=>t?r.directories.get(t)?.status??null:null),tp=t=>ds(r=>t?r.directories.get(t)?.branches??null:null),rv=t=>ds(r=>t?r.directories.get(t)?.log??null:null),nv=t=>ds(r=>t?r.directories.get(t)?.identity??null:null),sp=t=>ds(r=>t?r.directories.get(t)?.isGitRepo??null:null),ov=t=>ds(r=>t?r.directories.get(t)?.status?.files?.length??0:0),av=Jh("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 je({className:t,variant:r,size:s,asChild:n=!1,...o}){const a=n?$m:"button";return e.jsx(a,{"data-slot":"button",className:L(av({variant:r,size:s,className:t})),...o})}const En=Xh,go=({className:t,...r})=>e.jsx(Zh,{className:L("flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left text-foreground hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",t),...r}),In=({className:t,...r})=>e.jsx(eg,{className:L("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",t),...r}),iv={read:{displayName:"Read File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"offset",label:"Start Line",type:"text"},{key:"limit",label:"Lines to Read",type:"text"}]},write:{displayName:"Write File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"content",label:"Content",type:"code"}]},edit:{displayName:"Edit File",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"oldString",label:"Find",type:"code"},{key:"newString",label:"Replace",type:"code"},{key:"replaceAll",label:"Replace All",type:"text"}]},multiedit:{displayName:"Multi-Edit",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"edits",label:"Edits",type:"code",language:"json"}]},apply_patch:{displayName:"Apply Patch",category:"file",outputLanguage:"diff",inputFields:[{key:"patchText",label:"Patch",type:"code",language:"diff"}]},bash:{displayName:"Shell Command",category:"system",outputLanguage:"text",inputFields:[{key:"command",label:"Command",type:"command",language:"bash"},{key:"description",label:"Description",type:"text"},{key:"timeout",label:"Timeout (ms)",type:"text"}]},grep:{displayName:"Search Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"},{key:"include",label:"Include Pattern",type:"pattern"}]},glob:{displayName:"Find Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"}]},list:{displayName:"List Directory",category:"file",outputLanguage:"text",inputFields:[{key:"path",label:"Directory",type:"file"},{key:"ignore",label:"Ignore Patterns",type:"pattern"}]},task:{displayName:"Agent Task",category:"ai",outputLanguage:"markdown",inputFields:[{key:"description",label:"Task",type:"text"},{key:"prompt",label:"Instructions",type:"text"},{key:"subagent_type",label:"Agent Type",type:"text"}]},webfetch:{displayName:"Fetch URL",category:"web",outputLanguage:"auto",inputFields:[{key:"url",label:"URL",type:"text"},{key:"format",label:"Format",type:"text"},{key:"timeout",label:"Timeout",type:"text"}]},websearch:{displayName:"Web Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"numResults",label:"Results Count",type:"text"},{key:"type",label:"Search Type",type:"text"}]},codesearch:{displayName:"Code Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"tokensNum",label:"Tokens",type:"text"}]},todowrite:{displayName:"Update Todo List",category:"system",outputLanguage:"json",inputFields:[{key:"todos",label:"Todo Items",type:"code",language:"json"}]},todoread:{displayName:"Read Todo List",category:"system",outputLanguage:"json",inputFields:[]},skill:{displayName:"Load Skill",category:"ai",outputLanguage:"markdown",inputFields:[{key:"name",label:"Skill Name",type:"text"}]},question:{displayName:"Question",category:"ai",outputLanguage:"text",inputFields:[{key:"questions",label:"Questions",type:"code",language:"json"}]},plan_enter:{displayName:"Plan Mode",category:"ai",outputLanguage:"text",inputFields:[]},plan_exit:{displayName:"Build Mode",category:"ai",outputLanguage:"text",inputFields:[]}};function Cc(t){return iv[t]||{displayName:t.charAt(0).toUpperCase()+t.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function lv(t,r,s){const n=Cc(t);if(n.outputLanguage==="auto"){if(s?.filePath||s?.file_path||s?.sourcePath){const o=s.filePath||s.file_path||s.sourcePath,a=Ar(o);if(a)return a}if(t==="webfetch"){if(r.trim().startsWith("{")||r.trim().startsWith("["))try{return JSON.parse(r),"json"}catch{}if(r.trim().startsWith("<"))return"html";if(r.includes("```"))return"markdown"}return"text"}return n.outputLanguage||"text"}function Ar(t){const r=t.split(".").pop()?.toLowerCase(),s=t.split("/").pop()?.toLowerCase()||"",n={dockerfile:"dockerfile",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake",gemfile:"ruby",rakefile:"ruby",podfile:"ruby",vagrantfile:"ruby",guardfile:"ruby",brewfile:"ruby",fastfile:"ruby",appfile:"ruby",matchfile:"ruby",pluginfile:"ruby",scanfile:"ruby",snapfile:"ruby",".gitignore":"text",".gitattributes":"text",".gitmodules":"ini",".editorconfig":"ini",".npmrc":"ini",".yarnrc":"yaml",".prettierrc":"json",".eslintrc":"json",".babelrc":"json",".browserslistrc":"text","tsconfig.json":"jsonc","jsconfig.json":"jsonc",".env":"bash",".env.local":"bash",".env.development":"bash",".env.production":"bash",".env.test":"bash",procfile:"yaml",codeowners:"text","package-lock.json":"json","composer.lock":"json","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","cargo.lock":"toml","poetry.lock":"toml","gemfile.lock":"ruby","pubspec.lock":"yaml","packages.lock.json":"json","bun.lockb":"text","bun.lock":"json"};return n[s]?n[s]:{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",mts:"typescript",cts:"typescript",html:"html",htm:"html",xhtml:"html",vue:"html",svelte:"html",astro:"html",ejs:"html",hbs:"handlebars",handlebars:"handlebars",mustache:"handlebars",njk:"twig",nunjucks:"twig",twig:"twig",liquid:"liquid",css:"css",scss:"scss",sass:"sass",less:"less",styl:"stylus",stylus:"stylus",pcss:"css",postcss:"css",json:"json",jsonc:"json",json5:"json",jsonl:"json",ndjson:"json",geojson:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",xsl:"xml",xslt:"xml",xsd:"xml",dtd:"xml",plist:"xml",svg:"xml",rss:"xml",atom:"xml",xaml:"xml",csproj:"xml",vbproj:"xml",fsproj:"xml",props:"xml",targets:"xml",nuspec:"xml",resx:"xml",ini:"ini",cfg:"ini",conf:"ini",config:"ini",properties:"properties",env:"bash",csv:"text",tsv:"text",py:"python",pyw:"python",pyx:"python",pxd:"python",pxi:"python",pyi:"python",gyp:"python",gypi:"python",bzl:"python",rb:"ruby",erb:"erb",rake:"ruby",gemspec:"ruby",ru:"ruby",podspec:"ruby",thor:"ruby",jbuilder:"ruby",rabl:"ruby",builder:"ruby",php:"php",phtml:"php",php3:"php",php4:"php",php5:"php",php7:"php",phps:"php",inc:"php","blade.php":"php",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",sc:"scala",groovy:"groovy",gradle:"groovy",gvy:"groovy",gy:"groovy",gsh:"groovy",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hxx:"cpp",hh:"cpp","h++":"cpp",ino:"cpp",m:"objectivec",mm:"objectivec",cs:"csharp",csx:"csharp",cake:"csharp",fs:"fsharp",fsx:"fsharp",fsi:"fsharp",vb:"vbnet",go:"go",mod:"go",sum:"text",rs:"rust",swift:"swift",dart:"dart",lua:"lua",pl:"perl",pm:"perl",pod:"perl",t:"perl",r:"r",R:"r",rmd:"markdown",rnw:"r",jl:"julia",hs:"haskell",lhs:"haskell",ex:"elixir",exs:"elixir",eex:"elixir",heex:"elixir",leex:"elixir",erl:"erlang",hrl:"erlang",clj:"clojure",cljs:"clojure",cljc:"clojure",edn:"clojure",lisp:"lisp",cl:"lisp",el:"lisp",scm:"scheme",ss:"scheme",rkt:"scheme",ml:"ocaml",mli:"ocaml",re:"reason",rei:"reason",nim:"nim",nims:"nim",nimble:"nim",zig:"zig",v:"v",vsh:"v",cr:"crystal",d:"d",di:"d",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ksh:"bash",csh:"bash",tcsh:"bash",ps1:"powershell",psm1:"powershell",psd1:"powershell",bat:"batch",cmd:"batch",sql:"sql",psql:"sql",plsql:"sql",mysql:"sql",pgsql:"sql",sqlite:"sql",graphql:"graphql",gql:"graphql",sol:"solidity",asm:"nasm",s:"nasm",S:"nasm",nix:"nix",tf:"hcl",tfvars:"hcl",hcl:"hcl",dockerignore:"text",pp:"puppet",tex:"latex",latex:"latex",sty:"latex",cls:"latex",bib:"bibtex",bst:"bibtex",md:"markdown",mdx:"markdown",markdown:"markdown",mdown:"markdown",mkd:"markdown",rst:"text",adoc:"asciidoc",asciidoc:"asciidoc",org:"text",txt:"text",text:"text",rtf:"text",vim:"vim",vimrc:"vim",mk:"makefile",cmake:"cmake",diff:"diff",patch:"diff",prisma:"prisma",proto:"protobuf",thrift:"thrift",wat:"wasm",wast:"wasm",glsl:"glsl",vert:"glsl",frag:"glsl",geom:"glsl",comp:"glsl",hlsl:"hlsl",fx:"hlsl",cg:"cg",shader:"glsl",htaccess:"apacheconf",nginx:"nginx",kubeconfig:"yaml",ansible:"yaml"}[r||""]||null}const cv=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function zo(t){const r=t.split(".").pop()?.toLowerCase();return cv.includes(r||"")}function zl(t){const r=t.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif"}[r||""]||"image/png"}function dv(t,r){if(!t)return"";const s=n=>{const o=t[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(r==="bash"){const n=s("command");if(n)return n}if(r==="task"){const n=s("prompt");if(n)return n;const o=s("description");if(o)return o}if(r==="apply_patch"&&typeof t=="object"){const n=s("patchText")||s("patch_text")||s("patch");if(n)return n}if((r==="edit"||r==="multiedit")&&typeof t=="object"){const n=s("filePath")||s("file_path")||s("path");if(n)return`File path: ${n}`}if(r==="write"&&typeof t=="object"){const n=s("content");if(n)return n}return typeof t=="object"?Object.entries(t).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const l=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${l}: ${c}`}).join(`
|
|
12
|
+
`):String(t)}const rp=({mode:t,onModeChange:r,className:s})=>{const n=i.useCallback(o=>{o.stopPropagation(),r(t==="side-by-side"?"unified":"side-by-side")},[t,r]);return e.jsx(je,{size:"sm",variant:"ghost",className:L("h-5 w-5 p-0 opacity-60 hover:opacity-100",s),onClick:n,title:t==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:t==="side-by-side"?e.jsx(tg,{className:"h-3 w-3"}):e.jsx(sg,{className:"h-3 w-3"})})},Mc=Ae.createContext(void 0);function Hr(){const t=Ae.useContext(Mc);if(!t)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return t}function Ni(){return Ae.useContext(Mc)}const uv="Flexoki",mv="dark",fv={"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"},pv=[{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"}}],hv={name:uv,type:mv,colors:fv,tokenColors:pv},gv="Flexoki",xv="light",yv={"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"},bv=[{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"}}],wv={name:gv,type:xv,colors:yv,tokenColors:bv},Dc="flexoki-dark",Ac="flexoki-light",vv=hv,jv=wv;function np(t,r){return Object.defineProperty(t,"toString",{value:()=>r,enumerable:!1,configurable:!0}),Object.defineProperty(t,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0}),t}function op(t,r,s){const n=t.colors?.["editor.background"],o=t.colors?.["editor.foreground"];if(!n||!o)throw new Error(`Flexoki Shiki theme "${r}" is missing editor.background/editor.foreground`);const a=t.tokenColors??[];return{...t,name:r,type:s,fg:o,bg:n,settings:a}}const Ec=op(vv,Dc,"dark"),Ic=op(jv,Ac,"light");np(Ec,Dc);np(Ic,Ac);const ro={dark:Dc,light:Ac},Ud=[Ic,Ec];let Vd=!1;function ap(){Vd||(Kc(ro.dark,async()=>Ec),Kc(ro.light,async()=>Ic),Vd=!0)}const Ki=({...t})=>{const{theme:r="system"}=rg();return e.jsx(ng,{theme:r,className:"toaster group",closeButton:!1,style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--error-bg":"var(--popover)","--error-text":"var(--popover-foreground)","--error-border":"var(--border)","--success-bg":"var(--popover)","--success-text":"var(--popover-foreground)","--success-border":"var(--border)","--warning-bg":"var(--popover)","--warning-text":"var(--popover-foreground)","--warning-border":"var(--border)","--info-bg":"var(--popover)","--info-text":"var(--popover-foreground)","--info-border":"var(--border)"},...t})},Gd=async t=>{try{await navigator.clipboard.writeText(t)}catch(r){console.error("Failed to copy to clipboard:",r)}},U={...Qs,success:(t,r)=>Qs.success(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),info:(t,r)=>Qs.info(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),error:(t,r)=>Qs.error(t,{...r,action:r?.action||{label:"Copy",onClick:()=>Gd(String(t))}}),warning:(t,r)=>Qs.warning(t,{...r,action:r?.action||{label:"Copy",onClick:()=>Gd(String(t))}})},Fs=Ae.forwardRef(({className:t,...r},s)=>e.jsx(gt,{as:"textarea",ref:s,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:L("text-foreground border-input placeholder:text-muted-foreground appearance-none hover:border-input focus:border-ring focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-3 py-2 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...r}));Fs.displayName="Textarea";const Sv=`
|
|
13
|
+
:host {
|
|
14
|
+
font-family: var(--font-mono);
|
|
15
|
+
font-size: var(--text-code);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
:host, pre, [data-diffs], [data-code] {
|
|
19
|
+
transform: translateZ(0);
|
|
20
|
+
-webkit-transform: translateZ(0);
|
|
21
|
+
-webkit-backface-visibility: hidden;
|
|
22
|
+
backface-visibility: hidden;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
pre, [data-code] {
|
|
26
|
+
font-family: var(--font-mono);
|
|
27
|
+
font-size: var(--text-code);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
[data-code] {
|
|
31
|
+
-webkit-overflow-scrolling: touch;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/* Mobile touch selection support */
|
|
35
|
+
[data-line-number] {
|
|
36
|
+
touch-action: manipulation;
|
|
37
|
+
-webkit-tap-highlight-color: transparent;
|
|
38
|
+
cursor: pointer;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/* Ensure interactive line numbers work on touch */
|
|
42
|
+
pre[data-interactive-line-numbers] [data-line-number] {
|
|
43
|
+
touch-action: manipulation;
|
|
44
|
+
}
|
|
45
|
+
/* Reduce hunk separator height */
|
|
46
|
+
[data-separator-content] {
|
|
47
|
+
height: 24px !important;
|
|
48
|
+
}
|
|
49
|
+
[data-expand-button] {
|
|
50
|
+
height: 24px !important;
|
|
51
|
+
width: 24px !important;
|
|
52
|
+
}
|
|
53
|
+
[data-separator-multi-button] {
|
|
54
|
+
row-gap: 0 !important;
|
|
55
|
+
}
|
|
56
|
+
[data-expand-up] {
|
|
57
|
+
height: 12px !important;
|
|
58
|
+
min-height: 12px !important;
|
|
59
|
+
max-height: 12px !important;
|
|
60
|
+
margin: 0 !important;
|
|
61
|
+
margin-top: 3px !important;
|
|
62
|
+
padding: 0 !important;
|
|
63
|
+
border-radius: 4px 4px 0 0 !important;
|
|
64
|
+
}
|
|
65
|
+
[data-expand-down] {
|
|
66
|
+
height: 12px !important;
|
|
67
|
+
min-height: 12px !important;
|
|
68
|
+
max-height: 12px !important;
|
|
69
|
+
margin: 0 !important;
|
|
70
|
+
margin-top: -3px !important;
|
|
71
|
+
padding: 0 !important;
|
|
72
|
+
border-radius: 0 0 4px 4px !important;
|
|
73
|
+
}
|
|
74
|
+
`;function Nv(t,r,s){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s;return`${t}:${r.length}:${s.length}:${n.length}:${o.length}`}const kv=(t,r,s)=>{const a=(s.side==="deletions"?t:r).split(`
|
|
75
|
+
`),l=Math.max(1,s.start),c=Math.min(a.length,s.end);return l>c?"":a.slice(l-1,c).join(`
|
|
76
|
+
`)},Hl=({original:t,modified:r,language:s,fileName:n="file",renderSideBySide:o,wrapLines:a=!1,layout:l="fill"})=>{const{isMobile:c}=qt(),{inputBarOffset:d,isKeyboardOpen:u}=Me(),f=Ni()?.currentTheme?.metadata?.variant==="dark",p=Me(G=>G.setActiveMainTab),[h,g]=Ae.useState(null),[x,b]=Ae.useState(""),y=Ae.useRef(null),w=Ae.useCallback(()=>{if(c)return"50%";const G=document.querySelector("main.flex-1");if(G){const K=G.getBoundingClientRect();return`${K.left+K.width/2}px`}return"50%"},[c]),[S,M]=Ae.useState(w),N=be(G=>G.sendMessage),v=be(G=>G.currentSessionId),{currentProviderId:A,currentModelId:k,currentAgentName:C,currentVariant:j}=Ze(),T=tt(G=>G.getSessionAgentSelection),I=tt(G=>G.getAgentModelForSession),P=tt(G=>G.getAgentModelVariantForSession);Ae.useEffect(()=>{if(c)return;const G=()=>{M(w())};return window.addEventListener("resize",G),()=>window.removeEventListener("resize",G)},[c,w]);const D=Ae.useCallback(G=>{if(c&&G&&h&&G.start===G.end){const K=G.start,q=h.start,$=h.end,W=Math.min(q,$,K),Y=Math.max(q,$,K);if(K<q||K>$){g({...G,start:W,end:Y});return}}g(G),G||b("")},[c,h]);Ae.useEffect(()=>{if(!h)return;const G=q=>{const $=q.target;if(y.current?.contains($)||$.closest("[data-sonner-toast]")||$.closest("[data-sonner-toaster]"))return;q.composedPath().some(X=>X instanceof HTMLElement?X.hasAttribute("data-line-number")||X.closest?.("[data-line-number]"):!1)||(g(null),b(""))},K=setTimeout(()=>{document.addEventListener("click",G)},100);return()=>{clearTimeout(K),document.removeEventListener("click",G)}},[h]);const E=Ae.useCallback(async()=>{if(!h||!x.trim())return;if(!v){U.error("Select a session to send comment");return}const G=T(v)||C,K=G?I(v,G):null,q=K?.providerId||A,$=K?.modelId||k;if(!q||!$){U.error("Select a model to send comment");return}const W=G&&q&&$?P(v,G,q,$)??j:j,Y=kv(t,r,h),X=h.start,Z=h.end,z=h.side==="deletions"?"original":"modified",R=`Comment on \`${n}\` lines ${X}-${Z} (${z}):
|
|
77
|
+
\`\`\`${s}
|
|
78
|
+
${Y}
|
|
79
|
+
\`\`\`
|
|
80
|
+
|
|
81
|
+
${x}`;b(""),g(null),p("chat"),N(R,q,$,G,void 0,void 0,void 0,W).catch(de=>{console.error("Failed to send comment",de)})},[h,x,t,r,n,s,N,v,A,k,C,j,p,T,I,P]);ap();const F=Ae.useRef(null),B=Ae.useMemo(()=>{const G=Nv(n,t,r);if(F.current?.key===G)return F.current.fileDiff;const K={name:n,contents:t,cacheKey:`old-${G}`},q={name:n,contents:r,cacheKey:`new-${G}`},$=Sl(K,q);return F.current={key:G,fileDiff:$},$},[n,t,r,s]),V=Ae.useMemo(()=>({theme:{dark:ro.dark,light:ro.light},themeType:f?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!0,enableHoverUtility:!1,onLineSelected:D,unsafeCSS:Sv}),[f,o,a,D]);if(typeof window>"u")return null;const O=h?e.jsx("div",{className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-sidebar flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Fs,{value:x,onChange:G=>{b(G.target.value);const K=G.target;K.style.height="auto";const $=20*5+8;K.style.height=`${Math.min(K.scrollHeight,$)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!c,rows:1,onKeyDown:G=>{G.key==="Enter"&&(G.metaKey||G.ctrlKey)&&(G.preventDefault(),E()),G.key==="Escape"&&(G.preventDefault(),g(null),b(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.split("/").pop(),":",h.start,"-",h.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!c&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Xt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:G=>{x.trim()&&(G.preventDefault(),E())},onClick:()=>{c||E()},disabled:!x.trim(),className:L("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",x.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Uo,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return l==="fill"?e.jsxs("div",{className:L("flex flex-col relative","size-full"),style:{paddingBottom:c?"var(--oc-keyboard-inset, 0px)":void 0},children:[e.jsx("div",{className:"flex-1 relative min-h-0",children:e.jsx(gt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,children:e.jsx(Yc,{fileDiff:B,options:V,selectedLines:h})})}),h&&e.jsx("div",{className:L("pointer-events-auto relative pb-2 transition-none z-50 flex justify-center",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:O})]}):e.jsxs("div",{className:L("relative","w-full"),children:[e.jsx("div",{className:"pierre-diff-wrapper w-full overflow-x-auto overflow-y-visible",children:e.jsx(Yc,{fileDiff:B,options:V,selectedLines:h})}),h&&_m.createPortal(e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col justify-end items-start pointer-events-none transition-none transform-gpu",style:{paddingBottom:c?"var(--oc-keyboard-inset, 0px)":"0px",isolation:"isolate"},children:e.jsx("div",{className:L("pointer-events-auto relative pb-2 transition-none",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginLeft:S,transform:"translateX(-50%)",marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:O})}),document.body)]})},Cv=1100,ip=15e3,lp={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},Mv=lp.M,Fa=[{value:"single",label:"Single file",description:"Show one file at a time"},{value:"stacked",label:"All files",description:"Stack all modified files together"}],Dv=t=>{const r=t.index?.trim(),s=t.working_dir?.trim();return r&&r!=="?"?r.charAt(0):s?s.charAt(0):r?.charAt(0)||s?.charAt(0)||"M"},cp=t=>{const r=Dv(t);return lp[r]??Mv},Av=t=>{const{index:r,working_dir:s}=t;return r==="A"||s==="A"||r==="?"||s==="?"},ti=(t,r)=>{const s=t??0,n=r??0;return!s&&!n?null:e.jsxs("span",{className:"typography-meta flex flex-shrink-0 items-center gap-1 text-xs whitespace-nowrap",children:[s?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",s]}):null,n?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",n]}):null]})},Ev=i.memo(({changedFiles:t,selectedFile:r,selectedFileEntry:s,onSelectFile:n,isMobile:o,showModeSelector:a=!1,mode:l,onModeChange:c})=>{const d=i.useCallback(u=>{if(!o)return u;const m=u.lastIndexOf("/");return m>=0?u.slice(m+1):u},[o]);return t.length===0?null:e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[s?e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:d(s.path)}),ti(s.insertions,s.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Ut,{className:"size-4 opacity-50"})]})}),e.jsxs(os,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:[a&&l&&c?e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"typography-meta text-muted-foreground",children:"View mode"}),e.jsx(Va,{value:l,onValueChange:u=>c(u),children:Fa.map(u=>e.jsx(Ga,{value:u.value,className:"items-center",children:e.jsx("span",{className:"typography-meta text-foreground",children:u.label})},u.value))}),e.jsx(Ds,{})]}):null,e.jsx(Va,{value:r??"",onValueChange:n,children:t.map(u=>e.jsx(Ga,{value:u.path,children:e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:d(u.path)}),e.jsx("span",{className:"ml-auto",children:ti(u.insertions,u.deletions)})]})},u.path))})]})]})}),Iv=i.memo(({mode:t,onModeChange:r})=>{const s=Fa.find(n=>n.value===t)??Fa[0];return e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("span",{className:"min-w-0 truncate typography-meta",children:s.label}),e.jsx(Ut,{className:"size-4 opacity-50"})]})}),e.jsx(os,{className:"min-w-[220px]",children:e.jsx(Va,{value:t,onValueChange:n=>r(n),children:Fa.map(n=>e.jsx(Ga,{value:n.value,children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-meta text-foreground",children:n.label}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:n.description})]})},n.value))})})]})}),Pv=i.memo(({changedFiles:t,selectedFile:r,onSelectFile:s})=>t.length===0?null:e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:e.jsx("ul",{className:"flex flex-col gap-1",children:t.map(n=>{const o=cp(n),a=r===n.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(n.path),className:L("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",a?"bg-accent/70 text-foreground":"text-muted-foreground hover:bg-accent/40 hover:text-foreground"),children:[e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:o.color},title:o.description,"aria-label":o.description,children:o.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:n.path,children:n.path}),ti(n.insertions,n.deletions)]})},n.path)})})})),Tv=i.memo(({filePath:t,diff:r,isVisible:s,renderSideBySide:n})=>{const o=r.original.length>0,a=r.modified.length>0;if(!s)return e.jsx("div",{className:"absolute inset-0 hidden"});const l=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",c=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:l,children:[o&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${t}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${t}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Fv=i.memo(({filePath:t,diff:r,renderSideBySide:s})=>{const n=r.original.length>0,o=r.modified.length>0,a=s?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",l=s?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return e.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:e.jsxs("div",{className:a,children:[n&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${t}`,className:s?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:n?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${t}`,className:s?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Rv=i.memo(({filePath:t,diff:r,renderSideBySide:s,wrapLines:n})=>{const o=i.useMemo(()=>Ar(t)||"text",[t]);return zo(t)?e.jsx(Fv,{filePath:t,diff:r,renderSideBySide:s}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(Hl,{original:r.original,modified:r.modified,language:o,fileName:t,renderSideBySide:s,wrapLines:n,layout:"inline"})})}),Lv=i.memo(({filePath:t,diff:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=i.useMemo(()=>Ar(t)||"text",[t]);return zo(t)?e.jsx(Tv,{filePath:t,diff:r,isVisible:s,renderSideBySide:n}):s?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(Hl,{original:r.original,modified:r.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})}):e.jsx("div",{className:"absolute inset-0 hidden",children:e.jsx(Hl,{original:r.original,modified:r.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})})}),Ov=i.memo(({directory:t,filePath:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=ds(i.useCallback(c=>c.directories.get(t)?.diffCache.get(r)??null,[t,r])),l=i.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return l?e.jsx(Lv,{filePath:r,diff:l,isVisible:s,renderSideBySide:n,wrapLines:o}):null}),_v=i.memo(({directory:t,file:r,layout:s,wrapLines:n,scrollRootRef:o,isSelected:a,onSelect:l,registerSectionRef:c})=>{const{git:d}=Hs(),u=ds(i.useCallback(D=>D.directories.get(t)?.diffCache.get(r.path)??null,[t,r.path])),m=ds(D=>D.setDiff),f=Me(D=>D.setDiffFileLayout),[p,h]=i.useState(!0),[g,x]=i.useState(!1),[b,y]=i.useState(0),[w,S]=i.useState(null),[M,N]=i.useState(!1),v=i.useRef(null),A=i.useRef(null),k=i.useMemo(()=>cp(r),[r]),C=s==="side-by-side",j=i.useMemo(()=>u?{original:u.original,modified:u.modified}:null,[u]),T=i.useCallback(D=>{A.current=D,c(r.path,D)},[r.path,c]),I=i.useCallback(D=>{h(D),D&&x(!0)},[]),P=i.useCallback(()=>{l(r.path)},[r.path,l]);return i.useEffect(()=>{if(!p||g)return;const D=A.current;if(!D)return;if(!o.current||typeof IntersectionObserver>"u"){x(!0);return}const E=new IntersectionObserver(F=>{F.some(B=>B.isIntersecting)&&(x(!0),E.disconnect())},{root:o.current,rootMargin:"200px 0px",threshold:.1});return E.observe(D),()=>E.disconnect()},[g,p,o]),i.useEffect(()=>{if(!p||!g)return;if(!t||j){v.current=null,N(!1);return}const D=`${t}::${r.path}::${b}`;if(v.current===D)return;v.current=D,S(null),N(!0);let E=!1;return(async()=>{try{const F=d.getGitFileDiff(t,{path:r.path}),B=ip,V=new Promise((O,G)=>{setTimeout(()=>G(new Error(`Timed out after ${B}ms`)),B)}),ne=await Promise.race([F,V]);if(E)return;m(t,r.path,{original:ne.original??"",modified:ne.modified??""}),N(!1)}catch(F){if(E)return;const B=F instanceof Error?F.message:String(F);S(B),N(!1)}})(),()=>{E=!0,v.current===D&&(v.current=null)}},[t,j,b,r.path,d,g,p,m]),e.jsx("div",{ref:T,className:"scroll-mt-4",children:e.jsxs(En,{open:p,onOpenChange:I,className:"group/collapsible",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background",children:e.jsxs(go,{onClick:P,className:L("relative flex w-full items-center gap-2 px-3 py-1.5 transition-colors rounded-t-xl border border-border/60 overflow-hidden","bg-background hover:bg-background",p?"rounded-b-none":"rounded-b-xl",a?"text-primary":"text-muted-foreground hover:text-foreground"),children:[e.jsx("div",{className:L("absolute inset-0 pointer-events-none transition-colors",a?"bg-primary/10":"group-hover:bg-accent/40")}),e.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[e.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover:opacity-100 transition-opacity",children:p?e.jsx(Ut,{className:"size-4"}):e.jsx(er,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:k.color},title:k.description,"aria-label":k.description,children:k.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",style:{direction:"rtl",textAlign:"left"},title:r.path,children:r.path})]}),e.jsxs("div",{className:"relative flex items-center gap-2",children:[ti(r.insertions,r.deletions),e.jsx(rp,{mode:C?"side-by-side":"unified",onModeChange:D=>{const E=D==="side-by-side"?"side-by-side":"inline";f(r.path,E)},className:"opacity-70"})]})]})}),e.jsx(In,{children:e.jsxs("div",{className:"relative border border-t-0 border-border/60 bg-background rounded-b-xl overflow-hidden",children:[w?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:w}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>y(D=>D+1),children:"Retry"})]}):null,M&&!j&&!w?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(Ct,{size:16,className:"animate-spin"}),"Loading diff…"]}):null,j?e.jsx(Rv,{filePath:r.path,diff:j,renderSideBySide:C,wrapLines:n}):null]})})]})})}),$v=()=>{const{git:t}=Hs(),r=Qo(),{screenWidth:s,isMobile:n}=qt(),o=sp(r??null),a=ep(r??null),l=ds(H=>H.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=ds(),[m,f]=i.useState(null),[p,h]=i.useState(0),[g,x]=i.useState(null),b=i.useRef(null),y=Me(H=>H.pendingDiffFile),w=Me(H=>H.setPendingDiffFile),S=Me(H=>H.diffLayoutPreference),M=Me(H=>H.diffFileLayout),N=Me(H=>H.setDiffFileLayout),v=Me(H=>H.diffWrapLines),A=Me(H=>H.setDiffWrapLines),k=Me(H=>H.diffViewMode),C=Me(H=>H.setDiffViewMode),j=n||v,T=k==="stacked",I=n||s<=768,P=!I&&s>=1024,D=i.useRef(null),E=i.useRef(new Map),F=i.useRef(null),B=i.useMemo(()=>{if(!a?.files)return[];const H=a.diffStats??{};return a.files.map(ye=>({...ye,insertions:H[ye.path]?.insertions??0,deletions:H[ye.path]?.deletions??0,isNew:Av(ye)})).sort((ye,J)=>ye.path.localeCompare(J.path))},[a]),V=i.useMemo(()=>m?B.find(H=>H.path===m)??null:null,[B,m]),ne=i.useCallback(H=>{const ye=M[H.path];if(ye)return ye;if(S==="inline")return"inline";if(S==="side-by-side")return"side-by-side";const J=s<Cv;return H.isNew||J?"inline":"side-by-side"},[M,S,s]),O=i.useMemo(()=>V?ne(V):null,[ne,V]);i.useEffect(()=>{r&&(c(r),ds.getState().directories.get(r)?.status||d(r,t))},[r,c,d,t]),i.useEffect(()=>{y&&(f(y),w(null),T&&(F.current=y))},[T,y,w]),i.useEffect(()=>{!m&&!y&&B.length>0&&f(B[0].path)},[B,m,y]),i.useEffect(()=>{if(!T){F.current=null;return}const H=F.current;if(!H)return;const ye=E.current.get(H);ye&&(ye.scrollIntoView({behavior:"smooth",block:"start"}),F.current=null)},[B,T]),i.useEffect(()=>{m&&B.length>0&&(B.some(ye=>ye.path===m)||f(B[0]?.path??null))},[B,m]);const G=i.useCallback((H,ye)=>{const J=E.current;ye?J.set(H,ye):J.delete(H)},[]),K=i.useCallback((H,ye="smooth")=>{const J=E.current.get(H);return J?(J.scrollIntoView({behavior:ye,block:"start"}),!0):!1},[]),q=i.useCallback(H=>{f(H)},[]),$=i.useCallback(H=>{f(H),T&&!K(H)&&(F.current=H)},[T,K]),W=i.useCallback(H=>{C(H),H==="stacked"&&m&&!K(m,"auto")&&(F.current=m)},[K,m,C]),Y=i.useCallback(H=>{const ye=H==="side-by-side"?"side-by-side":"inline";if(T){B.forEach(J=>{N(J.path,ye)});return}V&&N(V.path,ye)},[B,T,V,N]),X=(O??"side-by-side")==="side-by-side",Z=!T||!P,z=ds(i.useCallback(H=>!r||!m?null:H.directories.get(r)?.diffCache.get(m)??null,[r,m])),R=!!z,de=!T&&!!m&&!R;i.useEffect(()=>{if(T)return;if(x(null),!r||!m){b.current=null;return}if(z){b.current=null;return}const H=`${r}::${m}::${p}`;if(b.current===H)return;b.current=H;let ye=!1;return(async()=>{try{const J=t.getGitFileDiff(r,{path:m}),ce=ip,ge=new Promise((me,le)=>{setTimeout(()=>le(new Error(`Timed out after ${ce}ms`)),ce)}),ee=await Promise.race([J,ge]);if(ye)return;u(r,m,{original:ee.original??"",modified:ee.modified??""})}catch(J){if(ye)return;const ce=J instanceof Error?J.message:String(J);x(ce)}})(),()=>{ye=!0,b.current===H&&(b.current=null)}},[r,T,m,z,t,u,p]);const we=()=>!r||B.length===0?null:B.map(H=>e.jsx(Ov,{directory:r,filePath:H.path,isVisible:H.path===m,renderSideBySide:X,wrapLines:j},H.path)),xe=()=>r?e.jsxs("div",{className:"flex flex-1 min-h-0 h-full gap-3 px-3 pb-3 pt-2",children:[P&&e.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:B.length})]}),e.jsx(Pv,{changedFiles:B,selectedFile:m,onSelectFile:$})]}),e.jsx(gt,{ref:D,outerClassName:"flex-1 min-h-0 h-full",className:"pr-2",disableHorizontal:!0,children:e.jsx("div",{className:"flex flex-col gap-3",children:B.map(H=>e.jsx(_v,{directory:r,file:H,layout:ne(H),wrapLines:j,scrollRootRef:D,isSelected:H.path===m,onSelect:q,registerSectionRef:G},H.path))})})]}):null,Pe=()=>r?l&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{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."}):B.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"}):T?xe():e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[we(),de&&!R&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:g?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:g}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{x(null),h(H=>H+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ct,{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(oc,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:l&&!a?"Loading changes…":`${B.length} ${B.length===1?"file":"files"} changed`})]}),!I&&e.jsx(Iv,{mode:k,onModeChange:W}),Z&&e.jsx(Ev,{changedFiles:B,selectedFile:m,selectedFileEntry:V,onSelectFile:$,isMobile:I,showModeSelector:I,mode:k,onModeChange:W}),e.jsx("div",{className:"flex-1"}),V&&e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>A(!v),className:L("h-5 w-5 p-0 transition-opacity",j?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:j?"Disable line wrap":"Enable line wrap",children:e.jsx(Nl,{className:"size-4"})}),V&&O&&e.jsx(rp,{mode:O==="side-by-side"?"side-by-side":"unified",onModeChange:Y})]}),Pe()]})},Bv=()=>{const{git:t}=Hs(),r=Qo(),{setActiveDirectory:s,fetchStatus:n}=ds(),o=ov(r??null);return i.useEffect(()=>{r&&(s(r),ds.getState().directories.get(r)?.status||n(r,t))},[r,s,n,t]),o},yn=Ae.forwardRef(({className:t,...r},s)=>e.jsx(Bm,{className:L("peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted-foreground/30",t),style:{width:"36px",height:"20px",minWidth:"36px",minHeight:"20px"},...r,ref:s,children:e.jsx(og,{className:L("pointer-events-none block rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"),style:{width:"16px",height:"16px",minWidth:"16px",minHeight:"16px"}})}));yn.displayName=Bm.displayName;const zv={},Ra=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s.length>1?s.replace(/\/+$/,""):s},qd=t=>Ra(t)??"__global__",Hv=t=>{const r=Object.entries(t??{}),s=r.filter(([,l])=>l?.status==="connected").length,n=r.length,o=r.some(([,l])=>l?.status==="failed"),a=r.some(([,l])=>l?.status==="needs_auth"||l?.status==="needs_client_registration");return{connected:s,total:n,hasFailed:o,hasAuthRequired:a}},ko=is()(hs((t,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:s=>{const n=qd(s??xt.getState().currentDirectory);return r().byDirectory[n]??zv},refresh:async s=>{const n=Ra(s?.directory??xt.getState().currentDirectory),o=qd(n);s?.silent||t(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const c=(await Oe.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};t(d=>({byDirectory:{...d.byDirectory,[o]:c},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const l=a instanceof Error?a.message:"Failed to load MCP status";t(c=>({loadingKeys:{...c.loadingKeys,[o]:!1},lastErrorKeys:{...c.lastErrorKeys,[o]:l}}))}},connect:async(s,n)=>{const o=Ra(n??xt.getState().currentDirectory);await Oe.getApiClient().mcp.connect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(s,n)=>{const o=Ra(n??xt.getState().currentDirectory);await Oe.getApiClient().mcp.disconnect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function Wv(t){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",stroke:"currentColor",strokeWidth:"0.5",fillRule:"evenodd",viewBox:"-0.5 -0.5 25 25",...t,children:[e.jsx("path",{d:"M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"}),e.jsx("path",{d:"M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"})]})}const Uv=t=>{if(!t)return"Unknown";switch(t.status){case"connected":return"Connected";case"failed":return`Failed: ${t.error||"Unknown error"}`;case"needs_auth":return"Needs authentication";case"needs_client_registration":return`Needs registration: ${t.error||""}`;default:return t.status}},Vv=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},Wl=({headerIconButtonClass:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(!1),{isMobile:l}=qt(),d=xt(k=>k.currentDirectory)??null,u=ko(k=>k.getStatusForDirectory(d)),m=ko(k=>k.refresh),f=ko(k=>k.connect),p=ko(k=>k.disconnect),h=i.useCallback(k=>{k||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),s(k)},[]),g=i.useCallback(k=>{a.current||o(k)},[]),[x,b]=i.useState(!1),[y,w]=i.useState(null);i.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),i.useEffect(()=>{r&&m({directory:d,silent:!0})},[r,m,d]);const S=i.useMemo(()=>Hv(u),[u]),M=i.useMemo(()=>Object.keys(u).sort((k,C)=>k.localeCompare(C)),[u]),N=i.useCallback(k=>{if(k?.preventDefault(),x)return;b(!0);const C=new Promise(j=>setTimeout(j,500));Promise.all([m({directory:d}),C]).finally(()=>{b(!1)})},[x,m,d]),v=()=>e.jsxs(e.Fragment,{children:[M.map(k=>{const C=u[k],j=Vv(C),T=C?.status==="connected",I=y===k,P=Uv(C);return e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-muted/50",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l?e.jsx("span",{className:L("h-2 w-2 rounded-full flex-shrink-0",j==="success"&&"bg-status-success",j==="error"&&"bg-status-error",j==="warning"&&"bg-status-warning",j==="default"&&"bg-muted-foreground/40"),"aria-label":P}):e.jsxs(dt,{delayDuration:300,children:[e.jsx(ut,{asChild:!0,children:e.jsx("span",{className:L("h-2 w-2 rounded-full flex-shrink-0",j==="success"&&"bg-status-success",j==="error"&&"bg-status-error",j==="warning"&&"bg-status-warning",j==="default"&&"bg-muted-foreground/40"),"aria-label":P})}),e.jsx(ct,{side:"left",children:e.jsx("p",{children:P})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:k})]})}),e.jsx(yn,{checked:T,disabled:I,className:"data-[state=checked]:bg-status-info",onCheckedChange:async D=>{w(k);try{D?await f(k,d):await p(k,d)}finally{w(null)}}})]},k)}),M.length===0&&e.jsx("div",{className:"px-2 py-3 typography-ui-label text-muted-foreground text-center",children:"Configure MCP servers in Opencode config."})]}),A=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:L(t,"relative"),onClick:l?()=>s(!0):void 0,children:[e.jsx(Wv,{className:"h-[1.0625rem] w-[1.0625rem]"}),S.total>0&&e.jsx("span",{className:L("absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full",S.hasFailed?"bg-status-error":S.hasAuthRequired?"bg-status-warning":S.connected>0?"bg-status-success":"bg-muted-foreground/40"),"aria-label":"MCP status"})]});return l?e.jsxs(e.Fragment,{children:[A,e.jsxs(Ws,{open:r,title:"MCP Servers",onClose:()=>s(!1),renderHeader:k=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"MCP Servers"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{type:"button",className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",disabled:x,onClick:N,"aria-label":"Refresh",children:e.jsx(Xr,{className:L("h-4 w-4",x&&"animate-spin")})}),k]})]}),children:[e.jsx("div",{className:"py-1",children:v()}),d&&e.jsx("div",{className:"px-2 py-1 border-t border-border/40 mt-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]}):e.jsxs(rs,{open:r,onOpenChange:h,children:[e.jsxs(dt,{delayDuration:1e3,open:r?!1:n,onOpenChange:g,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ns,{asChild:!0,children:A})}),e.jsx(ct,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsxs(os,{align:"end",className:"w-72",children:[e.jsxs("div",{className:"flex items-center justify-between px-2 py-1",children:[e.jsx("span",{className:"typography-ui-label font-semibold",children:"MCP Servers"}),e.jsx("button",{type:"button",className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",disabled:x,onClick:N,"aria-label":"Refresh",children:e.jsx(Xr,{className:L("h-4 w-4",x&&"animate-spin")})})]}),e.jsx(Ds,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:v()}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),e.jsx("div",{className:"px-2 py-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]})]})},dp=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Kd=(t,r)=>{const s=dp(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},Gv=t=>Kd(Kd(t,".opencode"),"plans"),qv=()=>"~/.opencode/plans",Kv=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},Yd=()=>{const t=Me(J=>J.setSessionSwitcherOpen),r=Me(J=>J.toggleSidebar),s=Me(J=>J.setSettingsDialogOpen),n=Me(J=>J.toggleCommandPalette),o=Me(J=>J.toggleHelpDialog),a=Me(J=>J.activeMainTab),l=Me(J=>J.setActiveMainTab),{getCurrentModel:c}=Ze(),d=Hs(),u=be(J=>J.getContextUsage),m=be(J=>J.currentSessionId),f=be(J=>J.sessions),p=xt(J=>J.homeDirectory),{isMobile:h}=qt(),g=Bv(),x=hi(J=>J.available),b=Bs(J=>J.status),y=Bs(J=>J.setStatus),w=i.useRef(null),[S,M]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),N=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Ae.useEffect(()=>{if(typeof window>"u")return;const J=typeof window.opencodeDesktop<"u";M(J)},[]);const v=c(),A=v&&typeof v.limit=="object"&&v.limit!==null?v.limit:null,k=A&&typeof A.context=="number"?A.context:0,C=A&&typeof A.output=="number"?A.output:0,j=u(k,C),T=Me(J=>J.isSessionSwitcherOpen),I=b?.connected?b.user?.avatarUrl:null,P=b?.connected?b.user?.login:null,D=b?.accounts??[],[E,F]=i.useState(!1),B=i.useMemo(()=>m?f.find(J=>J.id===m)??null:null,[m,f]),V=i.useMemo(()=>{const J=typeof B?.directory=="string"?B.directory:"";return dp(J||"")},[B?.directory]),[ne,O]=i.useState(!1),G=ne,K=i.useRef(""),q=i.useCallback(async J=>{if(!(!J||E)){F(!0);try{const ce=d.github?await d.github.authActivate(J):await(async()=>{const ge=await fetch("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:J})}),ee=await ge.json().catch(()=>null);if(!ge.ok||!ee)throw new Error(ee?.error||ge.statusText);return ee})();y(ce)}catch(ce){console.error("Failed to switch GitHub account:",ce)}finally{F(!1)}}},[E,d.github,y]);i.useEffect(()=>{let J=!1;const ce=async(le,fe)=>{if(!le||!fe||!d.files?.listDirectory)return!1;try{const oe=await d.files.listDirectory(le);return(Array.isArray(oe?.entries)?oe.entries:[]).some(re=>re?.name===fe&&!re?.isDirectory)}catch{return!1}},ge=async()=>{if(J)return;if(!B?.slug||!B?.time?.created||!V){O(!1),Me.getState().activeMainTab==="plan"&&Me.getState().setActiveMainTab("chat");return}const le=`${B.time.created}-${B.slug}.md`,fe=Gv(V),oe=Kv(qv(),p||null),[Q,re]=await Promise.all([ce(fe,le),ce(oe,le)]);if(J)return;const ue=Q||re;O(ue),!ue&&Me.getState().activeMainTab==="plan"&&Me.getState().setActiveMainTab("chat")},ee=`${m||"none"}:${V||"none"}:${B?.time?.created||0}:${B?.slug||"none"}`;K.current!==ee&&(K.current=ee,O(!1)),ge();const me=window.setInterval(()=>{ge()},3e3);return()=>{J=!0,window.clearInterval(me)}},[V,B?.slug,B?.time?.created,m,p,d.files]);const $=i.useCallback(()=>{if(typeof document>"u")return;const J=document.activeElement;if(!J)return;const ce=J.tagName;(ce==="INPUT"||ce==="TEXTAREA"||ce==="SELECT"||J.isContentEditable)&&J.blur()},[]),W=i.useCallback(()=>{if(h){$(),t(!T);return}r()},[$,h,T,t,r]),Y=i.useCallback(()=>{h&&$(),t(!1),s(!0)},[$,h,t,s]),X="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-secondary/50 transition-colors",Z=i.useMemo(()=>S&&N?"pl-[5.75rem]":"pl-3",[S,N]),z=i.useCallback(()=>{if(typeof document>"u")return;const J=w.current?.getBoundingClientRect().height;J&&document.documentElement.style.setProperty("--oc-header-height",`${J}px`)},[]);Ae.useEffect(()=>{if(typeof window>"u")return;z();const J=w.current;if(!J||typeof ResizeObserver>"u")return()=>{};const ce=new ResizeObserver(()=>{z()});return ce.observe(J),window.addEventListener("resize",z),window.addEventListener("orientationchange",z),()=>{ce.disconnect(),window.removeEventListener("resize",z),window.removeEventListener("orientationchange",z)}},[z]),Ae.useEffect(()=>{z()},[z,h]);const R=i.useCallback(async J=>{if(!J.target.closest("button, a, input, select, textarea")&&J.button===0&&S)try{const{getCurrentWindow:ce}=await js(async()=>{const{getCurrentWindow:ee}=await import("./vendor-.bun-Bui932eM.js").then(me=>me.dl);return{getCurrentWindow:ee}},__vite__mapDeps([0,1]));await ce().startDragging()}catch(ce){console.error("Failed to start window dragging:",ce)}},[S]),de=i.useCallback(async J=>{if(J.button===0&&S)try{const{getCurrentWindow:ce}=await js(async()=>{const{getCurrentWindow:ee}=await import("./vendor-.bun-Bui932eM.js").then(me=>me.dl);return{getCurrentWindow:ee}},__vite__mapDeps([0,1]));await ce().startDragging()}catch(ce){console.error("Failed to start window dragging:",ce)}},[S]),we=i.useMemo(()=>{const J=[{id:"chat",label:"Chat",icon:ag}];return G&&J.push({id:"plan",label:"Plan",icon:Qn}),J.push({id:"diff",label:"Diff",icon:tr,badge:!h&&g>0?g:void 0},{id:"files",label:"Files",icon:lr},{id:"terminal",label:"Terminal",icon:tn},{id:"git",label:"Git",icon:Vt,showDot:h&&g>0}),J},[g,h,G]);Ae.useEffect(()=>{const J=ce=>{if($s(ce)&&!ce.shiftKey&&!ce.altKey){const ge=parseInt(ce.key,10);ge>=1&&ge<=we.length&&(ce.preventDefault(),l(we[ge-1].id))}};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[we,l]);const xe=J=>{const ce=a===J.id,ge=J.icon,ee=J.id==="chat";return e.jsxs("button",{type:"button",onClick:()=>l(J.id),onMouseDown:ce?de:void 0,className:L("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",ce?"app-region-drag bg-secondary text-foreground shadow-sm":"app-region-no-drag text-muted-foreground hover:bg-secondary/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",ee&&!h&&"min-w-[100px] justify-center"),"aria-label":J.label,"aria-selected":ce,role:"tab",children:[h?e.jsx(ge,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),e.jsx("span",{className:"header-tab-label",children:J.label})]}),ee&&!h&&j&&j.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Bl,{totalTokens:j.totalTokens,percentage:j.percentage,contextLimit:j.contextLimit,outputLimit:j.outputLimit??0,size:"compact"})}),J.badge!==void 0&&J.badge>0&&e.jsx("span",{className:"ml-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary/10 px-1 text-[10px] font-bold text-primary",children:J.badge})]},J.id)},Pe=()=>e.jsxs("div",{onMouseDown:R,className:L("app-region-drag relative flex h-12 select-none items-center",Z),role:"tablist","aria-label":"Main navigation",children:[e.jsx("button",{type:"button",onClick:W,"aria-label":"Open sessions",className:`${X} mr-2`,children:e.jsx(ic,{className:"h-5 w-5"})}),e.jsx("div",{className:"flex items-center gap-1 p-1 bg-background/50 rounded-lg",children:we.map(J=>xe(J))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:X,children:e.jsx(Dn,{className:"h-5 w-5"})})}),e.jsx(ct,{children:e.jsxs("p",{children:["Command Palette (",Xt(),"+K)"]})})]}),e.jsx(Wl,{headerIconButtonClass:X}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:X,children:e.jsx(vn,{className:"h-5 w-5"})})}),e.jsx(ct,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Xt(),"+.)"]})})]}),b?.connected&&!h?D.length>1?e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsx("button",{type:"button",className:L(X,"h-8 w-8 p-0 overflow-hidden rounded-full border border-border/60 bg-muted/80"),title:P?`GitHub: ${P}`:"GitHub connected",disabled:E,children:I?e.jsx("img",{src:I,alt:P?`${P} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(Kr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs(os,{align:"end",className:"w-64",children:[e.jsx(Rr,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),e.jsx(Ds,{}),D.map(J=>{const ce=J.user,ge=!!J.current;return e.jsxs(Nt,{className:"gap-2",disabled:ge||E,onSelect:()=>{ge||q(J.id)},children:[ce?.avatarUrl?e.jsx("img",{src:ce.avatarUrl,alt:ce.login?`${ce.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:e.jsx(Kr,{className:"h-3 w-3 text-muted-foreground"})}),e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:ce?.name?.trim()||ce?.login||"GitHub"}),ce?.login?e.jsx("span",{className:"typography-micro text-muted-foreground truncate font-mono",children:ce.login}):null]}),ge?e.jsx(Pt,{className:"h-4 w-4 text-primary"}):null]},J.id)})]})]}):e.jsx("div",{className:"app-region-no-drag flex h-8 w-8 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:P?`GitHub: ${P}`:"GitHub connected",children:I?e.jsx("img",{src:I,alt:P?`${P} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(Kr,{className:"h-4 w-4 text-muted-foreground"})}):null]})]}),H=()=>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:[T?e.jsx("button",{onClick:()=>t(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-secondary","aria-label":"Back",children:e.jsx(ac,{className:"h-5 w-5"})}):e.jsx("button",{onClick:W,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-secondary","aria-label":"Open sessions",children:e.jsx(ig,{className:"h-5 w-5"})}),!T&&j&&j.totalTokens>0&&a==="chat"&&e.jsx(Bl,{totalTokens:j.totalTokens,percentage:j.percentage,contextLimit:j.contextLimit,outputLimit:j.outputLimit??0,size:"compact",isMobile:!0}),T&&e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),!T&&e.jsxs("div",{className:"app-region-no-drag flex items-center gap-1",children:[e.jsx("div",{className:"flex items-center gap-0.5",role:"tablist","aria-label":"Main navigation",children:we.map(J=>{const ce=a===J.id,ge=J.icon;return e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{h&&$(),l(J.id)},"aria-label":J.label,"aria-selected":ce,role:"tab",className:L(X,"relative",ce&&"text-foreground bg-secondary"),children:[e.jsx(ge,{className:"h-5 w-5"}),J.badge!==void 0&&J.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:J.badge}),J.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(ct,{children:e.jsx("p",{children:J.label})})]},J.id)})}),e.jsx(Wl,{headerIconButtonClass:X}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:Y,"aria-label":"Open settings",className:L(X,"relative"),children:[e.jsx(wn,{className:"h-5 w-5"}),x&&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(ct,{children:e.jsx("p",{children:x?"Settings (Update available)":"Settings"})})]})]})]}),ye=L("header-safe-area border-b border-border/50 relative z-10",S?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:w,className:ye,style:{"--padding-scale":"1"},children:h?H():Pe()})};function Pc({className:t,...r}){return e.jsx("div",{"data-slot":"card",className:L("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",t),...r})}function up({className:t,...r}){return e.jsx("div",{"data-slot":"card-header",className:L("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...r})}function mp({className:t,...r}){return e.jsx("div",{"data-slot":"card-title",className:L("leading-none font-semibold",t),...r})}function fp({className:t,...r}){return e.jsx("div",{"data-slot":"card-content",className:L("px-6",t),...r})}class ls extends i.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,s){this.setState({error:r,errorInfo:s})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:e.jsxs(Pc,{className:"w-full max-w-md",children:[e.jsx(up,{className:"text-center",children:e.jsxs(mp,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(kl,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(fp,{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(je,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ls,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let ua=0;function fs({...t}){return e.jsx(lg,{"data-slot":"dialog",...t})}function Yv({...t}){return e.jsx(ug,{"data-slot":"dialog-portal",...t})}const pp=Ae.forwardRef(({className:t,...r},s)=>(Ae.useEffect(()=>(ua+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{ua=Math.max(0,ua-1),ua===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(zm,{ref:s,"data-slot":"dialog-overlay",className:L("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",t),...r})));pp.displayName=zm.displayName;function ps({className:t,children:r,showCloseButton:s=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Yv,{"data-slot":"dialog-portal",children:[e.jsx(pp,{className:"rounded-none"}),e.jsxs(cg,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:L("bg-background text-foreground fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border p-6 shadow-none overflow-hidden pwa-dialog-content",t),...o,children:[r,s&&e.jsxs(dg,{"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(ss,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function bs({className:t,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:L("flex flex-col gap-2 text-center sm:text-left",t),...r})}function Gs({className:t,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:L("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",t),...r})}function ws({className:t,...r}){return e.jsx(mg,{"data-slot":"dialog-title",className:L("typography-markdown leading-none font-semibold text-foreground",t),...r})}function Ns({className:t,...r}){return e.jsx(fg,{"data-slot":"dialog-description",className:L("text-muted-foreground typography-ui-label",t),...r})}const Qd="https://github.com/btriapitsyn/openchamber/releases";async function Qv(){try{const t=await fetch("/api/openchamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return t.ok?{success:!0}:{success:!1,error:(await t.json().catch(()=>({}))).error||`Server error: ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Failed to install update"}}}async function Jv(t=30,r=2e3){for(let s=0;s<t;s++){try{if((await fetch("/health",{method:"GET"})).ok)return!0}catch{}await new Promise(n=>setTimeout(n,r))}return!1}const Ul=({open:t,onOpenChange:r,info:s,downloading:n,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Ae.useState(!1),[p,h]=Ae.useState("idle"),[g,x]=Ae.useState(null),b=s?.version?`${Qd}/tag/v${s.version}`:Qd,y=a?.total?Math.round(a.downloaded/a.total*100):0,w=u==="web",S=s?.updateCommand||"openchamber update";Ae.useEffect(()=>{t||(h("idle"),x(null))},[t]);const M=async()=>{try{await navigator.clipboard.writeText(S),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},N=Ae.useCallback(async()=>{h("updating"),x(null);const A=await Qv();if(!A.success){h("error"),x(A.error||"Update failed");return}h("restarting"),await new Promise(C=>setTimeout(C,2e3)),h("reconnecting"),await Jv()?window.location.reload():(h("error"),x("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),v=p!=="idle"&&p!=="error";return e.jsx(fs,{open:t,onOpenChange:v?void 0:r,children:e.jsxs(ps,{className:"max-w-md",children:[e.jsx(bs,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(pg,{className:"h-5 w-5 text-primary"}),p==="restarting"||p==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(s?.currentVersion||s?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s?.currentVersion&&e.jsx("span",{className:"font-mono",children:s.currentVersion}),s?.currentVersion&&s?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),s?.version&&e.jsx("span",{className:"font-mono text-primary",children:s.version})]}),w&&v&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Na,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"text-sm",children:[p==="updating"&&"Installing update...",p==="restarting"&&"Server restarting...",p==="reconnecting"&&"Waiting for server..."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),s?.body&&!v&&e.jsx(gt,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:s.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((A,k)=>/^\d+\.\d+\.\d+$/.test(A.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",A.trim(),`
|
|
82
|
+
`]},k):A.replace(/^- /gm,"• ").trim()+`
|
|
83
|
+
|
|
84
|
+
`)})}),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(hg,{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:M,className:L("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(Pt,{className:"h-4 w-4"}):e.jsx(za,{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:[y,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${y}%`}})})]}),(l||g)&&e.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-sm text-destructive",children:l||g})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:b,target:"_blank",rel:"noopener noreferrer",className:L("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(Xs,{className:"h-4 w-4"}),"GitHub"]}),!w&&!o&&!n&&e.jsxs("button",{onClick:c,className:L("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(Zr,{className:"h-4 w-4"}),"Download Update"]}),!w&&n&&e.jsxs("button",{disabled:!0,className:L("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(Na,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!w&&o&&e.jsxs("button",{onClick:d,className:L("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(Ls,{className:"h-4 w-4"}),"Restart to Update"]}),w&&!v&&e.jsxs("button",{onClick:N,className:L("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(Zr,{className:"h-4 w-4"}),"Update Now"]}),w&&v&&e.jsxs("button",{disabled:!0,className:L("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(Na,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Jd=264,Xd=200,Zd=500,eu="openchamber:check-for-updates",Xv=({isOpen:t,isMobile:r,children:s})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:l}=Me(),[c,d]=i.useState(!1),u=i.useRef(0),m=i.useRef(n||Jd),[f,p]=i.useState(!1),h=hi(),g=i.useRef(!1),x=h.checkForUpdates,{available:b,downloaded:y,checking:w}=h,[S,M]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");if(i.useEffect(()=>{if(typeof window>"u")return;const A=typeof window.opencodeDesktop<"u";M(A)},[]),i.useEffect(()=>{if(typeof window>"u")return;const A=()=>{typeof window.opencodeDesktop<"u"&&(g.current=!0,x())};return window.addEventListener(eu,A),()=>{window.removeEventListener(eu,A)}},[x]),i.useEffect(()=>{g.current&&(w||(b||y?p(!0):U.success("No updates available",{description:"You are running the latest version."}),g.current=!1))},[b,y,w]),i.useEffect(()=>{if(r||!c)return;const A=C=>{const j=C.clientX-u.current,T=Math.min(Zd,Math.max(Xd,m.current+j));o(T)},k=()=>{d(!1)};return window.addEventListener("pointermove",A),window.addEventListener("pointerup",k,{once:!0}),()=>{window.removeEventListener("pointermove",A),window.removeEventListener("pointerup",k)}},[r,c,o]),i.useEffect(()=>{r&&c&&d(!1)},[r,c]),r)return null;const N=t?Math.min(Zd,Math.max(Xd,n||Jd)):0,v=A=>{t&&(d(!0),u.current=A.clientX,m.current=N,A.preventDefault())};return e.jsxs("aside",{className:L("relative flex h-full overflow-hidden border-r border-border",S?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",c?"transition-none":"transition-[width] duration-300 ease-in-out",!t&&"border-r-0"),style:{width:`${N}px`,minWidth:`${N}px`,maxWidth:`${N}px`,overflowX:"clip"},"aria-hidden":!t||N===0,children:[t&&e.jsx("div",{className:L("absolute right-0 top-0 z-20 h-full w-[4px] cursor-col-resize hover:bg-primary/50 transition-colors",c&&"bg-primary"),onPointerDown:v,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:L("relative z-10 flex h-full flex-col transition-opacity duration-300 ease-in-out",!t&&"pointer-events-none select-none opacity-0"),style:{width:`${N}px`,overflowX:"hidden"},"aria-hidden":!t,children:[e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{children:s})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border h-12 px-2 bg-sidebar-accent/10",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:L("flex h-8 items-center gap-2 rounded-md px-2","text-sm font-semibold text-sidebar-foreground/90","hover:text-sidebar-foreground hover:bg-sidebar-accent","transition-all duration-200"),children:[e.jsx(wn,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),b||y?e.jsxs("button",{onClick:()=>p(!0),className:L("flex items-center gap-1.5 rounded-md px-2 py-1","text-xs font-semibold","bg-primary/10 text-primary","hover:bg-primary/20","transition-colors"),children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!S&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{onClick:()=>l(!0),className:L("flex h-8 w-8 items-center justify-center rounded-md","text-sidebar-foreground/70","hover:text-sidebar-foreground hover:bg-sidebar-accent","transition-all duration-200"),children:e.jsx(Ms,{className:"h-4 w-4"})})}),e.jsx(ct,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Ul,{open:f,onOpenChange:p,info:h.info,downloading:h.downloading,downloaded:h.downloaded,progress:h.progress,error:h.error,onDownload:h.downloadUpdate,onRestart:h.restartToUpdate,runtimeType:h.runtimeType})]})]})};function ki({className:t,...r}){return e.jsx(An,{"data-slot":"command",className:L("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",t),...r})}function Zv({title:t="Command Palette",description:r="Search for a command to run...",children:s,className:n,showCloseButton:o=!0,...a}){return e.jsxs(fs,{...a,children:[e.jsxs(bs,{className:"sr-only",children:[e.jsx(ws,{children:t}),e.jsx(Ns,{children:r})]}),e.jsx(ps,{className:L("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(ki,{className:"[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-input]]:h-8 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-item]]:typography-meta",children:s})})]})}function Ci({className:t,...r}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(Vs,{className:"size-4 shrink-0 opacity-50"}),e.jsx(An.Input,{"data-slot":"command-input",className:L("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",t),...r})]})}function Mi({className:t,children:r,scrollbarClassName:s,disableHorizontal:n,...o}){return e.jsx(gt,{as:An.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:L("scroll-py-1 overflow-x-hidden h-full min-h-0",t),scrollbarClassName:s??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:n??!0,...o,children:r})}function Di({...t}){return e.jsx(An.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...t})}function Qr({className:t,...r}){return e.jsx(An.Group,{"data-slot":"command-group",className:L("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium",t),...r})}function si({className:t,...r}){return e.jsx(An.Separator,{"data-slot":"command-separator",className:L("bg-border -mx-1 h-px",t),...r})}function vs({className:t,...r}){return e.jsx(An.Item,{"data-slot":"command-item",className:L("data-[selected=true]:bg-muted hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r})}function Ir({className:t,...r}){const s=a=>{const l=a.trim().toLowerCase();return l==="ctrl"||l==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):l==="cmd"||l==="⌘"||l==="command"||l==="meta"?e.jsx(Dn,{className:"size-3.5"}):l==="shift"||l==="⇧"?e.jsx(Jn,{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:L("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",t),...r,children:o.length>0?o.map((a,l)=>e.jsxs(Ae.Fragment,{children:[l>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),s(a)]},`${a}-${l}`)):r.children})}const tu=["artful","bionic","cosmic","disco","focal","groovy","jammy","kinetic","lunar","noble","bold","brave","calm","eager","gentle","happy","keen","lively","merry","swift","warm","wise","bright","clever","daring","agile","crisp","fresh","lucid","quick","sharp","vivid","zealous"],su=["aardvark","beaver","chipmunk","dolphin","falcon","gopher","hedgehog","jackal","koala","lemur","mongoose","narwhal","otter","pangolin","quokka","raccoon","salamander","toucan","walrus","yak","zebra","badger","condor","dingo","egret","ferret","gecko","heron","iguana"];function hp(){const t=tu[Math.floor(Math.random()*tu.length)],r=su[Math.floor(Math.random()*su.length)];return`${t}-${r}`}function ej(t){return hp()}const ru=t=>t.replace(/\\/g,"/").replace(/\/+$/,"")||t,gp=t=>{const r=ru(t),n=Ft.getState().projects.find(o=>ru(o.path)===r);return n?{id:n.id,path:n.path}:null};let $r=!1;async function Ai(){if($r)return null;const t=Ft.getState().getActiveProject();if(!t?.path)return U.error("No active project",{description:"Please select a project first."}),null;const r=t.path;let s=!1;try{s=await zr(r)}catch{}if(!s)return U.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;$r=!0,Us("Creating new worktree session...");try{const o=t.worktreeDefaults?.baseBranch,a={id:t.id,path:r},l=ej(),c=o&&o!=="HEAD"?o:void 0,d=await ho(a),u=await Si(a,{preferredName:l,setupCommands:d,startPoint:c}),m={...u,createdFromBranch:c??"HEAD"},f=await Ko(u.path).catch(()=>{}),p=f?{...m,status:f}:m,h=be.getState(),g=await h.createSession(void 0,u.path);if(!g)return await Yo(a,u).catch(()=>{}),U.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const x=Ze.getState(),b=x.agents;h.initializeNewOpenChamberSession(g.id,b),h.setSessionDirectory(g.id,u.path),h.setWorktreeMetadata(g.id,p);try{const y=x.getVisibleAgents();let w;if(x.settingsDefaultAgent){const S=y.find(M=>M.name===x.settingsDefaultAgent);S&&(w=S.name)}if(w||(w=y.find(S=>S.name==="build")?.name||y[0]?.name),w){x.setAgent(w),tt.getState().saveSessionAgentSelection(g.id,w);const S=x.settingsDefaultModel;if(S){const M=S.split("/");if(M.length===2){const[N,v]=M;if(x.getModelMetadata(N,v)){tt.getState().saveSessionModelSelection(g.id,N,v),tt.getState().saveAgentModelForSession(g.id,w,N,v);const k=x.settingsDefaultVariant;if(k){const T=x.providers.find(I=>I.id===N)?.models.find(I=>I.id===v)?.variants;T&&Object.prototype.hasOwnProperty.call(T,k)&&(x.setCurrentVariant(k),tt.getState().saveAgentModelVariantForSession(g.id,w,N,v,k))}}}}}}catch{}xt.getState().setDirectory(u.path,{showOverlay:!1});try{await h.loadSessions()}catch{}return U.success("Worktree created",{description:u.branch?`Branch: ${u.branch}`:"Ready"}),g}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return U.error("Failed to create worktree",{description:o}),null}finally{_s(),$r=!1}}async function tj(t,r){if($r)return null;let s=!1;try{s=await zr(t)}catch{}if(!s)return U.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;$r=!0,Us("Creating worktree session...");try{const n=gp(t);if(!n)throw new Error("Project is not registered in OpenChamber");const o=await ho(n),a=await Si(n,{preferredName:r,setupCommands:o,startPoint:r}),l={...a,createdFromBranch:r},c=await Ko(a.path).catch(()=>{}),d=c?{...l,status:c}:l,u=be.getState(),m=await u.createSession(void 0,a.path);if(!m)return await Yo(n,a).catch(()=>{}),U.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const f=Ze.getState(),p=f.agents;u.initializeNewOpenChamberSession(m.id,p),u.setSessionDirectory(m.id,a.path),u.setWorktreeMetadata(m.id,d);try{const h=f.getVisibleAgents();let g;if(f.settingsDefaultAgent){const x=h.find(b=>b.name===f.settingsDefaultAgent);x&&(g=x.name)}if(g||(g=h.find(x=>x.name==="build")?.name||h[0]?.name),g){f.setAgent(g),tt.getState().saveSessionAgentSelection(m.id,g);const x=f.settingsDefaultModel;if(x){const b=x.split("/");if(b.length===2){const[y,w]=b;if(f.getModelMetadata(y,w)){tt.getState().saveSessionModelSelection(m.id,y,w),tt.getState().saveAgentModelForSession(m.id,g,y,w);const M=f.settingsDefaultVariant;if(M){const A=f.providers.find(k=>k.id===y)?.models.find(k=>k.id===w)?.variants;A&&Object.prototype.hasOwnProperty.call(A,M)&&(f.setCurrentVariant(M),tt.getState().saveAgentModelVariantForSession(m.id,g,y,w,M))}}}}}}catch{}xt.getState().setDirectory(a.path,{showOverlay:!1});try{await u.loadSessions()}catch{}return U.success("Worktree created",{description:a.branch?`Branch: ${a.branch}`:"Ready"}),m}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return U.error("Failed to create worktree",{description:o}),null}finally{_s(),$r=!1}}async function xp(t,r,s,n){if($r)return null;let o=!1;try{o=await zr(t)}catch{}if(!o)return U.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;$r=!0,Us("Creating worktree session...");try{const a=s?.trim()||"HEAD",l=r?.trim();if(!l)throw new Error("Branch name is required");const c=n?.allowSuffix!==!1,d=gp(t);if(!d)throw new Error("Project is not registered in OpenChamber");const u=await ho(d);try{const m=await Si(d,{preferredName:l,setupCommands:u,startPoint:a,allowSuffix:c}),f={...m,createdFromBranch:a},p=await Ko(m.path).catch(()=>{}),h=p?{...f,status:p}:f,g=be.getState(),x=await g.createSession(void 0,m.path);if(!x)throw await Yo(d,m).catch(()=>{}),new Error("Could not create a session for the worktree.");const b=Ze.getState();g.initializeNewOpenChamberSession(x.id,b.agents),g.setSessionDirectory(x.id,m.path),g.setWorktreeMetadata(x.id,h);try{const y=b.getVisibleAgents();let w;if(b.settingsDefaultAgent){const S=y.find(M=>M.name===b.settingsDefaultAgent);S&&(w=S.name)}if(w||(w=y.find(S=>S.name==="build")?.name||y[0]?.name),w){b.setAgent(w),tt.getState().saveSessionAgentSelection(x.id,w);const S=b.settingsDefaultModel;if(S){const M=S.split("/");if(M.length===2){const[N,v]=M;if(b.getModelMetadata(N,v)){tt.getState().saveSessionModelSelection(x.id,N,v),tt.getState().saveAgentModelForSession(x.id,w,N,v);const k=b.settingsDefaultVariant;if(k){const T=b.providers.find(I=>I.id===N)?.models.find(I=>I.id===v)?.variants;T&&Object.prototype.hasOwnProperty.call(T,k)&&(b.setCurrentVariant(k),tt.getState().saveAgentModelVariantForSession(x.id,w,N,v,k))}}}}}}catch{}xt.getState().setDirectory(m.path,{showOverlay:!1});try{await g.loadSessions()}catch{}return U.success("Worktree created",{description:m.branch?`Branch: ${m.branch}`:"Ready"}),{id:x.id,branch:m.branch||l}}catch(m){const f=m instanceof Error?m.message:"Failed to create worktree session";return U.error("Failed to create worktree",{description:f}),null}}finally{_s(),$r=!1}}async function sj(t,r,s){return xp(t,r,s,{allowSuffix:!1})}const rj=()=>{const{isCommandPaletteOpen:t,setCommandPaletteOpen:r,setHelpDialogOpen:s,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:l,toggleSidebar:c}=Me(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=be(),f=Ze(E=>E.settingsAutoCreateWorktree),{currentDirectory:p}=xt(),{themeMode:h,setThemeMode:g}=Hr(),x=()=>{r(!1)},b=async()=>{n("chat"),a(!1),d(),x()},y=E=>{u(E),x()},w=E=>{g(E),x()},S=()=>{s(!0),x()},M=()=>{x(),Ai()},{isMobile:N}=qt(),v=()=>{if(N){const{isSessionSwitcherOpen:E}=Me.getState();a(!E)}else c();x()},A=()=>{n("diff"),x()},k=()=>{n("git"),x()},C=()=>{n("terminal"),x()},j=()=>{o(!0),x()},T=()=>{Do(),x()},I=()=>{l(!0),x()},P=m(p??""),D=i.useMemo(()=>P.slice(0,5),[P]);return e.jsxs(Zv,{open:t,onOpenChange:r,children:[e.jsx(Ci,{placeholder:"Type a command or search..."}),e.jsxs(Mi,{children:[e.jsx(Di,{children:"No results found."}),e.jsxs(Qr,{heading:"Actions",children:[e.jsxs(vs,{onSelect:v,children:[e.jsx(ic,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(Ir,{children:[Xt()," + L"]})]}),e.jsxs(vs,{onSelect:b,children:[e.jsx(us,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Ir,{children:f?`Shift + ${Xt()} + N`:`${Xt()} + N`})]}),e.jsxs(vs,{onSelect:M,children:[e.jsx(Vt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Ir,{children:f?`${Xt()} + N`:`Shift + ${Xt()} + N`})]}),e.jsxs(vs,{onSelect:S,children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(Ir,{children:[Xt()," + ."]})]}),e.jsxs(vs,{onSelect:A,children:[e.jsx(tr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(Ir,{children:[Xt()," + 2"]})]}),e.jsxs(vs,{onSelect:C,children:[e.jsx(tn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(Ir,{children:[Xt()," + 3"]})]}),e.jsxs(vs,{onSelect:k,children:[e.jsx(Vt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(Ir,{children:[Xt()," + 4"]})]}),e.jsxs(vs,{onSelect:I,children:[e.jsx(kr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(Ir,{children:[Xt()," + T"]})]}),e.jsxs(vs,{onSelect:j,children:[e.jsx(wn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(Ir,{children:[Xt()," + ,"]})]}),e.jsxs(vs,{onSelect:T,children:[e.jsx(Ls,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(si,{}),e.jsxs(Qr,{heading:"Theme",children:[e.jsxs(vs,{onSelect:()=>w("light"),children:[e.jsx(gg,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx(Pt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(vs,{onSelect:()=>w("dark"),children:[e.jsx(xg,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx(Pt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(vs,{onSelect:()=>w("system"),children:[e.jsx(Hm,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx(Pt,{className:"ml-auto h-4 w-4"})]})]}),D.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(si,{}),e.jsx(Qr,{heading:"Recent Sessions",children:D.map(E=>e.jsxs(vs,{onSelect:()=>y(E.id),children:[e.jsx(lc,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:E.title||"Untitled Session"})]},E.id))})]})]})]})},nj=(t,r)=>{const s=t.trim().toLowerCase();return s==="ctrl"||s==="control"?e.jsx(di,{className:"h-3.5 w-3.5"},`ctrl-${r}`):s==="⌘"||s==="cmd"||s==="command"||s==="meta"?e.jsx(Dn,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:t.trim()},`key-${r}`)},oj=t=>{const r=t.split("+").map(s=>s.trim()).filter(Boolean);return r.length===0?t.trim():r.map((s,n)=>e.jsxs(i.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),nj(s,n)]},`${s}-${n}`))},aj=()=>{const{isHelpDialogOpen:t,setHelpDialogOpen:r}=Me(),s=Ze(a=>a.settingsAutoCreateWorktree),n=Xt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:Dn},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:vn},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:ic},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:jn},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:cc},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:Cr}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:s?"Create New Session in Worktree":"Create New Session",icon:s?Vt:us},{keys:[`Shift + ${n} + N`],description:s?"Create New Session":"Create New Session in Worktree",icon:s?us:Vt},{keys:[`${n} + I`],description:"Focus Chat Input",icon:Wm},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Xn}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:yg},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:tr},{keys:[`${n} + 3`],description:"Open Files",icon:lr},{keys:[`${n} + 4`],description:"Open Terminal",icon:tn},{keys:[`${n} + 5`],description:"Open Git Panel",icon:Vt},{keys:[`${n} + T`],description:"Open Timeline",icon:kr},{keys:[`${n} + ,`],description:"Open Settings",icon:wn}]}];return e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ps,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(bs,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Ns,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:[e.jsx("div",{className:"space-y-4",children:o.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:a.category}),e.jsx("div",{className:"space-y-1",children:a.items.map((l,c)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l.icon&&e.jsx(l.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:l.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(l.keys)?l.keys:l.keys.split(" / ")).map((d,u)=>e.jsxs(i.Fragment,{children:[u>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:oj(d)})]},`${d}-${u}`))})]},c))})]},a.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(vn,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("p",{className:"font-medium mb-1",children:"Pro Tips:"}),e.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[e.jsxs("li",{children:["• Use Command Palette (",n," + K) to quickly access all actions"]}),e.jsx("li",{children:"• The 5 most recent sessions appear in the Command Palette"}),e.jsx("li",{children:"• Theme cycling remembers your preference across sessions"})]})]})]})})]})]})})},ij={xs:{container:"gap-[1px]",dot:"h-[3px] w-[3px]"},sm:{container:"gap-0.5",dot:"h-1 w-1"},md:{container:"gap-1",dot:"h-1.5 w-1.5"},lg:{container:"gap-1.5",dot:"h-2 w-2"}},yp=({className:t,size:r="md"})=>{const s=ij[r];return e.jsx("div",{className:L("grid grid-cols-3",s.container,t),"aria-label":"Loading",children:Array.from({length:9},(n,o)=>e.jsx("div",{className:L("rounded-full bg-current animate-grid-pulse",s.dot),style:{animationDelay:`${(o%3+Math.floor(o/3))*150}ms`}},o))})},Yi=new Set,Qi=new Set,Ji=new Set,no={onDeleteRequest(t){return Yi.add(t),()=>{Yi.delete(t)}},requestDelete(t){!t.sessions.length&&t.mode!=="worktree"||Yi.forEach(r=>r(t))},onCreateRequest(t){return Qi.add(t),()=>{Qi.delete(t)}},requestCreate(t){const r=t??{};Qi.forEach(s=>s(r))},onDirectoryRequest(t){return Ji.add(t),()=>{Ji.delete(t)}},requestDirectoryDialog(){Ji.forEach(t=>t())}};function bp(t){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...t,children:e.jsx("path",{d:"M232.49,192.49l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,0,1,17-17L180,187V141L128,89,76,141V187l11.51-11.52a12,12,0,0,1,17,17l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,1,1,17-17L52,187V136a12,12,0,0,1,3.51-8.49L116,67V24a12,12,0,0,1,24,0V67l60.49,60.48A12,12,0,0,1,204,136v51l11.51-11.52a12,12,0,0,1,17,17Z",transform:"rotate(180 128 128)"})})}function wt({className:t,type:r,...s}){return e.jsx("input",{type:r,"data-slot":"input",className:L("text-foreground border-input file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none hover:border-input focus:border-ring flex h-9 w-full min-w-0 rounded-lg border bg-transparent px-3 py-1 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...s})}const lj=t=>t.label||t.normalizedPath.split("/").pop()||t.normalizedPath;function cj({open:t,onOpenChange:r,project:s}){const[n,o]=Ae.useState(""),[a,l]=Ae.useState(null),[c,d]=Ae.useState([]),[u,m]=Ae.useState(!1),[f,p]=Ae.useState(null),[h,g]=Ae.useState(null),[x,b]=Ae.useState(null),[y,w]=Ae.useState(null),[S,M]=Ae.useState(null),[N,v]=Ae.useState(null),[A,k]=Ae.useState(""),[C,j]=Ae.useState(null),T=Ae.useCallback(async()=>{if(s){m(!0),p(null);try{const[q,$]=await Promise.all([wc(s.path),Ff(s.path)]);l(q),d($)}catch(q){p(q instanceof Error?q.message:"Failed to load"),l(null),d([])}finally{m(!1)}}},[s]);Ae.useEffect(()=>{if(!t){o(""),w(null),M(null),v(null),k(""),j(null);return}T()},[t,T]);const I=(q,$)=>{if(!$.trim())return q;const W=$.toLowerCase();return q.filter(Y=>Y.toLowerCase().includes(W))},P=async q=>{if(s){g(q);try{await tj(s.path,q),r(!1)}catch($){U.error("Failed to create worktree",{description:$ instanceof Error?$.message:"Create failed"})}finally{g(null)}}},D=Ae.useCallback(q=>{v(q),k(q)},[]),E=Ae.useCallback(()=>{v(null),k(""),j(null)},[]),F=Ae.useCallback(()=>{w(null),M(null)},[]),B=Ae.useCallback(async q=>{if(!s)return;const $=A.trim();if(!$||$===q){E();return}j(q);try{if(!(await zb(s.path,q,$))?.success)throw new Error("Rename rejected");await T(),E(),U.success("Branch renamed",{description:`${q} -> ${$}`})}catch(W){U.error("Failed to rename branch",{description:W instanceof Error?W.message:"Rename failed"}),j(null)}},[s,A,T,E]),V=Ae.useCallback(async q=>{if(s){b(q);try{const $=S===q;if(!(await $l(s.path,{branch:q,force:$}))?.success)throw new Error("Delete rejected");await T(),U.success("Branch deleted",{description:q}),w(null),M(null)}catch($){const W=$ instanceof Error?$.message:"Delete failed";/not fully merged/i.test(W)&&S!==q?(M(q),U.error("Branch not merged",{description:"Confirm again to force delete"})):U.error("Failed to delete branch",{description:W})}finally{b(null)}}},[s,T,S]),ne=new Set(c.map(q=>q.branch).filter(Boolean)),O=a?.all||[],K=I(O,n).filter(q=>!q.startsWith("remotes/"));return e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ps,{className:"max-w-2xl max-h-[70vh] flex flex-col overflow-hidden gap-3",children:[e.jsxs(bs,{className:"flex-shrink-0",children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"h-5 w-5"}),"Manage Branches"]}),e.jsx(Ns,{children:s?`Local branches for ${lj(s)}`:"Select a project"})]}),e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(wt,{placeholder:"Search branches...",value:n,onChange:q=>o(q.target.value),className:"pl-9"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"space-y-1",children:s?u?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading branches..."}):f?e.jsx("div",{className:"px-2 py-2 text-destructive text-sm",children:f}):K.length===0?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:n?"No matching branches":"No branches found"}):K.map(q=>{const $=a?.branches[q],W=!!$?.current,Y=h===q,X=x===q,Z=C===q,z=ne.has(q),R=N===q,de=y===q,we=S===q,xe=!!(W||z||X||Z||R),Pe=!!(z||X||Z||R);return e.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5 hover:bg-muted/30 rounded-md overflow-hidden",children:[e.jsx(Vt,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[R?e.jsx("form",{className:"flex w-full items-center min-w-0",onSubmit:H=>{H.preventDefault(),B(q)},children:e.jsx("input",{value:A,onChange:H=>k(H.target.value),className:"flex-1 min-w-0 h-5 bg-transparent text-sm leading-none outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename branch",onKeyDown:H=>{H.key==="Escape"&&(H.preventDefault(),E()),H.key==="Enter"&&(H.preventDefault(),B(q))}})}):e.jsx("span",{className:L("text-sm truncate",W&&"font-medium text-primary"),children:q}),W&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded flex-shrink-0 whitespace-nowrap",children:"current"}),z&&!R&&e.jsx("span",{className:"text-xs bg-muted/40 text-muted-foreground px-1.5 py-0.5 rounded flex-shrink-0 whitespace-nowrap",children:"worktree"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[$?.commit?e.jsx("span",{className:"font-mono",children:$.commit.slice(0,7)}):null,typeof $?.ahead=="number"&&$.ahead>0?e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["↑",$.ahead]}):null,typeof $?.behind=="number"&&$.behind>0?e.jsxs("span",{className:"text-[color:var(--status-warning)]",children:["↓",$.behind]}):null]})]}),!R&&!de?e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>P(q),disabled:Y,className:"inline-flex h-7 w-7 items-center justify-center rounded-md bg-primary/10 hover:bg-primary/20 text-primary transition-colors disabled:opacity-50","aria-label":"Create worktree from",children:Y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Vt,{className:"h-4 w-4"})})}),e.jsx(ct,{side:"left",children:"Create worktree from"})]}),e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>D(q),disabled:Pe,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-muted/40 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50","aria-label":"Rename",children:e.jsx(Um,{className:"h-4 w-4"})})}),e.jsx(ct,{side:"left",children:z?"Rename (remove worktree first)":"Rename"})]}),e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>w(q),disabled:xe,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50","aria-label":"Delete",children:X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(zs,{className:"h-4 w-4"})})}),e.jsx(ct,{side:"left",children:W?"Delete (current branch)":z?"Delete (remove worktree first)":"Delete"})]})]}):null,R?e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("button",{type:"button",onClick:()=>{B(q)},disabled:Z,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-muted/40 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50","aria-label":"Confirm rename",children:Z?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Pt,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:E,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-muted/40 text-muted-foreground hover:text-foreground transition-colors","aria-label":"Cancel rename",children:e.jsx(ss,{className:"h-4 w-4"})})]}):null,!R&&de?e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("span",{className:L("text-xs mr-1",we?"text-destructive":"text-muted-foreground"),children:we?"Force delete?":"Delete?"}),e.jsx("button",{type:"button",onClick:()=>{V(q)},disabled:X,className:L("inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors disabled:opacity-50",we?"bg-destructive/10 text-destructive hover:bg-destructive/15":"hover:bg-destructive/10 text-muted-foreground hover:text-destructive"),"aria-label":"Confirm delete",children:X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Pt,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:F,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-muted/40 text-muted-foreground hover:text-foreground transition-colors","aria-label":"Cancel delete",children:e.jsx(ss,{className:"h-4 w-4"})})]}):null]},q)}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No project selected"})})})]})})}const dj=t=>{const r=t.trim();if(!r)return null;const s=r.match(/\/issues\/(\d+)(?:\b|\/|$)/i);if(s){const o=Number(s[1]);return Number.isFinite(o)&&o>0?o:null}const n=r.match(/^#?(\d+)$/);if(n){const o=Number(n[1]);return Number.isFinite(o)&&o>0?o:null}return null},uj=t=>{const r={repo:t.repo??null,issue:t.issue,comments:t.comments};return`GitHub issue context (JSON)
|
|
85
|
+
${JSON.stringify(r,null,2)}`};function mj({open:t,onOpenChange:r}){const{github:s}=Hs(),n=Bs(W=>W.status),o=Bs(W=>W.hasChecked),a=Me(W=>W.setSettingsDialogOpen),l=Me(W=>W.setSidebarSection),c=Ft(W=>W.getActiveProject()),d=c?.path??null,u=c?.worktreeDefaults?.baseBranch||"main",[m,f]=i.useState(""),[p,h]=i.useState(!1),[g,x]=i.useState(null),[b,y]=i.useState([]),[w,S]=i.useState(1),[M,N]=i.useState(!1),[v,A]=i.useState(null),[k,C]=i.useState(!1),[j,T]=i.useState(!1),[I,P]=i.useState(null),D=i.useCallback(async()=>{if(!d){x(null),P("No active project");return}if(o&&n?.connected===!1){x({connected:!1}),y([]),N(!1),S(1),P(null);return}if(!s?.issuesList){x(null),P("GitHub runtime API unavailable");return}C(!0),P(null);try{const W=await s.issuesList(d,{page:1});x(W),y(W.issues??[]),S(W.page??1),N(!!W.hasMore),W.connected===!1&&P(null)}catch(W){P(W instanceof Error?W.message:String(W))}finally{C(!1)}},[s,o,n,d]),E=i.useCallback(async()=>{if(d&&s?.issuesList&&!(j||k)&&M){T(!0);try{const W=w+1,Y=await s.issuesList(d,{page:W});x(Y),y(X=>[...X,...Y.issues??[]]),S(Y.page??W),N(!!Y.hasMore)}catch(W){const Y=W instanceof Error?W.message:String(W);U.error("Failed to load more issues",{description:Y})}finally{T(!1)}}},[s,M,k,j,w,d]);i.useEffect(()=>{if(!t){f(""),h(!1),A(null),P(null),x(null),y([]),S(1),N(!1),C(!1);return}D()},[t,D]),i.useEffect(()=>{t&&o&&n?.connected===!1&&(x({connected:!1}),y([]),N(!1),S(1),P(null))},[o,n,t]);const F=o?g?.connected!==!1:!0,B=g?.repo?.url??null,V=i.useCallback(()=>{l("settings"),a(!0)},[a,l]),ne=i.useMemo(()=>{const W=m.trim().toLowerCase();return W?b.filter(Y=>String(Y.number)===W.replace(/^#/,"")?!0:Y.title.toLowerCase().includes(W)):b},[b,m]),O=i.useMemo(()=>dj(m),[m]),G=i.useCallback(()=>{const W=Ze.getState(),Y=W.getVisibleAgents();if(W.settingsDefaultAgent){const X=Y.find(Z=>Z.name===W.settingsDefaultAgent);if(X)return X.name}return Y.find(X=>X.name==="build")?.name||Y[0]?.name},[]),K=i.useCallback(()=>{const W=Ze.getState(),Y=W.settingsDefaultModel;if(!Y)return null;const X=Y.split("/");if(X.length!==2)return null;const[Z,z]=X;return!Z||!z||!W.getModelMetadata(Z,z)?null:{providerID:Z,modelID:z}},[]),q=i.useCallback((W,Y)=>{const X=Ze.getState(),Z=X.settingsDefaultVariant;if(!Z)return;const de=X.providers.find(we=>we.id===W)?.models.find(we=>we.id===Y)?.variants;if(de&&Object.prototype.hasOwnProperty.call(de,Z))return Z},[]),$=i.useCallback(async W=>{if(!d){U.error("No active project");return}if(!s?.issueGet||!s?.issueComments){U.error("GitHub runtime API unavailable");return}if(!v){A(W);try{const Y=await s.issueGet(d,W);if(Y.connected===!1){U.error("GitHub not connected");return}if(!Y.repo){U.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}const X=Y.issue;if(!X){U.error("Issue not found");return}const Z=await s.issueComments(d,W);if(Z.connected===!1){U.error("GitHub not connected");return}const z=Z.comments??[],R=`#${X.number} ${X.title}`.trim(),de=await(async()=>{if(p){const fe=`issue-${X.number}-${hp()}`,oe=await xp(d,fe,u||"main");if(!oe?.id)throw new Error("Failed to create worktree session");return oe.id}const le=await be.getState().createSession(R,d,null);if(!le?.id)throw new Error("Failed to create session");return le.id})();be.getState().updateSessionTitle(de,R).catch(()=>{});try{be.getState().initializeNewOpenChamberSession(de,Ze.getState().agents)}catch{}r(!1);const we=Ze.getState(),xe=St.getState().lastUsedProvider,Pe=K(),H=Pe?.providerID||we.currentProviderId||xe?.providerID,ye=Pe?.modelID||we.currentModelId||xe?.modelID,J=G()||we.currentAgentName||void 0;if(!H||!ye){U.error("No model selected");return}const ce=q(H,ye);try{tt.getState().saveSessionModelSelection(de,H,ye)}catch{}if(J){try{we.setAgent(J)}catch{}try{tt.getState().saveSessionAgentSelection(de,J)}catch{}try{tt.getState().saveAgentModelForSession(de,J,H,ye)}catch{}if(ce!==void 0){try{we.setCurrentVariant(ce)}catch{}try{tt.getState().saveAgentModelVariantForSession(de,J,H,ye,ce)}catch{}}}const ge="Review this issue using the provided issue context: title, body, labels, assignees, comments, metadata.",ee=`Review this issue using the provided issue context.
|
|
86
|
+
|
|
87
|
+
Process:
|
|
88
|
+
- First classify the issue type (bug / feature request / question/support / refactor / ops) and state it as: Type: <one label>.
|
|
89
|
+
- Gather any needed repository context (code, config, docs) to validate assumptions.
|
|
90
|
+
- After gathering, if anything is still unclear or cannot be verified, do not speculate—state what’s missing and ask targeted questions.
|
|
91
|
+
|
|
92
|
+
Output rules:
|
|
93
|
+
- Compact output; pick ONE template below and omit the others.
|
|
94
|
+
- No emojis. No code snippets. No fenced blocks.
|
|
95
|
+
- Short inline code identifiers allowed.
|
|
96
|
+
- Reference evidence with file paths and line ranges when applicable; if exact lines aren’t available, cite the file and say “approx” + why.
|
|
97
|
+
- Keep the entire response under ~300 words.
|
|
98
|
+
|
|
99
|
+
Templates (choose one):
|
|
100
|
+
Bug:
|
|
101
|
+
- Summary (1-2 sentences)
|
|
102
|
+
- Likely cause (max 2)
|
|
103
|
+
- Repro/diagnostics needed (max 3)
|
|
104
|
+
- Fix approach (max 4 steps)
|
|
105
|
+
- Verification (max 3)
|
|
106
|
+
|
|
107
|
+
Feature:
|
|
108
|
+
- Summary (1-2 sentences)
|
|
109
|
+
- Requirements (max 4)
|
|
110
|
+
- Unknowns/questions (max 4)
|
|
111
|
+
- Proposed plan (max 5 steps)
|
|
112
|
+
- Verification (max 3)
|
|
113
|
+
|
|
114
|
+
Question/Support:
|
|
115
|
+
- Summary (1-2 sentences)
|
|
116
|
+
- Answer/guidance (max 6 lines)
|
|
117
|
+
- Missing info (max 4)
|
|
118
|
+
|
|
119
|
+
Do not implement changes until I confirm; end with: “Next actions: <1 sentence>”.`,me=uj({repo:Y.repo,issue:X,comments:z});Oe.sendMessage({id:de,providerID:H,modelID:ye,agent:J,variant:ce,text:ge,additionalParts:[{text:ee,synthetic:!0},{text:me,synthetic:!0}]}).catch(le=>{const fe=le instanceof Error?le.message:String(le);U.error("Failed to send issue context",{description:fe})}),U.success("Session created from issue")}catch(Y){const X=Y instanceof Error?Y.message:String(Y);U.error("Failed to start session",{description:X})}finally{A(null)}}},[p,s,r,d,u,G,K,q,v]);return e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ps,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(bs,{className:"flex-shrink-0",children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Vm,{className:"h-5 w-5"}),"New Session From GitHub Issue"]}),e.jsx(Ns,{children:"Seeds a new session with hidden issue context (title/body/labels/comments)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(wt,{placeholder:"Search by title or #123, or paste issue URL",value:m,onChange:W=>f(W.target.value),className:"pl-9 w-full"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[d?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No active project selected."}),s?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"GitHub runtime API unavailable."}),k?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Loading issues..."]}):null,F===!1?e.jsxs("div",{className:"text-center text-muted-foreground py-8 space-y-3",children:[e.jsx("div",{children:"GitHub not connected. Connect your GitHub account in settings."}),e.jsx("div",{className:"flex justify-center",children:e.jsx(je,{variant:"outline",size:"sm",onClick:V,children:"Open settings"})})]}):null,I?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:I}):null,O&&d&&s&&F?e.jsxs("div",{className:L("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",v===O&&"bg-muted/30"),onClick:()=>{$(O)},children:[e.jsx("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:"#"}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:["Use issue #",O]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:v===O?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,ne.length===0&&!k&&F&&s&&d?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:m?"No issues found":"No open issues found"}):null,ne.map(W=>e.jsxs("div",{className:L("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",v===W.number&&"bg-muted/30"),onClick:()=>{$(W.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0",children:["#",W.number]}),e.jsx("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:W.title}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:v===W.number?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:W.url,target:"_blank",rel:"noopener noreferrer",className:"hidden group-hover:flex h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:Y=>Y.stopPropagation(),"aria-label":"Open in GitHub",children:e.jsx(Xs,{className:"h-4 w-4"})})})]},W.number)),M&&F&&d&&s?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{E()},disabled:j||!!v,className:L("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(j||!!v)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:j?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):"Load more"})}):null]}),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 items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":p,onClick:()=>h(W=>!W),onKeyDown:W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),h(Y=>!Y))},children:[e.jsx("button",{type:"button",onClick:W=>{W.preventDefault(),W.stopPropagation(),h(Y=>!Y)},"aria-label":"Toggle worktree",className:"flex h-5 w-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:p?e.jsx(Sn,{className:"h-4 w-4 text-primary"}):e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Create in worktree"}),e.jsx("span",{className:"typography-meta text-muted-foreground/70",children:"(issue-<number>-<slug>)"})]}),e.jsx("div",{className:"flex-1"}),B?e.jsx(je,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:B,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(je,{variant:"outline",size:"sm",onClick:D,disabled:k||!!v,children:"Refresh"})]})]})]})})}const fj=t=>{const r=t.trim();if(!r)return null;const s=r.match(/\/pull\/(\d+)(?:\b|\/|$)/i);if(s){const o=Number(s[1]);return Number.isFinite(o)&&o>0?o:null}const n=r.match(/^#?(\d+)$/);if(n){const o=Number(n[1]);return Number.isFinite(o)&&o>0?o:null}return null},pj=t=>`GitHub pull request context (JSON)
|
|
120
|
+
${JSON.stringify(t,null,2)}`;function hj({open:t,onOpenChange:r}){const{github:s}=Hs(),n=Bs(X=>X.status),o=Bs(X=>X.hasChecked),a=Me(X=>X.setSettingsDialogOpen),l=Me(X=>X.setSidebarSection),d=Ft(X=>X.getActiveProject())?.path??null,[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,g]=i.useState(!1),[x,b]=i.useState(null),[y,w]=i.useState([]),[S,M]=i.useState(1),[N,v]=i.useState(!1),[A,k]=i.useState(null),[C,j]=i.useState(!1),[T,I]=i.useState(!1),[P,D]=i.useState(null),E=i.useCallback(async()=>{if(!d){b(null),D("No active project");return}if(o&&n?.connected===!1){b({connected:!1}),w([]),v(!1),M(1),D(null);return}if(!s?.prsList){b(null),D("GitHub runtime API unavailable");return}j(!0),D(null);try{const X=await s.prsList(d,{page:1});b(X),w(X.prs??[]),M(X.page??1),v(!!X.hasMore),X.connected===!1&&D(null)}catch(X){D(X instanceof Error?X.message:String(X))}finally{j(!1)}},[s,o,n,d]),F=i.useCallback(async()=>{if(d&&s?.prsList&&!(T||C)&&N){I(!0);try{const X=S+1,Z=await s.prsList(d,{page:X});b(Z),w(z=>[...z,...Z.prs??[]]),M(Z.page??X),v(!!Z.hasMore)}catch(X){const Z=X instanceof Error?X.message:String(X);U.error("Failed to load more PRs",{description:Z})}finally{I(!1)}}},[s,N,C,T,S,d]);i.useEffect(()=>{if(!t){m(""),p(!1),g(!1),b(null),w([]),M(1),v(!1),k(null),j(!1),D(null);return}E()},[t,E]),i.useEffect(()=>{t&&o&&n?.connected===!1&&(b({connected:!1}),w([]),v(!1),M(1),D(null))},[o,n,t]);const B=o?x?.connected!==!1:!0,V=x?.repo?.url??null,ne=i.useCallback(()=>{l("settings"),a(!0)},[a,l]),O=i.useMemo(()=>{const X=u.trim().toLowerCase();return X?y.filter(Z=>String(Z.number)===X.replace(/^#/,"")?!0:Z.title.toLowerCase().includes(X)):y},[y,u]),G=i.useMemo(()=>fj(u),[u]),K=i.useCallback(()=>{const X=Ze.getState(),Z=X.getVisibleAgents();if(X.settingsDefaultAgent){const z=Z.find(R=>R.name===X.settingsDefaultAgent);if(z)return z.name}return Z.find(z=>z.name==="build")?.name||Z[0]?.name},[]),q=i.useCallback(()=>{const X=Ze.getState(),Z=X.settingsDefaultModel;if(!Z)return null;const z=Z.split("/");if(z.length!==2)return null;const[R,de]=z;return!R||!de||!X.getModelMetadata(R,de)?null:{providerID:R,modelID:de}},[]),$=i.useCallback((X,Z)=>{const z=Ze.getState(),R=z.settingsDefaultVariant;if(!R)return;const xe=z.providers.find(Pe=>Pe.id===X)?.models.find(Pe=>Pe.id===Z)?.variants;if(xe&&Object.prototype.hasOwnProperty.call(xe,R))return R},[]),W=i.useCallback(async(X,Z)=>{if(!d)return null;const z=Z.head,R=Z.headRepo;if(!z)throw new Error("PR head ref missing");const we=!!(R?.owner&&R?.repo&&X?.owner&&X?.repo&&(R.owner!==X.owner||R.repo!==X.repo))?R?.cloneUrl||R?.url||"":"origin";if(!we)throw new Error("PR head remote URL missing");const xe=`refs/heads/${z}`;if(!(await Bb(d,{remote:we,branch:xe}))?.success)throw new Error("Failed to fetch PR head");const H=Z.head,ye=await sj(d,H,"FETCH_HEAD");if(!ye?.id)throw new Error("Failed to create PR worktree session");return{id:ye.id}},[d]),Y=i.useCallback(async X=>{if(!d){U.error("No active project");return}if(!s?.prContext){U.error("GitHub runtime API unavailable");return}if(!A){k(X);try{const Z=await s.prContext(d,X,{includeDiff:h,includeCheckDetails:!1});if(Z.connected===!1){U.error("GitHub not connected");return}if(!Z.repo){U.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}if(!Z.pr){U.error("PR not found");return}const z=Z.pr,R=`#${z.number} ${z.title}`.trim(),de=await(async()=>{if(f)try{return(await W(Z.repo,z))?.id||null}catch(fe){const oe=fe instanceof Error?fe.message:String(fe);U.error("PR worktree failed",{description:oe})}return(await be.getState().createSession(R,d,null))?.id||null})();if(!de)throw new Error("Failed to create session");be.getState().updateSessionTitle(de,R).catch(()=>{});try{be.getState().initializeNewOpenChamberSession(de,Ze.getState().agents)}catch{}r(!1);const we=Ze.getState(),xe=St.getState().lastUsedProvider,Pe=q(),H=Pe?.providerID||we.currentProviderId||xe?.providerID,ye=Pe?.modelID||we.currentModelId||xe?.modelID,J=K()||we.currentAgentName||void 0;if(!H||!ye){U.error("No model selected");return}const ce=$(H,ye);try{tt.getState().saveSessionModelSelection(de,H,ye)}catch{}if(J){try{we.setAgent(J)}catch{}try{tt.getState().saveSessionAgentSelection(de,J)}catch{}try{tt.getState().saveAgentModelForSession(de,J,H,ye)}catch{}if(ce!==void 0){try{we.setCurrentVariant(ce)}catch{}try{tt.getState().saveAgentModelVariantForSession(de,J,H,ye,ce)}catch{}}}const ge="Review this pull request using the provided PR context: description, comments, files, diff, checks.",ee=`Before reporting issues:
|
|
121
|
+
- First identify the PR intent (what it’s trying to achieve) from title/body/diff, then evaluate whether the implementation matches that intent; call out missing pieces, incorrect behavior vs intent, and scope creep.
|
|
122
|
+
- Gather any needed repository context (code, config, docs) to validate assumptions.
|
|
123
|
+
- No speculation: if something is unclear or cannot be verified, say what’s missing and ask for it instead of guessing.
|
|
124
|
+
|
|
125
|
+
Output rules:
|
|
126
|
+
- Start with a 1-2 sentence summary.
|
|
127
|
+
- Provide a single concise PR review comment.
|
|
128
|
+
- No emojis. No code snippets. No fenced blocks.
|
|
129
|
+
- Short inline code identifiers allowed, but no snippets or fenced blocks.
|
|
130
|
+
- Reference evidence with file paths and line ranges (e.g., path/to/file.ts:120-138). If exact lines aren’t available, cite the file and say “approx” + why.
|
|
131
|
+
- Keep the entire comment under ~300 words.
|
|
132
|
+
|
|
133
|
+
Report:
|
|
134
|
+
- Must-fix issues (blocking) — brief why and a one-line action each.
|
|
135
|
+
- Nice-to-have improvements (optional) — brief why and a one-line action each.
|
|
136
|
+
|
|
137
|
+
Quality & safety (general):
|
|
138
|
+
- Call out correctness risks, edge cases, performance regressions, security/privacy concerns, and backwards-compatibility risks.
|
|
139
|
+
- Call out missing tests/verification steps and suggest the minimal validation needed.
|
|
140
|
+
- Note readability/maintainability issues when they materially affect future changes.
|
|
141
|
+
|
|
142
|
+
Applicability (only if relevant):
|
|
143
|
+
- If changes affect multiple components/targets/environments (e.g., client/server, OSs, deployments), state what is affected vs not, and why.
|
|
144
|
+
|
|
145
|
+
Architecture:
|
|
146
|
+
- Call out breakages, missing implementations across modules/targets, boundary violations, and cross-cutting concerns (errors, logging/observability, accessibility).
|
|
147
|
+
|
|
148
|
+
Precedence:
|
|
149
|
+
- If local precedent conflicts with best practices, state it and suggest a follow-up task.
|
|
150
|
+
|
|
151
|
+
Do not implement changes until I confirm; end with a short “Next actions” sentence describing the recommended plan.
|
|
152
|
+
|
|
153
|
+
Format exactly:
|
|
154
|
+
Must-fix:
|
|
155
|
+
- <issue> — <brief why> — <file:line-range> — Action: <one-line action>
|
|
156
|
+
Nice-to-have:
|
|
157
|
+
- <issue> — <brief why> — <file:line-range> — Action: <one-line action>
|
|
158
|
+
If no issues, write:
|
|
159
|
+
Must-fix:
|
|
160
|
+
- None
|
|
161
|
+
Nice-to-have:
|
|
162
|
+
- None`,me=pj(Z);Oe.sendMessage({id:de,providerID:H,modelID:ye,agent:J,variant:ce,text:ge,additionalParts:[{text:ee,synthetic:!0},{text:me,synthetic:!0}]}).catch(le=>{const fe=le instanceof Error?le.message:String(le);U.error("Failed to send PR context",{description:fe})}),U.success("Session created from PR")}catch(Z){const z=Z instanceof Error?Z.message:String(Z);U.error("Failed to start session",{description:z})}finally{k(null)}}},[f,W,s,h,r,d,K,q,$,A]);return e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ps,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(bs,{className:"flex-shrink-0",children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-5 w-5"}),"New Session From GitHub PR"]}),e.jsx(Ns,{children:"Seeds a new session with hidden PR context (title/body/comments/files/checks)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(wt,{placeholder:"Search by title or #123, or paste PR URL",value:u,onChange:X=>m(X.target.value),className:"pl-9 w-full"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[d?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No active project selected."}),s?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"GitHub runtime API unavailable."}),C?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Loading pull requests..."]}):null,B===!1?e.jsxs("div",{className:"text-center text-muted-foreground py-8 space-y-3",children:[e.jsx("div",{children:"GitHub not connected. Connect your GitHub account in settings."}),e.jsx("div",{className:"flex justify-center",children:e.jsx(je,{variant:"outline",size:"sm",onClick:ne,children:"Open settings"})})]}):null,P?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:P}):null,G&&d&&s&&B?e.jsxs("div",{className:L("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",A===G&&"bg-muted/30"),onClick:()=>{Y(G)},children:[e.jsx("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:"#"}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:["Use PR #",G]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:A===G?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,O.length===0&&!C&&B&&s&&d?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:u?"No PRs found":"No open PRs found"}):null,O.map(X=>e.jsxs("div",{className:L("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",A===X.number&&"bg-muted/30"),onClick:()=>{Y(X.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0",children:["#",X.number]}),e.jsx("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:X.title}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:A===X.number?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:X.url,target:"_blank",rel:"noopener noreferrer",className:"hidden group-hover:flex h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:Z=>Z.stopPropagation(),"aria-label":"Open in GitHub",children:e.jsx(Xs,{className:"h-4 w-4"})})})]},X.number)),N&&B&&d&&s?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{F()},disabled:T||!!A,className:L("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(T||!!A)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:T?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):"Load more"})}):null]}),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 items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":f,onClick:()=>p(X=>!X),onKeyDown:X=>{(X.key===" "||X.key==="Enter")&&(X.preventDefault(),p(Z=>!Z))},children:[e.jsx("button",{type:"button",onClick:X=>{X.preventDefault(),X.stopPropagation(),p(Z=>!Z)},"aria-label":"Toggle worktree",className:"flex h-5 w-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:f?e.jsx(Sn,{className:"h-4 w-4 text-primary"}):e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Create session in PR worktree"})]}),e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":h,onClick:()=>g(X=>!X),onKeyDown:X=>{(X.key===" "||X.key==="Enter")&&(X.preventDefault(),g(Z=>!Z))},children:[e.jsx("button",{type:"button",onClick:X=>{X.preventDefault(),X.stopPropagation(),g(Z=>!Z)},"aria-label":"Toggle diff",className:"flex h-5 w-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:h?e.jsx(Sn,{className:"h-4 w-4 text-primary"}):e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Include full diff"})]}),e.jsx("div",{className:"flex-1"}),V?e.jsx(je,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:V,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(je,{variant:"outline",size:"sm",onClick:E,disabled:C||!!A,children:"Refresh"})]})]})]})})}const nu="oc.sessions.projectCollapse",ou="oc.sessions.expandedParents",au=t=>{const r=new Date(t),s=new Date,n=(l,c)=>l.getFullYear()===c.getFullYear()&&l.getMonth()===c.getMonth()&&l.getDate()===c.getDate(),o=new Date(s);return o.setDate(s.getDate()-1),n(r,s)?"Today":n(r,o)?"Yesterday":r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},br=t=>{if(!t)return null;const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},iu=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),gj=({id:t,projectLabel:r,projectDescription:s,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:l,isDesktopRuntime:c,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:h,onNewWorktreeSession:g,onOpenBranchPicker:x,onNewSessionFromGitHubIssue:b,onNewSessionFromGitHubPR:y,onOpenMultiRunLauncher:w,onClose:S,sentinelRef:M,children:N,settingsAutoCreateWorktree:v})=>{const{attributes:A,listeners:k,setNodeRef:C,isDragging:j}=Eg({id:t}),[T,I]=i.useState(!1);return e.jsxs("div",{ref:C,className:L("relative",j&&"opacity-40"),children:[c&&e.jsx("div",{ref:M,"data-project-id":t,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("div",{className:L("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b select-none",!c&&"bg-sidebar"),style:{backgroundColor:c?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:l?"var(--color-border)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onContextMenu:P=>{P.preventDefault(),I(!0)},children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...A,children:[e.jsxs(dt,{delayDuration:1500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...k,className:"flex-1 min-w-0 flex items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-sm cursor-grab active:cursor-grabbing",children:e.jsx("span",{className:L("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(ct,{side:"right",sideOffset:8,children:s})]}),e.jsxs(rs,{open:T,onOpenChange:I,children:[e.jsx(ns,{asChild:!0,children:e.jsx("button",{type:"button",className:L("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",m?"opacity-70":"opacity-0 group-hover/project:opacity-100"),"aria-label":"Project menu",onClick:P=>P.stopPropagation(),children:e.jsx(sn,{className:"h-3.5 w-3.5"})})}),e.jsxs(os,{align:"end",className:"min-w-[180px]",children:[a&&!u&&v&&h&&e.jsxs(Nt,{onClick:h,children:[e.jsx(us,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),a&&!u&&!v&&g&&e.jsxs(Nt,{onClick:g,children:[e.jsx(Vt,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),a&&!u&&b&&e.jsxs(Nt,{onClick:b,children:[e.jsx(Vm,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub issue"]}),a&&!u&&y&&e.jsxs(Nt,{onClick:y,children:[e.jsx(Ha,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub PR"]}),a&&!u&&e.jsxs(Nt,{onClick:w,children:[e.jsx(bp,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),a&&!u&&x&&e.jsxs(Nt,{onClick:x,children:[e.jsx(Gm,{className:"mr-1.5 h-4 w-4"}),"Manage Branches"]}),e.jsxs(Nt,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(ss,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),a&&!u&&g&&v&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),g()},className:L("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground flex-shrink-0",m?"opacity-70":"opacity-100"),"aria-label":"New session in worktree",children:e.jsx(Vt,{className:"h-4 w-4"})})}),e.jsx(ct,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session in worktree"})})]}),(!v||!a)&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),h()},className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground flex-shrink-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"New session",children:e.jsx(us,{className:"h-4 w-4"})})}),e.jsx(ct,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session"})})]})]})}),N]})},xj=({projectLabel:t,isActiveProject:r})=>e.jsx("div",{className:"bg-sidebar border border-border rounded-md shadow-lg px-2 py-1.5",style:{width:"max-content",maxWidth:"280px"},children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:L("typography-ui font-semibold truncate",r?"text-primary":"text-foreground"),children:t})})}),ri=({mobileVariant:t=!1,onSessionSelected:r,allowReselect:s=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,l]=i.useState(null),[c,d]=i.useState(""),[u,m]=i.useState(null),f=i.useRef(null),[p,h]=i.useState(new Set),[g,x]=i.useState(()=>new Map),b=i.useRef(new Set),y=i.useMemo(()=>Ss(),[]),[w,S]=i.useState(new Set),[M,N]=i.useState(new Map),[v,A]=i.useState(new Set),[k,C]=i.useState(null),[j,T]=i.useState(!1),[I,P]=i.useState(null),[D,E]=i.useState(!1),[F,B]=i.useState(!1),[V,ne]=i.useState(null),[O,G]=i.useState(new Set),[K,q]=i.useState(null),$=i.useRef(new Map),W=i.useRef(0),Y=xt(te=>te.homeDirectory),X=xt(te=>te.currentDirectory),Z=xt(te=>te.setDirectory),z=Ft(te=>te.projects),R=Ft(te=>te.activeProjectId),de=Ft(te=>te.addProject),we=Ft(te=>te.removeProject),xe=Ft(te=>te.setActiveProject),Pe=Ft(te=>te.setActiveProjectIdOnly),H=Ft(te=>te.reorderProjects),ye=Me(te=>te.setActiveMainTab),J=Me(te=>te.setSessionSwitcherOpen),ce=Me(te=>te.openMultiRunLauncher),ge=Ze(te=>te.settingsAutoCreateWorktree),ee=be(te=>te.sessions),me=be(te=>te.sessionsByDirectory),le=be(te=>te.currentSessionId),fe=be(te=>te.setCurrentSession),oe=be(te=>te.updateSessionTitle),Q=be(te=>te.shareSession),re=be(te=>te.unshareSession),ue=be(te=>te.sessionMemoryState),he=be(te=>te.sessionActivityPhase),Ge=be(te=>te.permissions),qe=be(te=>te.worktreeMetadata),et=be(te=>te.availableWorktreesByProject),rt=be(te=>te.getSessionsByDirectory),vt=be(te=>te.openNewSessionDraft),[Ce,pe]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),He=i.useMemo(()=>zt(),[]);i.useEffect(()=>{try{const te=y.getItem(ou);if(te){const ie=JSON.parse(te);Array.isArray(ie)&&h(new Set(ie.filter(Ee=>typeof Ee=="string")))}const se=y.getItem(nu);if(se){const ie=JSON.parse(se);Array.isArray(ie)&&S(new Set(ie.filter(Ee=>typeof Ee=="string")))}}catch{}},[y]),i.useEffect(()=>{typeof window>"u"||pe(typeof window.opencodeDesktop<"u")},[]);const Se=i.useMemo(()=>[...ee].sort((te,se)=>(se.time?.updated||0)-(te.time?.updated||0)),[ee]);i.useEffect(()=>{let te=!1;const se=z.map(ie=>({id:ie.id,path:br(ie.path)})).filter(ie=>!!ie.path);return N(new Map),se.length===0?()=>{te=!0}:(se.forEach(ie=>{zr(ie.path).then(Ee=>{te||N(Re=>{const Ye=new Map(Re);return Ye.set(ie.id,Ee),Ye})}).catch(()=>{te||N(Ee=>{const Re=new Map(Ee);return Re.set(ie.id,null),Re})})}),()=>{te=!0})},[z]);const ke=i.useMemo(()=>{const te=new Map;return Se.forEach(se=>{const ie=se.parentID;ie&&te.set(se.id,ie)}),te},[Se]),Xe=i.useMemo(()=>{const te=new Map;return Se.forEach(se=>{const ie=se.parentID;if(!ie)return;const Ee=te.get(ie)??[];Ee.push(se),te.set(ie,Ee)}),te.forEach(se=>se.sort((ie,Ee)=>(Ee.time?.updated||0)-(ie.time?.updated||0))),te},[Se]);i.useEffect(()=>{le&&h(te=>{const se=new Set(te);let ie=ke.get(le)||null,Ee=!1;for(;ie;)se.has(ie)||(se.add(ie),Ee=!0),ie=ke.get(ie)||null;return Ee?se:te})},[le,ke]),i.useEffect(()=>{const te=new Set;Se.forEach(se=>{const ie=br(se.directory??null);ie&&te.add(ie)}),z.forEach(se=>{const ie=br(se.path);ie&&te.add(ie)}),te.forEach(se=>{const ie=g.get(se);ie&&ie!=="unknown"||b.current.has(se)||(b.current.add(se),Oe.listLocalDirectory(se).then(()=>{x(Ee=>{const Re=new Map(Ee);return Re.get(se)==="exists"?Ee:(Re.set(se,"exists"),Re)})}).catch(async()=>{if((se.includes("/opencode/worktree/")||se.includes("/.opencode/data/worktree/")||se.includes("/.local/share/opencode/worktree/"))&&await Oe.probeDirectory(se).catch(()=>!1)){x(Ye=>{const bt=new Map(Ye);return bt.get(se)==="exists"?Ye:(bt.set(se,"exists"),bt)});return}x(Re=>{const Ye=new Map(Re);return Ye.get(se)==="missing"?Re:(Ye.set(se,"missing"),Ye)})}).finally(()=>{b.current.delete(se)}))})},[Se,z,g]),i.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const at=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."})]}),We=i.useCallback((te,se,ie,Ee)=>{if(!ie){if(Ee&&Ee!==R&&Pe(Ee),se&&se!==X&&Z(se,{showOverlay:!1}),t&&(ye("chat"),J(!1)),!s&&te===le){r?.(te);return}fe(te),r?.(te)}},[R,s,X,le,t,r,ye,Pe,fe,Z,J]),Be=i.useCallback(async()=>{a&&c.trim()&&(await oe(a,c.trim()),l(null),d(""))},[a,c,oe]),Ve=i.useCallback(()=>{l(null),d("")},[]),mt=i.useCallback(async te=>{const se=await Q(te.id);se&&se.share?.url?U.success("Session shared",{description:"You can copy the link from the menu."}):U.error("Unable to share session")},[Q]),ft=i.useCallback((te,se)=>{navigator.clipboard.writeText(te).then(()=>{m(se),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{U.error("Failed to copy URL")})},[]),Ke=i.useCallback(async te=>{await re(te)?U.success("Session unshared"):U.error("Unable to unshare session")},[re]),lt=i.useCallback(te=>{const se=[],ie=Ee=>{(Xe.get(Ee)??[]).forEach(Ye=>{se.push(Ye),ie(Ye.id)})};return ie(te),se},[Xe]),jt=be(te=>te.deleteSession),yt=be(te=>te.deleteSessions),Mt=i.useCallback(async te=>{const se=lt(te.id),ie=qe.get(te.id);if(ie){const Ee=ie.path,Re=[],Ye=new Set;ee.forEach(bt=>{const pt=qe.get(bt.id);pt&&pt.path===Ee&&!Ye.has(bt.id)&&(Re.push(bt),Ye.add(bt.id),lt(bt.id).forEach(Lt=>{Ye.has(Lt.id)||(Re.push(Lt),Ye.add(Lt.id))}))}),no.requestDelete({sessions:Re,mode:"worktree",worktree:ie});return}if(se.length===0)await jt(te.id)?U.success("Session deleted",{action:{label:"OK",onClick:()=>{}}}):U.error("Failed to delete session");else{const Ee=[te.id,...se.map(bt=>bt.id)],{deletedIds:Re,failedIds:Ye}=await yt(Ee);Re.length>0&&U.success(`Deleted ${Re.length} session${Re.length===1?"":"s"}`,{action:{label:"OK",onClick:()=>{}}}),Ye.length>0&&U.error(`Failed to delete ${Ye.length} session${Ye.length===1?"":"s"}`)}},[lt,jt,yt,qe,ee]),es=i.useCallback(()=>{Ce&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(te=>{te.success&&te.path?de(te.path,{id:te.projectId})||U.error("Failed to add project",{description:"Please select a valid directory."}):te.error&&te.error!=="Directory selection cancelled"&&U.error("Failed to select directory",{description:te.error})}).catch(te=>{console.error("Desktop: Error selecting directory:",te),U.error("Failed to select directory")}):no.requestDirectoryDialog()},[de,Ce]),Ht=i.useCallback(te=>{h(se=>{const ie=new Set(se);ie.has(te)?ie.delete(te):ie.add(te);try{y.setItem(ou,JSON.stringify(Array.from(ie)))}catch{}return ie})},[y]),Wt=i.useCallback(te=>{const se=Xe.get(te.id)??[];return{session:te,children:se.map(ie=>Wt(ie)),worktree:qe.get(te.id)??null}},[Xe,qe]),kt=i.useCallback((te,se,ie)=>{const Ee=br(se??null),Re=[...te].sort((Dt,Ot)=>(Ot.time?.updated||0)-(Dt.time?.updated||0)),Ye=new Map(Re.map(Dt=>[Dt.id,Dt])),bt=new Map;Re.forEach(Dt=>{const Ot=Dt.parentID;if(!Ot)return;const as=bt.get(Ot)??[];as.push(Dt),bt.set(Ot,as)}),bt.forEach(Dt=>Dt.sort((Ot,as)=>(as.time?.updated||0)-(Ot.time?.updated||0)));const pt=new Map;ie.forEach(Dt=>{if(Dt.path){const Ot=br(Dt.path)??Dt.path;pt.set(Ot,Dt)}});const Jt=Dt=>{const Ot=br(Dt.directory??null),as=qe.get(Dt.id)??null;if(as)return as;if(Ot){const hr=pt.get(Ot)??null;if(hr&&Ot!==Ee)return hr}return null},Lt=Dt=>{const Ot=bt.get(Dt.id)??[];return{session:Dt,children:Ot.map(as=>Lt(as)),worktree:Jt(Dt)}},Cs=Re.filter(Dt=>{const Ot=Dt.parentID;return Ot?!Ye.has(Ot):!0}).map(Dt=>Lt(Dt));return[{id:"all",label:"All sessions",description:Ee?Yr(Ee,Y):null,isMain:!0,worktree:null,directory:Ee,sessions:Cs}]},[Y,qe]),gs=i.useCallback(te=>{A(se=>{const ie=new Set(se);return ie.has(te)?ie.delete(te):ie.add(te),ie})},[]),Qt=i.useCallback(te=>{W.current=Date.now()+150,S(se=>{const ie=new Set(se);ie.has(te)?ie.delete(te):ie.add(te);try{y.setItem(nu,JSON.stringify(Array.from(ie)))}catch{}return ie})},[y]),Tt=i.useMemo(()=>z.map(te=>({...te,normalizedPath:br(te.path)})).filter(te=>!!te.normalizedPath),[z]),Kt=i.useCallback(te=>{const se=He?[]:et.get(te.normalizedPath)??[],ie=[te.normalizedPath,...se.map(Ye=>br(Ye.path)??Ye.path).filter(Ye=>!!Ye)],Ee=new Set,Re=[];return ie.forEach(Ye=>{(me.get(Ye)??rt(Ye)).forEach(pt=>{Ee.has(pt.id)||(Ee.add(pt.id),Re.push(pt))})}),Re},[et,rt,me,He]),Rt=i.useMemo(()=>Tt.map(te=>{const se=Kt(te),ie=et.get(te.normalizedPath)??[],Ee=kt(se,te.normalizedPath,ie);return{project:te,groups:Ee}}),[Tt,Kt,kt,et]);i.useEffect(()=>{if(!Ce)return;const te=new IntersectionObserver(se=>{se.forEach(ie=>{const Ee=ie.target.dataset.projectId;Ee&&G(Re=>{const Ye=new Set(Re);return ie.isIntersecting?Ye.delete(Ee):Ye.add(Ee),Ye})})},{threshold:0});return $.current.forEach(se=>{se&&te.observe(se)}),()=>te.disconnect()},[Ce,Rt]);const _t=i.useCallback((te,se=0,ie,Ee)=>{const Re=te.session,Ye=br(Re.directory??null)??br(ie??null),pt=(Ye?g.get(Ye):null)==="missing",Jt=ue.get(Re.id),Lt=le===Re.id,ks=Re.title||"Untitled Session",Cs=te.children.length>0,Dt=p.has(Re.id),Ot=Re.summary?.additions,as=Re.summary?.deletions,hr=typeof Ot=="number"||typeof as=="number";if(a===Re.id)return e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",se>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:nt=>{nt.preventDefault(),Be()},children:[e.jsx("input",{value:c,onChange:nt=>d(nt.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:nt=>{nt.key==="Escape"&&Ve()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Pt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:Ve,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(ss,{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:[Cs?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:Dt?e.jsx(Ut,{className:"h-3 w-3"}):e.jsx(er,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:au(Re.time?.created||Date.now())}),Re.share?e.jsx(Ti,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,hr&&((Ot??0)!==0||(as??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,Ot??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,as??0)]})]}):null,Cs?e.jsxs("span",{className:"truncate",children:[te.children.length," ",te.children.length===1?"task":"tasks"]}):null]})]})},Re.id);const De=he?.get(Re.id)??"idle",ze=De==="busy"||De==="cooldown",_e=Ge.get(Re.id)?.length??0,st=Jt&&Jt.isZombie?e.jsx(kl,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(i.Fragment,{children:[e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1",Lt?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",pt?"opacity-75":"",se>0&&"pl-[20px]"),onContextMenu:nt=>{nt.preventDefault(),q(Re.id)},children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:pt,onClick:()=>We(Re.id,Ye,pt,Ee),className:L("flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[ze?e.jsx(yp,{size:"xs",className:"text-primary flex-shrink-0"}):null,e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:ks}),_e>0?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:"Permission required","aria-label":"Permission required",children:[e.jsx(bg,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:_e})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Cs?e.jsx("span",{role:"button",tabIndex:0,onClick:nt=>{nt.stopPropagation(),Ht(Re.id)},onKeyDown:nt=>{(nt.key==="Enter"||nt.key===" ")&&(nt.preventDefault(),nt.stopPropagation(),Ht(Re.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":Dt?"Collapse subsessions":"Expand subsessions",children:Dt?e.jsx(Ut,{className:"h-3 w-3"}):e.jsx(er,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:au(Re.time?.created||Date.now())}),Re.share?e.jsx(Ti,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,te.worktree?e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(Vt,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(ct,{side:"top",className:"text-xs",children:te.worktree.branch||te.worktree.label||"Worktree"})]}):null,hr&&((Ot??0)!==0||(as??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,Ot??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,as??0)]})]}):null,Cs?e.jsxs("span",{className:"truncate",children:[te.children.length," ",te.children.length===1?"task":"tasks"]}):null,pt?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(kl,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[st,e.jsxs(rs,{open:K===Re.id,onOpenChange:nt=>q(nt?Re.id:null),children:[e.jsx(ns,{asChild:!0,children:e.jsx("button",{type:"button",className:L("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:nt=>nt.stopPropagation(),onKeyDown:nt=>nt.stopPropagation(),children:e.jsx(sn,{className:t?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(os,{align:"end",className:"min-w-[180px]",children:[e.jsxs(Nt,{onClick:()=>{l(Re.id),d(ks)},className:"[&>svg]:mr-1",children:[e.jsx(Tr,{className:"mr-1 h-4 w-4"}),"Rename"]}),Re.share?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{onClick:()=>{Re.share?.url&&ft(Re.share.url,Re.id)},className:"[&>svg]:mr-1",children:u===Re.id?e.jsxs(e.Fragment,{children:[e.jsx(Pt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(rr,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(Nt,{onClick:()=>Ke(Re.id),className:"[&>svg]:mr-1",children:[e.jsx(wg,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(Nt,{onClick:()=>mt(Re),className:"[&>svg]:mr-1",children:[e.jsx(Ti,{className:"mr-1 h-4 w-4"}),"Share"]}),te.worktree?e.jsxs(Nt,{onClick:()=>{Ee&&Ee!==R&&xe(Ee),ye("chat"),t&&J(!1),vt({directoryOverride:te.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(Vt,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(Nt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Mt(Re),children:[e.jsx(zs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),Cs&&Dt?te.children.map(nt=>_t(nt,se+1,Ye??ie,Ee)):null]},Re.id)},[g,ue,he,Ge,le,p,a,c,Be,Ve,Ht,We,mt,ft,Ke,Mt,u,t,R,xe,ye,J,vt,K]),Yt=i.useCallback((te,se,ie)=>{const Ee=v.has(se),Re=n?10:5,Ye=te.sessions.length,bt=Ee?te.sessions:te.sessions.slice(0,Re),pt=Ye-bt.length;return e.jsxs(e.Fragment,{children:[bt.map(Jt=>_t(Jt,0,te.directory,ie)),Ye===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,pt>0&&!Ee?e.jsxs("button",{type:"button",onClick:()=>gs(se),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 ",pt," more ",pt===1?"session":"sessions"]}):null,Ee&&Ye>Re?e.jsx("button",{type:"button",onClick:()=>gs(se),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]})},[v,n,_t,gs]),Gt=vg(Qc(Ag,{activationConstraint:{distance:8}}),Qc(Dg,{coordinateGetter:Mg})),It=i.useCallback(te=>{ne(te.active.id)},[]),Ie=i.useCallback(te=>{const{active:se,over:ie}=te;if(ne(null),!ie||se.id===ie.id)return;const Ee=Tt.findIndex(Ye=>Ye.id===se.id),Re=Tt.findIndex(Ye=>Ye.id===ie.id);Ee!==-1&&Re!==-1&&H(Ee,Re)},[Tt,H]),Te=i.useCallback(()=>{ne(null)},[]),Le=i.useMemo(()=>{if(!V)return null;const te=Rt.find(ie=>ie.project.id===V);if(!te)return null;const se=te.project;return{id:se.id,label:iu(se.label?.trim()||rd(se.normalizedPath,Y)||se.normalizedPath),isActive:se.id===R}},[V,Rt,Y,R]);return e.jsxs("div",{className:L("flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-8 select-none pl-3.5 pr-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("p",{className:"typography-ui-label font-medium text-muted-foreground",children:"Projects"}),e.jsx("span",{className:"typography-micro text-muted-foreground/50",children:z.length})]}),e.jsx("button",{type:"button",onClick:es,className:L("inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!Ce&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(Cl,{className:"h-4.5 w-4.5"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:L("space-y-1 pb-1 pl-2.5 pr-1",""),children:Rt.length===0?at:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const te=Rt.find(Ee=>Ee.project.id===R)??Rt[0];if(!te)return at;const se=te.groups.find(Ee=>Ee.isMain&&Ee.sessions.length>0)??te.groups.find(Ee=>Ee.sessions.length>0)??te.groups.find(Ee=>Ee.isMain)??te.groups[0];if(!se)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const ie=`${te.project.id}:${se.id}`;return Yt(se,ie,te.project.id)})()}):e.jsxs(jg,{sensors:Gt,collisionDetection:Sg,onDragStart:It,onDragEnd:Ie,onDragCancel:Te,children:[e.jsx(Ng,{items:Tt.map(te=>te.id),strategy:kg,children:Rt.map(te=>{const se=te.project,ie=se.id,Ee=iu(se.label?.trim()||rd(se.normalizedPath,Y)||se.normalizedPath),Re=Yr(se.normalizedPath,Y),Ye=w.has(ie),bt=ie===R,pt=M.get(ie),Jt=k===ie;return e.jsx(gj,{id:ie,projectLabel:Ee,projectDescription:Re,isCollapsed:Ye,isActiveProject:bt,isRepo:!!pt,isHovered:Jt,isDesktopRuntime:Ce,isStuck:O.has(ie),hideDirectoryControls:n,mobileVariant:t,onToggle:()=>Qt(ie),onHoverChange:Lt=>C(Lt?ie:null),onNewSession:()=>{ie!==R&&xe(ie),ye("chat"),t&&J(!1),vt({directoryOverride:se.normalizedPath})},onNewWorktreeSession:()=>{ie!==R&&xe(ie),ye("chat"),t&&J(!1),Ai()},onOpenBranchPicker:()=>{P(ie),T(!0)},onNewSessionFromGitHubIssue:()=>{ie!==R&&xe(ie),ye("chat"),t&&J(!1),E(!0)},onNewSessionFromGitHubPR:()=>{ie!==R&&xe(ie),ye("chat"),t&&J(!1),B(!0)},onOpenMultiRunLauncher:()=>{ie!==R&&xe(ie),ce()},onClose:()=>we(ie),sentinelRef:Lt=>{$.current.set(ie,Lt)},settingsAutoCreateWorktree:ge,children:Ye?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:te.groups[0]?Yt(te.groups[0],`${ie}:all`,ie):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},ie)})}),e.jsx(Cg,{children:Le?e.jsx(xj,{projectLabel:Le.label,isActiveProject:Le.isActive}):null})]})}),e.jsx(cj,{open:j,onOpenChange:T,project:I?Tt.find(te=>te.id===I)??null:null}),e.jsx(mj,{open:D,onOpenChange:E}),e.jsx(hj,{open:F,onOpenChange:B})]})},Ei=()=>{const[t,r]=Ae.useState(!1);Ae.useEffect(()=>{r(ms())},[]);const s=Ae.useCallback(async a=>t?await jy(a):{success:!0,path:a},[t]),n=Ae.useCallback(async a=>t?await Sy(a):{success:!0},[t]),o=Ae.useCallback(async a=>t?await Ny(a):{success:!0},[t]);return{isDesktop:t,requestAccess:s,startAccessing:n,stopAccessing:o}},lu=({currentPath:t,onSelectPath:r,triggerClassName:s,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:l,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=i.useMemo(()=>ms(),[]),{isMobile:p}=qt(),[h,g]=i.useState([]),[x,b]=i.useState(new Set),[y,w]=i.useState(!0),[S,M]=i.useState(!1),[N,v]=i.useState(""),[A,k]=i.useState(new Set),[C,j]=i.useState(null),[T,I]=i.useState(""),[P,D]=i.useState(!0),E=i.useRef(null),{requestAccess:F,startAccessing:B,isDesktop:V}=Ei(),ne=i.useRef(c),O=i.useCallback(ee=>{if(!ee)return ee;if(ee==="/"||ee.length===0)return"/";let me=ee;for(;me.length>1&&me.endsWith("/");)me=me.slice(0,-1);return me.length===0?"/":me},[]),G=i.useMemo(()=>{if(!N)return null;const ee=N.replace(/\\/g,"/");return O(ee)},[N,O]),K=i.useMemo(()=>{if(typeof d=="string"&&d.length>0){const ee=d.replace(/\\/g,"/"),me=O(ee);if(me&&me!=="/")return me}return G&&G!=="/"?G:null},[d,G,O]),q=i.useMemo(()=>typeof u=="boolean"?!!(u&&K):!!K,[u,K]);i.useEffect(()=>{q||(w(!0),g([]))},[q]);const $=i.useCallback(ee=>{if(!ee||!q||!K)return!1;const me=ee.replace(/\\/g,"/"),le=O(me)??me;if(le===K)return!0;const fe=`${K}/`;return le.startsWith(fe)},[q,K,O]),W=async ee=>{if(q){if(a==="deferred"){r(ee);return}if(V){const me=await F(ee);me.success&&me.path?(await B(me.path),r(me.path)):(console.error("Failed to get directory access:",me.error),r(ee))}else r(ee)}};i.useEffect(()=>{let ee=!1;const me=oe=>{if(!oe)return!1;const Q=O(oe.replace(/\\/g,"/"));return!Q||Q==="/"?!1:(v(typeof Q=="string"?Q:oe.replace(/\\/g,"/")),!0)};return d&&me(d)||(async()=>{try{const oe=await Oe.getFilesystemHome();if(!ee&&me(oe))return}catch(oe){console.warn("Failed to resolve filesystem home directory:",oe)}try{const oe=await Oe.getSystemInfo();if(!ee&&me(oe?.homeDirectory))return}catch(oe){console.warn("Failed to resolve home directory from system info:",oe)}})(),()=>{ee=!0}},[d,O]),i.useEffect(()=>{let ee=!1;const me=Q=>{if(ee)return;const re=Q.filter(ue=>typeof ue=="string"&&ue.length>0).map(ue=>{const he=ue.replace(/\\/g,"/");return O(he)??he});k(new Set(re))},le=()=>{try{const Q=localStorage.getItem("pinnedDirectories");if(!Q)return;const re=JSON.parse(Q);Array.isArray(re)&&me(re)}catch(Q){console.warn("Failed to load pinned directories from local storage:",Q)}},fe=async()=>{try{let Q=[];if(f){const re=await Br();Q=Array.isArray(re?.pinnedDirectories)?re.pinnedDirectories:[]}else{const re=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(re.ok){const ue=await re.json();Q=Array.isArray(ue?.pinnedDirectories)?ue.pinnedDirectories:[]}}if(ee)return;me(Q)}catch(Q){console.warn("Failed to load pinned directories:",Q)}};le();const oe=Q=>{const re=Q.detail;re&&Array.isArray(re.pinnedDirectories)&&me(re.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",oe),fe(),()=>{ee=!0,window.removeEventListener("openchamber:settings-synced",oe)}},[f,O]);const Y=i.useRef(!0);i.useEffect(()=>{if(Y.current){Y.current=!1;return}const ee={pinnedDirectories:Array.from(A)};cs(ee)},[A]),i.useEffect(()=>{K&&k(ee=>{const me=Array.from(ee).map(le=>O(le.replace(/\\/g,"/"))??le).filter(le=>$(le));return new Set(me)})},[K,$,O]),i.useEffect(()=>{ne.current!==c&&(ne.current=c)},[c]);const X=ee=>{k(me=>{if(!$(ee))return me;const le=O(ee.replace(/\\/g,"/"))??ee.replace(/\\/g,"/"),fe=new Set(me);return fe.has(le)?fe.delete(le):fe.add(le),fe})},Z=i.useMemo(()=>Array.from(A).map(ee=>O(ee.replace(/\\/g,"/"))??ee).filter(ee=>$(ee)).map(ee=>({path:ee,name:ee.split("/").pop()||ee})).sort((ee,me)=>ee.name.localeCompare(me.name)),[A,$,O]),z=i.useCallback(async ee=>{const me=re=>c||!re.startsWith("."),le=K;if(!q||!le)return[];const fe=ee&&ee.length>0?ee:le,oe=fe?fe.replace(/\\/g,"/"):null,Q=oe?O(oe)??oe:null;if(Q){const re=`${le}/`;if(!(Q===le||Q.startsWith(re)))return[]}try{return(await Oe.listLocalDirectory(ee)).filter(ue=>{if(!ue.isDirectory||!me(ue.name))return!1;const he=ue.path.replace(/\\/g,"/"),Ge=O(he)??he,qe=Ge===le?le:`${le}/`;return Ge===le||Ge.startsWith(qe)}).map(ue=>({name:ue.name,path:ue.path.replace(/\\/g,"/"),isDirectory:!0})).sort((ue,he)=>ue.name.localeCompare(he.name))}catch{try{const ue=await Oe.getApiClient().file.list({path:".",directory:ee});return ue.data?ue.data.filter(he=>{if(he.type!=="directory"||!he.name||!me(he.name))return!1;const Ge=String(he.absolute||he.path||he.name).replace(/\\/g,"/"),qe=O(Ge)??Ge,et=qe===le?le:`${le}/`;return qe===le||qe.startsWith(et)}).map(he=>({name:he.name||"",path:String(he.absolute||he.path||he.name).replace(/\\/g,"/"),isDirectory:!0})).filter(he=>he.name!=="").sort((he,Ge)=>he.name.localeCompare(Ge.name)):[]}catch{return[]}}},[c,K,O,q]),R=i.useRef(!1),de=i.useCallback(async()=>{if(!q||!K){w(!0),g([]);return}R.current||w(!0);try{const ee=await z(K);g(ee),R.current=!0}catch{}finally{w(!1)}},[q,K,z]);i.useEffect(()=>{q&&(n==="inline"||S)&&de()},[n,S,q,de]);const we=async ee=>{if(!q)return;const me=x.has(ee.path),le=new Set(x);if(me){le.delete(ee.path),b(le);return}le.add(ee.path),b(le);const fe=await z(ee.path),oe=Q=>Q.map(re=>re.path===ee.path?{...re,children:fe}:re.children?{...re,children:oe(re.children)}:re);g(Q=>oe(Q))};i.useEffect(()=>{C&&E.current&&(E.current.focus(),E.current.select())},[C]);const xe=(ee,me=[])=>{const le="new_directory",fe=me.map(ue=>ue.name);if(!fe.includes(le))return le;let oe=1;const Q=new RegExp(`^${le}(\\d+)$`);for(const ue of fe){const he=ue.match(Q);if(he){const Ge=parseInt(he[1],10);Ge>oe&&(oe=Ge)}}let re=2;for(;fe.includes(`${le}${re}`);)re++;return`${le}${Math.max(re,oe+1)}`},Pe=async ee=>{if(q){if(x.has(ee.path)){const me=xe(ee.path,ee.children);I(me)}else{const me=new Set(x);if(me.add(ee.path),b(me),ee.children){const le=xe(ee.path,ee.children);I(le)}else{const le=await z(ee.path),fe=Q=>Q.map(re=>re.path===ee.path?{...re,children:le}:re.children?{...re,children:fe(re.children)}:re);g(Q=>fe(Q));const oe=xe(ee.path,le);I(oe)}}j(ee.path)}},H=async()=>{if(!C||!q)return;const ee=T.trim()||"new_directory",me=`${C}/${ee}`;try{await Oe.createDirectory(me);const le=await z(C),fe=oe=>oe.map(Q=>Q.path===C?{...Q,children:le}:Q.children?{...Q,children:fe(Q.children)}:Q);g(oe=>fe(oe)),j(null),I("")}catch(le){console.error("Failed to create directory:",le)}},ye=()=>{j(null),I("")},J=(ee,me=0)=>{const le=x.has(ee.path),fe=ee.isDirectory,oe=A.has(ee.path),Q=t===ee.path,re=n==="inline",ue=e.jsxs(e.Fragment,{children:[fe&&e.jsx("button",{onClick:he=>{he.stopPropagation(),we(ee)},className:L("hover:bg-accent rounded","p-0.5"),children:le?e.jsx(Ut,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(er,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!fe&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:he=>{he.stopPropagation(),W(ee.path),n==="dropdown"&&a==="immediate"&&M(!1)},onDoubleClick:he=>{he.stopPropagation(),l&&l(ee.path)},className:L("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",re&&Q?"text-primary":"text-foreground"),children:[e.jsx(lr,{className:L("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",re&&Q&&"text-primary")}),e.jsx("span",{className:L("font-medium truncate","typography-ui-label",re&&Q?"text-primary":"text-foreground"),children:ee.name})]}),e.jsx("button",{onClick:he=>{he.stopPropagation(),Pe(ee)},className:L("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(us,{className:L("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:he=>{he.stopPropagation(),X(ee.path)},className:L("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:oe?"Unpin directory":"Pin directory",children:oe?e.jsx(Fi,{className:L("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(Ig,{className:L("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:L("group flex items-center gap-1 rounded-lg mx-1 text-left transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",Q?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${me*(p?12:14)+(p?4:6)}px`},children:ue}),le&&e.jsxs(e.Fragment,{children:[C===ee.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(me+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(lr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(wt,{ref:E,value:T,onChange:he=>I(he.target.value),onKeyDown:he=>{he.key==="Enter"?(he.preventDefault(),he.stopPropagation(),H()):he.key==="Escape"&&(he.preventDefault(),he.stopPropagation(),ye())},onBlur:H,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:he=>{he.preventDefault(),he.stopPropagation(),H()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Pt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:he=>{he.preventDefault(),he.stopPropagation(),ye()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(ss,{className:"h-3 w-3 text-muted-foreground"})})]}),ee.children&&ee.children.map(he=>J(he,me+1))]})]},ee.path):e.jsxs("div",{children:[e.jsxs(Nt,{className:L("flex items-center gap-1 cursor-pointer group",t===ee.path&&"bg-accent"),style:{paddingLeft:`${me*12+8}px`},onSelect:he=>{he.preventDefault()},children:[fe&&e.jsx("button",{onClick:he=>{he.stopPropagation(),we(ee)},className:"p-0.5 hover:bg-accent rounded",children:le?e.jsx(Ut,{className:"h-3 w-3"}):e.jsx(er,{className:"h-3 w-3"})}),!fe&&e.jsx("div",{className:"w-4"}),ue]}),le&&e.jsxs("div",{children:[C===ee.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(me+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(lr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(wt,{ref:E,value:T,onChange:he=>I(he.target.value),onKeyDown:he=>{he.key==="Enter"?(he.preventDefault(),he.stopPropagation(),H()):he.key==="Escape"&&(he.preventDefault(),he.stopPropagation(),ye())},onBlur:H,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:he=>{he.preventDefault(),he.stopPropagation(),H()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Pt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:he=>{he.preventDefault(),he.stopPropagation(),ye()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(ss,{className:"h-3 w-3 text-muted-foreground"})})]}),ee.children&&ee.children.map(he=>J(he,me+1))]})]},ee.path)},ce=(ee,me)=>{if(n==="inline"){const le=t===me;return e.jsxs("div",{className:L("group flex items-center gap-2 mx-1 rounded-lg transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",le?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>W(me),onDoubleClick:fe=>{fe.stopPropagation(),l&&l(me)},className:L("flex flex-1 items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded min-w-0",le?"text-primary":"text-foreground"),children:[e.jsx(lr,{className:L("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",le?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:L("typography-ui-label font-medium truncate flex-shrink-0",le?"text-primary":"text-foreground"),children:ee}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:Yr(me,N)})]}),e.jsx("button",{onClick:()=>X(me),className:L("hover:bg-accent rounded-md transition-opacity",p?"p-1.5 opacity-60":"p-1 opacity-0 group-hover:opacity-100"),title:"Unpin directory",children:e.jsx(Fi,{className:L("text-primary","h-3.5 w-3.5")})})]},me)}return e.jsxs(Nt,{onSelect:le=>{le.preventDefault(),W(me),a==="immediate"&&M(!1)},className:L("flex items-start gap-2 cursor-pointer group py-2",t===me&&"bg-accent"),children:[e.jsx(lr,{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:ee}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Yr(me,N)})]}),e.jsx("button",{onClick:le=>{le.stopPropagation(),le.preventDefault(),X(me)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Fi,{className:"h-3 w-3 text-primary"})})]},me)},ge=e.jsx(e.Fragment,{children:q?e.jsxs(e.Fragment,{children:[Z.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>D(ee=>!ee),className:L("flex w-full items-center gap-1.5 typography-meta font-medium text-muted-foreground/80 hover:bg-accent/30 rounded transition-colors uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:[P?e.jsx(Ut,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(er,{className:p?"h-3.5 w-3.5":"h-3 w-3"}),e.jsx("span",{children:"Pinned"}),e.jsx("span",{className:"ml-auto typography-micro text-muted-foreground/60 normal-case tracking-normal",children:Z.length})]}),P&&Z.map(({name:ee,path:me})=>ce(ee,me)),n==="dropdown"&&e.jsx(Ds,{}),n==="inline"&&P&&e.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),e.jsx("div",{className:L("typography-meta font-medium text-muted-foreground/80 flex items-center gap-1.5 uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:"Browse"}),y?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):h.map(ee=>J(ee)),!y&&h.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No directories found"})]}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Locating home directory..."})});return n==="inline"?e.jsx("div",{className:L("overflow-hidden flex flex-col",o),children:e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:ge})}):e.jsxs(rs,{open:S,onOpenChange:M,children:[e.jsx(ns,{asChild:!0,children:e.jsxs(je,{variant:"ghost",className:L("w-full h-8 px-2.5 justify-between items-center rounded-lg border border-transparent bg-sidebar-accent/40 text-foreground/90 hover:bg-sidebar-accent/60 typography-meta",s),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(lr,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:t,children:Yr(t,N)})]}),e.jsx(Ut,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(os,{align:"start",className:"w-[350px]",children:e.jsx(gt,{outerClassName:"h-full",className:"w-full",children:ge})})]})},Ii=(t,r=200)=>{const[s,n]=Ae.useState(t);return Ae.useEffect(()=>{const o=window.setTimeout(()=>{n(t)},r);return()=>{window.clearTimeout(o)}},[t,r]),s},wp=i.forwardRef(({inputValue:t,homeDirectory:r,onSelectSuggestion:s,visible:n,onClose:o,showHidden:a},l)=>{const[c,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(0),h=i.useRef(null),g=i.useRef([]),x=i.useCallback((N,v)=>{const A=N.trim().toLowerCase();if(!A)return 0;const k=v.toLowerCase();let C=0,j=-1,T=0;for(let I=0;I<A.length;I+=1){const P=A[I];if(!P||P===" ")continue;const D=k.indexOf(P,j+1);if(D===-1)return null;const E=D-j-1;if(E===0?T+=1:T=0,C+=10,C+=Math.max(0,18-D),C-=Math.max(0,E),D===0)C+=12;else{const F=k[D-1];(F==="/"||F==="_"||F==="-"||F==="."||F===" ")&&(C+=10)}C+=T>0?12:0,j=D}return C+=Math.max(0,24-Math.round(k.length/3)),C},[]),b=i.useCallback(N=>N.startsWith("~")&&r?N.replace(/^~/,r):N,[r]),y=i.useCallback(N=>{const v=b(N);if(v.endsWith("/"))return v;const A=v.lastIndexOf("/");return A===-1?"":A===0?"/":v.substring(0,A+1)},[b]),w=i.useCallback(N=>{const v=b(N);if(v.endsWith("/"))return"";const A=v.lastIndexOf("/");return A===-1?v:v.substring(A+1)},[b]),S=Ii(t,150);i.useEffect(()=>{if(!n||!S){d([]);return}const N=y(S),v=w(S).toLowerCase();if(!N){d([]);return}let A=!1;return m(!0),Oe.listLocalDirectory(N).then(k=>{if(A)return;const C=k.filter(T=>!(!T.isDirectory||!a&&T.name.startsWith("."))),j=v?C.map(T=>{const I=x(v,T.name);return I!==null?{entry:T,score:I}:null}).filter(T=>T!==null).sort((T,I)=>I.score-T.score||T.entry.name.localeCompare(I.entry.name)).map(T=>T.entry):C.sort((T,I)=>T.name.localeCompare(I.name));d(j.slice(0,10)),p(0)}).catch(()=>{A||d([])}).finally(()=>{A||m(!1)}),()=>{A=!0}},[n,S,y,w,a,x]),i.useEffect(()=>{g.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),i.useEffect(()=>{if(!n)return;const N=v=>{const A=v.target;!A||!h.current||h.current.contains(A)||o()};return document.addEventListener("pointerdown",N,!0),()=>{document.removeEventListener("pointerdown",N,!0)}},[n,o]);const M=i.useCallback(N=>{const v=N.path.endsWith("/")?N.path:N.path+"/";s(v)},[s]);return i.useImperativeHandle(l,()=>({handleKeyDown:N=>{if(!n||c.length===0)return!1;const v=c.length;if(N.key==="Tab"){if(N.preventDefault(),N.shiftKey)p(A=>(A-1+v)%v);else if(v===1){const A=c[0];A&&M(A)}else p(A=>(A+1)%v);return!0}if(N.key==="ArrowDown")return N.preventDefault(),p(A=>(A+1)%v),!0;if(N.key==="ArrowUp")return N.preventDefault(),p(A=>(A-1+v)%v),!0;if(N.key==="Enter"){N.preventDefault();const A=(f%v+v)%v,k=c[A];return k&&M(k),o(),!0}return N.key==="Escape"?(N.preventDefault(),o(),!0):!1}}),[n,c,f,M,o]),!n||c.length===0&&!u?null:e.jsxs("div",{ref:h,className:"absolute z-[100] w-full max-h-48 bg-background border border-border rounded-lg shadow-lg top-full mt-1 left-0 flex flex-col overflow-hidden",children:[u?e.jsx("div",{className:"flex items-center justify-center py-3",children:e.jsx(Xr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:c.map((N,v)=>{const A=f===v;return e.jsxs("div",{ref:k=>{g.current[v]=k},className:L("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",A&&"bg-muted"),onClick:()=>{M(N),o()},onMouseEnter:()=>p(v),children:[e.jsx(Mr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:N.name})]},N.path)})}),e.jsx("div",{className:"px-3 py-1.5 border-t typography-meta text-muted-foreground bg-sidebar/50",children:"Tab cycle • ↑↓ navigate • Enter select"})]})});wp.displayName="DirectoryAutocomplete";const yj=({open:t,onOpenChange:r})=>{const{currentDirectory:s,homeDirectory:n,isHomeReady:o}=xt(),{addProject:a,getActiveProject:l}=Ft(),[c,d]=i.useState(null),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,g]=i.useState(!1),x=Vo(),{isDesktop:b,requestAccess:y,startAccessing:w}=Ei(),{isMobile:S}=qt(),[M,N]=i.useState(!1),v=i.useRef(null),A=i.useCallback(W=>W?Yr(W,n):"",[n]);i.useEffect(()=>{if(t){p(!1),g(!1),N(!1);const Y=l()?.path||s||n||"";d(Y),m(A(Y))}},[t,s,n,A,l]),i.useEffect(()=>{!t||f||c||n&&o&&(d(n),p(!0),m("~"))},[t,f,c,n,o]);const k=i.useCallback(()=>{r(!1)},[r]),C=i.useCallback(async W=>{if(!(!W||h)){g(!0);try{let Y=W,X;if(b){const z=await y(W);if(!z.success){U.error("Unable to access directory",{description:z.error||"Desktop denied directory access."});return}Y=z.path??W,X=z.projectId;const R=await w(Y);if(!R.success){U.error("Failed to open directory",{description:R.error||"Desktop could not grant file access."});return}}if(!a(Y,{id:X})){U.error("Failed to add project",{description:"Please select a valid directory path."});return}k()}catch(Y){U.error("Failed to select directory",{description:Y instanceof Error?Y.message:"Unknown error occurred."})}finally{g(!1)}}},[a,k,b,y,w,h]),j=i.useCallback(async()=>{const W=u.trim()||c;W&&await C(W)},[C,u,c]),T=i.useCallback(W=>{d(W),p(!0),m(A(W))},[A]),I=i.useCallback(async W=>{d(W),p(!0),m(A(W)),await C(W)},[C,A]),P=i.useCallback(W=>{const Y=W.target.value;if(m(Y),p(!0),N(Y.startsWith("/")||Y.startsWith("~")),Y.startsWith("/")||Y.startsWith("~")){const X=Y.startsWith("~")&&n?Y.replace(/^~/,n):Y;d(X)}},[n]),D=i.useCallback(W=>{v.current?.handleKeyDown(W)||W.key==="Enter"&&(W.preventDefault(),j())},[j]),E=i.useCallback(W=>{d(W),p(!0),m(A(W))},[A]),F=i.useCallback(()=>{N(!1)},[]),B=i.useCallback(()=>{gc(!x)},[x]),V=e.jsxs("button",{type:"button",onClick:B,className:"flex items-center gap-2 px-2 py-1 rounded-lg hover:bg-accent/40 transition-colors typography-meta text-muted-foreground flex-shrink-0",children:[x?e.jsx(Sn,{className:"h-4 w-4 text-primary"}):e.jsx(Nn,{className:"h-4 w-4"}),"Show hidden"]}),ne=e.jsxs(bs,{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(ws,{children:"Add project directory"}),e.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[e.jsx(Ns,{className:"flex-1",children:"Choose a folder to add as a project."}),V]})]}),O=e.jsxs("div",{className:"relative",children:[e.jsx(wt,{value:u,onChange:P,onKeyDown:D,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(wp,{ref:v,inputValue:u,homeDirectory:n,onSelectSuggestion:E,visible:M,onClose:F,showHidden:x})]}),G=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(lu,{variant:"inline",currentPath:c??s,onSelectPath:T,onDoubleClickPath:I,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:x,rootDirectory:o?n:null,isRootReady:o})}),K=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:O}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:V}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(lu,{variant:"inline",currentPath:c??s,onSelectPath:T,onDoubleClickPath:I,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:x,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),q=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[O,G]}),$=()=>e.jsxs(e.Fragment,{children:[e.jsx(je,{variant:"ghost",onClick:k,disabled:h,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(je,{onClick:j,disabled:h||!f||!c&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:h?"Adding...":"Add Project"})]});return S?e.jsx(Ws,{open:t,onClose:()=>r(!1),title:"Add project directory",className:"max-w-full",contentMaxHeightClassName:"max-h-[min(70vh,520px)] h-[min(70vh,520px)]",footer:e.jsx("div",{className:"flex flex-row gap-2",children:$()}),children:K}):e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ps,{className:L("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:W=>{W.preventDefault()},children:[ne,q,e.jsx(Gs,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-row gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:justify-end sm:border-0 sm:bg-transparent sm:px-0 sm:pt-4 sm:pb-0",children:$()})]})})},ma=t=>t?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,bj=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},wj=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),[o,a]=i.useState(null),[l,c]=i.useState([]),[d,u]=i.useState(!1),[m,f]=i.useState(!1),{deleteSession:p,deleteSessions:h,loadSessions:g,getWorktreeMetadata:x}=be(),{currentDirectory:b,homeDirectory:y,isHomeReady:w}=xt(),{projects:S,addProject:M,activeProjectId:N}=Ft(),{requestAccess:v,startAccessing:A}=Ei(),{isMobile:k,isTablet:C,hasTouchInput:j}=qt(),T=k||C||j,I=i.useMemo(()=>{const R=(N?S.find(de=>de.id===N)??null:null)?.path??b;return bj(R)},[N,b,S]),P=i.useMemo(()=>(o?.worktree?.status?.isDirty??!1)||l.some(z=>z.metadata.status?.isDirty),[o?.worktree?.status?.isDirty,l]),D=i.useMemo(()=>{const z=o?.worktree;return z&&typeof z.branch=="string"&&z.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:R})=>typeof R.branch=="string"&&R.branch.trim().length>0)},[o?.worktree,l]),E=o?.mode==="worktree",F=E,B=m||!E||!D;i.useEffect(()=>{g()},[g,b]);const V=i.useMemo(()=>S.map(z=>`${z.id}:${z.path}`).join("|"),[S]),ne=i.useRef(V);i.useEffect(()=>{V!==ne.current&&(ne.current=V,g())},[g,V]),i.useEffect(()=>{if(!(s||!w||S.length>0)){if(n(!0),ms()){v("").then(async z=>{if(!z.success||!z.path){z.error&&z.error!=="Directory selection cancelled"&&U.error("Failed to select directory",{description:z.error});return}const R=await A(z.path);if(!R.success){U.error("Failed to open directory",{description:R.error||"Desktop could not grant file access."});return}M(z.path,{id:z.projectId})||U.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(z=>{console.error("Desktop: Error selecting directory:",z),U.error("Failed to select directory")});return}r(!0)}},[M,s,w,S.length,v,A]);const O=i.useCallback(z=>{a({sessions:z.sessions,dateLabel:z.dateLabel,mode:z.mode??"session",worktree:z.worktree??null})},[]),G=i.useCallback(()=>{a(null),c([]),u(!1),f(!1)},[]);i.useEffect(()=>no.onDeleteRequest(z=>{O(z)}),[O]),i.useEffect(()=>no.onDirectoryRequest(()=>{r(!0)}),[]),i.useEffect(()=>{if(!o){c([]),u(!1);return}const z=o.sessions.map(de=>{const we=x(de.id);return we?{session:de,metadata:we}:null}).filter(de=>!!de);if(c(z),u(!1),z.length===0)return;let R=!1;return(async()=>{const de=await Promise.all(z.map(async({metadata:we})=>{if(we.status&&typeof we.status.isDirty=="boolean")return we.status;try{return await Ko(we.path)}catch{return we.status}})).catch(we=>(console.warn("Failed to inspect worktree status before deletion:",we),z.map(({metadata:xe})=>xe.status)));R||!Array.isArray(de)||c(we=>we.map((xe,Pe)=>({session:xe.session,metadata:{...xe.metadata,status:de[Pe]??xe.metadata.status}})))})(),()=>{R=!0}},[o,x]),i.useEffect(()=>{D||u(!1)},[D]);const K=i.useCallback(async()=>{if(o){f(!0);try{const z=F,R=z&&d;if(o.sessions.length===0&&E&&o.worktree){const de=d&&D;await Yo({id:N||`path:${I}`,path:I},o.worktree,{deleteRemoteBranch:de,force:!0});const we=de?"Worktree and remote branch removed.":"Worktree removed.";U.success("Worktree removed",{description:ma(we)}),G(),g();return}if(o.sessions.length===1){const de=o.sessions[0];if(!await p(de.id,{archiveWorktree:z,deleteRemoteBranch:R})){U.error("Failed to delete session"),f(!1);return}const xe=z?R?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;U.success("Session deleted",{description:ma(xe),action:{label:"OK",onClick:()=>{}}})}else{const de=o.sessions.map(Pe=>Pe.id),{deletedIds:we,failedIds:xe}=await h(de,{archiveWorktree:z,deleteRemoteBranch:R});if(we.length>0){const Pe=z?R?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,ye=[xe.length>0?`${xe.length} session${xe.length===1?"":"s"} could not be deleted.`:o.dateLabel?`Removed all sessions from ${o.dateLabel}.`:void 0,Pe].filter(Boolean).join(" ");U.success(`Deleted ${we.length} session${we.length===1?"":"s"}`,{description:ma(ye||void 0),action:{label:"OK",onClick:()=>{}}})}if(xe.length>0&&(U.error(`Failed to delete ${xe.length} session${xe.length===1?"":"s"}`,{description:ma("Please try again in a moment.")}),we.length===0)){f(!1);return}}G()}finally{f(!1)}}},[o,d,p,h,G,F,E,D,I,N,g]),q=o?.worktree??l[0]?.metadata??null,$=o?o.mode==="worktree"?o.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and ${o.sessions.length===1?"1 linked session":`${o.sessions.length} linked sessions`}.`:`This action permanently removes ${o.sessions.length===1?"1 session":`${o.sessions.length} sessions`}${o.dateLabel?` from ${o.dateLabel}`:""}.`:"",W=o?e.jsxs("div",{className:L(E?"space-y-3":"space-y-2"),children:[o.sessions.length>0&&e.jsxs("div",{className:L(E?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[E&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:o.sessions.length===1?"Linked session":"Linked sessions"}),e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:o.sessions.length})]}),e.jsxs("ul",{className:L(E?"mt-2 space-y-1":"space-y-0.5"),children:[o.sessions.slice(0,5).map(z=>e.jsxs("li",{className:L(E?"flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-muted-foreground":"typography-micro text-muted-foreground/80"),children:[e.jsx("span",{className:L(!E&&"hidden"),children:"•"}),e.jsx("span",{className:"truncate",children:z.title||"Untitled Session"})]},z.id)),o.sessions.length>5&&e.jsxs("li",{className:L(E?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",o.sessions.length-5," more"]})]})]}),E?e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),q?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:q.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:q?Yr(q.path,y):"Worktree path unavailable."}),P&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."})]}):e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,Y=E?D?e.jsxs("button",{type:"button",onClick:()=>{B||u(z=>!z)},disabled:B,className:L("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",B?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[d?e.jsx(Sn,{className:"size-4 text-primary"}):e.jsx(Nn,{className:"size-4"}),"Delete remote branch"]}):e.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,X=E?e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-col items-start gap-1",children:Y}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{variant:"ghost",onClick:G,disabled:m,children:"Cancel"}),e.jsx(je,{variant:"destructive",onClick:K,disabled:m,children:m?"Deleting…":"Delete worktree"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(je,{variant:"ghost",onClick:G,disabled:m,children:"Cancel"}),e.jsx(je,{variant:"destructive",onClick:K,disabled:m,children:m?"Deleting…":o?.sessions.length===1?"Delete session":"Delete sessions"})]}),Z=E?"Delete worktree":o?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[T?e.jsx(Ws,{open:!!o,onClose:()=>{m||G()},title:Z,footer:e.jsx("div",{className:"flex justify-end gap-2",children:X}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[$&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:$}),W]})}):e.jsx(fs,{open:!!o,onOpenChange:z=>{if(!z){if(m)return;G()}},children:e.jsxs(ps,{className:L(E?"max-w-xl max-h-[70vh] flex flex-col overflow-hidden gap-3":"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2"),children:[e.jsxs(bs,{children:[e.jsxs(ws,{className:L(E&&"flex items-center gap-2"),children:[E&&e.jsx(zs,{className:"h-5 w-5"}),Z]}),$&&e.jsx(Ns,{children:$})]}),e.jsx("div",{className:L(E&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:W}),e.jsx(Gs,{className:"mt-2 gap-2 pt-1 pb-1",children:X})]})}),e.jsx(yj,{open:t,onOpenChange:r})]})};function vj(){return new Worker(Pg,{type:"module"})}const jj=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function Sj(t,r,s){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s;return`${t}:${r.length}:${s.length}:${n.length}:${o.length}`}function cu(t){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>t(void 0),0);return()=>window.clearTimeout(r)}const Nj=({children:t})=>{const r=Fg(),s=ds(c=>c.activeDirectory),n=ds(c=>s?c.directories.get(s)?.lastStatusChange??0:0),o=ds(c=>s?c.directories.get(s)?.diffCache.size??0:0),a=Ae.useRef(!1),l=Ae.useRef(new Map);return Ae.useEffect(()=>{if(!r||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=Sl(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Ae.useEffect(()=>{if(!r||!s||!n||o===0)return;const c=ds.getState().directories.get(s);if(!c||c.diffCache.size===0||(l.current.get(s)??0)>=c.lastStatusChange)return;l.current.set(s,c.lastStatusChange);let u=!1,m=null;const f=Array.from(c.diffCache.entries());let p=0;const h=g=>{if(u)return;const x=Date.now();for(;p<f.length&&!(g&&g.timeRemaining()<8||!g&&Date.now()-x>8);){const[b,y]=f[p];p+=1,Ar(b);const w=Sj(b,y.original,y.modified),S={name:b,contents:y.original,cacheKey:`old-${w}`},M={name:b,contents:y.modified,cacheKey:`new-${w}`},N=Sl(S,M),v={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(v,N)}p<f.length&&(m=cu(h))};return h(void 0),p<f.length&&(m=cu(h)),()=>{u=!0,m?.()}},[r,s,n,o]),e.jsx(e.Fragment,{children:t})},kj=({children:t})=>{const s=Ni()?.currentTheme?.metadata?.variant==="dark";ap();const n=Ae.useMemo(()=>({theme:{dark:ro.dark,light:ro.light},themeType:s?"dark":"light",langs:jj}),[s]);return e.jsx(Tg,{poolOptions:{workerFactory:vj,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(Nj,{children:t})})},Vl=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),Cj=(t,r)=>{const s=Vl(t),n=Vl(r);return`${s}-${n}`.substring(0,60)},du=(t,r)=>`${t}/${r}`,Mj=()=>{const t=Ft.getState(),r=t.activeProjectId;if(!r)return null;const s=t.projects.find(o=>o.id===r);if(s?.path)return{id:s.id,path:s.path};const n=xt.getState().currentDirectory??null;if(n&&n.trim().length>0){const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n;return{id:`path:${o}`,path:o}}return null},Eo=is()(hs(t=>({isLoading:!1,error:null,createMultiRun:async r=>{const s=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:l,setupCommands:c}=r;if(!s)return t({error:"Group name is required"}),null;if(!n)return t({error:"Prompt is required"}),null;if(o.length<1)return t({error:"Select at least 1 model"}),null;if(o.length>5)return t({error:"Maximum 5 models allowed"}),null;t({isLoading:!0,error:null});try{const d=Mj();if(!d)return t({error:"Select a project",isLoading:!1}),null;const u=d.path;if(!await zr(u))return t({error:"Not in a git repository",isLoading:!1}),null;const f=Vl(s),p=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",h=p!=="HEAD"?p:void 0,g=[],x=c?.filter(v=>v.trim().length>0)??[],b=new Map;for(const v of o){const A=`${v.providerID}:${v.modelID}`;b.set(A,(b.get(A)||0)+1)}const y=new Map;for(const v of o){const A=`${v.providerID}:${v.modelID}`,k=b.get(A)||1,C=(y.get(A)||0)+1;y.set(A,C);const j=Cj(v.providerID,v.modelID),T=k>1?du(f,`${j}/${C}`):du(f,j);try{const I=await Si(d,{preferredName:T,setupCommands:x,startPoint:h??null}),P={...I,createdFromBranch:h??"HEAD"},D=k>1?`${f}/${v.providerID}/${v.modelID}/${C}`:`${f}/${v.providerID}/${v.modelID}`,E=await Oe.withDirectory(I.path,()=>Oe.createSession({title:D}));ht.getState().setWorktreeMetadata(E.id,P),g.push({sessionId:E.id,worktreePath:I.path,providerID:v.providerID,modelID:v.modelID,variant:v.variant})}catch(I){console.warn("[MultiRun] Failed to create session:",I)}}const w=c?.filter(v=>v.trim().length>0)??[];w.length>0&&Wf(d,w).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const S=g.map(v=>v.sessionId),M=g[0]?.sessionId??null;if(S.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const N=l?.map(v=>({type:"file",mime:v.mime,filename:v.filename,url:v.url}));try{await ht.getState().loadSessions()}catch{}return(async()=>{try{await Promise.allSettled(g.map(async v=>{try{await Oe.withDirectory(v.worktreePath,()=>Oe.sendMessage({id:v.sessionId,providerID:v.providerID,modelID:v.modelID,variant:v.variant,text:n,agent:a,files:N}))}catch(A){console.warn("[MultiRun] Failed to start run:",A)}}))}catch(v){console.warn("[MultiRun] Failed to start runs:",v)}})(),t({isLoading:!1}),{groupSlug:f,sessionIds:S,firstSessionId:M}}catch(d){return t({error:d instanceof Error?d.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{t({error:null})}}),{name:"multirun-store"}));function As({...t}){return e.jsx(Rg,{"data-slot":"select",...t})}function bn({...t}){return e.jsx(Hg,{"data-slot":"select-group",...t})}function kn({...t}){return e.jsx(_g,{"data-slot":"select-value",...t})}function Es({className:t,size:r="default",children:s,...n}){return e.jsxs(Lg,{"data-slot":"select-trigger","data-size":r,className:L("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-muted data-[state=open]:bg-muted focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 data-[size=lg]:h-8 data-[size=lg]:py-1.5 data-[size=chip]:h-7 data-[size=chip]:py-1 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...n,children:[s,e.jsx(Og,{asChild:!0,children:e.jsx(Ut,{className:"size-4 opacity-50"})})]})}function Is({className:t,children:r,position:s="popper",fitContent:n=!1,...o}){return e.jsx($g,{children:e.jsx(Bg,{"data-slot":"select-content",className:L("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden rounded-xl border shadow-none transform-gpu will-change-transform",s==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",n&&"w-max min-w-0",t),position:s,...o,children:e.jsx(gt,{as:zg,outerClassName:L("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:L("p-1",s==="popper"&&(n?"h-[var(--radix-select-trigger-height)] w-max min-w-0 scroll-my-1":"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1")),children:r})})})}function Yn({className:t,...r}){return e.jsx(Wg,{"data-slot":"select-label",className:L("text-muted-foreground px-2 py-1.5 typography-meta",t),...r})}function Bt({className:t,children:r,...s}){return e.jsxs(Ug,{"data-slot":"select-item",className:L("hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...s,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(Vg,{children:e.jsx(Pt,{className:"size-4"})})}),e.jsx(Gg,{children:r})]})}function ni({className:t,...r}){return e.jsx(qg,{"data-slot":"select-separator",className:L("bg-border pointer-events-none -mx-1 my-1 h-px",t),...r})}const Dj="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",Aj=Object.assign({"../assets/provider-logos/gocode.svg":Dj}),Gl=new Map;for(const[t,r]of Object.entries(Aj)){const s=t.match(/provider-logos\/([^/]+)\.svg$/i);s?.[1]&&r&&Gl.set(s[1].toLowerCase(),r)}function vp(t){const r=t?.toLowerCase()??null,s=r?Gl.has(r):!1,n=r?Gl.get(r)??null:null,[o,a]=Ae.useState(s?"local":"remote");Ae.useEffect(()=>{a(s?"local":"remote")},[s,r]);const l=Ae.useCallback(()=>{a(c=>c==="local"&&s?"remote":"none")},[s]);return r?o==="local"&&n?{src:n,onError:l,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:l,hasLogo:!0}:{src:null,onError:l,hasLogo:!1}:{src:null,onError:l,hasLogo:!1}}const ys=({providerId:t,alt:r,className:s,onError:n})=>{const{src:o,onError:a,hasLogo:l}=vp(t),c=i.useCallback(()=>{a(),n?.()},[a,n]);return!l||!o?null:e.jsx("img",{src:o,alt:r||`${t} logo`,className:L("dark:invert",s),onError:c})},Tc=t=>t.nativeEvent.isComposing||t.nativeEvent.keyCode===229,Fc=()=>{const{providers:t}=Ze(),{favoriteModels:r,recentModels:s}=Me(),n=i.useMemo(()=>r.map(({providerID:a,modelID:l})=>{const c=t.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null),[r,t]),o=i.useMemo(()=>s.map(({providerID:a,modelID:l})=>{const c=t.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:l})=>!r.some(c=>c.providerID===a&&c.modelID===l)),[s,t,r]);return{favoriteModelsList:n,recentModelsList:o}},jp="h-7",oi=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Ej=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Ij=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=Ej.format(t);return r.endsWith(".0")?r.slice(0,-2):r},Pj=({model:t,instanceIndex:r,totalSameModel:s,onRemove:n})=>{const o=t.displayName||`${t.providerID}/${t.modelID}`,a=s>1?`${o} (${r})`:o;return e.jsxs("div",{className:L("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",jp),children:[e.jsx(ys,{providerId:t.providerID,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:a}),e.jsx("button",{type:"button",onClick:n,className:"text-muted-foreground hover:text-foreground ml-0.5",children:e.jsx(ss,{className:"h-3.5 w-3.5"})})]})},Sp=({selectedModels:t,onAdd:r,onRemove:s,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:l=!0,maxModels:c})=>{const{providers:d,modelsMetadata:u}=Ze(),{favoriteModelsList:m,recentModelsList:f}=Fc(),[p,h]=i.useState(!1),[g,x]=i.useState(""),[b,y]=i.useState(0),[w,S]=i.useState(null),M=i.useRef(null),N=i.useRef(null),v=i.useRef(null),A=i.useRef([]),k=i.useMemo(()=>{const V=new Map;for(const ne of t){const O=`${ne.providerID}:${ne.modelID}`;V.set(O,(V.get(O)||0)+1)}return V},[t]),C=i.useCallback(V=>t.filter(O=>O.providerID===V.providerID&&O.modelID===V.modelID).findIndex(O=>O.instanceId===V.instanceId)+1,[t]),j=(V,ne)=>{const O=`${V}/${ne}`;return u.get(O)},T=V=>{const ne=V?.name||V?.id||"",O=String(ne);return O.length>40?O.substring(0,37)+"...":O},I=i.useCallback((V,ne)=>{if(!g.trim())return!0;const O=g.toLowerCase();return V.toLowerCase().includes(O)||ne.toLowerCase().includes(O)},[g]),P=i.useMemo(()=>m.filter(({model:V,providerID:ne})=>{const G=d.find(q=>q.id===ne)?.name||ne,K=T(V);return I(K,G)}),[m,d,I]),D=i.useMemo(()=>f.filter(({model:V,providerID:ne})=>{const G=d.find(q=>q.id===ne)?.name||ne,K=T(V);return I(K,G)}),[f,d,I]),E=i.useMemo(()=>d.map(V=>{const O=(Array.isArray(V.models)?V.models:[]).filter(G=>{const K=T(G);return I(K,V.name||V.id||"")});return{...V,models:O}}).filter(V=>V.models.length>0),[d,I]),F=P.length>0||D.length>0||E.length>0;i.useEffect(()=>{if(p&&v.current){const ne=v.current.getBoundingClientRect().top-100;S(Math.max(150,Math.min(400,ne)))}},[p]),i.useEffect(()=>{p&&M.current&&M.current.focus()},[p]),i.useEffect(()=>{if(!p)return;const V=ne=>{N.current&&!N.current.contains(ne.target)&&(h(!1),x(""),y(0))};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[p]),i.useEffect(()=>{y(0)},[g]);const B=(V,ne,O,G,K,q)=>{const $=`${ne}:${O}`,W=k.get($)||0,Y=j(ne,O),X=Ij(Y?.limit?.context),Z=G==="fav"||G==="recent";return e.jsxs("button",{ref:z=>{A.current[K]=z},type:"button",onClick:()=>{r({providerID:ne,modelID:O,displayName:V.name||O,instanceId:oi()})},onMouseEnter:()=>y(K),className:L("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",q?"bg-accent":"hover:bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[Z&&e.jsx(ys,{providerId:ne,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:T(V)}),X&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:X})]}),W>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",W]})]},`${G}-${$}`)};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:N,children:[e.jsxs(je,{ref:v,type:"button",variant:"outline",size:"sm",className:jp,onClick:()=>h(!p),children:[e.jsx(us,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const V=[];P.forEach(({model:K,providerID:q,modelID:$})=>{V.push({model:K,providerID:q,modelID:$,section:"fav"})}),D.forEach(({model:K,providerID:q,modelID:$})=>{V.push({model:K,providerID:q,modelID:$,section:"recent"})}),E.forEach(K=>{K.models.forEach(q=>{V.push({model:q,providerID:K.id,modelID:q.id,section:"provider"})})});const ne=V.length,O=K=>{if(!Tc(K))if(K.key==="ArrowDown"){K.preventDefault(),K.stopPropagation();const q=(b+1)%Math.max(1,ne);y(q),setTimeout(()=>{A.current[q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(K.key==="ArrowUp"){K.preventDefault(),K.stopPropagation();const q=(b-1+Math.max(1,ne))%Math.max(1,ne);y(q),setTimeout(()=>{A.current[q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(K.key==="Enter"){K.preventDefault(),K.stopPropagation();const q=V[b];q&&r({providerID:q.providerID,modelID:q.modelID,displayName:q.model.name||q.modelID,instanceId:oi()})}else K.key==="Escape"&&(K.preventDefault(),K.stopPropagation(),h(!1),x(""),y(0))};let G=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(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(wt,{ref:M,type:"text",placeholder:"Search models",value:g,onChange:K=>x(K.target.value),onKeyDown:O,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(gt,{outerClassName:"flex-1",style:{maxHeight:w?`${w}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!F&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),P.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),P.map(({model:K,providerID:q,modelID:$})=>{const W=G++;return B(K,q,$,"fav",W,b===W)})]}),D.length>0&&e.jsxs(e.Fragment,{children:[P.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(kr,{className:"h-4 w-4"}),"Recent"]}),D.map(({model:K,providerID:q,modelID:$})=>{const W=G++;return B(K,q,$,"recent",W,b===W)})]}),(P.length>0||D.length>0)&&E.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),E.map((K,q)=>e.jsxs(i.Fragment,{children:[q>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ys,{providerId:K.id,className:"h-4 w-4 flex-shrink-0"}),K.name]}),K.models.map($=>{const W=G++;return B($,K.id,$.id,"provider",W,b===W)})]},K.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),l&&t.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:t.map((V,ne)=>{const O=`${V.providerID}:${V.modelID}`,G=k.get(O)||1,K=C(V),$=d.find(z=>z.id===V.providerID)?.models.find(z=>z.id===V.modelID),W=$?.variants?Object.keys($.variants):[],Y=W.length>0,X="__default__",Z=V.variant??X;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Pj,{model:V,instanceIndex:K,totalSameModel:G,onRemove:()=>s(ne)}),Y&&e.jsxs(As,{value:Z,onValueChange:z=>{if(!n)return;n(ne,{...V,variant:z===X?void 0:z})},children:[e.jsxs(Es,{size:"chip",className:"px-2 gap-1.5 rounded-md bg-accent/50 border-border/30 hover:bg-accent/60 typography-meta font-medium text-foreground",children:[e.jsx(Cr,{className:L("h-3.5 w-3.5 flex-shrink-0",Z===X?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(kn,{placeholder:"Thinking"})]}),e.jsxs(Is,{fitContent:!0,children:[e.jsx(Bt,{value:X,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),W.map(z=>e.jsx(Bt,{value:z,className:"pr-2 [&>span:first-child]:hidden",children:z},z))]})]})]},V.instanceId)})})]}),o!==void 0&&t.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",c!==void 0?`to ${c} models`:"","."]})]})};function Rc(t){const[r,s]=i.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=i.useState(!1),[a,l]=i.useState(null);return i.useEffect(()=>{let c=!1;if(!t){l(null),o(!1),s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),l(null),(async()=>{try{const d=await zr(t);if(c)return;if(l(d),!d){s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await wc(t).catch(()=>null);if(c)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(g=>!g.startsWith("remotes/")).sort((g,x)=>g.localeCompare(x)).forEach(g=>{m.push({value:g,label:g,group:"local"})}),u.all.filter(g=>g.startsWith("remotes/")).map(g=>g.replace(/^remotes\//,"")).sort((g,x)=>g.localeCompare(x)).forEach(g=>{m.push({value:g,label:g,group:"remote"})})),s(m)}finally{c||o(!1)}})(),()=>{c=!0}},[t]),{branches:r,isLoading:n,isGitRepository:a}}const Np=({directory:t,value:r,onChange:s,className:n,disabled:o,id:a})=>{const{branches:l,isLoading:c,isGitRepository:d}=Rc(t),u=i.useMemo(()=>l.find(f=>f.value===r)?.label??null,[l,r]);i.useEffect(()=>{!l.some(p=>p.value===r)&&l.length>0&&s("HEAD")},[l,r,s]);const m=o||!d||c;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(As,{value:r,onValueChange:s,disabled:m,children:[e.jsx(Es,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(kn,{children:u}):e.jsx(kn,{placeholder:c?"Loading branches…":"Select a branch"})}),e.jsxs(Is,{fitContent:!0,children:[e.jsxs(bn,{children:[e.jsx(Yn,{children:"Default"}),l.filter(f=>f.group==="special").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),l.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(ni,{}),e.jsxs(bn,{children:[e.jsx(Yn,{children:"Local branches"}),l.filter(f=>f.group==="local").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,l.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(ni,{}),e.jsxs(bn,{children:[e.jsx(Yn,{children:"Remote branches"}),l.filter(f=>f.group==="remote").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null]})]}),d===!1&&e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."})]})},kp=({value:t,onChange:r,className:s,disabled:n,id:o})=>{const a=Ze(f=>f.getVisibleAgents),l=Ze(f=>f.loadAgents),c=Ze(f=>f.currentAgentName),d=a(),u=i.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{if(n)return;const f=t.trim();if(f.length>0&&u.some(g=>g.name===f))return;const p=typeof c=="string"&&c.trim().length>0?c.trim():null;if(p&&u.some(g=>g.name===p)){r(p);return}const h=u[0]?.name;h&&r(h)},[c,n,r,u,t]);const m=t.trim().length>0?t:void 0;return e.jsxs(As,{value:m,onValueChange:r,disabled:n,children:[e.jsx(Es,{id:o,size:"lg",className:s??"max-w-full typography-meta text-foreground",children:e.jsx(kn,{placeholder:"Select an agent"})}),e.jsx(Is,{fitContent:!0,children:u.length>0&&e.jsx(bn,{children:u.map(f=>e.jsx(Bt,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},Tj=10*1024*1024,uu=5,mu=({initialPrompt:t,onCreated:r,onCancel:s})=>{const[n,o]=i.useState(""),[a,l]=i.useState(()=>t??""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState([]),[h,g]=i.useState(!1),[x,b]=i.useState([]),[y,w]=i.useState(!1),[S,M]=i.useState(!1),N=i.useRef(null),v=xt(R=>R.currentDirectory??null),A=i.useMemo(()=>{if(typeof window>"u")return null;const R=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof R=="string"&&R.trim().length>0?R.trim():null},[]),k=Ft(R=>R.activeProjectId),C=Ft(R=>R.projects),j=i.useMemo(()=>{if(k){const de=C.find(we=>we.id===k);if(de?.path)return{id:de.id,path:de.path}}const R=v??A;return R?{id:`path:${R}`,path:R}:null},[k,C,v,A]),[T,I]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),P=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const R=typeof window.opencodeDesktop<"u";I(R)},[]);const D=i.useMemo(()=>T&&P?"pl-[5.75rem]":"pl-3",[T,P]),E=i.useCallback(async R=>{if(!R.target.closest("button, a, input, select, textarea")&&R.button===0&&T)try{const{getCurrentWindow:de}=await js(async()=>{const{getCurrentWindow:xe}=await import("./vendor-.bun-Bui932eM.js").then(Pe=>Pe.dl);return{getCurrentWindow:xe}},__vite__mapDeps([0,1]));await de().startDragging()}catch{}},[T]),[F,B]=i.useState("HEAD"),{isLoading:V,isGitRepository:ne}=Rc(v),O=Eo(R=>R.createMultiRun),G=Eo(R=>R.error),K=Eo(R=>R.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&l(R=>R.trim().length>0?R:t)},[t]),i.useEffect(()=>{if(!j)return;let R=!1;return M(!0),(async()=>{try{const de=await ho(j);R||b(de)}catch{}finally{R||M(!1)}})(),()=>{R=!0}},[j]);const q=R=>{c.length>=uu||(d(de=>[...de,R]),K())},$=R=>{d(de=>de.filter((we,xe)=>xe!==R)),K()},W=i.useCallback((R,de)=>{d(we=>we.map((xe,Pe)=>Pe===R?de:xe))},[]),Y=async R=>{const de=R.target.files;if(!de)return;let we=0;for(let xe=0;xe<de.length;xe++){const Pe=de[xe];if(Pe.size>Tj){U.error(`File "${Pe.name}" is too large (max 10MB)`);continue}try{const H=await new Promise((J,ce)=>{const ge=new FileReader;ge.onload=()=>J(ge.result),ge.onerror=ce,ge.readAsDataURL(Pe)}),ye={id:oi(),filename:Pe.name,mimeType:Pe.type||"application/octet-stream",size:Pe.size,dataUrl:H};p(J=>[...J,ye]),we++}catch(H){console.error("File attach failed",H),U.error(`Failed to attach "${Pe.name}"`)}}we>0&&U.success(`Attached ${we} file${we>1?"s":""}`),N.current&&(N.current.value="")},X=R=>{p(de=>de.filter(we=>we.id!==R))},Z=async R=>{if(R.preventDefault(),!!a.trim()&&!(c.length<2)){g(!0),K();try{const de=c.map(({instanceId:ye,...J})=>J),we=f.map(ye=>({mime:ye.mimeType,filename:ye.filename,url:ye.dataUrl})),xe=x.filter(ye=>ye.trim().length>0),Pe={name:n.trim(),prompt:a.trim(),models:de,agent:u||void 0,worktreeBaseBranch:F,files:we.length>0?we:void 0,setupCommands:xe.length>0?xe:void 0},H=await O(Pe);H&&(H.firstSessionId&&be.getState().setCurrentSession(H.firstSessionId),r?.())}finally{g(!1)}}},z=!!(n.trim()&&a.trim()&&c.length>=2&&ne&&!V);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{onMouseDown:E,className:L("flex h-12 items-center justify-between border-b app-region-drag select-none",D),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"})}),s&&e.jsx("div",{className:"flex items-center pr-3",children:e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close",className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:e.jsx(ss,{className:"h-5 w-5"})})}),e.jsx(ct,{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:Z,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(wt,{id:"group-name",value:n,onChange:R=>o(R.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(Np,{directory:v,value:F,onChange:B,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:F||"HEAD"}),"."]})]}),e.jsxs(En,{open:y,onOpenChange:w,children:[e.jsxs(go,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",x.filter(R=>R.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",x.filter(R=>R.trim()).length," configured)"]})]}),e.jsx(Ut,{className:L("h-4 w-4 text-muted-foreground transition-transform duration-200",y&&"rotate-180")})]}),e.jsx(In,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_PROJECT_PATH"})," for project root."]}),S?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[x.map((R,de)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(wt,{value:R,onChange:we=>{const xe=[...x];xe[de]=we.target.value,b(xe)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const we=x.filter((xe,Pe)=>Pe!==de);b(we)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(ss,{className:"h-4 w-4"})})]},de)),e.jsxs("button",{type:"button",onClick:()=>b([...x,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(us,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",htmlFor:"multirun-agent",children:"Agent"}),e.jsx(kp,{value:u,onChange:m,id:"multirun-agent"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:["Prompt ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Fs,{id:"prompt",value:a,onChange:R=>l(R.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:N,type:"file",multiple:!0,className:"hidden",onChange:Y,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(je,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>N.current?.click(),children:[e.jsx(Wa,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(R=>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:[R.mimeType.startsWith("image/")?e.jsx(Dr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(vr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:R.filename,children:R.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",R.size<1024?`${R.size}B`:R.size<1024*1024?`${(R.size/1024).toFixed(1)}KB`:`${(R.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>X(R.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(ss,{className:"h-3.5 w-3.5"})})]},R.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(Sp,{selectedModels:c,onAdd:q,onRemove:$,onUpdate:W,minModels:2,maxModels:uu})]}),G&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:G}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(je,{type:"button",variant:"outline",onClick:s,children:"Cancel"}),e.jsx(je,{type:"submit",disabled:!z||h,children:h?"Creating...":e.jsxs(e.Fragment,{children:["Start (",c.length," models)"]})})]})]})})})]})},Fj=(t={})=>{const{edgeThreshold:r=30,minSwipeDistance:s=50,maxSwipeTime:n=300,enabled:o=!0}=t,{isMobile:a,setSessionSwitcherOpen:l,isSessionSwitcherOpen:c}=Me(),d=Ae.useRef(null),u=Ae.useRef(null);return Ae.useEffect(()=>{if(!o||!a)return;const m=g=>{const x=g.touches[0];if(!x){d.current=null;return}x.clientX<=r?d.current={x:x.clientX,y:x.clientY,time:Date.now()}:d.current=null},f=g=>{if(!d.current)return;const x=g.touches[0];if(!x)return;x.clientX-d.current.x>10&&g.preventDefault()},p=g=>{if(!d.current)return;const x=g.changedTouches[0];if(!x){d.current=null,u.current=null;return}u.current={x:x.clientX,y:x.clientY,time:Date.now()};const{x:b,y,time:w}=d.current,{x:S,y:M,time:N}=u.current,v=S-b,A=M-y,k=N-w,C=Math.abs(A)<Math.abs(v),j=k<=n,T=Math.abs(A)<s;v>=s&&C&&j&&T&&!c&&l(!0),d.current=null,u.current=null},h=()=>{d.current=null,u.current=null};return document.addEventListener("touchstart",m,{passive:!0,capture:!0}),document.addEventListener("touchmove",f,{passive:!1,capture:!0}),document.addEventListener("touchend",p,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",m,{capture:!0}),document.removeEventListener("touchmove",f,{capture:!0}),document.removeEventListener("touchend",p,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0})}},[o,a,r,s,n,l,c]),null},Cp=t=>t==="full"?{text:"var(--status-info)",border:"color-mix(in srgb, var(--status-info) 25%, transparent)",background:"color-mix(in srgb, var(--status-info) 4%, transparent)",borderWidth:1.5}:t==="allow"?{text:"var(--status-info)",border:"color-mix(in srgb, var(--status-info) 25%, transparent)",background:"color-mix(in srgb, var(--status-info) 4%, transparent)",borderWidth:1.5}:null;Ae.memo(()=>{const t=Ae.useRef(null),{addAttachedFile:r}=be(),{isMobile:s}=Me(),n=Xf(),o=s?"h-9 w-9":"h-7 w-7",a=s?"h-5 w-5":"h-[18px] w-[18px]",l=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],h=be.getState().attachedFiles.length;try{await r(p),be.getState().attachedFiles.length>h&&m++}catch(g){console.error("File attach failed",g),U.error(g instanceof Error?g.message:"Failed to attach file")}}m>0&&U.success(`Attached ${m} file${m>1?"s":""}`)},c=async u=>{const m=u.target.files;m&&(await l(m),t.current&&(t.current.value=""))},d=async()=>{try{const m=await(await fetch("/api/vscode/pick-files")).json(),f=Array.isArray(m?.files)?m.files:[],p=Array.isArray(m?.skipped)?m.skipped:[];if(p.length>0){const g=p.map(x=>`${x?.name||"file"}: ${x?.reason||"skipped"}`).join(`
|
|
163
|
+
`);U.error(`Some files were skipped:
|
|
164
|
+
${g}`)}const h=f.map(g=>{if(!g?.dataUrl)return null;try{const[x,b]=g.dataUrl.split(","),y=g.mimeType||x?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!b)return null;const w=atob(b),S=new Uint8Array(w.length);for(let N=0;N<w.length;N++)S[N]=w.charCodeAt(N);const M=new Blob([S],{type:y});return new File([M],g.name||"file",{type:y})}catch(x){return console.error("Failed to decode VS Code picked file",x),null}}).filter(Boolean);h.length>0&&await l(h)}catch(u){console.error("VS Code file pick failed",u),U.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:t,type:"file",multiple:!0,className:"hidden",onChange:c,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():t.current?.click()},className:L(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(Wa,{className:L(a,"text-current")})})]})});const Rj=Ae.memo(({file:t,onRemove:r})=>{const s=()=>t.mimeType.startsWith("image/")?e.jsx(Dr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("text")||t.mimeType.includes("code")?e.jsx(vr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("json")||t.mimeType.includes("xml")?e.jsx(ui,{className:"h-3.5 w-3.5"}):e.jsx(vr,{className:"h-3.5 w-3.5"}),n=l=>l<1024?l+" B":l<1048576?(l/1024).toFixed(1)+" KB":(l/1048576).toFixed(1)+" MB",a=(l=>{const d=l.replace(/\\/g,"/").split("/");return d[d.length-1]||l})(t.filename);return e.jsxs("div",{className:"flex w-full sm:inline-flex sm:w-auto items-center gap-1.5 px-3 sm:px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta max-w-full min-w-0",children:[e.jsx("div",{title:t.source==="server"?"Server file":"Local file",children:t.source==="server"?e.jsx(Kg,{className:"h-3 w-3 text-primary flex-shrink-0"}):e.jsx(Hm,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"})}),s(),e.jsx("div",{className:"overflow-hidden max-w-[120px] sm:max-w-[180px] flex-1 min-w-0",children:e.jsx("span",{className:"truncate block",title:t.serverPath||a,children:a})}),e.jsx("span",{className:"ml-auto text-muted-foreground flex-shrink-0 text-xs",children:n(t.size)}),e.jsx("button",{onClick:r,className:"hover:text-destructive min-h-6 min-w-6 sm:min-h-0 sm:min-w-0 sm:p-0.5 flex items-center justify-center flex-shrink-0 rounded focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",title:"Remove file",children:e.jsx(ss,{className:"h-4 w-4 sm:h-3 sm:w-3"})})]})}),Lj=Ae.memo(()=>{const{attachedFiles:t,removeAttachedFile:r}=be();return t.length===0?null:e.jsx("div",{className:"pb-2 overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm: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 flex-shrink-0",children:"Attached:"}),t.map(s=>e.jsx(Rj,{file:s,onRemove:()=>r(s.id)},s.id))]})})}),Mp=Ae.memo(({files:t,onShowPopup:r})=>{const s=t.filter(d=>d.type==="file"&&(d.mime||d.url)),n=d=>{if(!d)return"Unnamed file";const m=d.replace(/\\/g,"/").split("/");return m[m.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(Dr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(vr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(ui,{className:"h-3.5 w-3.5"}):e.jsx(vr,{className:"h-3.5 w-3.5"}):e.jsx(vr,{className:"h-3.5 w-3.5"}),a=s.filter(d=>d.mime?.startsWith("image/")&&d.url),l=s.filter(d=>!d.mime?.startsWith("image/")),c=i.useCallback(d=>{if(!r||!d?.url)return;const u=n(d.filename)||"Image",m={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};r(m)},[r]);return s.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("div",{className:"overflow-hidden max-w-[200px]",children:e.jsx("span",{className:"truncate block",title:n(d.filename),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(dt,{delayDuration:1e3,children:[e.jsx(ut,{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(Dr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(ct,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Dp=Ae.memo(({message:t,sessionId:r,onEdit:s})=>{const n=wr(l=>l.removeFromQueue),o=i.useMemo(()=>{const l=t.content.split(`
|
|
165
|
+
`),c=l[0]||"",d=50;return c.length>d?c.substring(0,d)+"...":c+(l.length>1?"...":"")},[t.content]),a=t.attachments?.length??0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta group",children:[e.jsx(Yg,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>s(t),className:"flex items-center gap-1.5 hover:text-foreground transition-colors text-left",title:"Click to edit",children:[e.jsx("span",{className:"truncate max-w-[200px]",children:o||"(empty)"}),a>0&&e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["+",a," file",a>1?"s":""]})]}),e.jsx("button",{type:"button",onClick:()=>n(r,t.id),className:"ml-1 hover:text-destructive p-0.5 opacity-60 group-hover:opacity-100 transition-opacity",title:"Remove from queue",children:e.jsx(ss,{className:"h-3 w-3"})})]})});Dp.displayName="QueuedMessageChip";const fu=[],Ap=Ae.memo(({onEditMessage:t})=>{const r=be(a=>a.currentSessionId),s=wr(i.useCallback(a=>r?a.queuedMessages[r]??fu:fu,[r])),n=wr(a=>a.popToInput),o=i.useCallback(a=>{if(!r)return;const l=n(r,a.id);if(l){if(l.attachments&&l.attachments.length>0){const c=fr.getState().attachedFiles;fr.setState({attachedFiles:[...c,...l.attachments]})}t(l.content,l.attachments)}},[r,n,t]);return s.length===0||!r?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Queued:"}),s.map(a=>e.jsx(Dp,{message:a,sessionId:r,onEdit:o},a.id))]})})});Ap.displayName="QueuedMessageChips";const Oj=i.forwardRef(({searchQuery:t,onFileSelect:r,onClose:s},n)=>{const{currentDirectory:o}=xt(),{addServerFile:a}=be(),l=yi(P=>P.searchFiles),c=Ii(t,180),d=Vo(),u=xi(),[m,f]=i.useState([]),[p,h]=i.useState(!1),[g,x]=i.useState(0),[b,y]=i.useState(360),[w,S]=i.useState({}),[M,N]=i.useState({}),v=i.useRef([]),A=i.useRef([]),k=i.useRef([]),C=i.useRef(null),j=i.useCallback((P,D)=>{const E=P.trim().toLowerCase();if(!E)return 0;const F=D.toLowerCase();let B=0,V=-1,ne=0;for(let O=0;O<E.length;O+=1){const G=E[O];if(!G||G===" ")continue;const K=F.indexOf(G,V+1);if(K===-1)return null;const q=K-V-1;if(q===0?ne+=1:ne=0,B+=10,B+=Math.max(0,18-K),B-=Math.max(0,q),K===0)B+=12;else{const $=F[K-1];($==="/"||$==="_"||$==="-"||$==="."||$===" ")&&(B+=10)}B+=ne>0?12:0,V=K}return B+=Math.max(0,24-Math.round(F.length/3)),B},[]);i.useEffect(()=>{const P=D=>{const E=D.target;!E||!C.current||C.current.contains(E)||s()};return document.addEventListener("pointerdown",P,!0),()=>{document.removeEventListener("pointerdown",P,!0)}},[s]),i.useEffect(()=>{if(!o){f([]);return}const D=(c??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();let E=!1;return h(!0),l(o,D,80,{includeHidden:d,respectGitignore:!u}).then(F=>{if(E)return;const B=D?F.map(V=>{const ne=V.relativePath||V.name||V.path,O=j(D,ne);return O===null?null:{file:V,score:O,labelLength:ne.length}}).filter(Boolean):F.map(V=>({file:V,score:0,labelLength:(V.relativePath||V.name||V.path).length}));B.sort((V,ne)=>ne.score-V.score||V.labelLength-ne.labelLength||V.file.path.localeCompare(ne.file.path)),f(B.slice(0,15).map(V=>V.file))}).catch(()=>{E||f([])}).finally(()=>{E||h(!1)}),()=>{E=!0}},[o,c,j,l,d,u]),i.useEffect(()=>{x(0),S({}),N({})},[m]),i.useEffect(()=>{v.current[g]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[g]),i.useEffect(()=>{let P=null;const D=()=>{P!==null&&cancelAnimationFrame(P),P=requestAnimationFrame(()=>{const E={},F={};A.current.forEach((B,V)=>{if(!B)return;const O=k.current[V]?.offsetWidth??B.scrollWidth,G=Math.max(0,O-B.clientWidth),K=G>8;if(E[V]=K,K){const q=Math.max(.6,G/110);F[V]=q}}),S(E),N(F)})};return D(),window.addEventListener("resize",D),()=>{P!==null&&cancelAnimationFrame(P),window.removeEventListener("resize",D)}},[m]),i.useEffect(()=>{const P=A.current[g];if(!P)return;const D=()=>{const F=P.clientWidth;F>0&&y(F)};if(D(),typeof ResizeObserver>"u")return;const E=new ResizeObserver(D);return E.observe(P),()=>{E.disconnect()}},[g]);const T=i.useCallback(async P=>{await a(P.path,P.name),r(P)},[a,r]);i.useImperativeHandle(n,()=>({handleKeyDown:P=>{if(P==="Escape"){s();return}const D=m.length;if(D!==0){if(P==="ArrowDown"){x(E=>(E+1)%D);return}if(P==="ArrowUp"){x(E=>(E-1+D)%D);return}if(P==="Enter"||P==="Tab"){const E=(g%D+D)%D,F=m[E];F&&T(F)}}}}),[m,g,s,T]);const I=P=>{switch(P.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(tr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(tr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(vr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Dr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(ui,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:C,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"px-0",children:p?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Xr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[m.map((P,D)=>{const E=P.relativePath||P.name,F=gf(E,{maxLength:45}),B=g===D,V=w[D]??!1,ne=M[D]??2.6,O=e.jsxs("div",{ref:G=>{v.current[D]=G},className:L("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",B&&"bg-muted"),onClick:()=>T(P),onMouseEnter:()=>x(D),children:[I(P),e.jsxs("span",{ref:G=>{A.current[D]=G},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:B?{"--file-mention-marquee-width":`${b}px`,"--file-mention-marquee-duration":`${ne}s`}:void 0,"aria-label":E,children:[e.jsx("span",{ref:G=>{k.current[D]=G},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:E}),V&&B?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:E}):e.jsx("span",{className:"block truncate",children:F})]})]});return e.jsx(i.Fragment,{children:O},P.path)}),m.length>0&&e.jsx("div",{className:"h-2"}),m.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No files found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})}),Ep=i.forwardRef(({searchQuery:t,onCommandSelect:r,onClose:s},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=be(zn(w=>{const S=w.currentSessionId;return{hasMessagesInCurrentSession:(S?w.messages.get(S)?.length??0:0)>0,currentSessionId:S}})),l=!!a,[c,d]=i.useState([]),[u,m]=i.useState(!1),{commands:f,loadCommands:p}=nn(),[h,g]=i.useState(0),x=i.useRef([]),b=i.useRef(null);i.useEffect(()=>{const w=S=>{const M=S.target;!M||!b.current||b.current.contains(M)||s()};return document.addEventListener("pointerdown",w,!0),()=>{document.removeEventListener("pointerdown",w,!0)}},[s]),i.useEffect(()=>{p()},[p]),i.useEffect(()=>{(async()=>{m(!0);try{const S=f.map(C=>({name:C.name,description:C.description,agent:C.agent??void 0,model:C.model??void 0,isBuiltIn:C.name==="init"||C.name==="review",scope:C.scope})),M=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],N=new Map;M.forEach(C=>N.set(C.name,C)),S.forEach(C=>N.set(C.name,C));const v=Array.from(N.values()),A=!o,k=(t?v.filter(C=>Js(C.name,t)||C.description&&Js(C.description,t)):v).filter(C=>A||C.name!=="init");k.sort((C,j)=>{const T=C.name.toLowerCase().startsWith(t.toLowerCase()),I=j.name.toLowerCase().startsWith(t.toLowerCase());return T&&!I?-1:!T&&I?1:C.name.localeCompare(j.name)}),d(k)}catch{const S=!o,M=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],N=(t?M.filter(v=>Js(v.name,t)||v.description&&Js(v.description,t)):M).filter(v=>S||v.name!=="init");d(N)}finally{m(!1)}})()},[t,o,l,f]),i.useEffect(()=>{g(0)},[c]),i.useEffect(()=>{x.current[h]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[h]),i.useImperativeHandle(n,()=>({handleKeyDown:w=>{const S=c.length;if(w==="Escape"){s();return}if(S!==0){if(w==="ArrowDown"){g(M=>(M+1)%S);return}if(w==="ArrowUp"){g(M=>(M-1+S)%S);return}if(w==="Enter"||w==="Tab"){const M=(h%S+S)%S,N=c[M];N&&r(N)}}}}),[c,h,s,r]);const y=w=>{switch(w.name){case"init":return e.jsx(vr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(Zn,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(Xg,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(kr,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(Jg,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(tn,{className:"h-3.5 w-3.5 text-cyan-500"});default:return w.isBuiltIn?e.jsx(Qg,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(Dn,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:b,className:"absolute z-[100] min-w-0 w-full max-w-[450px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:u?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Xr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[c.map((w,S)=>{const M=w.isBuiltIn,N=w.scope==="project";return e.jsxs("div",{ref:v=>{x.current[S]=v},className:L("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",S===h&&"bg-muted"),onClick:()=>r(w),onMouseEnter:()=>g(S),children:[e.jsx("div",{className:"mt-0.5",children:y(w)}),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:["/",w.name]}),M?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):w.scope?e.jsx("span",{className:L("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",N?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:w.scope}):null,w.agent&&e.jsx("span",{className:"text-[10px] leading-none font-bold tracking-tight bg-[var(--surface-subtle)] text-[var(--surface-foreground)] border-[var(--interactive-border)] px-1.5 py-1 rounded border flex-shrink-0",children:w.agent})]}),w.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:w.description})]})]},w.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"})]})});Ep.displayName="CommandAutocomplete";const _j=t=>t?t!=="primary":!1,Ip=i.forwardRef(({searchQuery:t,onAgentSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{getVisibleAgents:m}=Ze(),{agents:f,loadAgents:p}=on();i.useEffect(()=>{f.length===0&&p()},[p,f.length]),i.useEffect(()=>{const x=m().filter(w=>_j(w.mode)).map(w=>{const S=f.find(M=>M.name===w.name);return{name:w.name,description:w.description,mode:w.mode??void 0,scope:S?.scope,isBuiltIn:S?pn(S):!1}}),b=t.trim(),y=b.length?x.filter(w=>Js(w.name,b)):x;y.sort((w,S)=>w.name.localeCompare(S.name)),d(y),l(0)},[m,t,f]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const g=x=>{const b=x.target;!b||!o.current||o.current.contains(b)||s()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[s]),i.useImperativeHandle(n,()=>({handleKeyDown:g=>{if(g==="Escape"){s();return}if(c.length){if(g==="ArrowDown"){l(x=>(x+1)%c.length);return}if(g==="ArrowUp"){l(x=>(x-1+c.length)%c.length);return}if(g==="Enter"||g==="Tab"){const x=c[(a+c.length)%c.length];x&&r(x.name)}}}}),[c,r,s,a]);const h=(g,x)=>{const b=g.isBuiltIn,y=g.scope==="project";return e.jsx("div",{ref:w=>{u.current[x]=w},className:L("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",x===a&&"bg-muted"),onClick:()=>r(g.name),onMouseEnter:()=>l(x),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-semibold",children:["#",g.name]}),b?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):g.scope?e.jsx("span",{className:L("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",y?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:g.scope}):null]}),g.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:g.description})]})},g.name)};return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((g,x)=>h(g,x))}):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"})]})});Ip.displayName="AgentMentionAutocomplete";const Pp=i.forwardRef(({searchQuery:t,onSkillSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{skills:m,loadSkills:f}=mr();i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const h=t.trim(),x=[...h.length?m.filter(b=>Js(b.name,h)):m].sort((b,y)=>b.scope==="project"&&y.scope!=="project"?-1:b.scope!=="project"&&y.scope==="project"?1:b.name.localeCompare(y.name));d(x),l(0)},[m,t]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const h=g=>{const x=g.target;!x||!o.current||o.current.contains(x)||s()};return document.addEventListener("pointerdown",h,!0),()=>{document.removeEventListener("pointerdown",h,!0)}},[s]),i.useImperativeHandle(n,()=>({handleKeyDown:h=>{if(h==="Escape"){s();return}if(c.length){if(h==="ArrowDown"){l(g=>(g+1)%c.length);return}if(h==="ArrowUp"){l(g=>(g-1+c.length)%c.length);return}if(h==="Enter"||h==="Tab"){const g=c[a];g&&r(g.name)}}}}),[c,r,s,a]);const p=(h,g)=>{const x=h.scope==="project";return e.jsx("div",{ref:b=>{u.current[g]=b},className:L("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",g===a&&"bg-muted"),onClick:()=>r(h.name),onMouseEnter:()=>l(g),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold truncate",children:h.name}),e.jsx("span",{className:L("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0 transition-colors",x?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:h.scope})]}),h.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:h.description})]})},`${h.name}-${h.scope}`)};return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((h,g)=>p(h,g))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No skills found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Pp.displayName="SkillAutocomplete";function $j({className:t,children:r,...s}){return e.jsxs(Zg,{"data-slot":"scroll-area",className:L("relative",t),...s,children:[e.jsx(ex,{"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(Bj,{}),e.jsx(tx,{})]})}function Bj({className:t,orientation:r="vertical",...s}){return e.jsx(sx,{"data-slot":"scroll-area-scrollbar",orientation:r,className:L("flex touch-none p-px select-none",r==="vertical"&&"h-full w-2.5 border-l border-l-transparent",r==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",t),...s,children:e.jsx(rx,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const zj=({onFilesSelected:t,multiSelect:r=!1,children:s,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:l}=qt(),c=l,{currentDirectory:d}=xt(),u=yi(oe=>oe.searchFiles),m=Vo(),f=xi(),[p,h]=i.useState(!1),[g,x]=i.useState(0),[b,y]=i.useState(!1),[w,S]=i.useState(""),M=Ii(w,200),[N,v]=i.useState(new Set),[A,k]=i.useState(new Set),[C,j]=i.useState({}),T=i.useRef(new Set),I=i.useRef(new Set),[P,D]=i.useState([]),[E,F]=i.useState(!1),[B,V]=i.useState(!1),[ne,O]=i.useState(!1),[G,K]=i.useState(null),q=n??p,$=o??h,W=i.useCallback(oe=>oe.slice().sort((Q,re)=>Q.type!==re.type?Q.type==="directory"?-1:1:Q.name.localeCompare(re.name)),[]),Y=i.useCallback((oe,Q)=>W(Q.filter(re=>m||!re.name.startsWith(".")).map(re=>{const ue=re.name,he=!re.isDirectory&&ue.includes(".")?ue.split(".").pop()?.toLowerCase():void 0;return{name:ue,path:re.path||`${oe}/${ue}`,type:re.isDirectory?"directory":"file",size:0,extension:he}})),[W,m]),X=i.useCallback(async oe=>{V(!0),K(null);try{const Q=await Oe.listLocalDirectory(oe,{respectGitignore:!f}),re=Y(oe,Q.map(ue=>({name:ue.name,path:ue.path,isDirectory:ue.isDirectory})));T.current=new Set([oe]),I.current=new Set,j({[oe]:re}),k(new Set)}catch{K("Failed to load directory contents"),T.current=new Set([oe]),I.current=new Set,j({[oe]:[]}),k(new Set)}finally{V(!1)}},[Y,f]),Z=i.useCallback(async oe=>{const Q=oe.trim();if(!Q)return;const re=`${Q}::${g}`;if(!T.current.has(re)&&!I.current.has(re)){I.current=new Set(I.current),I.current.add(re);try{const ue=await Oe.listLocalDirectory(Q,{respectGitignore:!f}),he=Y(Q,ue.map(Ge=>({name:Ge.name,path:Ge.path,isDirectory:Ge.isDirectory})));T.current=new Set(T.current),T.current.add(re),j(Ge=>({...Ge,[Q]:he}))}catch{j(ue=>ue[Q]?ue:{...ue,[Q]:[]})}finally{I.current=new Set(I.current),I.current.delete(re)}}},[Y,f,g]);i.useEffect(()=>{(q||b)&&d&&X(d)},[q,b,d,X]),i.useEffect(()=>{x(oe=>oe+1)},[m,f]),i.useEffect(()=>{if(!(q||b)||!d){D([]),F(!1);return}const oe=M.trim().replace(/^\.\//,"").replace(/^\/+/,"");if(!oe){D([]),F(!1);return}const Q=oe.toLowerCase();let re=!1;return F(!0),u(d,Q,150,{includeHidden:m,respectGitignore:!f}).then(ue=>{if(re)return;const he=ue.map(Ge=>({name:Ge.name,path:Ge.path,type:"file",extension:Ge.extension,relativePath:Ge.relativePath,size:0}));D(he)}).catch(()=>{re||D([])}).finally(()=>{re||F(!1)}),()=>{re=!0}},[q,b,d,M,u,m,f]),i.useEffect(()=>{!q&&!b&&(v(new Set),S(""),D([]),F(!1),T.current=new Set,I.current=new Set,j({}),k(new Set))},[q,b]);const z=oe=>{if(oe.type==="directory")return A.has(oe.path)?e.jsx(lr,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(lr,{className:"h-3.5 w-3.5 text-primary/60"});switch(oe.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(tr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(tr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Qn,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Dr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Qn,{className:"h-3.5 w-3.5 text-muted-foreground"})}},R=async oe=>{A.has(oe)?k(re=>{const ue=new Set(re);return ue.delete(oe),ue}):(k(re=>{const ue=new Set(re);return ue.add(oe),ue}),await Z(oe))},de=oe=>{v(r?Q=>{const re=new Set(Q);return re.has(oe)?re.delete(oe):re.add(oe),re}:new Set([oe]))},we=async()=>{const oe=new Map;Object.values(C).forEach(ue=>{ue.forEach(he=>{he.type==="file"&&oe.set(he.path,he)})});const Q=new Map(P.map(ue=>[ue.path,ue])),re=Array.from(N).map(ue=>oe.get(ue)??Q.get(ue)).filter(ue=>!!ue);O(!0);try{await t(re),v(new Set),$(!1),y(!1)}finally{O(!1)}},xe=i.useMemo(()=>d?C[d]??[]:[],[C,d]),Pe=w.trim().length>0,H=oe=>C[oe]??[],ye=oe=>{if(d&&oe.startsWith(d)){const Q=oe.substring(d.length);return Q.startsWith("/")?Q.substring(1):Q}return oe.split("/").pop()||oe},J=(oe,Q)=>{const re=Pe?oe.relativePath||ye(oe.path):oe.name,ue=Pe&&re.includes("/")&&re.length>45,he=ue?gf(re,{maxLength:c?42:48}):re,Ge=e.jsxs("div",{className:L("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",oe.type==="file"&&N.has(oe.path)&&"bg-primary/10"),style:{paddingLeft:`${Q*12}px`},onClick:qe=>{qe.preventDefault(),qe.stopPropagation(),oe.type==="file"&&de(oe.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:z(oe)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":re,children:he})]}),oe.type==="file"&&N.has(oe.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return ue?e.jsxs(dt,{delayDuration:120,children:[e.jsx(ut,{asChild:!0,children:Ge}),e.jsx(ct,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:re})})]},oe.path):i.cloneElement(Ge,{key:oe.path})},ce=(oe,Q)=>{const re=oe.type==="directory",ue=re?H(oe.path):[],he=A.has(oe.path),Ge=re&&he&&I.current.has(oe.path)&&ue.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:L("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!re&&N.has(oe.path)&&"bg-primary/10"),style:{paddingLeft:`${Q*12}px`},onClick:qe=>{qe.preventDefault(),qe.stopPropagation(),re?R(oe.path):de(oe.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:z(oe)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:oe.name}),!re&&N.has(oe.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),re&&he&&ue.length>0&&e.jsx("div",{children:ue.map(qe=>ce(qe,Q+1))}),re&&he&&Ge&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(Q+1)*12}px`},children:"Loading…"})]},oe.path)},ge=N.size>0?`${N.size} file${N.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:ge}),e.jsx(je,{size:"sm",onClick:we,disabled:N.size===0||ne,className:"h-6 typography-meta",children:ne?"Attaching...":"Attach Files"})]}),me=c?"flex-1 min-h-[240px]":"h-[300px]",le=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(Vs,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(wt,{value:w,onChange:oe=>S(oe.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:oe=>oe.stopPropagation()}),w&&e.jsx("button",{onClick:oe=>{oe.stopPropagation(),S("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(ss,{className:"h-3 w-3"})})]})}),e.jsxs($j,{className:me,children:[B&&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..."})}),G&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:G})}),!B&&!G&&e.jsxs("div",{className:"py-1 px-2",children:[Pe?E?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):P.map(oe=>J(oe,0)):xe.map(oe=>ce(oe,0)),!Pe&&xe.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),Pe&&!E&&P.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),fe=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:oe=>{oe.preventDefault(),oe.stopPropagation(),y(!0)},children:s});return a==="modal"?e.jsxs(e.Fragment,{children:[s?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:oe=>{oe.preventDefault(),oe.stopPropagation(),$(!0)},children:s}):null,e.jsx(Ws,{open:q,onClose:()=>$(!1),title:"Select Project Files",footer:ee,children:e.jsx("div",{className:"flex flex-col gap-0",children:le})})]}):c?e.jsxs(e.Fragment,{children:[fe,e.jsx(Ws,{open:b,onClose:()=>y(!1),title:"Select Project Files",footer:ee,children:e.jsx("div",{className:"flex flex-col gap-0",children:le})})]}):e.jsxs(rs,{open:q,onOpenChange:$,children:[e.jsx(ns,{asChild:!0,children:s}),e.jsxs(os,{className:L("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[le,e.jsx(Ds,{}),ee]})]})},fa=[{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 Gr(t){if(!t||t==="build")return fa[0];let r=0;for(let n=0;n<t.length;n++){const o=t.charCodeAt(n);r=(r<<5)-r+o,r=r&r}const s=1+Math.abs(r)%(fa.length-1);return fa[s]}const Hj=typeof window<"u"?i.useLayoutEffect:i.useEffect,Wj=(t,r=[])=>{const[s,n]=i.useState(!1),o=i.useCallback(()=>{const a=t.current;if(!a)return;const l=a.scrollWidth>a.clientWidth+1;n(l)},[t]);return Hj(()=>{o()},[o,...r]),i.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const l=new ResizeObserver(()=>{o()});return l.observe(a),()=>l.disconnect()},[o,t]),i.useEffect(()=>{if(typeof window>"u")return;const a=()=>o();return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[o]),s},pa=t=>t==="primary"||t==="all"||t===void 0||t===null,ql=t=>{if(!Array.isArray(t))return null;const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},Xi=(t,r)=>{const s=ql(t);if(!(!s||s.length===0)){for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},Uj=[{key:"tool_call",icon:mi,label:"Tool calling",isActive:t=>t?.tool_call===!0},{key:"reasoning",icon:Cr,label:"Reasoning",isActive:t=>t?.reasoning===!0}],Vj={text:{icon:Wm,label:"Text"},image:{icon:Dr,label:"Image"},video:{icon:ox,label:"Video"},audio:{icon:nx,label:"Audio"},pdf:{icon:ui,label:"PDF"}},Gj=t=>t.trim().toLowerCase(),jo=(t,r)=>{const s=r==="input"?t?.modalities?.input:t?.modalities?.output;return!Array.isArray(s)||s.length===0?[]:Array.from(new Set(s.map(o=>Gj(o)))).map(o=>{const a=Vj[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},qj=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Kj=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),or=t=>{if(typeof t!="number"||Number.isNaN(t))return"—";if(t===0)return"0";const r=qj.format(t);return r.endsWith(".0")?r.slice(0,-2):r},ha=t=>typeof t!="number"||!Number.isFinite(t)?"—":Kj.format(t),Zi=t=>Uj.filter(r=>r.isActive(t)).map(r=>({key:r.key,icon:r.icon,label:r.label})),pu=t=>{if(!t)return"—";const r=t.match(/^(\d{4})-(\d{2})$/);if(r){const s=Number.parseInt(r[1],10),n=Number.parseInt(r[2],10)-1,o=new Date(Date.UTC(s,n,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return t},hu=t=>{if(!t)return"—";const r=new Date(t);return Number.isNaN(r.getTime())?t:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(r)},gu=({className:t})=>{const{providers:r,currentProviderId:s,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:l,setProvider:c,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:h,getCurrentAgent:g,getVisibleAgents:x}=Ze(),b=x(),{currentSessionId:y,messages:w,saveSessionAgentSelection:S,saveAgentModelForSession:M,getAgentModelForSession:N,saveAgentModelVariantForSession:v,getAgentModelVariantForSession:A,analyzeAndSaveExternalSessionChoices:k}=be(),C=tt(De=>De.hasHydrated),j=tt(De=>y?De.sessionAgentSelections.get(y)??null:null),T=i.useRef(null);i.useEffect(()=>{if(!y){T.current=null;return}j&&(T.current=j)},[y,j]);const I=y?T.current:null,P=y&&(j||I)||a,D=y??"__global__",E=tt(De=>{if(P)return De.getSessionAgentEditMode(D,P,"ask")}),F=tt(De=>De.setSessionAgentEditMode),{toggleFavoriteModel:B,isFavoriteModel:V,addRecentModel:ne,isModelSelectorOpen:O,setModelSelectorOpen:G}=Me(),{favoriteModelsList:K,recentModelsList:q}=Fc(),{isMobile:$}=qt(),W=qw(),Y=Xf(),X=$,[Z,z]=i.useState(null),[R,de]=i.useState(null),[we,xe]=i.useState(""),Pe=i.useCallback(()=>z(null),[]),H=i.useCallback(()=>de(null),[]),ye=i.useRef(void 0),[J,ce]=i.useState(()=>{const De=new Set;return s&&De.add(s),De}),ge=O,ee=G,[me,le]=i.useState(""),[fe,oe]=i.useState(0),Q=i.useRef([]);i.useEffect(()=>{Z==="model"&&ce(()=>{const De=new Set;return s&&De.add(s),De})},[Z,s]),i.useEffect(()=>{Z!=="model"&&xe("")},[Z]);const re=i.useRef(ge);i.useEffect(()=>{const De=re.current;re.current=ge,ge||(le(""),oe(0),De&&!X&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[ge,X]),i.useEffect(()=>{oe(0)},[me]);const ue=i.useMemo(()=>P?b.find(De=>De.name===P):g?.(),[b,g,P]),he=i.useMemo(()=>ue?Xi(ue.permission,"edit")??"allow":"deny",[ue]),Ge=!!P,qe=he==="ask",et=qe?E==="allow"||E==="full":he==="allow",rt=!Ge||!qe,vt=$?"mobile":Y?"vscode":"default",Ce=vt==="mobile"?"h-9":vt==="vscode"?"h-6":"h-8",pe=vt==="mobile"?"h-5 w-5":"h-4 w-4",He=vt==="mobile"?"h-5 w-5":"h-4 w-4",Se=X?"typography-micro":"typography-meta",ke=vt==="mobile"||vt==="vscode"?"gap-x-1":"gap-x-3",Xe=i.useCallback((De,ze=pe)=>{const _e=L(ze,"flex-shrink-0"),st=Cp(De),Ne={color:st?st.text:"var(--foreground)"};return De==="full"?e.jsx(Tr,{className:_e,style:Ne}):De==="allow"?e.jsx(ka,{className:_e,style:Ne}):De==="deny"?e.jsx(Xn,{className:_e,style:Ne}):e.jsx(vn,{className:_e,style:Ne})},[pe]),at=i.useCallback(De=>{!Ge||!a||!qe||F(D,a,De?"allow":"ask","ask")},[qe,a,Ge,F,D]),We=p(),Be=Array.isArray(We?.models)?We.models:[],Ve=s&&n?h(s,n):void 0,mt=Zi(Ve),ft=jo(Ve,"input"),Ke=jo(Ve,"output"),lt=i.useMemo(()=>`${s}/${n}`?m():[],[m,s,n]),jt=lt.length>0,yt=[{label:"Input",value:ha(Ve?.cost?.input)},{label:"Output",value:ha(Ve?.cost?.output)},{label:"Cache read",value:ha(Ve?.cost?.cache_read)},{label:"Cache write",value:ha(Ve?.cost?.cache_write)}],Mt=[{label:"Context",value:or(Ve?.limit?.context)},{label:"Output",value:or(Ve?.limit?.output)}],es=i.useRef(void 0),Ht=y?w.get(y)?.length??-1:-1,Wt=i.useRef(null);i.useEffect(()=>{if(!y)return;const De=Wt.current;!De||De.sessionId!==y||j&&b.some(ze=>ze.name===j)&&(De.resolved=!0,De.inFlight=!1)},[b,y,j]);const kt=i.useCallback((De,ze,_e)=>{if(!De||!ze)return"model-missing";const st=r.find(_=>_.id===De);return st?(Array.isArray(st.models)?st.models:[]).find(_=>_.id===ze)?(c(De),d(ze),y&&_e&&M(y,_e,De,ze),"applied"):"model-missing":"provider-missing"},[r,c,d,y,M]);i.useEffect(()=>{if(!y){Wt.current=null;return}if(!C||r.length===0||b.length===0)return;(!Wt.current||Wt.current.sessionId!==y)&&(Wt.current={sessionId:y,resolved:!1,inFlight:!1});const De=Wt.current;if(!De||De.resolved||De.inFlight)return;let ze=!1;const _e=()=>{if(ze)return;const _=Wt.current;_&&_.sessionId===y&&(_.resolved=!0,_.inFlight=!1)},st=()=>{const _=y?tt.getState().getSessionAgentSelection(y)||T.current:null;if(_){a!==_&&f(_);const ve=N(y,_);if(ve){const ae=kt(ve.providerId,ve.modelId,_);if(ae==="applied")return"resolved";if(ae==="provider-missing")return"waiting"}else return"resolved"}for(const ve of b){const ae=N(y,ve.name);if(!ae)continue;a!==ve.name&&f(ve.name),tt.getState().getSessionAgentSelection(y)||T.current||S(y,ve.name);const $e=kt(ae.providerId,ae.modelId,ve.name);if($e==="applied")return"resolved";if($e==="provider-missing")return"waiting"}return"continue"},nt=()=>{if(b.length===0)return;const _=y?tt.getState().getSessionAgentSelection(y)||T.current:null,ve=(y?tt.getState().getSessionAgentSelection(y)||T.current:null)||a;if(ve&&b.some($e=>$e.name===ve)){a!==ve&&f(ve);return}const ae=b.filter($e=>pa($e.mode)),Fe=b.find($e=>$e.name==="build")||ae[0]||b[0];Fe&&(_||S(y,Fe.name),a!==Fe.name&&f(Fe.name),Fe.model?.providerID&&Fe.model?.modelID&&kt(Fe.model.providerID,Fe.model.modelID,Fe.name))};return(async()=>{try{const _=st();if(_==="resolved"){_e();return}if(_==="waiting"||Ht===-1)return;if(Ht>0){De.inFlight=!0;try{const ve=await k(y,b);if(ze)return;if(ve.size>0){let ae=null,Fe=-1/0;for(const[$e,Ue]of ve)Ue.timestamp>Fe&&(Fe=Ue.timestamp,ae=$e);if(ae){const $e=tt.getState().getSessionAgentSelection(y)||T.current;if($e&&$e!==ae){_e();return}$e||S(y,ae),a!==ae&&f(ae);const Ue=ve.get(ae);if(Ue){const Je=kt(Ue.providerId,Ue.modelId,ae);if(Je==="applied"){_e();return}if(Je==="provider-missing")return}else{_e();return}}}}catch(ve){ze||console.error("[ModelControls] Error resolving session from messages:",ve)}finally{const ve=Wt.current;!ze&&ve&&ve.sessionId===y&&(ve.inFlight=!1)}}if(ze)return;nt(),_e()}catch(_){ze||console.error("[ModelControls] Error in session switch:",_)}})(),()=>{ze=!0}},[y,Ht,b,a,N,f,kt,k,S,C,r,j]),i.useEffect(()=>{if(!C||!y||r.length===0||b.length===0)return;const De=j||a;if(!De)return;const ze=N(y,De);if(!ze)return;const _e=r.find(_=>_.id===ze.providerId);if(!_e||!(Array.isArray(_e.models)?_e.models.some(_=>_.id===ze.modelId):!1))return;const nt=s===ze.providerId,Ne=n===ze.modelId;nt&&Ne||(De!==a&&f(De),kt(ze.providerId,ze.modelId,De))},[C,y,a,s,n,r,b,N,kt,f,j]),i.useEffect(()=>{if(!C)return;(async()=>{try{if(a!==es.current&&(es.current=a,a&&y)){await new Promise(st=>setTimeout(st,50));const ze=N(y,a);if(ze){const st=kt(ze.providerId,ze.modelId,a);if(st==="applied"||st==="provider-missing")return}const _e=b.find(st=>st.name===a);if(_e?.model?.providerID&&_e?.model?.modelID&&kt(_e.model.providerID,_e.model.modelID,a)==="provider-missing")return}}catch(ze){console.error("[ModelControls] Agent change error:",ze)}})()},[a,y,N,kt,b,C]),i.useEffect(()=>{if(!C||!a){u(void 0);return}if(!s||!n){u(void 0);return}if(lt.length===0){u(void 0);return}if(o&&!lt.includes(o)){u(void 0);return}if(!y){if(!o){const _e=l&<.includes(l)?l:void 0;u(_e)}return}const De=A(y,a,s,n),ze=De&<.includes(De)?De:void 0;u(ze)},[lt,C,y,a,s,n,o,A,u,l]);const gs=i.useCallback(De=>{u(De),y&&a&&s&&n&&v(y,a,s,n,De)},[a,n,s,y,v,u]),Qt=De=>{try{f(De),ee(!1),y&&S(y,De),X&&Pe()}catch(ze){console.error("[ModelControls] Handle agent change error:",ze)}},Tt=(De,ze)=>{try{const _e=kt(De,ze,a||void 0);if(_e!=="applied"){_e==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",De):_e==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:De,modelId:ze});return}ne(De,ze),ee(!1),X&&Pe(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(_e){console.error("[ModelControls] Handle model change error:",_e)}},Kt=De=>{const ze=typeof De?.name=="string"?De.name:typeof De?.id=="string"?De.id:"";return ze.length>40?ze.substring(0,37)+"...":ze},Rt=()=>r.find(ze=>ze.id===s)?.name||s,_t=()=>{if(!s||!n||Be.length===0)return"Not selected";const De=Be.find(ze=>ze.id===n);return Kt(De)},Yt=_t(),Gt=i.useRef(null),It=Wj(Gt,[Yt,X]),Ie=()=>{if(!P){const ze=b.filter(nt=>pa(nt.mode)),st=ze.find(nt=>nt.name==="build")||ze[0];return st?Te(st.name):"Select Agent"}const De=b.find(ze=>ze.name===P);return Te(De?De.name:P)},Te=De=>De.charAt(0).toUpperCase()+De.slice(1),Le=(De,ze,_e)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:ze,"aria-label":ze,role:"img",children:e.jsx(De,{className:"h-3.5 w-3.5"})},_e),te=i.useCallback(De=>{ce(ze=>{const _e=new Set(ze);return _e.has(De)?_e.delete(De):_e.add(De),_e})},[]),se=i.useCallback(De=>{ye.current&&clearTimeout(ye.current),ye.current=setTimeout(()=>{de(De)},500)},[]),ie=i.useCallback(()=>{ye.current&&clearTimeout(ye.current)},[]);i.useEffect(()=>()=>{ye.current&&clearTimeout(ye.current)},[]);const Ee=()=>!X||R!=="model"?null:e.jsx(Ws,{open:!0,onClose:H,title:Ve?.name||_t(),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:Rt()})]}),mt.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:mt.map(({key:De,icon:ze,label:_e})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Le(ze,_e,`cap-${De}`),e.jsx("span",{className:"typography-meta text-foreground",children:_e})]},De))})]}),(ft.length>0||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:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[ft.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:ft.map(({key:De,icon:ze,label:_e})=>Le(ze,`${_e} input`,`input-${De}`))})]}),Ke.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:Ke.map(({key:De,icon:ze,label:_e})=>Le(ze,`${_e} output`,`output-${De}`))})]})]})]}),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:or(Ve?.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:or(Ve?.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:pu(Ve?.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:hu(Ve?.release_date)})]})]})]})]})}),Re=()=>{if(!X||R!=="agent"||!ue)return null;const De=!!(ue.prompt&&ue.prompt.trim().length>0),ze=ue.model?.providerID&&ue.model?.modelID,_e=ue.temperature!==void 0||ue.topP!==void 0,st=ve=>{const ae=ql(ue.permission)??[],Fe=ae.some(Ue=>Ue.permission===ve&&Ue.pattern!=="*"),$e=Xi(ae,ve)??"ask";return Fe?{mode:"ask",label:"Custom"}:$e==="allow"?{mode:"allow",label:"Allow"}:$e==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},nt=st("edit"),Ne=st("bash"),_=st("webfetch");return e.jsx(Ws,{open:!0,onClose:H,title:Te(ue.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[ue.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:ue.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:ue.mode==="primary"?"Primary":ue.mode==="subagent"?"Subagent":ue.mode==="all"?"All":"—"})]}),(ze||_e)&&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"}),ze&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[ue.model.providerID," / ",ue.model.modelID]}),_e&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[ue.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:ue.temperature})]}),ue.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:ue.topP})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Permissions"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Xe(nt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:nt.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Xe(Ne.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ne.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Xe(_.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:_.label})]})]})]})]}),De&&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(ka,{className:"h-4 w-4 text-foreground"})]})})]})})},Ye=()=>{if(!X)return null;const De=we.trim(),ze=r.map(_e=>{const st=Array.isArray(_e.models)?_e.models:[],nt=De.length===0?!0:Js(_e.name,De)||Js(_e.id,De),Ne=De.length===0?st:st.filter(_=>{const ve=Kt(_),ae=typeof _.id=="string"?_.id:"";return Js(ve,De)||Js(ae,De)});return{provider:_e,providerModels:Ne,matchesProvider:nt}}).filter(({matchesProvider:_e,providerModels:st})=>_e||st.length>0);return e.jsx(Ws,{open:Z==="model",onClose:Pe,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(Vs,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(wt,{value:we,onChange:_e=>xe(_e.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),we&&e.jsx("button",{type:"button",onClick:()=>xe(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Xn,{className:"h-4 w-4"})})]})}),ze.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."}),!we&&K.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(Fr,{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:K.map(({model:_e,providerID:st,modelID:nt})=>{const Ne=st===s&&nt===n,_=h(st,nt);return e.jsxs("button",{type:"button",onClick:()=>Tt(st,nt),className:L("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",Ne?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ys,{providerId:st,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Kt(_e)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(_?.limit?.context||_?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[_?.limit?.context?`${or(_?.limit?.context)} ctx`:"",_?.limit?.context&&_?.limit?.output?" • ":"",_?.limit?.output?`${or(_?.limit?.output)} out`:""]})})]},`fav-mobile-${st}-${nt}`)})})]}),!we&&q.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(kr,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:q.map(({model:_e,providerID:st,modelID:nt})=>{const Ne=st===s&&nt===n,_=h(st,nt);return e.jsxs("button",{type:"button",onClick:()=>Tt(st,nt),className:L("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",Ne?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ys,{providerId:st,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Kt(_e)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(_?.limit?.context||_?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[_?.limit?.context?`${or(_?.limit?.context)} ctx`:"",_?.limit?.context&&_?.limit?.output?" • ":"",_?.limit?.output?`${or(_?.limit?.output)} out`:""]})})]},`recent-mobile-${st}-${nt}`)})})]}),ze.map(({provider:_e,providerModels:st})=>{if(st.length===0&&!De.length)return null;const nt=_e.id===s,Ne=J.has(_e.id)||De.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:()=>te(_e.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Ne,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{providerId:_e.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:_e.name}),nt&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Ne?e.jsx(Ut,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(er,{className:"h-3 w-3 text-muted-foreground"})]}),Ne&&st.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:st.map(_=>{const ve=nt&&_.id===n,ae=h(_e.id,_.id),Fe=Zi(ae).slice(0,3),$e=jo(ae,"input");return e.jsxs("div",{className:L("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 last:border-b-0","rounded-lg transition-colors",!ve&&"hover:bg-muted",ve?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>Tt(_e.id,_.id),className:L("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:Kt(_)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(ae?.limit?.context||ae?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[ae?.limit?.context?e.jsxs("span",{children:[or(ae?.limit?.context)," ctx"]}):null,ae?.limit?.context&&ae?.limit?.output?e.jsx("span",{children:"•"}):null,ae?.limit?.output?e.jsxs("span",{children:[or(ae?.limit?.output)," out"]}):null]}),(Fe.length>0||$e.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Fe,...$e].map(({key:Ue,icon:Je,label:ot})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:ot,"aria-label":ot,children:e.jsx(Je,{className:"h-3 w-3"})},`meta-${_e.id}-${_.id}-${Ue}`))})]})]}),e.jsx("button",{type:"button",onClick:Ue=>{Ue.preventDefault(),Ue.stopPropagation(),B(_e.id,_.id)},className:L("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",V(_e.id,_.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":V(_e.id,_.id)?"Unfavorite":"Favorite",title:V(_e.id,_.id)?"Remove from favorites":"Add to favorites",children:V(_e.id,_.id)?e.jsx(Fr,{className:"h-4 w-4"}):e.jsx(Gn,{className:"h-4 w-4"})})]},_.id)})})]},_e.id)})]})})},bt=()=>{if(!X||!jt)return null;const De=!o,ze=_e=>{gs(_e),Pe(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(Ws,{open:Z==="variant",onClose:Pe,title:"Thinking",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{type:"button",className:L("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",De?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ze(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),De&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),lt.map(_e=>{const st=o===_e,nt=_e.charAt(0).toUpperCase()+_e.slice(1);return e.jsxs("button",{type:"button",className:L("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",st?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ze(_e),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:nt}),st&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},_e)})]})})},pt=()=>{if(!X)return null;const De=b.filter(ze=>pa(ze.mode));return e.jsx(Ws,{open:Z==="agent",onClose:Pe,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[De.map(ze=>{const _e=ze.name===P,st=Gr(ze.name);return e.jsxs("button",{type:"button",className:L("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",st.class,_e?"active":"border-border/40"),onClick:()=>Qt(ze.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:L("h-2 w-2 rounded-full",st.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:_e?{color:`var(${st.var})`}:void 0,children:Te(ze.name)})]}),ze.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:ze.description})]},ze.name)}),e.jsx("div",{className:"rounded-xl bg-transparent",children:e.jsxs("div",{className:"flex items-center justify-between px-2 py-2",children:[e.jsx("span",{className:L("typography-meta font-medium",rt?"text-muted-foreground":"text-foreground"),children:"Auto-approve edits"}),e.jsx(yn,{checked:et,disabled:rt,onCheckedChange:at})]})})]})})},Jt=()=>e.jsx(ct,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ve?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:Ve.name||_t()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:Rt()})]}),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:mt.length>0?mt.map(({key:De,icon:ze,label:_e})=>Le(ze,_e,`cap-${De}`)):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:ft.length>0?ft.map(({key:De,icon:ze,label:_e})=>Le(ze,`${_e} input`,`input-${De}`)):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:Ke.length>0?Ke.map(({key:De,icon:ze,label:_e})=>Le(ze,`${_e} output`,`output-${De}`)):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)"}),yt.map(De=>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:De.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:De.value})]},De.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"}),Mt.map(De=>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:De.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:De.value})]},De.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:pu(Ve.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:hu(Ve.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),Lt=(De,ze,_e,st,nt,Ne)=>{const _=h(ze,_e),ve=Zi(_).map(it=>({...it,id:`cap-${it.key}`})),ae=[...jo(_,"input"),...jo(_,"output")],Fe=Array.from(new Map(ae.map(it=>[it.key,it])).values()).map(it=>({...it,id:`mod-${it.key}`})),$e=[...ve,...Fe],Ue=or(_?.limit?.context),Je=s===ze&&n===_e,ot=V(ze,_e),Et=st==="fav"||st==="recent";return e.jsxs("div",{ref:it=>{Q.current[nt]=it},className:L("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",Ne?"bg-accent":"hover:bg-accent/50"),onClick:()=>Tt(ze,_e),onMouseEnter:()=>oe(nt),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[Et&&e.jsx(ys,{providerId:ze,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Kt(De)}),_?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:Ue}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[$e.length>0&&e.jsx("div",{className:L("items-center gap-0.5",Ne?"flex":"hidden group-hover:flex"),children:$e.map(({id:it,icon:ts,label:gr})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":gr,role:"img",title:gr,children:e.jsx(ts,{className:"h-2.5 w-2.5"})},it))}),Je&&e.jsx(Pt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:it=>{it.preventDefault(),it.stopPropagation(),B(ze,_e)},className:L("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",ot?"text-yellow-500":"text-muted-foreground"),"aria-label":ot?"Unfavorite":"Favorite",title:ot?"Remove from favorites":"Add to favorites",children:ot?e.jsx(Fr,{className:"h-3.5 w-3.5"}):e.jsx(Gn,{className:"h-3.5 w-3.5"})})]})]},`${st}-${ze}-${_e}`)},ks=(De,ze,_e)=>_e.trim()?Js(De,_e)||Js(ze,_e):!0,Cs=()=>{const De=K.filter(({model:ae,providerID:Fe})=>{const Ue=r.find(ot=>ot.id===Fe)?.name||Fe,Je=Kt(ae);return ks(Je,Ue,me)}),ze=q.filter(({model:ae,providerID:Fe})=>{const Ue=r.find(ot=>ot.id===Fe)?.name||Fe,Je=Kt(ae);return ks(Je,Ue,me)}),_e=r.map(ae=>{const $e=(Array.isArray(ae.models)?ae.models:[]).filter(Ue=>{const Je=Kt(Ue);return ks(Je,ae.name||ae.id||"",me)});return{...ae,models:$e}}).filter(ae=>ae.models.length>0),st=De.length>0||ze.length>0||_e.length>0,nt=[];De.forEach(({model:ae,providerID:Fe,modelID:$e})=>{nt.push({model:ae,providerID:Fe,modelID:$e,section:"fav"})}),ze.forEach(({model:ae,providerID:Fe,modelID:$e})=>{nt.push({model:ae,providerID:Fe,modelID:$e,section:"recent"})}),_e.forEach(ae=>{ae.models.forEach(Fe=>{nt.push({model:Fe,providerID:ae.id,modelID:Fe.id,section:"provider"})})});const Ne=nt.length,_=ae=>{if(ae.key==="ArrowDown")ae.preventDefault(),ae.stopPropagation(),oe(Fe=>(Fe+1)%Math.max(1,Ne)),setTimeout(()=>{const Fe=(fe+1)%Math.max(1,Ne);Q.current[Fe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(ae.key==="ArrowUp")ae.preventDefault(),ae.stopPropagation(),oe(Fe=>(Fe-1+Math.max(1,Ne))%Math.max(1,Ne)),setTimeout(()=>{const Fe=(fe-1+Math.max(1,Ne))%Math.max(1,Ne);Q.current[Fe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(ae.key==="Enter"){ae.preventDefault(),ae.stopPropagation();const Fe=nt[fe];Fe&&Tt(Fe.providerID,Fe.modelID)}else ae.key==="Escape"&&(ae.preventDefault(),ae.stopPropagation(),ee(!1))};let ve=0;return e.jsxs(dt,{delayDuration:1e3,children:[X?e.jsxs("button",{type:"button",onClick:()=>z("model"),onTouchStart:()=>se("model"),onTouchEnd:ie,onTouchCancel:ie,className:L("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",Ce),children:[s?e.jsx(ys,{providerId:s,className:L(He,"flex-shrink-0")}):e.jsx(Tr,{className:L(He,"text-muted-foreground")}),e.jsx("span",{ref:Gt,className:L("model-controls__model-label typography-micro font-medium overflow-hidden min-w-0",$?"max-w-[120px]":"max-w-[220px]"),children:e.jsx("span",{className:L("marquee-text",It&&"marquee-text--active"),children:Yt})})]}):e.jsxs(rs,{open:ge,onOpenChange:ee,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ns,{asChild:!0,children:e.jsxs("div",{className:L("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",Ce),children:[s?e.jsxs(e.Fragment,{children:[e.jsx(ys,{providerId:s,className:L(He,"flex-shrink-0")}),e.jsx(Tr,{className:L(He,"text-primary/60 hidden")})]}):e.jsx(Tr,{className:L(He,"text-muted-foreground")}),e.jsx("span",{ref:Gt,className:L("model-controls__model-label overflow-hidden",Se,"font-medium whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:e.jsx("span",{className:L("marquee-text",It&&"marquee-text--active"),children:Yt})},`${s}-${n}`)]})})}),e.jsxs(os,{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(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(wt,{type:"text",placeholder:"Search models",value:me,onChange:ae=>le(ae.target.value),onKeyDown:_,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(gt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!st&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),De.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Rr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),De.map(({model:ae,providerID:Fe,modelID:$e})=>{const Ue=ve++;return Lt(ae,Fe,$e,"fav",Ue,fe===Ue)})]}),ze.length>0&&e.jsxs(e.Fragment,{children:[De.length>0&&e.jsx(Ds,{}),e.jsxs(Rr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(kr,{className:"h-4 w-4"}),"Recent"]}),ze.map(({model:ae,providerID:Fe,modelID:$e})=>{const Ue=ve++;return Lt(ae,Fe,$e,"recent",Ue,fe===Ue)})]}),(De.length>0||ze.length>0)&&_e.length>0&&e.jsx(Ds,{}),_e.map((ae,Fe)=>e.jsxs(i.Fragment,{children:[Fe>0&&e.jsx(Ds,{}),e.jsxs(Rr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ys,{providerId:ae.id,className:"h-4 w-4 flex-shrink-0"}),ae.name]}),ae.models.map($e=>{const Ue=ve++;return Lt($e,ae.id,$e.id,"provider",Ue,fe===Ue)})]},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"})]})]}),Jt()]})},Dt=()=>{if(!ue)return e.jsx(ct,{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 De=!!(ue.prompt&&ue.prompt.trim().length>0),ze=ue.model?.providerID&&ue.model?.modelID,_e=ue.temperature!==void 0||ue.topP!==void 0,st=ve=>{const ae=ql(ue.permission)??[],Fe=ae.some(Ue=>Ue.permission===ve&&Ue.pattern!=="*"),$e=Xi(ae,ve)??"ask";return Fe?{mode:"ask",label:"Custom"}:$e==="allow"?{mode:"allow",label:"Allow"}:$e==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},nt=st("edit"),Ne=st("bash"),_=st("webfetch");return e.jsx(ct,{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:Te(ue.name)}),ue.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:ue.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:ue.mode==="primary"?"Primary":ue.mode==="subagent"?"Subagent":ue.mode==="all"?"All":"—"})]}),(ze||_e)&&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"}),ze?e.jsxs("span",{className:"typography-meta text-foreground",children:[ue.model.providerID," / ",ue.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),_e&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[ue.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:ue.temperature})]}),ue.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:ue.topP})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Permissions"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Xe(nt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:nt.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Xe(Ne.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ne.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Xe(_.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:_.label})]})]})]}),De&&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(ka,{className:"h-4 w-4 text-foreground"})]})]})})},Ot=()=>{if(!jt)return null;const De=o??"Default",ze=!o,_e=ze?"text-muted-foreground":"text-[color:var(--status-info)]";return X?e.jsxs("button",{type:"button",onClick:()=>z("variant"),className:L("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ce,"cursor-pointer hover:opacity-70"),children:[e.jsx(Cr,{className:L(He,"flex-shrink-0",_e)}),e.jsx("span",{className:L("model-controls__variant-label",Se,"font-medium truncate min-w-0",$&&"max-w-[60px]",_e),children:De})]}):e.jsxs(dt,{delayDuration:800,children:[e.jsxs(rs,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(ns,{asChild:!0,children:e.jsxs("div",{className:L("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Ce),children:[e.jsx(Cr,{className:L(He,"flex-shrink-0",_e)}),e.jsx("span",{className:L("model-controls__variant-label",Se,"font-medium min-w-0 truncate",W?"max-w-[180px]":void 0,_e),children:De})]})})}),e.jsxs(os,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Rr,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(Nt,{className:"typography-meta",onSelect:()=>gs(void 0),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:"Default"}),ze&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),lt.length>0&&e.jsx(Ds,{}),lt.map(st=>{const nt=o===st,Ne=st.charAt(0).toUpperCase()+st.slice(1);return e.jsx(Nt,{className:"typography-meta",onSelect:()=>gs(st),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:Ne}),nt&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},st)})]})]}),e.jsx(ct,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",De]})})]})},as=()=>X?e.jsxs("button",{type:"button",onClick:()=>z("agent"),onTouchStart:()=>se("agent"),onTouchEnd:ie,onTouchCancel:ie,className:L("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ce,"cursor-pointer hover:opacity-70"),children:[e.jsx(jn,{className:L(He,"flex-shrink-0",P?"":"text-muted-foreground"),style:P?{color:`var(${Gr(P).var})`}:void 0}),e.jsx("span",{className:L("model-controls__agent-label",Se,"font-medium truncate min-w-0",$&&"max-w-[60px]"),style:P?{color:`var(${Gr(P).var})`}:void 0,children:Ie()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(dt,{delayDuration:1e3,children:[e.jsxs(rs,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(ns,{asChild:!0,children:e.jsxs("div",{className:L("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Ce),children:[e.jsx(jn,{className:L(He,"flex-shrink-0",P?"":"text-muted-foreground"),style:P?{color:`var(${Gr(P).var})`}:void 0}),e.jsx("span",{className:L("model-controls__agent-label",Se,"font-medium min-w-0 truncate",W?"max-w-[220px]":void 0),style:P?{color:`var(${Gr(P).var})`}:void 0,children:Ie()})]})})}),e.jsxs(os,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[b.filter(De=>pa(De.mode)).map(De=>e.jsx(Nt,{className:"typography-meta",onSelect:()=>Qt(De.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:L("h-1 w-1 rounded-full agent-dot",Gr(De.name).class)}),e.jsx("span",{className:"font-medium",children:Te(De.name)})]}),De.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:De.description})]})},De.name)),e.jsx(Ds,{}),e.jsx("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:e.jsx("div",{className:"rounded-xl bg-transparent",children:e.jsxs("div",{className:"flex items-center justify-between px-2 py-2",children:[e.jsx("span",{className:L("typography-meta font-medium",rt?"text-muted-foreground":"text-foreground"),children:"Auto-approve edits"}),e.jsx(yn,{checked:et,disabled:rt,onCheckedChange:at})]})})})]})]}),Dt()]})}),hr=L("@container/model-controls flex items-center min-w-0",$&&"w-full",t);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:hr,children:e.jsxs("div",{className:L("flex items-center min-w-0 flex-1 justify-end",ke,$&&"overflow-hidden"),children:[Ot(),Cs(),as()]})}),Ye(),bt(),pt(),Ee(),Re()]})},Yj=t=>t?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(t):!0,xu=(t,r)=>{if(typeof t!="string"||t.length===0)return{sanitizedText:t,mention:null};const s=r.filter(o=>o.mode&&o.mode!=="primary");if(s.length===0||!t.includes("#"))return{sanitizedText:t,mention:null};let n=null;for(const o of s){const a=new RegExp(`#${o.name}\\b`,"gi");let l;for(;(l=a.exec(t))!==null;){const c=l.index,d=c+l[0].length,u=c>0?t[c-1]:null;if(!Yj(u))continue;const m={name:o.name,source:{value:l[0],start:c,end:d}};n||(n=m)}}return n?{sanitizedText:t,mention:n}:{sanitizedText:t,mention:null}},Tp=t=>({id:t.id,content:t.content,status:t.status||"pending",priority:t.priority||"medium"}),Kl=is()(hs((t,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async s=>{if(s){t({isLoading:!0});try{const n=be.getState().getDirectoryForSession(s),a=(n?await Oe.withDirectory(n,()=>Oe.getSessionTodos(s)):await Oe.getSessionTodos(s)).map(Tp);t(l=>{const c=new Map(l.sessionTodos);return c.set(s,a),{sessionTodos:c,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),t({isLoading:!1})}}},updateTodos:(s,n)=>{t(o=>{const a=new Map(o.sessionTodos);return a.set(s,n),{sessionTodos:a}})},getTodosForSession:s=>r().sessionTodos.get(s)||[],clearTodos:s=>{t(n=>{const o=new Map(n.sessionTodos);return o.delete(s),{sessionTodos:o}})}}),{name:"todo-store"})),Qj=(t,r)=>{const s=r.map(Tp);Kl.getState().updateTodos(t,s)},yu=[{variant:"shine",component:({children:t,className:r,...s})=>e.jsx(Bn.span,{...s,className:L("bg-[linear-gradient(110deg,#bfbfbf,35%,#000,50%,#bfbfbf,75%,#bfbfbf)] dark:bg-[linear-gradient(110deg,#404040,35%,#fff,50%,#404040,75%,#404040)]","bg-[length:200%_100%] bg-clip-text text-transparent",r),initial:{backgroundPosition:"200% 0"},animate:{backgroundPosition:"-200% 0"},transition:{repeat:Number.POSITIVE_INFINITY,duration:2,ease:"linear"},children:t})},{variant:"generate-effect",component:({children:t,className:r,...s})=>typeof t!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:t.split("").map((n,o)=>Ae.createElement(Bn.span,{...s,key:n+String(o),className:L("inline-block whitespace-pre text-primary-foreground",r),initial:{opacity:0,filter:"blur(4px)",rotateX:90,y:5},whileInView:{opacity:1,filter:"blur(0px)",rotateX:0,y:0},transition:{ease:"easeOut",duration:.3,delay:o*.015},viewport:{once:!0}},n))})},{variant:"glitch",component:({children:t,className:r,...s})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...s,className:L("invisible",r),children:t}),e.jsx("span",{...s,className:L("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",r),children:t}),e.jsx("span",{...s,className:L("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",r),children:t})]})},{variant:"hover-enter",component:({children:t,className:r,...s})=>{if(typeof t!="string")return null;const n=.25,o=.025,a=t.split("").map(l=>l===" "?" ":l);return e.jsxs(Bn.span,{...s,className:L("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",r),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((l,c)=>e.jsx(Bn.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))}),e.jsx("div",{className:L("absolute inset-0"),children:a.map((l,c)=>e.jsx(Bn.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))})]})}},{variant:"shake",component:({children:t,className:r,...s})=>e.jsx("span",{...s,className:L("text-primary-muted hover:animate-text-shake",r),children:t})},{variant:"hover-decoration",component:({children:t,className:r,...s})=>e.jsx("div",{className:L("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:e.jsx("span",{...s,className:L("text-primary-muted",r),children:t})})}];function el({variant:t="shine",className:r,...s}){const a=yu.find(l=>l.variant===t)?.component||yu[0].component;return e.jsx($m,{children:e.jsx(a,{...s,className:r})})}const bu=1500,Jj=2e3;function Xj({statusText:t,isGenericStatus:r,isWaitingForPermission:s,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:l}){const[c,d]=Ae.useState("idle"),[u,m]=Ae.useState(null),[f,p]=Ae.useState(!1),h=Ae.useRef(0),g=Ae.useRef(null),x=Ae.useRef(null),b=Ae.useRef(null),y=Ae.useRef(null),w=Ae.useRef(!1),S=Ae.useRef(!1),M=Ae.useRef(!1),N=Ae.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null),b.current&&(clearTimeout(b.current),b.current=null)},[]),v=Ae.useCallback((P,D)=>{N(),g.current=null,m(P),p(D),d("showing"),h.current=Date.now(),w.current=!0},[N]),A=Ae.useCallback(()=>{if(x.current)return;const P=Date.now()-h.current,D=Math.max(0,bu-P);x.current=setTimeout(()=>{x.current=null;const E=g.current;E&&v(E.text,E.permission)},D)},[v]),k=Ae.useCallback(P=>{if(N(),g.current=null,!w.current){d("idle"),m(null),l?.(!1);return}if(P==="done"&&o&&y.current===o){d("idle"),m(null),w.current=!1,l?.(!1);return}P==="done"&&o&&(y.current=o),d(P),m(null),l?.(!0),b.current=setTimeout(()=>{b.current=null,d("idle"),w.current=!1,l?.(!1)},Jj)},[N,o,l]);if(Ae.useEffect(()=>{if(n&&!M.current){M.current=!0,k("aborted");return}if(M.current=!!n,a&&!S.current){S.current=!0,k("done");return}if(!a&&S.current&&(S.current=!1),!(c==="done"||c==="aborted")&&t){const D=Date.now()-h.current;if(c==="idle"||!u)v(t,!!s);else if(t!==u||!!s!==f){if(r)return;D>=bu?v(t,!!s):(g.current={text:t,permission:!!s},A())}}},[t,s,n,a,c,u,f,v,k,A,r]),Ae.useEffect(()=>()=>N(),[N]),Ae.useEffect(()=>{const P=()=>{typeof document>"u"||document.visibilityState==="visible"&&(c==="done"||c==="aborted")&&(N(),d("idle"),m(null),w.current=!1)};return document.addEventListener("visibilitychange",P),()=>document.removeEventListener("visibilitychange",P)},[c,N]),c==="idle"&&!u)return null;let C,j=!0;c==="done"?(C="Done",j=!1):c==="aborted"?(C="Aborted",j=!1):u?C=u.charAt(0).toUpperCase()+u.slice(1):C="Working";const T=j?`${C}...`:C,I=c!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${I?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":C,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:c==="done"?e.jsx(el,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):c==="aborted"?e.jsx(el,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(el,{variant:"shine",className:"typography-ui-header",children:T})})})}const wu={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Zj=({todo:t})=>{const r=wu[t.status]||wu.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:L("flex-1 typography-ui-label",r.textClassName),children:t.content})})},vu=[],e0=({isWorking:t,statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:l,isComplete:c,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=i.useState(!1),h=be(D=>D.currentSessionId),g=Kl(D=>h?D.sessionTodos.get(h)??vu:vu),x=Kl(D=>D.loadTodos),{isMobile:b}=Me(),y=b||zt();i.useEffect(()=>{h&&x(h)},[h,x]);const w=i.useMemo(()=>{const D={in_progress:0,pending:1,completed:2,cancelled:3};return[...g].filter(E=>E.status!=="cancelled").sort((E,F)=>D[E.status]-D[F.status])},[g]),S=i.useMemo(()=>w.find(D=>D.status==="in_progress")||w.find(D=>D.status==="pending")||null,[w]),M=i.useMemo(()=>{const D=g.filter(F=>F.status!=="cancelled").length;return{completed:g.filter(F=>F.status==="completed").length,total:D}},[g]),N=w.some(D=>D.status==="in_progress"||D.status==="pending"),v=!m&&(o||!a),[A,k]=i.useState(!1),C=t||c||o||A||N||m,j=i.useRef(null);if(i.useEffect(()=>{if(!f)return;const D=E=>{j.current&&!j.current.contains(E.target)&&p(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[f]),!C)return null;const T=()=>p(D=>!D),I=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(Xn,{size:18,"aria-hidden":"true"})}):null,P=N?e.jsxs("button",{type:"button",onClick:T,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!y&&S?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:S.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[M.completed,"/",M.total]}),f?e.jsx(di,{className:"h-3.5 w-3.5"}):e.jsx(Ut,{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(Xn,{size:16,"aria-hidden":"true"}),"Aborted"]})}):v?e.jsx(Xj,{statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,completionId:l??null,isComplete:c,onResultVisibilityChange:k},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:j,children:[I,P,f&&N&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:L("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:[M.completed,"/",M.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:w.map(D=>e.jsx(Zj,{todo:D},D.id))})]})]})]})})},La=t=>!t||typeof t!="object"?!1:!!t.synthetic,ju=t=>!Array.isArray(t)||t.length===0?!1:t.every(r=>La(r)),t0=t=>!Array.isArray(t)||t.length===0?[]:t.some(s=>!La(s))&&t.some(n=>La(n))?t.filter(n=>!La(n)):t,s0={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function r0(t){const r=be(s=>!t||!s.sessionActivityPhase?"idle":s.sessionActivityPhase.get(t)??"idle");return i.useMemo(()=>{if(r==="idle")return s0;const s=r==="busy",n=r==="cooldown";return{phase:r,isWorking:s||n,isBusy:s,isCooldown:n}},[r])}function Lc(){const t=be(r=>r.currentSessionId);return r0(t)}const n0={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},Su=t=>t.role==="assistant",o0=t=>t.type==="reasoning",Fp=t=>t.type==="text",Nu=t=>{if(Fp(t))return t.text;const r=t;if(typeof r.text=="string")return r.text;if(typeof r.content=="string")return r.content;if(typeof r.value=="string")return r.value},ku=t=>(Fp(t)||o0(t),t.time),a0=t=>{if(t.tool)return t.tool;const r=t;return typeof r.name=="string"?r.name:"tool"};function Rp(){const{currentSessionId:t,messages:r,permissions:s,sessionAbortFlags:n}=be(zn(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:l}=Lc(),c=i.useMemo(()=>t?r.get(t)??[]:[],[t,r]),d=i.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=c.filter(C=>Su(C.info)&&!ju(C.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const g=[...h].sort((C,j)=>{const T=typeof C.info.time?.created=="number"?C.info.time.created:null,I=typeof j.info.time?.created=="number"?j.info.time.created:null;return T!==null&&I!==null&&T!==I?T-I:C.info.id.localeCompare(j.info.id)}),x=g[g.length-1];let b,y;const w=new Set(["edit","write","apply_patch"]);for(let C=(x.parts??[]).length-1;C>=0;C-=1){const j=x.parts?.[C];if(j)switch(j.type){case"reasoning":{const T=j.time??ku(j);(!T||typeof T.end>"u")&&!b&&(b="reasoning");break}case"tool":{const T=j.state?.status;if((T==="running"||T==="pending")&&!b){const I=a0(j);w.has(I)?b="editing":(b="tool",y=I)}break}case"text":{const T=Nu(j)??"";if(typeof T=="string"&&T.trim().length>0){const I=ku(j);(!I||typeof I.end>"u")&&!b&&(b="text")}break}}}const S={read:"reading file",write:"writing file",edit:"editing file",multiedit:"editing files",apply_patch:"applying patch",bash:"running command",grep:"searching content",glob:"finding files",list:"listing directory",task:"delegating task",webfetch:"fetching URL",websearch:"searching web",codesearch:"web code search",todowrite:"updating todos",todoread:"reading todos",skill:"learning skill",question:"asking question",plan_enter:"switching to planning",plan_exit:"switching to building"},M=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],N=C=>S[C]??`using ${C}`,v=()=>M[Math.floor(Math.random()*M.length)],A=b===void 0,k=b==="editing"?"editing file":b==="tool"&&y?N(y):b==="reasoning"?"thinking":b==="text"?"composing":v();return{activePartType:b,activeToolName:y,statusText:k,isGenericStatus:A}},[c]),u=i.useMemo(()=>{const h=t,g=h?n?.get(h)??null:null,x=!!(g&&!g.acknowledged);return{wasAborted:x,abortActive:x}},[t,n]),m=i.useMemo(()=>{if(u.wasAborted)return{...n0,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,g=o==="busy",x=l;let b="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?b="tooling":b=x?"cooldown":"streaming"),{activity:b,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:g,isCooldown:x,lifecyclePhase:g?"streaming":x?"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:x}},[o,a,l,d,u]),f=i.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const g=c.filter(y=>Su(y.info)&&!ju(y.parts));if(g.length===0)return{isActive:h,characterCount:0};const x=g[g.length-1];let b=0;return(x.parts??[]).forEach(y=>{if(y.type!=="text")return;const w=Nu(y)??"";typeof w=="string"&&w.trim().length>0&&(b+=w.length)}),{isActive:h,characterCount:b}},[c,a,d.activePartType]),p=i.useMemo(()=>{if(m.wasAborted||m.abortActive)return m;const h=t;return(h?s?.get(h)??[]:[]).length>0?{...m,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:m},[t,s,m]);return{forming:f,working:p}}const i0=8,Cu=[],l0=t=>t==="primary"||t==="all"||t===void 0||t===null,c0=t=>{if(!Array.isArray(t))return null;const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},d0=(t,r)=>{const s=c0(t);if(!(!s||s.length===0)){for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},ga=({onOpenSettings:t,scrollToBottom:r})=>{const[s,n]=i.useState(""),[o,a]=i.useState(!1),[l,c]=i.useState(!1),[d,u]=i.useState(""),[m,f]=i.useState(!1),[p,h]=i.useState(""),[g,x]=i.useState(!1),[b,y]=i.useState(""),[w,S]=i.useState(!1),[M,N]=i.useState(""),[v,A]=i.useState(null),k=i.useRef(null),C=i.useRef(null),j=i.useRef(null),T=i.useRef(null),I=i.useRef(null),P=i.useRef(null),D=be(_=>_.sendMessage),E=be(_=>_.currentSessionId),F=be(_=>_.newSessionDraft?.open),B=be(_=>_.abortCurrentOperation),V=be(_=>_.acknowledgeSessionAbort),ne=be(_=>_.abortPromptSessionId),O=be(_=>_.abortPromptExpiresAt),G=be(_=>_.clearAbortPrompt),K=be(_=>_.sessionAbortFlags),q=be(_=>_.attachedFiles),$=be(_=>_.addAttachedFile),W=be(_=>_.addServerFile),Y=be(_=>_.clearAttachedFiles),X=be(_=>_.saveSessionAgentSelection),Z=be(_=>_.consumePendingInputText),z=be(_=>_.pendingInputText),{currentProviderId:R,currentModelId:de,currentVariant:we,currentAgentName:xe,setAgent:Pe,getVisibleAgents:H}=Ze(),ye=H(),{isMobile:J,inputBarOffset:ce,isKeyboardOpen:ge,setTimelineDialogOpen:ee,cornerRadius:me}=Me(),{working:le}=Rp(),[fe,oe]=i.useState(!1),Q=i.useRef(null),re=i.useRef(!1),ue=i.useRef(!1),he=wr(_=>_.queueModeEnabled),Ge=wr(i.useCallback(_=>E?_.queuedMessages[E]??Cu:Cu,[E])),qe=wr(_=>_.addToQueue),et=wr(_=>_.clearQueue),{phase:rt}=Lc(),vt=i.useRef(rt),Ce=i.useRef(!1),pe=i.useCallback(_=>{if(!J||_.pointerType!=="touch")return;const ve=k.current;if(!ve||document.activeElement===ve)return;_.preventDefault(),_.stopPropagation();const ae=document.scrollingElement;ae&&ae.scrollTop!==0&&(ae.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{ve.focus({preventScroll:!0})}catch{ve.focus()}const Fe=ve.value.length;try{ve.setSelectionRange(Fe,Fe)}catch{}},[J]);i.useEffect(()=>{if(z!==null){const _=Z();_&&(n(_),setTimeout(()=>{k.current?.focus()},0))}},[z,Z]);const He=i.useMemo(()=>{const _=E&&tt.getState().getSessionAgentSelection(E)||xe;if(_)return ye.find(ve=>ve.name===_)},[ye,xe,E]),Se=i.useMemo(()=>He?d0(He.permission,"edit")??"allow":"deny",[He]),ke=tt(i.useCallback(_=>{if(!xe)return;const ve=E??"__global__";return _.getSessionAgentEditMode(ve,xe,"ask")},[xe,E])),Xe=!!(E&&xe),at=i.useMemo(()=>{if(Se==="allow")return"allow";if(Se!=="ask")return"ask";const _=Xe?ke??"ask":"ask";return _==="allow"||_==="full"?"allow":"ask"},[Se,Xe,ke]),We=i.useMemo(()=>Cp(at),[at]),Be=i.useCallback(_=>zt()?`color-mix(in srgb, ${_} 55%, transparent)`:_,[]),Ve=i.useMemo(()=>{const _=zt()?1:2,ve={borderRadius:me};if(!We)return{...ve,borderWidth:_};const ae=We.border??We.text;return{...ve,borderColor:Be(ae),borderWidth:_}},[We,Be,me]),mt=s.trim()||q.length>0,ft=Ge.length>0,Ke=mt||ft,lt=le.isWorking,jt=i.useMemo(()=>E?ne===E&&!!O:!1,[ne,O,E]),yt=i.useCallback(()=>{if(!mt||!E)return;const _=s.replace(/^\n+|\n+$/g,""),ve=q.map(ae=>({...ae}));qe(E,{content:_,attachments:ve.length>0?ve:void 0}),n(""),ve.length>0&&Y(),J||k.current?.focus()},[mt,E,s,q,qe,Y,J]),Mt=async _=>{if(_?.preventDefault(),!Ke||!E&&!F)return;if(r?.({instant:!0,force:!0}),!R||!de){console.warn("Cannot send message: provider or model not selected");return}let ve="",ae=[],Fe;const $e=[];for(let ot=0;ot<Ge.length;ot++){const Et=Ge[ot],{sanitizedText:it,mention:ts}=xu(Et.content,ye);!Fe&&ts?.name&&(Fe=ts.name),ot===0?(ve=it,ae=Et.attachments??[]):$e.push({text:it,attachments:Et.attachments})}if(mt){const ot=s.replace(/^\n+|\n+$/g,""),{sanitizedText:Et,mention:it}=xu(ot,ye),ts=q.map(gr=>({...gr}));!Fe&&it?.name&&(Fe=it.name),Ge.length===0?(ve=Et,ae=ts):$e.push({text:Et,attachments:ts.length>0?ts:void 0})}if(!ve&&$e.length===0)return;E&&ft&&et(E),n(""),q.length>0&&Y(),J&&k.current?.blur();const Ue=ve.trimStart();if(Ue.startsWith("/")){const ot=Ue.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(ot==="undo"&&E){await be.getState().handleSlashUndo(E),r?.({instant:!0,force:!0});return}else if(ot==="redo"&&E){await be.getState().handleSlashRedo(E),r?.({instant:!0,force:!0});return}else if(ot==="timeline"&&E){ee(!0),n("");return}else if(ot==="compact"&&E){try{const{opencodeClient:Et}=await js(async()=>{const{opencodeClient:gr}=await Promise.resolve().then(()=>_y);return{opencodeClient:gr}},void 0),it=Et.getDirectory();if((await Et.getApiClient().session.summarize({sessionID:E,directory:it||void 0,providerID:R,modelID:de})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(Et){console.error("Failed to compact session:",Et),U.error("Failed to compact session")}n("");return}}const Je=[...ae,...$e.flatMap(ot=>ot.attachments??[])];D(ve,R,de,xe,ae,Fe,$e.length>0?$e:void 0,we).catch(ot=>{const Et=ot instanceof Error?ot.message:typeof ot=="string"?ot:String(ot??""),it=Et.toLowerCase();console.error("Message send failed:",Et||ot);const ts=it.includes("timeout")||it.includes("timed out")||it.includes("may still be processing")||it.includes("being processed")||it.includes("failed to fetch")||it.includes("networkerror")||it.includes("network error")||it.includes("gateway timeout")||it==="failed to send message";if(it.includes("payload too large")||it.includes("413")||it.includes("entity too large")){U.error("Attachments are too large to send. Please try reducing the number or size of images."),Je.length>0&&fr.setState({attachedFiles:Je});return}ts||(Je.length>0&&fr.setState({attachedFiles:Je}),U.error(Et||"Message failed to send. Attachments restored."))}),J||k.current?.focus()},es=i.useRef(Mt);es.current=Mt,i.useEffect(()=>{const _=vt.current==="busy"||vt.current==="cooldown",ve=rt==="idle",ae=E&&K.has(E)&&(()=>{const Fe=K.get(E);return Fe?Date.now()-Fe.timestamp<2e3:!1})();_&&ve&&Ge.length>0&&!Ce.current&&!ae&&(Ce.current=!0,setTimeout(()=>{E&&R&&de&&es.current(),Ce.current=!1},100)),vt.current=rt},[rt,Ge.length,E,R,de,K]);const Ht=_=>{if(!Tc(_)){if(m&&T.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),T.current.handleKeyDown(_.key);return}if(g&&I.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),I.current.handleKeyDown(_.key);return}if(w&&P.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),P.current.handleKeyDown(_.key);return}if(l&&j.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),j.current.handleKeyDown(_.key);return}if(_.key==="Tab"&&!m&&!g&&!l){_.preventDefault(),gs();return}if(_.key==="Enter"&&!_.shiftKey&&!J){_.preventDefault();const ve=_.ctrlKey||_.metaKey,ae=mt&&E&&rt!=="idle";he?ve||!ae?Mt():yt():ve&&ae?yt():Mt()}}},Wt=i.useCallback(()=>{Q.current&&(clearTimeout(Q.current),Q.current=null),oe(!0),Q.current=setTimeout(()=>{oe(!1),Q.current=null},1800)},[]),kt=i.useCallback(()=>{G(),Wt(),B()},[B,G,Wt]),gs=()=>{const _=ye.filter($e=>l0($e.mode));if(_.length<=1)return;const ae=(_.findIndex($e=>$e.name===xe)+1)%_.length,Fe=_[ae];Pe(Fe.name),E&&X(E,Fe.name)},Qt=i.useCallback(()=>{const _=k.current;if(!_)return;_.style.height="auto";const ve=_.ownerDocument?.defaultView,ae=ve?ve.getComputedStyle(_):null,Fe=ae?parseFloat(ae.lineHeight):NaN,$e=ae?parseFloat(ae.paddingTop):NaN,Ue=ae?parseFloat(ae.paddingBottom):NaN,Je=22,Et=Number.isNaN($e)||Number.isNaN(Ue)?16:$e+Ue,ts=(Number.isNaN(Fe)?Je:Fe)*i0+Et,gr=_.scrollHeight||_.offsetHeight,Wr=Math.min(gr,ts);_.style.height=`${Wr}px`,_.style.maxHeight=`${ts}px`,A(Xo=>Xo&&Xo.height===Wr&&Xo.maxHeight===ts?Xo:{height:Wr,maxHeight:ts})},[]);i.useLayoutEffect(()=>{Qt()},[Qt,s,J]);const Tt=i.useCallback((_,ve)=>{if(_.startsWith("/")){const Je=_.indexOf(" "),ot=_.indexOf(`
|
|
166
|
+
`),Et=Math.min(Je===-1?_.length:Je,ot===-1?_.length:ot);if(ve<=Et&&Je===-1){const it=_.substring(1,Et);h(it),f(!0),c(!1),x(!1),S(!1);return}}f(!1);const ae=_.substring(0,ve),Fe=ae.lastIndexOf("#");if(Fe!==-1){const Je=Fe>0?ae[Fe-1]:null,ot=ae.substring(Fe+1),Et=ot.includes(" ")||ot.includes(`
|
|
167
|
+
`);if((!Je||/\s/.test(Je))&&!Et){y(ot),x(!0),c(!1);return}}x(!1),y("");const $e=ae.lastIndexOf("/");if($e!==-1){const Je=$e>0?ae[$e-1]:null,ot=ae.substring($e+1),Et=ot.includes(" ")||ot.includes(`
|
|
168
|
+
`);if((!Je||/\s/.test(Je))&&!Et){N(ot),S(!0),c(!1),x(!1);return}}S(!1),N("");const Ue=ae.lastIndexOf("@");if(Ue!==-1){const Je=ae.substring(Ue+1);!Je.includes(" ")&&!Je.includes(`
|
|
169
|
+
`)?(u(Je),c(!0)):c(!1)}else c(!1)},[y,h,u,x,f,c,S,N]),Kt=i.useCallback(_=>{if(!_)return;const ve=k.current;if(!ve){const Je=s+_;n(Je),Tt(Je,Je.length),requestAnimationFrame(()=>Qt());return}const ae=ve.selectionStart??s.length,Fe=ve.selectionEnd??s.length,$e=`${s.substring(0,ae)}${_}${s.substring(Fe)}`;n($e);const Ue=ae+_.length;requestAnimationFrame(()=>{const Je=k.current;Je&&(Je.selectionStart=Ue,Je.selectionEnd=Ue),Qt()}),Tt($e,Ue)},[Qt,s,Tt]),Rt=_=>{const ve=_.target.value,ae=_.target.selectionStart??ve.length;n(ve),Qt(),Tt(ve,ae)},_t=i.useCallback(async _=>{const ve=new Map;Array.from(_.clipboardData.files||[]).forEach(Ue=>{Ue.type.startsWith("image/")&&ve.set(`${Ue.name}-${Ue.size}`,Ue)}),Array.from(_.clipboardData.items||[]).forEach(Ue=>{if(Ue.kind==="file"&&Ue.type.startsWith("image/")){const Je=Ue.getAsFile();Je&&ve.set(`${Je.name}-${Je.size}`,Je)}});const ae=Array.from(ve.values());if(ae.length===0||!E&&!F)return;_.preventDefault();const Fe=_.clipboardData.getData("text");Fe&&Kt(Fe);let $e=0;for(const Ue of ae){const Je=be.getState().attachedFiles.length;try{await $(Ue),be.getState().attachedFiles.length>Je&&($e+=1)}catch(ot){console.error("Clipboard image attach failed",ot),U.error(ot instanceof Error?ot.message:"Failed to attach image from clipboard")}}$e>0&&U.success(`Attached ${$e} image${$e>1?"s":""} from clipboard`)},[$,E,F,Kt]),Yt=_=>{const ve=k.current?.selectionStart||0,Fe=s.substring(0,ve).lastIndexOf("@");if(Fe!==-1){const $e=s.substring(0,Fe)+_.name+s.substring(ve);n($e)}c(!1),u(""),k.current?.focus()},Gt=_=>{const ae=k.current?.selectionStart??s.length,$e=s.substring(0,ae).lastIndexOf("#");if($e!==-1){const Ue=s.substring(0,$e)+`#${_} `+s.substring(ae);n(Ue);const Je=$e+_.length+2;requestAnimationFrame(()=>{k.current&&(k.current.selectionStart=Je,k.current.selectionEnd=Je),Qt(),Tt(Ue,Je)})}x(!1),y(""),k.current?.focus()},It=_=>{const ae=k.current?.selectionStart??s.length,$e=s.substring(0,ae).lastIndexOf("/");if($e!==-1){const Ue=s.substring(0,$e)+`${_} `+s.substring(ae);n(Ue);const Je=$e+_.length+1;requestAnimationFrame(()=>{k.current&&(k.current.selectionStart=Je,k.current.selectionEnd=Je),Qt(),Tt(Ue,Je)})}S(!1),N(""),k.current?.focus()},Ie=_=>{n(`/${_.name} `);const ve=k.current;ve&&(ve._commandMetadata=_),f(!1),h(""),setTimeout(()=>{k.current&&(k.current.focus(),k.current.setSelectionRange(k.current.value.length,k.current.value.length))},0)};i.useEffect(()=>{E&&k.current&&!J&&k.current.focus()},[E,J]),i.useEffect(()=>{ne&&ne!==E&&G()},[ne,E,G]);const Te=_=>{_.preventDefault(),_.stopPropagation(),(E||F)&&!o&&a(!0)},Le=_=>{_.preventDefault(),_.stopPropagation(),_.currentTarget===_.target&&a(!1)},te=async _=>{if(_.preventDefault(),_.stopPropagation(),a(!1),!E&&!F)return;const ve=Array.from(_.dataTransfer.files);let ae=0;for(const Fe of ve){const $e=be.getState().attachedFiles.length;try{await $(Fe),be.getState().attachedFiles.length>$e&&(ae+=1)}catch(Ue){console.error("File attach failed",Ue),U.error(Ue instanceof Error?Ue.message:"Failed to attach file")}}ae>0&&U.success(`Attached ${ae} file${ae>1?"s":""}`)},se=i.useCallback(async _=>{let ve=0;for(const ae of _){const Fe=be.getState().attachedFiles.length;try{await W(ae.path,ae.name),be.getState().attachedFiles.length>Fe&&(ve+=1)}catch($e){console.error("Server file attach failed",$e),U.error($e instanceof Error?$e.message:"Failed to attach file")}}ve>0&&U.success(`Attached ${ve} file${ve>1?"s":""}`)},[W]),ie=i.useRef(null),[Ee,Re]=i.useState(!1),Ye=i.useCallback(async _=>{let ve=0;const ae=Array.isArray(_)?_:Array.from(_);for(const Fe of ae){const $e=be.getState().attachedFiles.length;try{await $(Fe),be.getState().attachedFiles.length>$e&&(ve+=1)}catch(Ue){console.error("File attach failed",Ue),U.error(Ue instanceof Error?Ue.message:"Failed to attach file")}}ve>0&&U.success(`Attached ${ve} file${ve>1?"s":""}`)},[$]),bt=i.useCallback(async()=>{try{const ve=await(await fetch("/api/vscode/pick-files")).json(),ae=Array.isArray(ve?.files)?ve.files:[],Fe=Array.isArray(ve?.skipped)?ve.skipped:[];if(Fe.length>0){const Ue=Fe.map(Je=>`${Je?.name||"file"}: ${Je?.reason||"skipped"}`).join(`
|
|
170
|
+
`);U.error(`Some files were skipped:
|
|
171
|
+
${Ue}`)}const $e=ae.map(Ue=>{if(!Ue?.dataUrl)return null;try{const[Je,ot]=Ue.dataUrl.split(","),Et=Ue.mimeType||Je?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!ot)return null;const it=atob(ot),ts=new Uint8Array(it.length);for(let Wr=0;Wr<it.length;Wr++)ts[Wr]=it.charCodeAt(Wr);const gr=new Blob([ts],{type:Et});return new File([gr],Ue.name||"file",{type:Et})}catch(Je){return console.error("Failed to decode VS Code picked file",Je),null}}).filter(Boolean);$e.length>0&&await Ye($e)}catch(_){console.error("VS Code file pick failed",_),U.error(_ instanceof Error?_.message:"Failed to pick files in VS Code")}},[Ye]),pt=i.useCallback(()=>{if(zt()){bt();return}ie.current?.click()},[bt]),Jt=i.useCallback(async _=>{const ve=_.target.files;ve&&(await Ye(ve),_.target.value="")},[Ye]),Lt="gap-x-1.5 gap-y-0",ks=zt(),Cs=J?"px-1.5 py-1.5":ks?"px-1.5 py-1":"px-2.5 py-1.5",Dt=J?"h-9 w-9":ks?"h-[22px] w-[22px]":"h-7 w-7",Ot=J?"h-5 w-5":ks?"h-4 w-4":"h-[18px] w-[18px]",as=L(Dt,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),De=!J&&jt&<?e.jsx("button",{type:"button",onClick:kt,className:L(as,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(Xn,{className:L(Ot)})}):e.jsx("button",{type:J?"button":"submit",disabled:!Ke||!E&&!F,onPointerDownCapture:_=>{!J||_.pointerType!=="touch"||!Ke||!E&&!F||(ue.current=!0,_.preventDefault(),_.stopPropagation(),Mt())},onClick:_=>{if(J){if(ue.current){ue.current=!1;return}_.preventDefault(),Mt()}},className:L(as,Ke&&(E||F)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Uo,{className:L(Ot)})}),ze=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:ie,type:"file",multiple:!0,className:"hidden",onChange:Jt,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(zj,{onFilesSelected:se,multiSelect:!0,presentation:J?"modal":"dropdown",open:Ee,onOpenChange:Re,children:J?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsx("button",{type:"button",className:as,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(qm,{className:L(Ot,"text-current")})})}),e.jsxs(os,{align:"start",children:[e.jsxs(Nt,{onSelect:()=>{requestAnimationFrame(()=>pt())},children:[e.jsx(Wa,{}),"Attach files"]}),e.jsxs(Nt,{onSelect:()=>{requestAnimationFrame(()=>{Re(!0)})},children:[e.jsx(ax,{}),"Attach from project"]})]})]})]})]}),_e=t?e.jsx("button",{type:"button",onClick:t,className:as,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(jn,{className:L(Ot,"text-current")})}):null,st=e.jsxs(e.Fragment,{children:[ze,_e]}),nt=le.statusText;i.useEffect(()=>{const _=!!le.wasAborted;!re.current&&_&&!fe&&(Wt(),E&&V(E)),re.current=_},[V,E,fe,Wt,le.wasAborted]),i.useEffect(()=>()=>{Q.current&&(clearTimeout(Q.current),Q.current=null)},[]);const Ne=J&<return e.jsxs("form",{onSubmit:Mt,className:L("relative pt-0 pb-2 md:pb-4",J&&ge?"ios-keyboard-safe-area":"bottom-safe-area"),"data-keyboard-avoid":"true",style:J&&ce>0&&!ge?{marginBottom:`${ce}px`}:void 0,children:[e.jsx("div",{className:"absolute bottom-full left-0 right-0",children:e.jsx(e0,{isWorking:le.isWorking,statusText:nt,isGenericStatus:le.isGenericStatus,isWaitingForPermission:le.isWaitingForPermission,wasAborted:le.wasAborted,abortActive:le.abortActive,completionId:le.lastCompletionId,isComplete:le.isComplete,showAbort:Ne,onAbort:kt,showAbortStatus:fe})}),e.jsxs("div",{ref:C,className:L("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:Te,onDragLeave:Le,onDrop:te,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:as,onClick:()=>pt(),title:"Attach files","aria-label":"Attach files",children:e.jsx(Wa,{className:L(Ot,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(Lj,{}),e.jsx(Ap,{onEditMessage:_=>{n(_),setTimeout(()=>{k.current?.focus()},0)}}),e.jsxs("div",{className:L("border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:Ve,children:[m&&e.jsx(Ep,{ref:T,searchQuery:p,onCommandSelect:Ie,onClose:()=>f(!1)}),g&&e.jsx(Ip,{ref:I,searchQuery:b,onAgentSelect:Gt,onClose:()=>x(!1)}),w&&e.jsx(Pp,{ref:P,searchQuery:M,onSkillSelect:It,onClose:()=>S(!1)}),l&&e.jsx(Oj,{ref:j,searchQuery:d,onFileSelect:Yt,onClose:()=>c(!1)}),e.jsx(Fs,{ref:k,"data-chat-input":"true",value:s,onChange:Rt,onKeyDown:Ht,onPaste:_t,onPointerDownCapture:pe,placeholder:E||F?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!E&&!F,className:L("min-h-[52px] resize-none border-0 px-3 shadow-none rounded-b-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent",J?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:v?`${v.height}px`:void 0,maxHeight:v?`${v.maxHeight}px`:void 0,borderTopLeftRadius:me,borderTopRightRadius:me},rows:1}),e.jsx("div",{className:L("bg-transparent",Cs,J?"flex items-center gap-x-1.5":L("flex items-center justify-between",Lt)),style:{borderBottomLeftRadius:me,borderBottomRightRadius:me},"data-chat-input-footer":"true",children:J?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:st}),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(gu,{className:L("w-full flex items-center justify-end min-w-0")})}),De]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:L("flex items-center flex-shrink-0",Lt),children:st}),e.jsxs("div",{className:L("flex items-center flex-1 justify-end",Lt,"md:gap-x-3"),children:[e.jsx(gu,{className:L("flex-1 min-w-0 justify-end")}),De]})]})})]})]})]})};function tl({className:t,...r}){return e.jsx("div",{"data-slot":"skeleton",className:L("bg-accent animate-pulse rounded-xl",t),...r})}const Mu=(t,r,s,n,o=4)=>{const a=[];for(let l=0;l<o;l++)for(let c=0;c<o;c++){const d=c/o,u=(c+1)/o,m=l/o,f=(l+1)/o,p=(w,S,M)=>w+(S-w)*M,h=(w,S,M,N,v,A)=>{const k=p(w,S,v),C=p(N,M,v);return p(k,C,A)},g={x:h(t.x,r.x,s.x,n.x,d,m),y:h(t.y,r.y,s.y,n.y,d,m)},x={x:h(t.x,r.x,s.x,n.x,u,m),y:h(t.y,r.y,s.y,n.y,u,m)},b={x:h(t.x,r.x,s.x,n.x,u,f),y:h(t.y,r.y,s.y,n.y,u,f)},y={x:h(t.x,r.x,s.x,n.x,d,f),y:h(t.y,r.y,s.y,n.y,d,f)};a.push({path:`M${g.x} ${g.y} L${x.x} ${x.y} L${b.x} ${b.y} L${y.x} ${y.y} Z`,row:l,col:c})}return a},Oc=({className:t="",width:r=70,height:s=70,isAnimated:n=!1})=>{const o=Ni();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const l=a?"white":"black",c=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,h=50,g={x:50,y:h-m},x={x:50-m*f,y:h-m*p},b={x:50+m*f,y:h-m*p},y={x:50,y:h},w={x:50-m*f,y:h+m*p},S={x:50+m*f,y:h+m*p},M={x:50,y:h+m},v=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(g.y+x.y+y.y+b.y)/4})`,A=Mu(x,y,M,w),k=Mu(y,b,S,M),C=Ae.useMemo(()=>{const j=[];for(let T=0;T<32;T++)j.push(.1+Math.random()*.5);return j},[]);return e.jsxs("svg",{width:r,height:s,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,role:"img","aria-label":"OpenChamber logo",children:[e.jsx("path",{d:`M${y.x} ${y.y} L${x.x} ${x.y} L${w.x} ${w.y} L${M.x} ${M.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),A.map((j,T)=>e.jsx("path",{d:j.path,fill:u,opacity:C[T]},`left-${T}`)),e.jsx("path",{d:`M${y.x} ${y.y} L${b.x} ${b.y} L${S.x} ${S.y} L${M.x} ${M.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),k.map((j,T)=>e.jsx("path",{d:j.path,fill:u,opacity:C[T+16]},`right-${T}`)),e.jsx("path",{d:`M${g.x} ${g.y} L${x.x} ${x.y} L${y.x} ${y.y} L${b.x} ${b.y} Z`,fill:"none",stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${v} 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 u0({children:t,className:r,interval:s=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:l=!0,mode:c="popLayout"}){const[d,u]=Ae.useState(0),m=Ae.Children.toArray(t);Ae.useEffect(()=>{if(!l)return;const p=s*1e3,h=setInterval(()=>{u(g=>{const x=(g+1)%m.length;return a?.(x),x})},p);return()=>clearInterval(h)},[m.length,s,a,l]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:L("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(ix,{mode:c,initial:!1,children:e.jsx(Bn.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const m0=["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"],f0=()=>{const t=Ni();let r=!0;t?r=t.currentTheme.metadata.variant!=="light":typeof window<"u"&&(r=window.matchMedia("(prefers-color-scheme: dark)").matches);const s=r?"rgba(255,255,255,0.4)":"rgba(0,0,0,0.4)";return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[e.jsx(Oc,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(u0,{className:"text-body-md",interval:4,transition:{duration:.5},children:m0.map(n=>e.jsxs("span",{style:{color:s},children:['"',n,'…"']},n))})]})},sl=i.memo(f0),p0={'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"}},h0={'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 qr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return qr.instance||(qr.instance=new qr),qr.instance}recordSessionStart(r){this.sessionStartTimes.set(r,Date.now())}getSessionStartTime(r){return this.sessionStartTimes.get(r)}shouldAnimateMessage(r,s){if(r.role!=="assistant"||this.seenMessageIds.has(r.id))return!1;const n=this.sessionStartTimes.get(s);if(!n)return this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created),!1;const o=r.time.created>n-5e3;return o||(this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created)),o}clearSession(r){this.sessionStartTimes.delete(r)}hasSessionTiming(r){return this.sessionStartTimes.has(r)}hasBeenAnimated(r){return this.seenMessageIds.has(r)}markMessageAsAnimated(r,s){this.seenMessageIds.add(r),this.messageCreationTimes.set(r,s)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function Pi(t){const r=t.colors.syntax,s=t.colors.surface;return{'code[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"0",margin:"0",overflow:"auto"},comment:{color:r.base.comment,fontStyle:"italic"},prolog:{color:r.base.comment},doctype:{color:r.base.comment},cdata:{color:r.base.comment},punctuation:{color:r.tokens?.punctuation||s.mutedForeground},property:{color:r.tokens?.variableProperty||r.base.variable},tag:{color:r.tokens?.tag||r.base.keyword},"attr-name":{color:r.tokens?.tagAttribute||r.base.variable},"attr-value":{color:r.tokens?.tagAttributeValue||r.base.string},boolean:{color:r.tokens?.boolean||r.base.number},number:{color:r.base.number},constant:{color:r.tokens?.constant||r.base.number},symbol:{color:r.tokens?.constant||r.base.number},string:{color:r.base.string},char:{color:r.base.string},function:{color:r.base.function},builtin:{color:r.tokens?.functionBuiltin||r.base.function},"class-name":{color:r.tokens?.className||r.base.type},namespace:{color:r.tokens?.namespace||r.base.type,opacity:.8},keyword:{color:r.base.keyword},atrule:{color:r.base.keyword},selector:{color:r.base.function},operator:{color:r.base.operator},variable:{color:r.base.variable},regex:{color:r.tokens?.regex||r.base.string},url:{color:r.base.function,textDecoration:"underline"},entity:{color:r.base.function,cursor:"help"},".language-css .token.string":{color:r.base.string},".style .token.string":{color:r.base.string},deleted:{color:t.colors.status.error,backgroundColor:t.colors.status.errorBackground},inserted:{color:t.colors.status.success,backgroundColor:t.colors.status.successBackground},title:{color:t.colors.primary.base,fontWeight:"bold"},"code-block":{color:r.base.string},"code-snippet":{color:r.base.string},list:{color:r.base.variable},hr:{color:s.mutedForeground},table:{color:r.base.function},blockquote:{color:s.mutedForeground,fontStyle:"italic"},important:{color:r.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:r.tokens?.decorator||r.base.function},annotation:{color:r.tokens?.decorator||r.base.function}}}const g0=i.createContext(!1),pr=({children:t,className:r,skipAnimation:s})=>{const n=i.useContext(g0),o=s||n,[a,l]=i.useState(o);return i.useEffect(()=>{if(o)return;let c=null;const d=()=>l(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?c=window.requestAnimationFrame(d):d(),()=>{c!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(c)}},[o]),o?e.jsx(e.Fragment,{children:t}):e.jsx("div",{className:L("w-full transition-all duration-300 ease-out",a?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:t})},x0=({isUser:t,providerID:r,agentName:s,modelName:n,variant:o,isDarkTheme:a})=>{const{src:l,onError:c,hasLogo:d}=vp(r);return e.jsx(pr,{children:e.jsx("div",{className:L("mb-2"),children:e.jsx("div",{className:L("flex items-center justify-between gap-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0",children:t?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(sr,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&l?e.jsx("img",{src:l,alt:`${r} logo`,className:"h-4 w-4",style:{filter:a?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:c}):e.jsx(Cr,{className:"h-4 w-4",style:{color:`var(${Gr(s).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:L("font-bold typography-ui-header tracking-tight leading-none",t?"text-primary":"text-foreground"),children:t?"You":n||"Assistant"}),!t&&s&&e.jsxs("div",{className:L("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",Gr(s).class),children:[e.jsx(jn,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:s})]}),!t&&o&&e.jsxs("div",{className:L("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",o==="Default"?void 0:"agent-info"),style:o==="Default"?{"--agent-color":"var(--muted-foreground)","--agent-color-bg":"var(--muted-foreground)"}:void 0,children:[e.jsx(Cr,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:o.length>0?o[0].toLowerCase()+o.slice(1):o})]})]})]})})})})},y0=i.memo(x0),b0=t=>`https://opencode.ai/docs/agents/#${encodeURIComponent(t)}`,w0=({part:t,messageId:r,agentMention:s})=>{const n=t,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[l,c]=i.useState(!1),[d,u]=i.useState(!1),m=i.useRef(null);i.useEffect(()=>{const h=m.current;if(!h||l)return;const g=()=>{u(h.scrollHeight>h.clientHeight)};g();const x=new ResizeObserver(g);return x.observe(h),()=>x.disconnect()},[a,l]);const f=i.useCallback(()=>{(d||l)&&c(h=>!h)},[d,l]);if(!a||a.trim().length===0)return null;const p=()=>{if(!s?.token||!a.includes(s.token))return a;const h=a.indexOf(s.token),g=a.slice(0,h),x=a.slice(h+s.token.length);return e.jsxs(e.Fragment,{children:[g,e.jsx("a",{href:b0(s.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:b=>b.stopPropagation(),children:s.token}),x]})};return e.jsx("div",{className:L("break-words whitespace-pre-wrap font-sans typography-markdown",!l&&"line-clamp-3",(d||l)&&"cursor-pointer"),ref:m,onClick:f,children:p()},t.id||`${r}-user-text`)},v0=i.memo(w0),Du=(t,r)=>{const s=t[Symbol.toPrimitive];if(typeof s=="function")try{if(s()===r)return t}catch{}try{Object.defineProperty(t,"toString",{value:()=>r,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(t,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0})}catch{}return t},Au=()=>{if(!zt()||typeof window>"u")return Ud;const t=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(t?.light&&t?.dark){const r=Du({...t.light},`vscode-shiki-light:${String(t.light?.name??"theme")}`),s=Du({...t.dark},`vscode-shiki-dark:${String(t.dark?.name??"theme")}`);return[r,s]}return Ud},j0=()=>{const[t,r]=i.useState(Au);return i.useEffect(()=>{if(!zt()||typeof window>"u")return;const s=n=>{r(Au())};return window.addEventListener("openchamber:vscode-shiki-themes",s),()=>window.removeEventListener("openchamber:vscode-shiki-themes",s)},[]),t},Lp=t=>{const r=[],s=[],n=t.querySelector("thead");n&&n.querySelectorAll("th").forEach(l=>r.push(l.innerText.trim()));const o=t.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(l=>{const c=l.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),s.push(d)}),{headers:r,rows:s}},Op=({headers:t,rows:r})=>{const s=o=>o.includes(",")||o.includes('"')||o.includes(`
|
|
172
|
+
`)?`"${o.replace(/"/g,'""')}"`:o,n=[];return t.length>0&&n.push(t.map(s).join(",")),r.forEach(o=>n.push(o.map(s).join(","))),n.join(`
|
|
173
|
+
`)},S0=({headers:t,rows:r})=>{const s=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return t.length>0&&n.push(t.map(s).join(" ")),r.forEach(o=>n.push(o.map(s).join(" "))),n.join(`
|
|
174
|
+
`)},N0=({headers:t,rows:r})=>{if(t.length===0)return"";const s=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${t.map(s).join(" | ")} |`),n.push(`| ${t.map(()=>"---").join(" | ")} |`),r.forEach(o=>{const a=t.map((l,c)=>s(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
|
|
175
|
+
`)},k0=(t,r,s)=>{const n=new Blob([r],{type:s}),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)},C0=({tableRef:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(null);i.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const l=async c=>{const d=t.current?.querySelector("table");if(d)try{const u=Lp(d),m=c==="csv"?Op(u):S0(u);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([m],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),s(!0),o(!1),setTimeout(()=>s(!1),2e3)}catch(u){console.error("Failed to copy table:",u)}};return e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>o(!n),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:r?e.jsx(Pt,{className:"size-3.5"}):e.jsx(rr,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>l("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>l("tsv"),children:"TSV"})]})]})},M0=({tableRef:t})=>{const[r,s]=i.useState(!1),n=i.useRef(null);i.useEffect(()=>{const a=l=>{n.current&&!n.current.contains(l.target)&&s(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const l=t.current?.querySelector("table");if(l)try{const c=Lp(l),d=a==="csv"?Op(c):N0(c);k0(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),s(!1)}catch(c){console.error("Failed to download table:",c)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>s(!r),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(Zr,{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"})]})]})},D0=({children:t,className:r})=>{const s=i.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:s,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(C0,{tableRef:s}),e.jsx(M0,{tableRef:s})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:L("w-full border-collapse border border-border",r),"data-streamdown":"table",children:t})})]})},A0=({children:t,className:r,style:s,...n})=>{const[o,a]=i.useState(!1),l=i.useRef(null),c=i.useMemo(()=>{if(!s)return s;const m={...s},f=g=>{if(typeof g!="string")return{value:void 0,vars:{}};const[x,...b]=g.split(";").map(w=>w.trim()).filter(Boolean),y={};for(const w of b){const S=w.indexOf(":");if(S===-1)continue;const M=w.slice(0,S).trim(),N=w.slice(S+1).trim();!M.startsWith("--")||N.length===0||(y[M]=N)}return{value:x,vars:y}},p=f(s.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[g,x]of Object.entries(p.vars))m[g]=x;const h=f(s.color);h.value&&(m.color=h.value,m["--shiki-light"]=h.value);for(const[g,x]of Object.entries(h.vars))m[g]=x;return m},[s]),d=()=>l.current&&l.current.querySelector("code")?.innerText||"",u=async()=>{const m=d();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:l,children:[e.jsx("pre",{...n,className:L(r),style:c,children:t}),e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:u,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(Pt,{className:"size-3.5"}):e.jsx(rr,{className:"size-3.5"})})})]})},E0={pre:A0,table:D0},Nr=({content:t,className:r,variant:s="assistant"})=>{const n=j0(),o=s==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:L("break-words",r),children:e.jsx(lx,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:E0,children:t})})},I0=t=>{let r=t.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},P0=t=>t?t.includes("<file_diagnostics>")||t.includes("This file has errors")||t.includes("please fix"):!1,T0=t=>t?t.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Eu=(t,r)=>!t||typeof t!="object"?String(t):dv(t,r||""),rl=(t,r,s)=>{let n=I0(t);if((r==="edit"||r==="multiedit")&&P0(n)&&(n=T0(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&s?.diff){const o=s.diff;return typeof o=="string"?o:String(o)}return n},F0=(t,r)=>{try{const s=t.trim().split(`
|
|
176
|
+
`).filter(Boolean);if(s.length===0)return null;const n=[];return s.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,l,c]=a,d=Math.floor(l.length/2),u=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:L("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:Lr.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}},R0=(t,r,s)=>{try{const n=t.trim().split(`
|
|
177
|
+
`).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const l=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(l){const[,c,d,u]=l,m=u!==void 0?d:"",f=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].push({lineNum:m,content:f})}}),e.jsxs("div",{className:L("space-y-2 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Lr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,l])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:L("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:l.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:L("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}},L0=(t,r,s)=>{try{const n=t.trim().split(`
|
|
178
|
+
`).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(l=>{const c=l.lastIndexOf("/"),d=c>0?l.substring(0,c):"/",u=c>=0?l.substring(c+1):l;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:L("space-y-2 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Lr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(l=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:L("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[l,"/"]}),e.jsx("div",{className:L("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[l].sort().map(c=>e.jsxs("div",{className:L("flex items-center gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:c})]},c))})]},l))]})}catch{return null}},O0=(t,r)=>{try{const s=JSON.parse(t);if(!Array.isArray(s))return null;const n={in_progress:s.filter(a=>a.status==="in_progress"),pending:s.filter(a=>a.status==="pending"),completed:s.filter(a=>a.status==="completed"),cancelled:s.filter(a=>a.status==="cancelled")},o=a=>{const l="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:l,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:l,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:L("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Lr.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",s.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||l))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||l))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-3 h-3",style:{color:"var(--status-success)"}}),e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:"Completed"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.completed.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Pt,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||l))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||l))})]})]})}catch{return null}},_0=(t,r,s)=>{try{return e.jsx("div",{className:L("typography-code max-w-none w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:Lr.tool.popup,children:e.jsx(Nr,{content:t,variant:"tool"})})}catch{return null}},_p=t=>{const r=t.split(`
|
|
179
|
+
`);let s="";const n=[];let o=0;for(;o<r.length;){const a=r[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(s=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const l=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),c=l?parseInt(l[1]):0,d=l?parseInt(l[2]):0,u=[];let m=c,f=d,p=o+1;for(;p<r.length&&!r[p].startsWith("@@")&&!r[p].startsWith("Index:");){const h=r[p];h.startsWith("+")?(u.push({type:"added",lineNumber:f,content:h.substring(1)}),f++):h.startsWith("-")?(u.push({type:"removed",lineNumber:m,content:h.substring(1)}),m++):h.startsWith(" ")&&(u.push({type:"context",lineNumber:f,content:h.substring(1)}),m++,f++),p++}n.push({file:s,oldStart:c,newStart:d,lines:u}),o=p;continue}o++}return n},Yl=(t,r,s)=>lv(r,t,s),$p=t=>{const r="h-3.5 w-3.5 flex-shrink-0",s=t.toLowerCase();return s==="edit"||s==="multiedit"||s==="apply_patch"||s==="str_replace"||s==="str_replace_based_edit_tool"?e.jsx(Um,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(Km,{className:r}):s==="read"||s==="view"||s==="file_read"||s==="cat"?e.jsx(Qn,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"?e.jsx(tn,{className:r}):s==="list"||s==="ls"||s==="dir"||s==="list_files"?e.jsx(lr,{className:r}):s==="search"||s==="grep"||s==="find"||s==="ripgrep"?e.jsx(cx,{className:r}):s==="glob"?e.jsx(dx,{className:r}):s==="fetch"||s==="curl"||s==="wget"||s==="webfetch"?e.jsx(Ml,{className:r}):s==="web-search"||s==="websearch"||s==="search_web"||s==="codesearch"||s==="google"||s==="bing"||s==="duckduckgo"||s==="perplexity"?e.jsx(Ml,{className:r}):s==="todowrite"||s==="todoread"?e.jsx(Ym,{className:r}):s==="skill"?e.jsx(Qm,{className:r}):s==="question"?e.jsx(ux,{className:r}):s==="plan_enter"?e.jsx(mx,{className:r}):s==="plan_exit"?e.jsx(fx,{className:r}):s.startsWith("git")?e.jsx(Vt,{className:r}):e.jsx(mi,{className:r})},$0=(t,r,s=Date.now())=>{const o=(r?r-t:s-t)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},B0=({start:t,end:r,active:s})=>{const[n,o]=i.useState(()=>Date.now());return i.useEffect(()=>{if(!s)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[s]),e.jsx(e.Fragment,{children:$0(t,r,n)})},z0=t=>{if(!t?.diff||typeof t.diff!="string")return null;const r=t.diff.split(`
|
|
180
|
+
`);let s=0,n=0;for(const o of r)o.startsWith("+")&&!o.startsWith("+++")&&s++,o.startsWith("-")&&!o.startsWith("---")&&n++;return s===0&&n===0?null:{added:s,removed:n}},Oa=(t,r,s)=>{if(s)return t.split("/").pop()||t;if(t.startsWith(r)){const n=t.substring(r.length);return n.startsWith("/")?n.substring(1):n}return t},H0=t=>{const r=t.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!r)return null;const s=[],n=r[1],o=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let a;for(;(a=o.exec(n))!==null;)s.push({question:a[1],answer:a[2]});return s.length>0?s:null},W0=(t,r,s,n)=>{const o=r,a=o.metadata,l=o.input;if(t.tool==="apply_patch"){const d=Array.isArray(a?.files)?a?.files:[],u=d[0],m=u?.relativePath||u?.filePath;return d.length>1?`${d.length} files`:typeof m=="string"?Oa(m,n,s):"Patch"}if(t.tool==="question"&&l?.questions&&Array.isArray(l.questions)){const d=l.questions.length;return`Asked ${d} question${d!==1?"s":""}`}if((t.tool==="edit"||t.tool==="multiedit")&&l){const d=l?.filePath||l?.file_path||l?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return Oa(d,n,s)}if((t.tool==="read"||t.tool==="write")&&l){const d=l?.filePath||l?.file_path||l?.path;if(typeof d=="string")return Oa(d,n,s)}if(t.tool==="bash"&&l?.command&&typeof l.command=="string"){const d=l.command.split(`
|
|
181
|
+
`)[0];return s?d.substring(0,50):d.substring(0,100)}if(t.tool==="task"&&l?.description&&typeof l.description=="string")return s?l.description.substring(0,40):l.description.substring(0,80);if(t.tool==="skill"&&l?.name&&typeof l.name=="string")return l.name;if(t.tool==="plan_enter")return"Switching to planning";if(t.tool==="plan_exit")return"Switching to building";const c=l?.description||a?.description||"title"in r&&r.title||"";return typeof c=="string"?c:""},Ql=({children:t,maxHeightClass:r="max-h-[60vh]",className:s,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(gt,{outerClassName:L("w-full min-w-0 flex-none overflow-hidden",r,n),className:L("tool-output-surface p-2 rounded-xl w-full min-w-0 border border-border/20 bg-transparent",s),disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:t})}),U0=t=>{const r=t.state?.title;return typeof r=="string"&&r.trim().length>0?r:typeof t.tool=="string"&&t.tool.trim().length>0?t.tool:"tool"},V0=t=>t.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),G0=({entries:t,isExpanded:r,hasPrevTool:s,hasNextTool:n,output:o,sessionId:a})=>{const l=be(x=>x.setCurrentSession),c=i.useMemo(()=>t.filter(x=>x.state?.status==="completed"),[t]),d=typeof o=="string"?V0(o):"",u=d.length>0,[m,f]=i.useState(!1),p=x=>{x.stopPropagation(),a&&l(a)};if(c.length===0&&!u&&!a)return null;const h=r?c:c.slice(-6),g=Math.max(0,c.length-h.length);return e.jsxs("div",{className:L("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',s?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[c.length>0?e.jsx(Ql,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[g>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",g," more…"]}):null,h.map((x,b)=>{const y=typeof x.tool=="string"&&x.tool.trim().length>0?x.tool:"tool",w=U0(x),S=Cc(y).displayName;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:$p(y)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:S}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:w})]},x.id??`${y}-${b}`)})]})}):null,a&&e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:x=>x.stopPropagation(),onClick:p,children:[e.jsx(Xs,{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:L("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:x=>x.stopPropagation(),onClick:x=>{x.stopPropagation(),f(b=>!b)},children:[m?e.jsx(Ut,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(er,{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(Ql,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Nr,{content:d,variant:"tool"})})}):null]}):null]})},Bp=i.memo(({diff:t,syntaxTheme:r,input:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:_p(t).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,l)=>e.jsxs("div",{className:L("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Or,{style:r,language:Ar(typeof s?.file_path=="string"?s.file_path:typeof s?.filePath=="string"?s.filePath:n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},l))})]},o))}));Bp.displayName="DiffPreview";const zp=i.memo(({content:t,syntaxTheme:r,filePath:s,displayPath:n})=>{const o=i.useMemo(()=>t.split(`
|
|
182
|
+
`),[t]),a=i.useMemo(()=>Ar(s??"")||Yl(t,"write",s?{filePath:s}:void 0),[t,s]),l=Math.max(o.length,1),c=l===1?"line 1":`lines 1-${l}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${c})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Or,{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))})]})});zp.displayName="WriteInputPreview";const Hp=i.memo(({content:t,filePath:r,displayPath:s})=>{const n=zl(r),o=r.toLowerCase().endsWith(".svg"),a=i.useMemo(()=>o&&!t.startsWith("data:")?`data:image/svg+xml;base64,${btoa(t)}`:t.startsWith("data:")?t:`data:${n};base64,${t}`,[t,n,o]);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-2",children:s}),e.jsx("div",{className:"flex justify-center p-4 bg-muted/10 rounded-lg border border-border/10",children:e.jsx("img",{src:a,alt:s,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})});Hp.displayName="ImagePreview";const Wp=i.memo(({part:t,state:r,syntaxTheme:s,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:l})=>{const c=r,d=c.metadata,u=c.input,m=c.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",h=typeof d?.diff=="string"?d.diff:null,g=t.tool==="write"?typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0:void 0,x=t.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,b=t.tool==="write"&&!!x,y=g?zo(g):!1,w=b?g?Oa(g,o,n):"New file":null,S=i.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&t.tool==="bash"?Eu(u,t.tool):typeof u.content=="string"?u.content??"":Eu(u,t.tool),[u,t.tool]),M=t.tool!=="apply_patch"&&S.trim().length>0,N=(A,k)=>e.jsx(Ql,{maxHeightClass:k?.maxHeightClass,className:k?.className,disableHorizontal:k?.disableHorizontal,outerClassName:k?.outerClassName,children:A}),v=()=>{if(t.tool==="question"){if(r.status==="completed"&&f){const A=H0(p);if(A&&A.length>0)return N(e.jsx("div",{className:"space-y-2",children:A.map((k,C)=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:k.question}),e.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:k.answer})]},C))}),{maxHeightClass:"max-h-[40vh]"})}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(t.tool==="todowrite"||t.tool==="todoread"){if(r.status==="completed"&&f){const A=O0(p,{unstyled:!0});return N(A??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(t.tool==="list"&&f){const A=F0(p,{unstyled:!0});return N(A??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="grep"&&f){const A=R0(p,n,{unstyled:!0});return N(A??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="glob"&&f){const A=L0(p,n,{unstyled:!0});return N(A??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="task"&&f)return N(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Nr,{content:p,variant:"tool"})}));if((t.tool==="web-search"||t.tool==="websearch"||t.tool==="search_web")&&f){const A=_0(p,s,{unstyled:!0});return N(A??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="codesearch"&&f)return N(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Nr,{content:p,variant:"tool"})}));if(t.tool==="skill"&&f)return N(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Nr,{content:p,variant:"tool"})}));if((t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch")&&h)return N(e.jsx(Bp,{diff:h,syntaxTheme:s,input:u}),{className:"p-1"});if(f&&p.trim()){if(t.tool==="read"){const A=rl(p,t.tool,d),k=A.split(`
|
|
183
|
+
`),C=typeof u?.offset=="number"?u.offset:0,j=typeof u?.limit=="number"?u.limit:void 0,T=I=>I.trim().startsWith("(");return N(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:k.map((I,P)=>{const D=T(I),E=C+P+1,F=!D&&(j===void 0||P<j);return e.jsxs("div",{className:L("typography-code font-mono flex w-full min-w-0",D&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-3 self-start select-none",children:F?E:""}),e.jsx("div",{className:"flex-1 min-w-0",children:D?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:I}):e.jsx(Or,{style:s,language:Yl(A,t.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:I})})]},P)})}),{className:"p-1"})}return N(e.jsx(Or,{style:s,language:Yl(rl(p,t.tool,d),t.tool,u),PreTag:"div",customStyle:{...Ca.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:rl(p,t.tool,d)}),{className:"p-1"})}return N(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:L("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",l?"before:bottom-[-0.6rem]":"before:bottom-0"),children:t.tool==="todowrite"||t.tool==="todoread"||t.tool==="question"?v():e.jsxs(e.Fragment,{children:[b&&y?e.jsx("div",{className:"my-1",children:N(e.jsx(Hp,{content:x,filePath:g,displayPath:w??"New file"}))}):b?e.jsx("div",{className:"my-1",children:N(e.jsx(zp,{content:x,syntaxTheme:s,filePath:g,displayPath:w??"New file"}))}):M?e.jsx("div",{className:"my-1",children:N(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:S}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,t.tool!=="write"&&r.status==="completed"&&"output"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),v()]}),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})]})]})})});Wp.displayName="ToolExpandedContent";const Jl=({part:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:l=!1,hasNextTool:c=!1})=>{const d=t.state,u=xt(E=>E.currentDirectory),m=t.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",p=d.status==="running"||d.status==="pending",h=d.status==="error",g=i.useRef(r);i.useEffect(()=>{!f&&!m||g.current!==r&&(g.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const x=d,b=x.metadata,y=x.input,w=x.time,S=i.useRef({}),M=i.useRef(t.id);if(M.current!==t.id&&(M.current=t.id,S.current={}),m){if(typeof w?.start=="number"){const E=S.current.start;(typeof E!="number"||w.start<E)&&(S.current.start=w.start)}typeof w?.end=="number"&&(S.current.end=w.end)}const N=m?S.current.start??w?.start:w?.start,v=m?S.current.end??w?.end:w?.end,A=i.useMemo(()=>{if(!m)return;const E=b;return typeof E?.sessionId=="string"?E.sessionId:void 0},[m,b]),k=i.useMemo(()=>{if(!m)return[];const E=b?.summary;return Array.isArray(E)?E.filter(F=>typeof F=="object"&&F!==null):[]},[m,b]),C=i.useRef(k.length);i.useEffect(()=>{m&&C.current!==k.length&&(C.current=k.length,a?.("structural"))},[m,a,k.length]);const j=t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch"?z0(b):null,T=W0(t,d,o,u),I=Cc(t.tool).displayName,P=i.useContext(Nc),D=E=>{if(m||!P?.editor){s(t.id);return}let F;if((t.tool==="edit"||t.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(t.tool))&&(F=y?.filePath||y?.file_path||y?.path||b?.filePath||b?.file_path||b?.path),typeof F=="string"){E.stopPropagation();let B=F;F.startsWith("/")||(B=u.endsWith("/")?u+F:u+"/"+F),P.editor.openFile(B)}else s(t.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:L("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:D,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:E=>{E.stopPropagation(),s(t.id)},children:[e.jsx("div",{className:L("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&h?{color:"var(--status-error)"}:{},children:$p(t.tool)}),e.jsx("div",{className:L("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(Ut,{className:"h-3.5 w-3.5"}):e.jsx(er,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:I})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[T&&e.jsx("span",{className:L("truncate",o&&"max-w-[120px]"),children:T}),j&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",j.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",j.removed]})]}),typeof N=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(B0,{start:N,end:typeof v=="number"?v:void 0,active:!!(m&&p&&typeof v!="number")})})]})]}),m&&(k.length>0||p||f||A)?e.jsx(G0,{entries:k,isExpanded:r,hasPrevTool:l,hasNextTool:c,output:typeof x.output=="string"?x.output:void 0,sessionId:A}):null,!m&&r?e.jsx(Wp,{part:t,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:l,hasNextTool:c}):null]})},q0={thinking:{label:"Thinking",Icon:Cr},justification:{label:"Justification",Icon:lc}},K0=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
|
|
184
|
+
`).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
|
|
185
|
+
`).trim(),Y0=t=>{if(!t)return"";const r=t.trim(),s=r.indexOf(`
|
|
186
|
+
`),n=r.indexOf("."),o=[s>=0?s:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?r.substring(0,a).trim():r},Up=({text:t,variant:r,onContentChange:s,blockId:n})=>{const[o,a]=i.useState(!1),l=i.useMemo(()=>Y0(t),[t]),{label:c,Icon:d}=q0[r];return i.useEffect(()=>{t.trim().length!==0&&s?.("structural")},[s,o,t]),!t||t.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:L("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:L("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:L("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(Ut,{className:"h-3.5 w-3.5"}):e.jsx(er,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:c})]}),l&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:l})})]}),o&&e.jsx("div",{className:L("relative pr-2 pb-2 pt-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:e.jsx(gt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:t})})]})},Q0=({part:t,onContentChange:r,messageId:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>K0(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(Up,{text:a,variant:"thinking",onContentChange:r,blockId:t.id||`${s}-reasoning`}):null},J0=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
|
|
187
|
+
`).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
|
|
188
|
+
`).trim(),X0=({part:t,messageId:r,onContentChange:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>J0(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(Up,{text:a,variant:"justification",onContentChange:s,blockId:t.id||`${r}-justification`}):null},Z0=i.memo(X0),Iu=6,eS=t=>[...t].sort((r,s)=>{const n=typeof r.endedAt=="number"?r.endedAt:void 0,o=typeof s.endedAt=="number"?s.endedAt:void 0;return n===void 0&&o===void 0?0:n===void 0?1:o===void 0?-1:n-o}),Pu=t=>{const r={},s=t.filter(n=>n.kind==="tool");return s.forEach((n,o)=>{const a=n.part.id;a&&(r[a]={hasPrev:o>0,hasNext:o<s.length-1})}),r},tS=({parts:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:l,onContentChange:c,diffStats:d})=>{const u=i.useRef(r),[m,f]=i.useState(!1),[p,h]=i.useState(0),g=i.useRef(new Set);i.useEffect(()=>{if(u.current===r)return;const k=u.current===!1;if(u.current=r,c?.("structural"),r&&k){h(j=>j+1),f(!0),g.current.clear();const C=setTimeout(()=>f(!1),50);return()=>clearTimeout(C)}else f(!1)},[r,c]);const x=i.useMemo(()=>eS(t),[t]),b=Pu(x),y=i.useMemo(()=>x.slice(-Iu),[x]),w=i.useMemo(()=>{const k=new Set;return y.forEach(C=>{C.part.id&&k.add(C.part.id)}),k},[y]),S=i.useMemo(()=>Pu(y),[y]),M=Math.max(0,x.length-Iu);if(x.length===0)return null;const N=r?x:y,v=r?b:S,A=M>0;return e.jsx(pr,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:L("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl",A&&"cursor-pointer"),onClick:A?s:void 0,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:A?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:L("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(eo,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:L("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(Ut,{className:"h-3.5 w-3.5"}):e.jsx(er,{className:"h-3.5 w-3.5"})})]}):e.jsx(eo,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),d&&(d.additions>0||d.deletions>0)&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,d.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,d.deletions)]})]})})]}),e.jsxs("div",{className:L("relative pr-2 pb-1 pt-1 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:[!r&&M>0&&e.jsxs("div",{className:"typography-micro text-muted-foreground/70 mb-1 cursor-pointer hover:text-muted-foreground",onClick:s,children:["+",M," more..."]}),N.map((k,C)=>{const j=k.part.id||`group-part-${C}`,T=v[j],I=`${j}-exp${p}`,P=k.part.id?w.has(k.part.id):!1;let D=!1;switch(m&&P?D=!0:!r&&k.part.id&&(g.current.has(k.part.id)?D=!0:g.current.add(k.part.id)),k.kind){case"tool":return e.jsx(pr,{skipAnimation:D,children:e.jsx(Jl,{part:k.part,isExpanded:a.has(j),onToggle:l,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:T?.hasPrev??!1,hasNextTool:T?.hasNext??!1})},I);case"reasoning":return e.jsx(pr,{skipAnimation:D,children:e.jsx(Q0,{part:k.part,messageId:k.messageId,onContentChange:c})},I);case"justification":return e.jsx(pr,{skipAnimation:D,children:e.jsx(Z0,{part:k.part,messageId:k.messageId,onContentChange:c})},I);default:return null}})]})]})})},sS=i.memo(tS),_c=t=>{const r=t,s=r.text;return typeof s=="string"?s:r.content||r.value||""},Vp=t=>{if(t.type!=="text")return!1;const r=_c(t);return!r||r.trim().length===0},rS=(t,r={})=>{const{includeReasoning:s=!0}=r,n=t.some(o=>!o.synthetic);return t.filter(o=>{const l=!!o.synthetic;return l&&o.type==="text"&&_c(o).includes("<system-reminder>")||l&&n||!s&&o.type==="reasoning"?!1:!(o.type==="patch")})},nS=t=>{const r=t/1e3;if(r<60)return`${r.toFixed(1)}s`;const s=Math.floor(r/60),n=Math.round(r%60);return`${s}m ${n}s`},oS=new Set(["task"]),xa=t=>typeof t=="string"&&oS.has(t.toLowerCase()),aS=({messageId:t,parts:r,isMobile:s,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:l,onShowPopup:c,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=i.useState(!1),h=i.useRef(null),g=i.useMemo(()=>r.filter(k=>k.type!=="text"?!1:!Vp(k)),[r]),x=d?.token;let b=!1;const y=!!a,w=!!l,S=!!(n??s),M=!!o,N=i.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),v=i.useCallback(()=>{!S||!y||!M||typeof window>"u"||(N(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[y,N,M,S]);i.useEffect(()=>{M||(p(!1),N())},[N,M]);const A=i.useCallback(k=>{!a||!M||(k.stopPropagation(),k.preventDefault(),a(),S&&v())},[M,S,a,v]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&y&&M?v:void 0,children:[e.jsx("div",{className:"leading-relaxed overflow-hidden text-foreground/90 text-base",children:g.map((k,C)=>{let j;return d&&x&&!b&&_c(k).includes(x)&&(j=d,b=!0),e.jsx(pr,{children:e.jsx(v0,{part:k,messageId:t,isMobile:s,agentMention:j})},`user-text-${C}`)})}),e.jsx(Mp,{files:r,onShowPopup:c}),y&&M||u||m?e.jsxs("div",{className:L("mt-1 flex items-center justify-end gap-2"),children:[u&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{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:k=>k.stopPropagation(),onClick:k=>{k.stopPropagation(),u()},children:e.jsx(Zn,{className:"h-3.5 w-3.5"})})}),e.jsx(ct,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{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:k=>k.stopPropagation(),onClick:k=>{k.stopPropagation(),m()},children:e.jsx(Vt,{className:"h-3.5 w-3.5"})})}),e.jsx(ct,{sideOffset:6,children:"Fork from here"})]}),y&&M&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{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:k=>k.stopPropagation(),onClick:A,onFocus:()=>p(!0),onBlur:()=>{w||p(!1)},children:w?e.jsx(Pt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(rr,{className:"h-3.5 w-3.5"})})}),e.jsx(ct,{sideOffset:6,children:"Copy message"})]})]}):null]})},iS=({messageId:t,parts:r,isMessageCompleted:s,messageFinish:n,messageCompletedAt:o,syntaxTheme:a,isMobile:l,hasTouchInput:c,expandedTools:d,onToggleTool:u,onShowPopup:m,streamPhase:f,allowAnimation:p,onContentChange:h,hasTextContent:g=!1,onCopyMessage:x,copiedMessage:b=!1,onAuxiliaryContentComplete:y,showReasoningTraces:w=!1,turnGroupingContext:S,errorMessage:M})=>{const[N,v]=i.useState(!1),A=i.useRef(null),k=!!x,C=!!b,j=!!(c??l),T=!s,I=i.useMemo(()=>r.filter(Ke=>!Vp(Ke)).filter(Ke=>Ke.type!=="compaction"),[r]),P=i.useMemo(()=>I.filter(Ke=>Ke.type==="tool"),[I]),D=i.useMemo(()=>I.filter(Ke=>Ke.type==="text"),[I]),E=be(Ke=>Ke.createSessionFromAssistantMessage),F=Me(Ke=>Ke.openMultiRunLauncherWithPrompt),B=S?.isLastAssistantInTurn??!1,V=n==="stop",ne=P.length>0,O=i.useMemo(()=>P.some(Ke=>{const jt=(Ke.state??{})?.status;return jt==="pending"||jt==="running"||jt==="started"}),[P]),G=i.useCallback(Ke=>{const lt=Ke.state??{},jt=lt?.status;if(jt==="pending"||jt==="running"||jt==="started")return!1;const yt=lt?.time??{},Mt=typeof yt?.end=="number"?yt.end:void 0,es=typeof yt?.start=="number"?yt.start:void 0;return!(typeof Mt!="number"||typeof es=="number"&&Mt<es)},[]),K=i.useMemo(()=>P.length===0?!0:O?!1:P.every(Ke=>G(Ke)),[P,O,G]),q=i.useMemo(()=>I.filter(Ke=>Ke.type==="reasoning"),[I]),$=i.useMemo(()=>q.length===0?!0:q.every(Ke=>typeof Ke.time?.end=="number"),[q]),W=typeof n!="string",Y=q.length>0&&ne&&(O||W||!K),X=T||ne&&(O||W||!K),Z=T||Y,z=ne||q.length>0,R=D.length===0,de=z&&R&&!X&&!Z&&K&&$,we=i.useRef(!1),xe=i.useRef(!1);i.useEffect(()=>{xe.current=!1},[t]),i.useEffect(()=>{if(!de){we.current=!1;return}we.current||(we.current=!0,y?.())},[de,y]),i.useEffect(()=>{if(T){xe.current=!1;return}if(ne){xe.current=!1;return}q.length!==0&&(Z||!$||xe.current||(xe.current=!0,h?.("structural")))},[T,ne,h,$,q.length,Z]);const Pe=!!g&&!T,H=i.useCallback(()=>{A.current!==null&&typeof window<"u"&&(window.clearTimeout(A.current),A.current=null)},[]),ye=i.useCallback(()=>{!j||!k||!Pe||typeof window>"u"||(H(),v(!0),A.current=window.setTimeout(()=>{v(!1),A.current=null},1800))},[k,H,Pe,j]);i.useEffect(()=>{Pe||(v(!1),H())},[H,Pe]);const J=i.useCallback(Ke=>{!x||!Pe||(Ke.stopPropagation(),Ke.preventDefault(),x(),j&&ye())},[Pe,j,x,ye]),ce=i.useCallback(Ke=>{Ke.stopPropagation(),Ke.preventDefault(),E&&E(t)},[E,t]),ge=i.useCallback(Ke=>{Ke.stopPropagation(),Ke.preventDefault();const lt=Sc(D);if(!lt.trim())return;const jt=`${jw}
|
|
189
|
+
|
|
190
|
+
${lt}`;F(jt)},[D,F]);i.useEffect(()=>()=>{H()},[H]);const ee=i.useMemo(()=>{const Ke={},lt=P.filter(jt=>xa(jt.tool)||X?!1:G(jt));return lt.forEach((jt,yt)=>{Ke[jt.id]={hasPrev:yt>0,hasNext:yt<lt.length-1}}),Ke},[P,X,G]),me=i.useMemo(()=>S?.activityParts??[],[S]),le=i.useMemo(()=>S?me.filter(Ke=>Ke.messageId===t):[],[me,t,S]),fe=i.useMemo(()=>S?S.activityGroupSegments.filter(Ke=>Ke.anchorMessageId===t):[],[t,S]),oe=i.useMemo(()=>{const Ke=new Map;return le.forEach(lt=>{Ke.set(lt.part,lt)}),Ke},[le]),Q=i.useMemo(()=>S?(w?me:me.filter(lt=>lt.kind==="tool")).filter(lt=>{if(lt.kind!=="tool")return!0;const jt=lt.part.tool;return!xa(jt)}):[],[me,w,S]),[re,ue]=i.useState(!1);i.useEffect(()=>{if(!S)return;const Ke=S.activityGroupSegments.some(lt=>lt.afterToolPartId!==null);(Q.length>1||Ke&&Q.length>0)&&ue(!0)},[S,Q.length]);const he=!!(S&&re),Ge=!!(S&&he&&Q.length>0&&fe.length>0),qe=i.useMemo(()=>P.filter(Ke=>xa(Ke.tool)),[P]),et=i.useMemo(()=>{const Ke=[],lt=yt=>{!S||!Ge||fe.filter(Mt=>(Mt.afterToolPartId??null)===yt).forEach(Mt=>{const es=w?Mt.parts:Mt.parts.filter(Ht=>Ht.kind==="tool");es.length!==0&&Ke.push(e.jsx(sS,{parts:es,isExpanded:S.isGroupExpanded,onToggle:S.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,diffStats:S.diffStats},`progressive-group-${Mt.id}`))})};lt(null),qe.forEach(yt=>{Ke.push(e.jsx(pr,{children:e.jsx(Jl,{part:yt,isExpanded:d.has(yt.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${yt.id}`)),lt(yt.id)});const jt=[];return I.forEach((yt,Mt)=>{const es=oe.get(yt);if(!es||!S)return;let Ht=null,Wt=null;if(!he){if(es.kind==="tool"){const kt=yt;if(xa(kt.tool))return;const Qt=kt.state?.time,Tt=G(kt);if(!(!X&&Tt))return;const Rt=ee[kt.id];Wt=e.jsx(pr,{children:e.jsx(Jl,{part:kt,isExpanded:d.has(kt.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:Rt?.hasPrev??!1,hasNextTool:Rt?.hasNext??!1})},`tool-${kt.id}`),Ht=Tt&&typeof Qt?.end=="number"?Qt.end:null}Wt&&jt.push({part:yt,index:Mt,endTime:Ht,element:Wt})}}),jt.sort((yt,Mt)=>yt.endTime===null&&Mt.endTime===null?yt.index-Mt.index:yt.endTime===null?1:Mt.endTime===null?-1:yt.endTime-Mt.endTime),jt.forEach(({element:yt})=>{Ke.push(yt)}),Ke},[oe,fe,d,l,G,h,m,u,X,he,w,a,ee,S,I,qe,Ge]),rt=S?.turnId,vt=be(Ke=>Ke.currentSessionId),Ce=St(Ke=>{if(!rt||!vt)return;const lt=Ke.messages.get(vt);if(!lt)return;const jt=lt.find(es=>es.info?.id===rt);if(!jt)return;const Mt=jt.info.summary?.body;return typeof Mt=="string"&&Mt.trim().length>0?Mt:void 0}),pe=typeof S?.summaryBody=="string"&&S.summaryBody.trim().length>0?S.summaryBody:Ce,He=i.useRef(void 0);pe&&pe.trim().length>0&&(He.current=pe);const Se=i.useRef(rt);Se.current!==rt&&(Se.current=rt,He.current=void 0);const ke=He.current,Xe=S?.isLastAssistantInTurn&&ke&&ke.trim().length>0,at=!!M,We=B&&g&&(V||!!M),[Be,Ve]=i.useState(!1),mt=i.useMemo(()=>{if(!B||!V)return;const Ke=S?.userMessageCreatedAt;if(!(typeof Ke!="number"||typeof o!="number")&&!(o<=Ke))return nS(o-Ke)},[B,V,S?.userMessageCreatedAt,o]),ft=e.jsxs(e.Fragment,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{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:Ke=>Ke.stopPropagation(),onClick:ce,children:e.jsx(px,{className:"h-4 w-4"})})}),e.jsx(ct,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{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:Ke=>Ke.stopPropagation(),onClick:ge,children:e.jsx(bp,{className:"h-4 w-4"})})}),e.jsx(ct,{sideOffset:6,children:"Start new multi-run from this answer"})]}),x&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{type:"button",variant:"ghost",size:"icon","data-visible":N||C?"true":void 0,className:L("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!Pe&&"opacity-50"),disabled:!Pe,"aria-label":"Copy message text","aria-hidden":!Pe,onPointerDown:Ke=>Ke.stopPropagation(),onClick:J,onFocus:()=>{Pe&&v(!0)},onBlur:()=>{C||v(!1)},children:C?e.jsx(Pt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(rr,{className:"h-3.5 w-3.5"})})}),e.jsx(ct,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:L("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:j&&k&&Pe?ye:void 0,children:e.jsxs("div",{children:[e.jsxs("div",{className:"leading-relaxed overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[et,at&&e.jsx(pr,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Nr,{content:M??""})})},"assistant-error"),Xe&&e.jsx(pr,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Ve(!0),onMouseLeave:()=>Ve(!1),children:[e.jsx(Nr,{content:ke}),We&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[mt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Jc,{className:"h-3.5 w-3.5"}),mt]}):e.jsx("span",{}),e.jsx("div",{className:L("flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",Be&&"opacity-100 pointer-events-auto"),children:ft})]})]})},"summary-body")]}),e.jsx(Mp,{files:r,onShowPopup:m}),!Xe&&We&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[mt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Jc,{className:"h-3.5 w-3.5"}),mt]}):e.jsx("span",{}),e.jsx("div",{className:"flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",children:ft})]})]})})},lS=({isUser:t,...r})=>t?e.jsx(aS,{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(iS,{...r}),Tu=i.memo(lS),nl=t=>{const r=t,s=r?.clientRole,n=r?.role;return r?.userMessageMarker===!0||s==="user"||n==="user"||r?.origin==="user"||r?.source==="user"?{role:"user",isUser:!0}:{role:s||n||"assistant",isUser:!1}},cS=i.lazy(()=>js(()=>import("./ToolOutputDialog-Dz-mXTUL.js"),__vite__mapDeps([2,0,1,3,4]))),dS=new Set(["task","edit","multiedit","write","bash"]),Fu=t=>typeof t=="string"&&dS.has(t.toLowerCase());function ol(t){const r=i.useRef({hasValue:!1,value:void 0});return t!=null&&(!r.current.hasValue||r.current.value!==t)&&(r.current={hasValue:!0,value:t}),r.current.hasValue?r.current.value:t}const Ys=(t,r)=>{if(typeof t=="object"&&t!==null)return t[r]},uS=({message:t,previousMessage:r,nextMessage:s,onContentChange:n,animationHandlers:o,turnGroupingContext:a})=>{const{isMobile:l,hasTouchInput:c}=qt(),{currentTheme:d}=Hr(),u=i.useRef(null),m=be(zn(se=>({lifecyclePhase:se.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const ie=t.info.sessionID??se.currentSessionId??null;return ie?(se.streamingMessageIds.get(ie)??null)===t.info.id:!1})(),currentSessionId:se.currentSessionId,getAgentModelForSession:se.getAgentModelForSession,getSessionModelSelection:se.getSessionModelSelection,revertToMessage:se.revertToMessage,forkFromMessage:se.forkFromMessage}))),{lifecyclePhase:f,isStreamingMessage:p,currentSessionId:h,getAgentModelForSession:g,getSessionModelSelection:x,revertToMessage:b,forkFromMessage:y}=m,w=Ze(se=>se.providers),{showReasoningTraces:S,toolCallExpansion:M}=Me(zn(se=>({showReasoningTraces:se.showReasoningTraces,toolCallExpansion:se.toolCallExpansion})));i.useEffect(()=>{h&&qr.getInstance().recordSessionStart(h)},[h]);const[N,v]=i.useState(null),[A,k]=i.useState(!1),[C,j]=i.useState(new Set),[T,I]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{j(new Set)},[t.info.id,M]);const D=i.useMemo(()=>nl(t.info),[t.info]).isUser,E=t.info.sessionID,{currentContextAgent:F,savedSessionAgentSelection:B}=tt(zn(se=>({currentContextAgent:E?se.currentAgentContext.get(E):void 0,savedSessionAgentSelection:E?se.sessionAgentSelections.get(E):void 0}))),V=i.useMemo(()=>{if(!D)return t.parts;const se=ie=>{const Ee=ie.trim();return!!(Ee.startsWith("User has requested to enter plan mode")||Ee.startsWith("The plan at "))};return t.parts.filter(ie=>{if(!(ie?.synthetic===!0))return!0;if(ie.type!=="text")return!1;const Re=ie?.text;return typeof Re=="string"?se(Re):!1}).map(ie=>ie.type==="compaction"?{type:"text",text:"/compact"}:ie)},[D,t.parts]),ne=i.useMemo(()=>{if(D||!r)return null;const se=Ys(r.info,"clientRole"),ie=Ys(r.info,"role");if((typeof se=="string"?se:typeof ie=="string"?ie:void 0)!=="user")return null;const Re=Ys(r.info,"mode"),Ye=Ys(r.info,"agent"),bt=Ys(r.info,"providerID"),pt=Ys(r.info,"modelID"),Jt=Ys(r.info,"variant"),Lt=typeof Re=="string"&&Re.trim().length>0?Re:typeof Ye=="string"&&Ye.trim().length>0?Ye:void 0,ks=typeof bt=="string"&&bt.trim().length>0?bt:void 0,Cs=typeof pt=="string"&&pt.trim().length>0?pt:void 0,Dt=typeof Jt=="string"&&Jt.trim().length>0?Jt:void 0;return!Lt&&!ks&&!Cs&&!Dt?null:{agentName:Lt,providerId:ks,modelId:Cs,variant:Dt}},[D,r]),O=i.useMemo(()=>{if(D||!r)return!1;const se=Array.isArray(r.parts)?r.parts:[];for(let ie=0;ie<se.length;ie++){const Ee=se[ie];if(Ee?.type!=="text"||Ee?.synthetic!==!0)continue;const Re=typeof Ee.text=="string"?Ee.text.trim():"";if(Re.startsWith("User has requested to enter plan mode")||Re.startsWith("The plan at "))return!0}return!1},[D,r]),G=i.useMemo(()=>{if(D)return;const se=t.info.time;if(!(typeof se?.completed=="number"&&se.completed>0)&&O&&ne?.agentName)return ne.agentName;const Ee=Ys(t.info,"mode");if(typeof Ee=="string"&&Ee.trim().length>0)return Ee;const Re=Ys(t.info,"agent");if(typeof Re=="string"&&Re.trim().length>0)return Re;if(ne?.agentName)return ne.agentName;if(E)return F||(B??void 0)},[D,t.info,O,ne,E,F,B]),K=D?null:Ys(t.info,"providerID"),q=D?null:Ys(t.info,"modelID"),$=i.useMemo(()=>{if(D||!E)return null;if(ne?.providerId&&ne?.modelId)return{providerId:ne.providerId,modelId:ne.modelId};if(G){const ie=g(E,G);if(ie?.providerId&&ie?.modelId)return ie}const se=x(E);return se?.providerId&&se?.modelId?se:null},[D,E,G,ne,g,x]),W=i.useMemo(()=>D?null:typeof K=="string"&&K.trim().length>0?K:$?.providerId??null,[D,K,$]),Y=i.useMemo(()=>D?null:typeof q=="string"&&q.trim().length>0?q:$?.modelId??null,[D,q,$]),X=i.useMemo(()=>{if(!D&&W&&Y&&w.length>0){const se=w.find(ie=>ie.id===W);if(se?.models&&Array.isArray(se.models)){const Re=se.models.find(Ye=>Ye.id===Y)?.name;return typeof Re=="string"?Re:void 0}}},[D,W,Y,w]),Z=i.useMemo(()=>{if(D||!W||!Y)return!1;const se=w.find(Re=>Re.id===W);if(!se?.models||!Array.isArray(se.models))return!1;const Ee=se.models.find(Re=>Re.id===Y)?.variants;return!!(Ee&&Object.keys(Ee).length>0)},[D,Y,W,w]),z=ol(G),R=ol(W??void 0),de=ol(X),we=z??void 0,xe=R??null,Pe=de??void 0,H=i.useMemo(()=>{const se=t.info.time;return typeof se?.completed=="number"?se.completed:null},[t.info.time]),ye=i.useMemo(()=>D?!0:!!(H&&H>0),[D,H]),J=i.useMemo(()=>{const se=t.info.finish;return typeof se=="string"?se:void 0},[t.info]),ce=i.useMemo(()=>rS(V,{includeReasoning:S}),[V,S]),ge=i.useMemo(()=>D||ye?ce:[],[D,ye,ce]),ee=i.useMemo(()=>D?[]:ce.filter(se=>se.type==="text"),[D,ce]),me=i.useMemo(()=>D?[]:ce.filter(ie=>ie.type==="tool"),[D,ce]),le=i.useMemo(()=>{if(M==="collapsed"||M==="activity")return C;const se=new Set;for(const Ee of me){const Re=Ee.tool;Ee.id&&Fu(Re)&&se.add(Ee.id)}if(a?.isFirstAssistantInTurn)for(const Ee of a.activityParts){if(Ee.kind!=="tool")continue;const Re=Ee.part;Re.id&&Fu(Re.tool)&&se.add(Re.id)}const ie=new Set(se);for(const Ee of C)ie.has(Ee)?ie.delete(Ee):ie.add(Ee);return ie},[C,M,me,a]),fe=i.useMemo(()=>{if(!D)return;const se=t.parts.find(Ye=>Ye.type==="agent");if(!se)return;const ie=se,Ee=typeof ie.name=="string"?ie.name:void 0;if(!Ee)return;const Re=ie.source&&typeof ie.source.value=="string"&&ie.source.value.trim().length>0?ie.source.value:`#${Ee}`;return{name:Ee,token:Re}},[D,t.parts]),oe=typeof J!="string",Q=i.useMemo(()=>D?!1:ee.length===0||me.length===0?oe:!0,[ee.length,me.length,oe,D]),re=d?.metadata.variant,ue=i.useMemo(()=>re?re==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[re]),he=i.useMemo(()=>d?Pi(d):ue?p0:h0,[d,ue]),Ge=i.useMemo(()=>D?!1:qr.getInstance().shouldAnimateMessage(t.info,h||t.info.sessionID),[t.info,h,D]),qe=i.useRef(!1),et=i.useMemo(()=>r?nl(r.info):null,[r]),rt=i.useMemo(()=>s?nl(s.info):null,[s]),vt=i.useMemo(()=>D||!rt?!1:!rt.isUser&&rt.role==="assistant",[D,rt]),Ce=i.useMemo(()=>ye?"completed":f||(p?"streaming":"completed"),[ye,f,p]),pe=i.useMemo(()=>{if(D)return!0;const se=a?.headerMessageId;if(se){if(t.info.id===se){if(Ce==="completed")return!0;const Ee=Ce==="streaming"||Ce==="cooldown",Re=qe.current;return Ee&&!Re&&(qe.current=!0),Re||Ee}return!1}return et?et.isUser:!0},[D,et,a,Ce,t.info]),He=i.useCallback(se=>{navigator.clipboard.writeText(se),v(se),setTimeout(()=>v(null),2e3)},[]),Se=a?.turnId,{assistantSummaryFromStore:ke,variantFromTurnStore:Xe}=St(zn(se=>{if(!Se||!t.info.sessionID)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const ie=se.messages.get(t.info.sessionID);if(!ie)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const Ee=ie.find(pt=>pt.info?.id===Se);if(!Ee)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const Ye=Ee.info.summary?.body,bt=Ee.info.variant;return{assistantSummaryFromStore:typeof Ye=="string"&&Ye.trim().length>0?Ye:void 0,variantFromTurnStore:typeof bt=="string"&&bt.trim().length>0?bt:void 0}})),at=D?void 0:Xe??ne?.variant,We=!D&&Z?at??"Default":void 0,Be=typeof a?.summaryBody=="string"&&a.summaryBody.trim().length>0?a.summaryBody:ke,Ve=i.useRef(void 0);Be&&Be.trim().length>0&&(Ve.current=Be);const mt=i.useRef(Se);mt.current!==Se&&(mt.current=Se,Ve.current=void 0);const ft=Ve.current,Ke=i.useMemo(()=>{if(D)return;const se=t.info?.error;if(!se)return;const ie=typeof se.data?.message=="string"?se.data.message:void 0,Ee=typeof se.message=="string"?se.message:void 0,Re=typeof se.name=="string"?se.name:void 0,Ye=ie||Ee||Re;if(Ye)return`Opencode failed to send message with error:
|
|
191
|
+
\`${Ye}\``},[D,t.info]),lt=i.useMemo(()=>D?ge.filter(Ee=>Ee.type==="text").map(Ee=>(Ee.text||Ee.content||"").trim()).filter(Ee=>Ee.length>0).join(`
|
|
192
|
+
`).replace(/\n\s*\n+/g,`
|
|
193
|
+
`):Ke&&Ke.trim().length>0?Ke:ft&&ft.trim().length>0?ft:Sc(ge),[Ke,ft,ge,D]),jt=lt.length>0,yt=i.useCallback(async se=>{if(!se)return!1;if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(se),!0}catch{}if(typeof document>"u")return!1;const ie=document.createElement("textarea");ie.value=se,ie.setAttribute("readonly",""),ie.style.position="fixed",ie.style.top="-1000px",ie.style.left="-1000px",document.body.appendChild(ie),ie.select(),ie.setSelectionRange(0,ie.value.length);const Ee=document.execCommand("copy");return document.body.removeChild(ie),Ee},[]),Mt=i.useCallback(async()=>{await yt(lt)&&(k(!0),setTimeout(()=>k(!1),2e3))},[yt,lt]),es=i.useCallback(()=>{!E||!t.info.id||b(E,t.info.id)},[E,t.info.id,b]),Ht=i.useCallback(()=>{!E||!t.info.id||y(E,t.info.id)},[E,t.info.id,y]),Wt=i.useCallback(se=>{j(ie=>{const Ee=new Set(ie);return Ee.has(se)?Ee.delete(se):Ee.add(se),Ee})},[]),kt=o??null,gs=i.useRef(!1),Qt=i.useRef(!1),Tt=i.useRef(!1),Kt=i.useRef(!1),Rt=i.useRef(!1);i.useEffect(()=>{Qt.current=!1,Tt.current=!1,Kt.current=!1,Rt.current=!1,gs.current=!1},[t.info.id]);const _t=i.useCallback(()=>{D||gs.current||(gs.current=!0,n?.("structural"))},[D,n]),Yt=i.useCallback(se=>{se.image&&I(se)},[]),Gt=i.useCallback(se=>{I(ie=>({...ie,open:se}))},[]),It=!!Ys(t.info,"animationSettled"),Ie=Ce==="streaming",Te=i.useMemo(()=>D?!1:ce.some(se=>se.type==="reasoning"),[D,ce]),Le=Ge&&!It&&!Ie,te=!D&&Ge&&ee.length>0&&!Q;return i.useEffect(()=>{if(kt?.onStreamingCandidate){if(!te){Tt.current&&(Te&&kt?.onReasoningBlock?kt.onReasoningBlock():kt?.onReservationCancelled&&kt.onReservationCancelled(),Tt.current=!1);return}Rt.current||(Rt.current=!0,kt.onStreamingCandidate(),Tt.current=!0)}},[kt,te,Te]),i.useEffect(()=>{kt?.onAnimationStart&&Le&&(Kt.current||(kt.onAnimationStart(),Kt.current=!0))},[kt,Le]),i.useEffect(()=>{if(D)return;const se=kt?.onAnimatedHeightChange;if(!se||!(Le||te))return;const Ee=u.current;if(!Ee)return;if(typeof window>"u"||typeof ResizeObserver>"u"){se(Ee.getBoundingClientRect().height);return}let Re=null;const Ye=pt=>{if(typeof window>"u"){se(pt);return}Re!==null&&window.cancelAnimationFrame(Re),Re=window.requestAnimationFrame(()=>{se(pt)})},bt=new ResizeObserver(pt=>{const Jt=pt[0];Jt&&Ye(Jt.contentRect.height)});return bt.observe(Ee),Ye(Ee.getBoundingClientRect().height),()=>{Re!==null&&(window.cancelAnimationFrame(Re),Re=null),bt.disconnect()}},[Le,D,kt,te]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:L("group w-full",pe?"pt-6":"pt-0",D?"pb-4":vt?"pb-0":"pb-8"),"data-message-id":t.info.id,ref:u,children:e.jsx("div",{className:"chat-message-column relative",children:D?ge.length===0?null:e.jsx(pr,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-sm bg-primary/10 dark:bg-primary/10 px-5 py-3 shadow-sm border border-primary/5",children:e.jsx(Tu,{messageId:t.info.id,parts:ge,isUser:D,isMessageCompleted:ye,messageFinish:J,syntaxTheme:he,isMobile:l,hasTouchInput:c,copiedCode:N,onCopyCode:He,expandedTools:C,onToggleTool:Wt,onShowPopup:Yt,streamPhase:Ce,allowAnimation:Le,onContentChange:n,shouldShowHeader:!1,hasTextContent:jt,onCopyMessage:Mt,copiedMessage:A,showReasoningTraces:S,onAuxiliaryContentComplete:_t,agentMention:fe,onRevert:es,onFork:D?Ht:void 0,errorMessage:Ke})})})}):e.jsxs("div",{className:"relative pl-4 ml-1",children:[pe&&e.jsx(y0,{isUser:D,providerID:xe,agentName:we,modelName:Pe,variant:We,isDarkTheme:ue}),e.jsx(Tu,{messageId:t.info.id,parts:ce,isUser:D,isMessageCompleted:ye,messageFinish:J,messageCompletedAt:H??void 0,syntaxTheme:he,isMobile:l,hasTouchInput:c,copiedCode:N,onCopyCode:He,expandedTools:le,onToggleTool:Wt,onShowPopup:Yt,streamPhase:Ce,allowAnimation:Le,onContentChange:n,shouldShowHeader:pe,hasTextContent:jt,onCopyMessage:Mt,copiedMessage:A,onAuxiliaryContentComplete:_t,showReasoningTraces:S,agentMention:fe,turnGroupingContext:a,errorMessage:Ke})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(cS,{popup:T,onOpenChange:Gt,syntaxTheme:he,isMobile:l})})]})},Gp=i.memo(uS),mS=({diff:t,syntaxTheme:r,filePath:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:_p(t).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file||s?.split("/").pop()||"file"} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,l)=>e.jsxs("div",{className:L("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Or,{style:r,language:Ar(s||n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},l))})]},o))}),fS=({content:t,syntaxTheme:r,filePath:s})=>{const n=t.split(`
|
|
194
|
+
`),o=Ar(s??"")||"text",a=s?.split("/").pop()||"New file",l=Math.max(n.length,1),c=l===1?"line 1":`lines 1-${l}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${c})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Or,{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))})]})},pS=t=>{const r="h-3 w-3",s=t.toLowerCase();return s==="edit"||s==="multiedit"||s==="str_replace"||s==="str_replace_based_edit_tool"?e.jsx(Tr,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(Km,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?e.jsx(tn,{className:r}):s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?e.jsx(Ml,{className:r}):e.jsx(mi,{className:r})},hS=t=>{const r=t.toLowerCase();return r==="edit"||r==="multiedit"||r==="str_replace"||r==="str_replace_based_edit_tool"?"edit":r==="write"||r==="create"||r==="file_write"?"write":r==="bash"||r==="shell"||r==="cmd"||r==="terminal"||r==="shell_command"?"bash":r==="webfetch"||r==="fetch"||r==="curl"||r==="wget"?"webfetch":t},gS=({permission:t,onResponse:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(!1),{respondToPermission:l}=be(),{currentTheme:c}=Hr(),d=i.useMemo(()=>Pi(c),[c]),u=async y=>{n(!0);try{await l(t.sessionID,t.id,y),a(!0),r?.(y)}catch{}finally{n(!1)}};if(o)return null;const m=t.permission||"unknown",f=m.toLowerCase(),p=(y,w="")=>{const S=t.metadata[y];return typeof S=="string"?S:typeof S=="number"?String(S):w},h=y=>{const w=t.metadata[y];return typeof w=="number"?w:void 0},g=y=>!!t.metadata[y],x=hS(m),b=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const S=p("command")||p("cmd")||p("script"),M=p("description"),N=p("cwd")||p("working_directory")||p("directory")||p("path"),v=h("timeout");return e.jsxs(e.Fragment,{children:[M&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:M}),N&&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:N})]}),v&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",v,"ms"]}),S&&e.jsx("div",{children:e.jsx(Or,{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"),M=p("changes")||p("diff"),N=g("replace_all")||g("replaceAll");return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),M&&e.jsx(gt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(mS,{diff:M,syntaxTheme:d,filePath:S})})]})}if(f==="write"||f==="create"||f==="file_write"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),M=p("content")||p("text")||p("data");return M?e.jsx(gt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(fS,{content:M,syntaxTheme:d,filePath:S})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const S=p("url")||p("uri")||p("endpoint"),M=p("method")||"GET",N=t.metadata.headers&&typeof t.metadata.headers=="object"?t.metadata.headers:void 0,v=p("body")||p("data")||p("payload"),A=h("timeout"),k=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:M}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:S})]})]}),N&&Object.keys(N).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(gt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(Or,{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(N,null,2)})})]}),v&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(gt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(Or,{language:typeof v=="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 v=="object"?JSON.stringify(v,null,2):String(v)})})]}),(A||k)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[A&&e.jsxs("span",{children:["Timeout: ",A,"ms"]}),A&&k&&e.jsx("span",{children:" • "}),k&&e.jsxs("span",{children:["Response format: ",k]})]})]})}const y=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}),y&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(gt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(y)})})]}),Object.keys(t.metadata).length>0&&!y&&!w&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(gt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:JSON.stringify(t.metadata,null,2)})})]})]})};return e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20 bg-muted/5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{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:[pS(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:x})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[t.patterns.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Patterns:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:t.patterns.join(", ")})]}),b()]}),e.jsxs("div",{className:"px-2 pb-2 sm:pb-1.5 pt-1.5 sm:pt-1 flex flex-col sm:flex-row sm:items-center sm:flex-wrap gap-1.5 border-t border-border/20",children:[e.jsxs("button",{onClick:()=>u("once"),disabled:s,className:L("flex items-center gap-1.5 sm:gap-1 px-3 sm:px-2 py-1.5 sm:py-1 typography-meta font-medium rounded transition-all min-h-[32px] sm:min-h-0 w-full sm:w-auto","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Pt,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),"Allow Once"]}),t.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:s,className:L("flex items-center gap-1.5 sm:gap-1 px-3 sm:px-2 py-1.5 sm:py-1 typography-meta font-medium rounded transition-all min-h-[32px] sm:min-h-0 w-full sm:w-auto","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(kr,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),(()=>{const y=t.always||t.metadata.always||[];if(y.length===0)return"Always Allow";const S=y.slice(0,2).join(", "),M=y.length>2;return e.jsx("span",{className:"truncate max-w-[180px]",children:M?`Always: ${S}...`:`Always: ${S}`})})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:s,className:L("flex items-center gap-1.5 sm:gap-1 px-3 sm:px-2 py-1.5 sm:py-1 typography-meta font-medium rounded transition-all min-h-[32px] sm:min-h-0 w-full sm:w-auto","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(kr,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:s,className:L("flex items-center gap-1.5 sm:gap-1 px-3 sm:px-2 py-1.5 sm:py-1 typography-meta font-medium rounded transition-all min-h-[32px] sm:min-h-0 w-full sm:w-auto","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(ss,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),"Deny"]}),s&&e.jsx("div",{className:"flex justify-center w-full sm:w-auto sm:ml-auto py-1 sm:py-0 typography-meta text-muted-foreground",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})})]})]})})})},al="summary",xS=({question:t})=>{const{respondToQuestion:r,rejectQuestion:s}=be(),[n,o]=i.useState("0"),[a,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState({}),[f,p]=i.useState({}),[h,g]=i.useState({}),x=i.useMemo(()=>t.questions??[],[t.questions]),b=n===al,y=b?-1:Math.max(0,Math.min(x.length-1,Number(n)||0)),w=b?null:x[y],S=i.useMemo(()=>{if(b)return null;const E=w?.header?.trim();return E&&E.length>0?E:null},[w?.header,b]);i.useEffect(()=>{o("0"),m({}),p({}),g({}),d(!1)},[t.id]);const M=i.useMemo(()=>{const E=x.map((F,B)=>({value:String(B),label:F.header?.trim()||`Q${B+1}`}));return x.length>1&&E.push({value:al,label:"Summary"}),E},[x]),N=i.useCallback(E=>{if(!!f[E])return(h[E]??"").trim()||"(no answer)";const B=u[E]??[];return B.length>0?B.join(", "):"(no answer)"},[f,h,u]),v=!!w?.multiple,A=u[y]??[],k=!!f[y],C=i.useMemo(()=>{if(x.length===0)return!1;for(let E=0;E<x.length;E+=1){if(!!f[E]){if(!(h[E]??"").trim())return!1;continue}if((u[E]??[]).length===0)return!1}return!0},[f,h,x.length,u]),j=i.useCallback(()=>{const E=[];for(let F=0;F<x.length;F+=1){if(!!f[F]){const V=(h[F]??"").trim();E.push(V?[V]:[]);continue}E.push(u[F]??[])}return E},[f,h,x.length,u]),T=i.useCallback(E=>{w&&(p(F=>({...F,[y]:!1})),m(F=>{const B=F[y]??[];if(v){const ne=B.includes(E)?B.filter(O=>O!==E):[...B,E];return{...F,[y]:ne}}return{...F,[y]:[E]}}))},[y,w,v]),I=i.useCallback(()=>{p(E=>({...E,[y]:!0})),m(E=>({...E,[y]:[]}))},[y]),P=i.useCallback(async()=>{if(C){l(!0);try{const E=j();await r(t.sessionID,t.id,E),d(!0)}catch{}finally{l(!1)}}},[j,t.id,t.sessionID,C,r]),D=i.useCallback(async()=>{l(!0);try{await s(t.sessionID,t.id),d(!0)}catch{}finally{l(!1)}},[t.id,t.sessionID,s]);return c||x.length===0?null:e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Input needed"}),S?e.jsx("span",{className:"ml-auto typography-micro font-medium text-foreground/70 px-1.5 py-0.5 rounded bg-muted/30 border border-border/20",children:S}):null]})}),e.jsxs("div",{className:"px-2 py-2",children:[M.length>1?e.jsx("div",{className:"flex items-center gap-1 mb-2 flex-wrap",children:M.map(E=>{const F=n===E.value,B=E.value===al;return e.jsxs("button",{type:"button",onClick:()=>o(E.value),className:L("px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1",F?"bg-muted/40 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-muted/20"),children:[B?e.jsx(Ym,{className:"h-3 w-3"}):null,E.label]},E.value)})}):null,b?e.jsx("div",{className:"space-y-2",children:x.map((E,F)=>{const B=N(F),V=B!=="(no answer)";return e.jsxs("button",{type:"button",onClick:()=>o(String(F)),className:"w-full text-left rounded px-1.5 py-1 hover:bg-muted/20 transition-colors",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:E.header||`Question ${F+1}`}),e.jsx("div",{className:L("typography-meta",V?"text-foreground":"text-muted-foreground/50 italic"),children:B})]},F)})}):w?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:w.question}),v?e.jsx("div",{className:"typography-micro text-muted-foreground mb-1.5",children:"Select multiple"}):null,e.jsxs("div",{className:"space-y-0.5",children:[w.options.map((E,F)=>{const B=A.includes(E.label),V=/\(recommended\)/i.test(E.label);return e.jsx("button",{type:"button",onClick:()=>T(E.label),disabled:a,className:L("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",B?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5 shrink-0",children:B?e.jsx(hx,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(Dl,{className:"h-3.5 w-3.5 text-muted-foreground/50"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:L("typography-meta break-all",B?"text-foreground font-medium":"text-foreground/80"),children:E.label}),V?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),E.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:E.description}):null]})]})},`${F}:${E.label}`)}),e.jsx("button",{type:"button",onClick:I,disabled:a,className:L("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",k?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mo,{className:L("h-3.5 w-3.5",k?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:L("typography-meta",k?"text-foreground font-medium":"text-muted-foreground"),children:"Other…"})]})}),k?e.jsx("div",{className:"pl-6 pr-1 pt-0.5",children:e.jsx("textarea",{ref:E=>{if(E){E.style.height="auto";const F=20,B=F*2,V=F*4;E.style.height=`${Math.min(Math.max(E.scrollHeight,B),V)}px`}},value:h[y]??"",onChange:E=>{const F=E.target;F.style.height="auto";const B=20,V=B*2,ne=B*4;F.style.height=`${Math.min(Math.max(F.scrollHeight,V),ne)}px`,g(O=>({...O,[y]:F.value}))},placeholder:"Your answer",disabled:a,rows:2,className:"w-full bg-transparent border border-border/30 focus:border-primary rounded px-2 py-1 outline-none typography-meta text-foreground placeholder:text-muted-foreground/50 transition-colors resize-none overflow-hidden",autoFocus:!0})}):null]})]}):null]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{type:"button",onClick:P,disabled:a||!C,className:L("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-success)/0.1)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(Pt,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:D,disabled:a,className:L("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-error)/0.1)] text-[var(--status-error)] hover:bg-[rgb(var(--status-error)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(ss,{className:"h-3 w-3"}),"Dismiss"]}),a?e.jsx("div",{className:"ml-auto",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})}):null]})]})})})},yS=t=>{const r=[];let s=null;return t.forEach(n=>{const o=n.info.clientRole??n.info.role;o==="user"?(s={turnId:n.info.id,userMessage:n,assistantMessages:[]},r.push(s)):o==="assistant"&&s&&s.assistantMessages.push(n)}),r},Jo=i.createContext(null),$c=i.createContext(null),qp=i.createContext(null);let Ru=null;const On=new Map,bS=t=>{const r=i.useContext(Jo),s=i.useContext($c),n=i.useContext(qp);return i.useMemo(()=>{if(!r||!s||!n)return;Ru!==r&&(On.clear(),Ru=r);const o=r.messageToTurn.get(t);if(!o||!o.assistantMessages.some(T=>T.info.id===t))return;const l=r.lastTurnId===o.turnId,d=(s.turnUiStates.get(o.turnId)??{isExpanded:r.defaultActivityExpanded}).isExpanded,u=l?`${t}-${d}-${n.sessionIsWorking}`:`${t}-${d}`,m=On.get(u);if(m)return m;const f=r.turnActivityInfo.get(o.turnId),p=f?.activityParts??[],h=f?.activityGroupSegments??[],g=!!f?.hasTools,x=!!f?.hasReasoning,b=f?.summaryBody,y=f?.diffStats,w=o.assistantMessages[0]?.info.id,S=t===w,M=o.assistantMessages[o.assistantMessages.length-1]?.info.id,N=t===M,v=w,A=l&&n.sessionIsWorking,k=o.userMessage.info.time,C=typeof k?.created=="number"?k.created:void 0,j={turnId:o.turnId,isFirstAssistantInTurn:S,isLastAssistantInTurn:N,summaryBody:b,activityParts:p,activityGroupSegments:h,headerMessageId:v,hasTools:g,hasReasoning:x,diffStats:y,userMessageCreatedAt:C,isWorking:A,isGroupExpanded:d,toggleGroup:()=>s.toggleGroup(o.turnId)};if(On.size>500){const T=On.keys().next().value;T&&On.delete(T)}return On.set(u,j),j},[r,s,n,t])},Kp=t=>{const r=i.useContext(Jo);return i.useMemo(()=>r?r.messageNeighbors.get(t)??{}:{},[r,t])},wS=()=>i.useContext(Jo)?.lastTurnMessageIds??new Set,vS=t=>{const r=i.useContext(Jo),s=i.useContext($c);return i.useMemo(()=>{if(!r||!s)return;const n=r.messageToTurn.get(t);if(!n||!n.assistantMessages.some(N=>N.info.id===t))return;const a=r.turnActivityInfo.get(n.turnId),l=a?.activityParts??[],c=a?.activityGroupSegments??[],d=!!a?.hasTools,u=!!a?.hasReasoning,m=a?.summaryBody,f=a?.diffStats,p=n.assistantMessages[0]?.info.id,h=t===p,g=n.assistantMessages[n.assistantMessages.length-1]?.info.id,x=t===g,b=p,y=s.turnUiStates.get(n.turnId)??{isExpanded:r.defaultActivityExpanded},w=n.userMessage.info.time,S=typeof w?.created=="number"?w.created:void 0;return{turnId:n.turnId,isFirstAssistantInTurn:h,isLastAssistantInTurn:x,summaryBody:m,activityParts:l,activityGroupSegments:c,headerMessageId:b,hasTools:d,hasReasoning:u,diffStats:f,userMessageCreatedAt:S,isWorking:!1,isGroupExpanded:y.isExpanded,toggleGroup:()=>s.toggleGroup(n.turnId)}},[r,s,t])},jS=new Set(["task"]),Lu=t=>typeof t=="string"&&jS.has(t.toLowerCase()),SS=t=>{for(const r of t.assistantMessages)if(r.info.finish==="stop"){const n=r.parts.find(o=>o.type==="text");if(n){const o=n.text??n.content;if(typeof o=="string"&&o.trim().length>0)return o}}},NS=t=>{const r=SS(t);let s;const o=t.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let y=0,w=0,S=0;o.forEach(M=>{if(!M)return;const N=typeof M.additions=="number"?M.additions:0,v=typeof M.deletions=="number"?M.deletions:0;(N!==0||v!==0)&&(S+=1),y+=N,w+=v}),S>0&&(s={additions:y,deletions:w,files:S})}let a=!1,l=!1;t.assistantMessages.forEach(y=>{y.parts.forEach(w=>{w.type==="tool"?a=!0:w.type==="reasoning"&&(l=!0)})});const c=[];let d=0;t.assistantMessages.forEach(y=>{const w=y.info.id;y.info.finish,y.parts.forEach(S=>{const M=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${w}-activity-${d++}`;if(S.type==="tool"){const v=S.state?.time,A=typeof v?.end=="number"?v.end:void 0;c.push({id:M,turnId:t.turnId,messageId:w,kind:"tool",part:S,endedAt:A});return}if(S.type==="reasoning"){const N=S.text??S.content;if(typeof N!="string"||N.trim().length===0)return;const v=S.time,A=typeof v?.end=="number"?v.end:void 0;c.push({id:M,turnId:t.turnId,messageId:w,kind:"reasoning",part:S,endedAt:A});return}})});const u=[],m=new WeakMap;c.forEach(y=>{m.set(y.part,y)});const f=new Map,p=[],h=new Map;let g=null;t.assistantMessages.forEach(y=>{const w=y.info.id;y.parts.forEach(S=>{if(S.type==="tool"){const v=S.tool;if(Lu(v)){const A=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${w}-task-${p.length+1}`;f.has(A)||(f.set(A,w),p.push(A)),g=A;return}}const M=m.get(S);if(!M)return;if(M.kind==="tool"){const v=M.part.tool;if(Lu(v))return}const N=h.get(g)??[];N.push(M),h.set(g,N)})});const x=y=>{if(y.length===0)return;const w=new Map;y.forEach(N=>{w.set(N.messageId,(w.get(N.messageId)??0)+1)});let S,M=0;for(const N of t.assistantMessages){const v=w.get(N.info.id)??0;if(v>0&&!S&&(S=N.info.id),M+=v,M>=2)return N.info.id}return S};return[null,...p].forEach(y=>{const w=h.get(y)??[];if(w.length===0)return;const S=y===null?x(w):f.get(y);S&&u.push({id:`${t.turnId}:${S}:${y??"start"}`,anchorMessageId:S,afterToolPartId:y,parts:w})}),{activityParts:c,activityGroupSegments:u,hasTools:a,hasReasoning:l,summaryBody:r,diffStats:s}},kS=t=>{const r=new Map;return t.forEach((s,n)=>{r.set(s.info.id,{previousMessage:n>0?t[n-1]:void 0,nextMessage:n<t.length-1?t[n+1]:void 0})}),r},CS=({messages:t,children:r})=>{const{isWorking:s}=Lc(),n=Me(f=>f.toolCallExpansion),o=n==="activity"||n==="detailed",a=i.useMemo(()=>{const f=yS(t),p=f.length>0?f[f.length-1].turnId:null,h=new Map;f.forEach(y=>{h.set(y.userMessage.info.id,y),y.assistantMessages.forEach(w=>{h.set(w.info.id,y)})});const g=new Map;f.forEach(y=>{g.set(y.turnId,NS(y))});const x=kS(t),b=new Set;if(f.length>0){const y=f[f.length-1];b.add(y.userMessage.info.id),y.assistantMessages.forEach(w=>{b.add(w.info.id)})}return{turns:f,messageToTurn:h,turnActivityInfo:g,lastTurnId:p,lastTurnMessageIds:b,defaultActivityExpanded:o,messageNeighbors:x}},[t,o]),[l,c]=i.useState(()=>new Map);i.useEffect(()=>{c(new Map)},[n]);const d=i.useCallback(f=>{c(p=>{const h=new Map(p),g=h.get(f)??{isExpanded:o};return h.set(f,{isExpanded:!g.isExpanded}),h})},[o]),u=i.useMemo(()=>({turnUiStates:l,toggleGroup:d}),[l,d]),m=i.useMemo(()=>({sessionIsWorking:s}),[s]);return e.jsx(Jo.Provider,{value:a,children:e.jsx($c.Provider,{value:u,children:e.jsx(qp.Provider,{value:m,children:r})})})},Yp=i.memo(({message:t,onContentChange:r,animationHandlers:s,scrollToBottom:n})=>{const{previousMessage:o,nextMessage:a}=Kp(t.info.id),l=vS(t.info.id);return e.jsx(Gp,{message:t,previousMessage:o,nextMessage:a,onContentChange:r,animationHandlers:s,scrollToBottom:n,turnGroupingContext:l})});Yp.displayName="StaticMessageRow";const Qp=i.memo(({message:t,onContentChange:r,animationHandlers:s,scrollToBottom:n})=>{const{previousMessage:o,nextMessage:a}=Kp(t.info.id),l=bS(t.info.id);return e.jsx(Gp,{message:t,previousMessage:o,nextMessage:a,onContentChange:r,animationHandlers:s,scrollToBottom:n,turnGroupingContext:l})});Qp.displayName="DynamicMessageRow";const MS=({displayMessages:t,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:n})=>{const o=wS();return e.jsx(e.Fragment,{children:t.map(a=>{const c=o.has(a.info.id)?Qp:Yp;return e.jsx(c,{message:a,onContentChange:r,animationHandlers:s(a.info.id),scrollToBottom:n},a.info.id)})})},DS=({messages:t,permissions:r,questions:s,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:l,onLoadOlder:c,scrollToBottom:d})=>{i.useEffect(()=>{r.length===0&&s.length===0||n("permission")},[r,s,n]);const u=i.useMemo(()=>{const m=new Set;return t.filter(f=>{const p=f.info?.id;if(typeof p=="string"){if(m.has(p))return!1;m.add(p)}return!0}).map(f=>{const p=t0(f.parts);return p===f.parts?f:{...f,parts:p}})},[t]);return e.jsx(CS,{messages:u,children:e.jsxs("div",{children:[a&&e.jsx("div",{className:"flex justify-center py-3",children:l?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:c,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx(MS,{displayMessages:u,onMessageContentChange:n,getAnimationHandlers:o,scrollToBottom:d}),(s.length>0||r.length>0)&&e.jsxs("div",{children:[s.map(m=>e.jsx(xS,{question:m},m.id)),r.map(m=>e.jsx(gS,{permission:m},m.id))]}),e.jsx("div",{className:"flex-shrink-0",style:{height:"10vh"},"aria-hidden":"true"})]})})},AS=i.memo(DS);function ES(...t){return r=>{t.forEach(s=>{typeof s=="function"?s(r):s&&typeof s=="object"&&(s.current=r)})}}const Jp=i.forwardRef(({orientation:t="vertical",offset:r=72,size:s=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:l,className:c,children:d,...u},m)=>{const f=i.useRef(null),p=i.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const g=i.useMemo(()=>{const w={...l};return w["--scroll-shadow-size"]=`${s}px`,w},[s,l]),x=i.useCallback((w,S,M,N,v)=>{const A=`${N}${v.charAt(0).toUpperCase()}${v.slice(1)}Scroll`;S&&M?(w.dataset[A]="true",w.removeAttribute(`data-${N}-scroll`),w.removeAttribute(`data-${v}-scroll`)):(w.dataset[`${N}Scroll`]=String(S),w.dataset[`${v}Scroll`]=String(M),w.removeAttribute(`data-${N}-${v}-scroll`))},[]),b=i.useCallback(w=>{["top","bottom","top-bottom","left","right","left-right"].forEach(S=>{w.removeAttribute(`data-${S}-scroll`)})},[]),y=i.useCallback(()=>{const w=f.current;if(!w)return;if(!n){b(w);return}const S=t==="vertical"?w.scrollTop>r:w.scrollLeft>r;let M=t==="vertical"?w.scrollTop+w.clientHeight+r<w.scrollHeight:w.scrollLeft+w.clientWidth+r<w.scrollWidth;o&&t==="vertical"&&(M=!1),x(w,S,M,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const N=S&&M?"both":S?t==="vertical"?"top":"left":M?t==="vertical"?"bottom":"right":"none";N!==p.current&&(p.current=N,a?.(N))},[b,o,n,r,a,t,x]);return i.useEffect(()=>{const w=f.current;if(!w)return;let S=null;const M=()=>{S===null&&(S=requestAnimationFrame(()=>{S=null,y()}))},N=()=>y(),v=typeof ResizeObserver<"u"?new ResizeObserver(M):null,A=typeof MutationObserver<"u"?new MutationObserver(M):null;return y(),w.addEventListener("scroll",N,{passive:!0}),v?.observe(w),A?.observe(w,{childList:!0,subtree:!0,characterData:!0}),()=>{S!==null&&cancelAnimationFrame(S),w.removeEventListener("scroll",N),v?.disconnect(),A?.disconnect()}},[y]),e.jsx("div",{...u,ref:ES(f,m),className:c,"data-orientation":t,"data-scroll-shadow":h??!0,style:g,children:d})});Jp.displayName="ScrollShadow";const IS=160,PS=({containerRef:t})=>{const[r,s]=i.useState(!0),n=i.useRef(!0),o=i.useRef(!1),a=i.useRef(null),l=i.useRef(null),c=i.useRef(0),d=i.useRef(0),u=i.useRef(!1),m=i.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,l.current=null,u.current=!1},[]),f=i.useCallback(M=>{const N=t.current;if(!N){m();return}l.current===null&&(l.current=M),u.current&&(d.current=N.scrollHeight-N.clientHeight);const v=Math.min(1,(M-l.current)/IS),A=1-Math.pow(1-v,3),k=c.current,C=d.current,j=k+(C-k)*A;if(N.scrollTop=j,v<1){a.current=window.requestAnimationFrame(f);return}N.scrollTop=C,m(),n.current&&(n.current=!1,s(!1))},[m,t,s]),p=i.useCallback((M,N)=>{const v=t.current;if(!v)return;const A=Math.max(0,M),k=N?.instant??!1,C=N?.followBottom??!1;if(o.current=!1,typeof window>"u"||k){m(),v.scrollTop=A;const T=A<=1;n.current!==T&&(n.current=T,s(T));return}if(C&&u.current&&a.current!==null)return;if(m(),Math.abs(A-v.scrollTop)<=.5){v.scrollTop=A;const T=A<=1;n.current!==T&&(n.current=T,s(T));return}c.current=v.scrollTop,d.current=A,l.current=null,u.current=C,a.current=window.requestAnimationFrame(f)},[m,t,f,s]),h=i.useCallback(()=>{o.current=!0},[]),g=i.useCallback(()=>{o.current=!0},[]),x=i.useCallback(()=>o.current,[]),b=i.useCallback(()=>t.current?.scrollTop??0,[t]),y=i.useCallback(()=>t.current?.scrollHeight??0,[t]),w=i.useCallback(()=>t.current?.clientHeight??0,[t]),S=i.useCallback(()=>{const M=t.current;if(!M)return;o.current&&a.current!==null&&m();const N=M.scrollTop<=1;n.current!==N&&(n.current=N,s(N))},[m,t]);return i.useEffect(()=>{const M=t.current;if(M)return M.addEventListener("wheel",g,{passive:!0}),M.addEventListener("touchstart",g,{passive:!0}),()=>{M.removeEventListener("wheel",g),M.removeEventListener("touchstart",g)}},[t,g]),i.useEffect(()=>()=>{m()},[m]),i.useMemo(()=>({handleScroll:S,scrollToPosition:p,forceManualMode:h,isAtTop:r,isManualOverrideActive:x,getScrollTop:b,getScrollHeight:y,getClientHeight:w}),[S,p,h,r,x,b,y,w])},TS=typeof window<"u"?i.useLayoutEffect:i.useEffect,FS=200,RS=250,LS=.1,OS=({currentSessionId:t,sessionMessages:r,updateViewportAnchor:s,isSyncing:n,isMobile:o})=>{const a=i.useRef(null),l=PS({containerRef:a}),c=i.useCallback(()=>{const P=a.current;if(!P||P.clientHeight<=0)return 0;const D=P.clientHeight*LS;return Math.max(24,Math.min(200,D))},[]),[d,u]=i.useState(!1),[m,f]=i.useState(!0),p=i.useRef(null),h=i.useRef(t??null),g=i.useRef(0),x=i.useRef(0),b=i.useRef(!0),y=i.useRef(0);i.useEffect(()=>{h.current=t??null},[t]);const w=i.useCallback(()=>{g.current=Date.now()+FS},[]),S=i.useCallback(()=>{const P=a.current;return P?P.scrollHeight-P.scrollTop-P.clientHeight:0},[]),M=i.useCallback(P=>{b.current!==P&&(b.current=P,f(P))},[]),N=i.useCallback(P=>{const D=a.current;if(!D)return;const E=D.scrollHeight-D.clientHeight;w(),l.scrollToPosition(Math.max(0,E),P)},[w,l]),v=i.useCallback(()=>{const P=a.current;if(!P){u(!1);return}if(!(P.scrollHeight>P.clientHeight)){u(!1);return}const E=S();u(E>c())},[S,c]),A=i.useCallback((P,D)=>{a.current&&(w(),l.scrollToPosition(Math.max(0,P),D))},[w,l]),k=i.useCallback(P=>{a.current&&(M(!0),N(P),u(!1))},[N,M]),C=i.useCallback(P=>{const D=a.current;if(!D||!t)return;const E=Date.now(),F=E<g.current,B=E-x.current<=RS;l.handleScroll(),v();const V=D.scrollTop;P?.isTrusted&&!F&&B&&V<y.current&&b.current&&M(!1),b.current||S()<=c()&&M(!0),y.current=V;const{scrollTop:ne,scrollHeight:O,clientHeight:G}=D,K=(ne+G/2)/Math.max(O,1),q=Math.floor(K*r.length);s(t,q)},[t,S,c,l,r.length,M,v,s]);i.useEffect(()=>{const P=a.current;if(!P)return;const D=()=>{x.current=Date.now()};return P.addEventListener("scroll",C,{passive:!0}),P.addEventListener("wheel",D,{passive:!0}),P.addEventListener("touchmove",D,{passive:!0}),()=>{P.removeEventListener("scroll",C),P.removeEventListener("wheel",D),P.removeEventListener("touchmove",D)}},[C]),TS(()=>{if(!t||t===p.current)return;p.current=t,qr.getInstance().recordSessionStart(t),M(!0),u(!1),a.current&&(w(),N({instant:!0}))},[t,w,N,M]),i.useEffect(()=>{if(!b.current||n||!a.current)return;S()>c()&&(w(),N({instant:!0}))},[S,c,n,w,N,r]),i.useEffect(()=>{const P=a.current;if(!P||typeof ResizeObserver>"u")return;const D=new ResizeObserver(()=>{v(),b.current&&S()>c()&&N({instant:!0})});D.observe(P);const E=new MutationObserver(()=>{b.current&&S()>c()&&N({instant:!0})});return E.observe(P,{childList:!0,subtree:!0}),()=>{D.disconnect(),E.disconnect()}},[S,c,N,v]),i.useEffect(()=>{if(typeof window>"u"){v();return}const P=window.requestAnimationFrame(()=>{v()});return()=>{window.cancelAnimationFrame(P)}},[t,r.length,v]);const j=i.useRef(new Map),T=i.useCallback(()=>{v(),b.current&&S()>c()&&N({instant:!0})},[S,c,N,v]),I=i.useCallback(P=>{const D=j.current.get(P);if(D)return D;const E={onChunk:()=>{v(),b.current&&S()>c()&&N({instant:!0})},onComplete:()=>{v()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{v(),b.current&&S()>c()&&N({instant:!0})},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return j.current.set(P,E),E},[S,c,N,v]);return{scrollRef:a,handleMessageContentChange:T,getAnimationHandlers:I,showScrollButton:d,scrollToBottom:k,scrollToPosition:A,isPinned:m}};function _S(t){const s=Date.now()-t,n=Math.floor(s/1e3),o=Math.floor(n/60),a=Math.floor(o/60),l=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:l<7?`${l}d ago`:new Date(t).toLocaleDateString()}const $S=({open:t,onOpenChange:r,onScrollToMessage:s})=>{const n=be(x=>x.currentSessionId),o=St(x=>n?x.messages.get(n)||[]:[]),a=be(x=>x.revertToMessage),l=be(x=>x.forkFromMessage),c=be(x=>x.loadSessions),[d,u]=i.useState(null),[m,f]=i.useState(""),p=i.useMemo(()=>o.filter(b=>b.info.role==="user").reverse(),[o]),h=i.useMemo(()=>{if(!m.trim())return p;const x=m.toLowerCase();return p.filter(b=>Ou(b.parts).toLowerCase().includes(x))},[p,m]),g=async x=>{if(n){u(x);try{await l(n,x),await c(),r(!1)}finally{u(null)}}};return n?e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ps,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(bs,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(kr,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Ns,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(wt,{placeholder:"Search messages...",value:m,onChange:x=>f(x.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(x=>{const b=Ou(x.parts),y=x.info.time.created,w=_S(y),S=p.length-p.indexOf(x);return e.jsxs("div",{className:"group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",onClick:()=>{s?.(x.info.id),r(!1)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:[S,"."]}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:[b||"[No text content]",b&&b.length>=80&&"…"]}),e.jsxs("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground whitespace-nowrap group-hover:hidden",children:w}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{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 M=>{M.stopPropagation(),await a(n,x.info.id),r(!1)},children:e.jsx(Zn,{className:"h-4 w-4"})})}),e.jsx(ct,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{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:M=>{M.stopPropagation(),g(x.info.id)},disabled:d===x.info.id,children:d===x.info.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Vt,{className:"h-4 w-4"})})}),e.jsx(ct,{sideOffset:6,children:"Fork from here"})]})]})]})]},x.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(Zn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Undo to this point (message text will populate input)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function Ou(t){const r=t.find(s=>s.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const Xp=()=>{const{currentSessionId:t,messages:r,permissions:s,questions:n,streamingMessageIds:o,isLoading:a,loadMessages:l,loadMoreMessages:c,updateViewportAnchor:d,sessionMemoryState:u,openNewSessionDraft:m,isSyncing:f,messageStreamStates:p,trimToViewportWindow:h,sessionActivityPhase:g,newSessionDraft:x}=be(),{isTimelineDialogOpen:b,setTimelineDialogOpen:y}=Me(),w=i.useMemo(()=>t?o.get(t)??null:null,[t,o]),{isMobile:S}=qt(),M=!!x?.open;i.useEffect(()=>{!t&&!M&&m()},[t,M,m]);const N=i.useMemo(()=>t?r.get(t)||[]:[],[t,r]),v=i.useMemo(()=>t?s.get(t)||[]:[],[t,s]),A=i.useMemo(()=>t?n.get(t)||[]:[],[t,n]);i.useMemo(()=>[...v,...A],[v,A]);const{scrollRef:k,handleMessageContentChange:C,getAnimationHandlers:j,showScrollButton:T,scrollToBottom:I,scrollToPosition:P,isPinned:D}=OS({currentSessionId:t,sessionMessages:N,updateViewportAnchor:d,isSyncing:f,isMobile:S}),F=!!i.useMemo(()=>t?u.get(t)??null:null,[t,u])?.hasMoreAbove,[B,V]=i.useState(!1);i.useEffect(()=>{V(!1)},[t]);const ne=i.useCallback(async()=>{if(!t||B)return;const G=k.current,K=G?.scrollHeight??null,q=G?.scrollTop??null;V(!0);try{if(await c(t,"up"),G&&K!==null&&q!==null){const $=G.scrollHeight-K;P(q+$,{instant:!0})}}finally{V(!1)}},[t,B,c,k,P]),O=i.useCallback(G=>{const K=k.current;if(!K)return;const q=K.querySelector(`[data-message-id="${G}"]`);if(q){const $=K.getBoundingClientRect(),X=q.getBoundingClientRect().top-$.top+K.scrollTop-50;K.scrollTo({top:X,behavior:"smooth"})}},[k]);return i.useEffect(()=>{if(!t||(r.has(t)?r.get(t)??[]:[]).length>0)return;(async()=>{try{await l(t)}finally{const $=g?.get(t)??"idle";($==="busy"||$==="cooldown")&&D||(typeof window>"u"?I():window.requestAnimationFrame(()=>{I()}))}})()},[t,D,l,r,I,g]),!t&&!M?e.jsx("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(sl,{})}):!t&&M?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(sl,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(ga,{scrollToBottom:I})})]}):t?a&&N.length===0&&!w&&!r.has(t)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-message-column space-y-4",children:[1,2,3].map(K=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(tl,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(tl,{className:"h-4 w-24"}),e.jsx(tl,{className:"h-20 w-full"})]})]},K))})}),e.jsx(ga,{scrollToBottom:I})]}):N.length===0&&!w?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(sl,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(ga,{scrollToBottom:I})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(Jp,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:k,style:{contain:"strict","--scroll-shadow-size":"48px",transform:"translateZ(0)",willChange:"scroll-position",backfaceVisibility:"hidden"},"data-scroll-shadow":"true","data-scrollbar":"chat",children:e.jsx("div",{className:"relative z-0 min-h-full",children:e.jsx(AS,{messages:N,permissions:v,questions:A,onMessageContentChange:C,getAnimationHandlers:j,hasMoreAbove:F,isLoadingOlder:B,onLoadOlder:ne,scrollToBottom:I})})}),e.jsx(kc,{containerRef:k})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[T&&N.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(je,{variant:"outline",size:"sm",onClick:()=>I({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(fo,{className:"h-4 w-4"})})}),e.jsx(ga,{scrollToBottom:I})]}),e.jsx($S,{open:b,onOpenChange:y,onScrollToMessage:O})]}):null};class Zp extends i.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,s){this.setState({error:r,errorInfo:s})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(Pc,{className:"w-full max-w-md",children:[e.jsx(up,{className:"text-center",children:e.jsxs(mp,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(gx,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(fp,{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(je,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ls,{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 Io=()=>{const t=be(r=>r.currentSessionId);return e.jsx(Zp,{sessionId:t||void 0,children:e.jsx(Xp,{})})},_u=new fi,$u=new fi,Bu=new fi,zu=new fi,Hu=t=>{if(!t)return[];const r=Math.max(1,t.start),s=Math.max(r,t.end);return kx.fromClass(class{decorations;constructor(n){this.decorations=this.build(n)}update(n){(n.docChanged||n.viewportChanged)&&(this.decorations=this.build(n.view))}build(n){const o=new Cx;for(let a=r;a<=s&&a<=n.state.doc.lines;a+=1){const l=n.state.doc.line(a);o.add(l.from,l.from,Mx.line({class:"oc-cm-selected-line"}))}return o.finish()}},{decorations:n=>n.decorations})};function Xl({value:t,onChange:r,extensions:s,className:n,readOnly:o,lineNumbersConfig:a,highlightLines:l}){const c=i.useRef(null),d=i.useRef(null),u=i.useRef(t),m=i.useRef(r);return i.useEffect(()=>{u.current=t},[t]),i.useEffect(()=>{m.current=r},[r]),i.useEffect(()=>{if(!c.current)return;const f=xx.create({doc:u.current,extensions:[yx({fixed:!0}),_u.of(Xc(a)),bx(),wx.of(" "),vx.of([jx,...Sx,...Nx]),fn.updateListener.of(p=>{if(!p.docChanged)return;const h=p.state.doc.toString();u.current=h,m.current(h)}),$u.of(fn.editable.of(!o)),Bu.of(s??[]),zu.of(Hu(l))]});return d.current=new fn({state:f,parent:c.current}),()=>{d.current?.destroy(),d.current=null}},[]),i.useEffect(()=>{const f=d.current;f&&f.dispatch({effects:[_u.reconfigure(Xc(a)),$u.reconfigure(fn.editable.of(!o)),Bu.reconfigure(s??[]),zu.reconfigure(Hu(l))]})},[s,l,a,o]),i.useEffect(()=>{const f=d.current;if(!f)return;const p=f.state.doc.toString();p!==t&&f.dispatch({changes:{from:0,to:p.length,insert:t}})},[t]),e.jsx("div",{ref:c,className:L("h-full w-full","[&_.cm-editor]:h-full [&_.cm-editor]:w-full","[&_.cm-scroller]:font-mono [&_.cm-scroller]:text-[var(--text-code)] [&_.cm-scroller]:leading-6",n)})}const Zl=({currentMode:t,onToggle:r})=>{const s=t==="preview",n=s?"Switch to edit mode":"Switch to preview mode",o=s?"Edit":"Preview";return e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{variant:"ghost",size:"icon",onClick:r,"aria-label":n,className:"size-8",children:s?e.jsx(Dx,{className:"size-4","aria-hidden":"true"}):e.jsx(Ax,{className:"size-4","aria-hidden":"true"})})}),e.jsx(ct,{sideOffset:8,children:o})]})};function ec(t){const r=t.metadata.variant==="dark",s=t.config?.fonts?.mono||"monospace",n=t.colors.syntax.highlights||{},o=t.colors.syntax.tokens||{},a=fn.theme({"&":{backgroundColor:"var(--background)",color:t.colors.syntax.base.foreground,fontSize:"var(--text-code)",lineHeight:"1.5rem"},".cm-scroller":{fontFamily:s,backgroundColor:"var(--background)"},".cm-comment":{color:t.colors.syntax.base.comment},".cm-keyword":{color:t.colors.syntax.base.keyword},".cm-string":{color:t.colors.syntax.base.string},".cm-string-2":{color:o.stringEscape||t.colors.syntax.base.string},".cm-number":{color:t.colors.syntax.base.number},".cm-atom":{color:o.boolean||t.colors.syntax.base.number},".cm-builtin":{color:o.functionCall||t.colors.syntax.base.function},".cm-def":{color:o.variableGlobal||t.colors.syntax.base.variable},".cm-attribute":{color:o.variableOther||o.variableProperty||t.colors.syntax.base.operator},".cm-meta":{color:t.colors.syntax.base.comment},".cm-property":{color:o.variableProperty||t.colors.syntax.base.keyword},".cm-variable":{color:t.colors.syntax.base.variable},".cm-variable-2":{color:o.variableOther||t.colors.syntax.base.function},".cm-variable-3":{color:o.variableGlobal||t.colors.syntax.base.type},".cm-tag":{color:o.tag||t.colors.syntax.base.keyword},".cm-link":{color:o.url||t.colors.syntax.base.keyword,textDecoration:"underline"},".cm-content":{caretColor:t.colors.interactive.cursor},".cm-cursor, .cm-dropCursor":{borderLeftColor:t.colors.interactive.cursor},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:t.colors.interactive.selection},".cm-gutters":{backgroundColor:"var(--background)",color:n.lineNumber||t.colors.syntax.base.comment,borderRight:`1px solid ${t.colors.interactive.border}`,position:"sticky",paddingRight:"8px",left:0,zIndex:2,boxShadow:"0 0 0 var(--background)"},".cm-gutter":{backgroundColor:"var(--background)"},".cm-gutterElement":{backgroundColor:"var(--background)"},".cm-lineNumbers":{backgroundColor:"var(--background)"},".cm-lineNumbers .cm-gutterElement":{paddingLeft:"8px",paddingRight:"8px",minWidth:"42px"},".cm-activeLineGutter":{color:n.lineNumberActive||t.colors.syntax.base.foreground},".cm-activeLine":{backgroundColor:t.colors.surface.overlay},"&.cm-focused":{outline:"none"}},{dark:r}),l=Jm.define([{tag:Qe.comment,color:t.colors.syntax.base.comment},{tag:Qe.docComment,color:o.commentDoc||t.colors.syntax.base.comment},{tag:Qe.keyword,color:t.colors.syntax.base.keyword},{tag:Qe.controlKeyword,color:t.colors.syntax.base.keyword},{tag:Qe.operatorKeyword,color:t.colors.syntax.base.operator},{tag:Qe.moduleKeyword,color:o.keywordImport||t.colors.syntax.base.keyword},{tag:[Qe.definitionKeyword,Qe.modifier],color:o.storageModifier||t.colors.syntax.base.keyword},{tag:Qe.atom,color:o.boolean||t.colors.syntax.base.number},{tag:[Qe.null,Qe.self],color:t.colors.syntax.base.number},{tag:[Qe.meta,Qe.documentMeta],color:t.colors.syntax.base.comment},{tag:Qe.string,color:t.colors.syntax.base.string},{tag:Qe.escape,color:o.stringEscape||t.colors.syntax.base.foreground},{tag:Qe.regexp,color:o.regex||t.colors.syntax.base.string},{tag:Qe.number,color:t.colors.syntax.base.number},{tag:Qe.bool,color:o.boolean||t.colors.syntax.base.number},{tag:Qe.operator,color:t.colors.syntax.base.operator},{tag:[Qe.derefOperator,Qe.updateOperator,Qe.definitionOperator,Qe.typeOperator,Qe.controlOperator],color:t.colors.syntax.base.operator},{tag:[Qe.logicOperator,Qe.bitwiseOperator,Qe.arithmeticOperator],color:t.colors.syntax.base.operator},{tag:[Qe.compareOperator],color:o.diffModified||t.colors.syntax.base.operator},{tag:[Qe.punctuation,Qe.separator,Qe.bracket,Qe.paren,Qe.brace,Qe.squareBracket,Qe.angleBracket],color:o.punctuation||t.colors.syntax.base.comment},{tag:Qe.function(Qe.variableName),color:o.functionCall||t.colors.syntax.base.function},{tag:Qe.function(Qe.definition(Qe.variableName)),color:t.colors.syntax.base.function},{tag:Qe.function(Qe.propertyName),color:o.method||o.functionCall||t.colors.syntax.base.function},{tag:Qe.namespace,color:o.namespace||t.colors.syntax.base.type},{tag:Qe.moduleKeyword,color:o.module||t.colors.syntax.base.keyword},{tag:Qe.macroName,color:o.macro||t.colors.syntax.base.keyword},{tag:Qe.labelName,color:o.label||t.colors.syntax.base.keyword},{tag:Qe.annotation,color:o.decorator||t.colors.syntax.base.keyword},{tag:Qe.propertyName,color:o.variableProperty||t.colors.syntax.base.keyword},{tag:Qe.attributeName,color:o.tagAttribute||t.colors.syntax.base.keyword},{tag:Qe.standard(Qe.variableName),color:o.method||t.colors.syntax.base.function},{tag:Qe.definition(Qe.variableName),color:t.colors.syntax.base.variable},{tag:Qe.local(Qe.variableName),color:t.colors.syntax.base.variable},{tag:Qe.special(Qe.variableName),color:o.variableOther||t.colors.syntax.base.function},{tag:Qe.variableName,color:t.colors.syntax.base.variable},{tag:Qe.special(Qe.string),color:t.colors.syntax.base.string},{tag:Qe.className,color:o.className||t.colors.syntax.base.type},{tag:Qe.typeName,color:t.colors.syntax.base.type},{tag:Qe.constant(Qe.variableName),color:o.constant||t.colors.syntax.base.variable},{tag:Qe.literal,color:o.constant||t.colors.syntax.base.variable},{tag:Qe.tagName,color:o.tag||t.colors.syntax.base.keyword},{tag:Qe.attributeValue,color:o.tagAttributeValue||t.colors.syntax.base.string},{tag:[Qe.heading,Qe.heading1,Qe.heading2,Qe.heading3,Qe.heading4,Qe.heading5,Qe.heading6],color:t.colors.syntax.base.keyword,fontWeight:"600"},{tag:Qe.monospace,color:t.colors.syntax.base.string},{tag:Qe.link,color:o.url||t.colors.syntax.base.keyword,textDecoration:"underline"}]);return[a,Xm(l)]}const tc=po.define(Ex),eh=po.define(Ix),BS=po.define(Px),zS=po.define(Tx),HS=po.define(Fx),WS=po.define(Rx);function US(t){const r=t.trim().toLowerCase();switch(r){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return tc;case"toml":return eh;case"diff":case"patch":return BS;case"json":case"jsonc":case"json5":return af().language;case"js":case"javascript":return Hn().language;case"jsx":return Hn({jsx:!0}).language;case"ts":case"typescript":return Hn({typescript:!0}).language;case"tsx":return Hn({typescript:!0,jsx:!0}).language;case"yaml":case"yml":return rf().language;case"html":return nf().language;case"css":return of().language;case"xml":case"svg":return ef().language;case"py":case"python":return sf().language;case"sql":return tf().language;case"rs":case"rust":return Zm().language;default:return Ox.matchLanguageName(_x,r,!0)}}const VS=t=>t.split("/").pop()?.toLowerCase()??"",GS=()=>Xm(Jm.define([{tag:[Qe.heading1,Qe.heading2,Qe.heading3,Qe.heading4,Qe.heading5,Qe.heading6],fontWeight:"600"},{tag:Qe.strong,fontWeight:"600"},{tag:Qe.emphasis,fontStyle:"italic"},{tag:Qe.strikethrough,textDecoration:"line-through"},{tag:[Qe.link,Qe.url],color:"var(--markdown-link, currentColor)",textDecoration:"underline"},{tag:Qe.monospace,color:"var(--markdown-inline-code, currentColor)",backgroundColor:"var(--markdown-inline-code-bg, transparent)"},{tag:Qe.quote,color:"var(--markdown-blockquote, currentColor)",fontStyle:"italic"},{tag:Qe.list,color:"color-mix(in srgb, var(--muted-foreground) 40%, var(--foreground) 60%)"},{tag:Qe.heading,color:"var(--markdown-heading1, currentColor)"}]));function th(t){const r=t.toLowerCase();switch(VS(r)){case"dockerfile":return zS;case"makefile":case"gnumakefile":return tc}const n=r.lastIndexOf("."),o=n>=0?r.slice(n+1):"";switch(o){case"ts":case"tsx":case"mts":case"cts":return Hn({typescript:!0,jsx:o==="tsx"});case"js":case"jsx":case"mjs":case"cjs":return Hn({typescript:!1,jsx:o==="jsx"});case"json":case"jsonc":case"json5":case"jsonl":case"ndjson":case"geojson":return af();case"css":case"scss":case"sass":case"less":return of();case"html":case"htm":return nf();case"md":case"mdx":case"markdown":case"mdown":case"mkd":return[Lx({codeLanguages:US}),GS()];case"yml":case"yaml":return rf();case"toml":return eh;case"ini":case"cfg":case"conf":case"config":case"properties":return WS;case"sh":case"bash":case"zsh":case"fish":case"env":return tc;case"py":case"pyw":case"pyi":return sf();case"sql":case"psql":case"plsql":return tf();case"xml":case"xsl":case"xslt":case"xsd":case"dtd":case"plist":case"svg":return ef();case"rs":return Zm();case"rb":case"erb":case"rake":case"gemspec":return HS;default:return null}}const Po=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},il=(t,r)=>{const s=Po(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},qS=(t,r,s)=>il(il(il(t,".opencode"),"plans"),`${r}-${s}.md`),KS=(t,r)=>`~/.opencode/plans/${t}-${r}.md`,YS=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},QS=(t,r)=>{const s=Po(r.currentDirectory),n=Po(r.homeDirectory),o=Po(t);return s&&o.startsWith(s+"/")?o.slice(s.length+1):n&&o===n?"~":n&&o.startsWith(n+"/")?`~${o.slice(n.length)}`:o},JS=()=>{const t=be(R=>R.currentSessionId),r=be(R=>R.sessions),s=xt(R=>R.homeDirectory),n=Hs(),o=be(R=>R.sendMessage),{currentProviderId:a,currentModelId:l,currentAgentName:c,currentVariant:d}=Ze(),u=tt(R=>R.getSessionAgentSelection),m=tt(R=>R.getAgentModelForSession),f=tt(R=>R.getAgentModelVariantForSession),p=Me(R=>R.setActiveMainTab),{inputBarOffset:h,isKeyboardOpen:g}=Me(),{isMobile:x}=qt(),{currentTheme:b}=Hr();i.useMemo(()=>Pi(b),[b]);const y=i.useMemo(()=>t?r.find(R=>R.id===t)??null:null,[t,r]),w=i.useMemo(()=>{const R=typeof y?.directory=="string"?y.directory:"";return Po(R||"")},[y?.directory]),[S,M]=i.useState(null),N=i.useMemo(()=>!S||!w||!s?S:QS(S,{currentDirectory:w,homeDirectory:s}),[S,w,s]),[v,A]=i.useState(""),[k,C]=i.useState(!1),[j,T]=i.useState(!1),[I,P]=i.useState(!1),[D,E]=i.useState("edit"),F=i.useRef(null),B=i.useRef(null),[V,ne]=i.useState(null),[O,G]=i.useState(""),K="openchamber:plan:md-viewer-mode";i.useEffect(()=>{try{const R=localStorage.getItem(K);if(!R)return;const de=JSON.parse(R);(de==="preview"||de==="edit")&&E(de)}catch{}},[]);const q=i.useCallback(R=>{E(R);try{localStorage.setItem(K,JSON.stringify(R))}catch{}},[]),$=i.useRef(!1),W=i.useRef(null);i.useEffect(()=>{const R=()=>{$.current=!1,W.current=null};return document.addEventListener("mouseup",R),()=>document.removeEventListener("mouseup",R)},[]),i.useEffect(()=>{ne(null),G("")},[v]),i.useEffect(()=>{if(!V)return;const R=we=>{const xe=we.target;document.querySelector("[data-comment-ui]")?.contains(xe)||xe.closest(".cm-gutterElement")||xe.closest("[data-sonner-toast]")||xe.closest("[data-sonner-toaster]")||(ne(null),G(""))},de=window.setTimeout(()=>{document.addEventListener("click",R)},100);return()=>{window.clearTimeout(de),document.removeEventListener("click",R)}},[V]);const Y=i.useCallback((R,de)=>{const we=R.split(`
|
|
195
|
+
`),xe=Math.max(1,de.start),Pe=Math.min(we.length,de.end);return xe>Pe?"":we.slice(xe-1,Pe).join(`
|
|
196
|
+
`)},[]),X=i.useCallback(async()=>{if(!V||!O.trim()||!t)return;const R=u(t)||c,de=R?m(t,R):null,we=de?.providerId||a,xe=de?.modelId||l;if(!we||!xe)return;const Pe=R&&we&&xe?f(t,R,we,xe)??d:d,H=V.start,ye=V.end,J=Y(v,V),ce=N&&N.split("/").pop()||"plan",ge=S&&Ar(S)||"markdown",ee=`Comment on \`${ce}\` lines ${H}-${ye}:
|
|
197
|
+
|
|
198
|
+
\`\`\`${ge}
|
|
199
|
+
${J}
|
|
200
|
+
\`\`\`
|
|
201
|
+
|
|
202
|
+
${O}`;G(""),ne(null),p("chat"),o(ee,we,xe,R,void 0,void 0,void 0,Pe).catch(()=>{})},[V,O,t,a,l,c,d,v,S,N,Y,o,p,u,m,f]),Z=i.useMemo(()=>{const R=[ec(b)],de=th(S||"plan.md");return de&&R.push(de),R.push(fn.lineWrapping),R},[b,S]);i.useEffect(()=>{let R=!1;const de=async Pe=>{if(n.files?.readFile)return(await n.files.readFile(Pe))?.content??"";const H=await fetch(`/api/fs/read?path=${encodeURIComponent(Pe)}`);if(!H.ok)throw new Error(`Failed to read plan file (${H.status})`);return H.text()},we=async Pe=>{if(Pe&&(M(null),A("")),!y?.slug||!y?.time?.created||!w){M(null),A("");return}Pe&&C(!0);try{const H=qS(w,y.time.created,y.slug),ye=YS(KS(y.time.created,y.slug),s||null);let J=null,ce=null;try{ce=await de(H),J=H}catch{}if(!J)try{ce=await de(ye),J=ye}catch{}if(R)return;if(!J||ce===null){M(null),A("");return}M(J),A(ce)}catch{if(R)return;M(null),A("")}finally{!R&&Pe&&C(!1)}};we(!0);const xe=window.setInterval(()=>{we(!1)},3e3);return()=>{R=!0,window.clearInterval(xe)}},[w,y?.slug,y?.time?.created,s,n.files]),i.useEffect(()=>()=>{F.current!==null&&window.clearTimeout(F.current),B.current!==null&&window.clearTimeout(B.current)},[]);const z=()=>V?e.jsx("div",{"data-comment-ui":!0,className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-background flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Fs,{value:O,onChange:R=>{G(R.target.value);const de=R.target;de.style.height="auto";const xe=20*5+8;de.style.height=`${Math.min(de.scrollHeight,xe)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!x,rows:1,onKeyDown:R=>{R.key==="Enter"&&(R.metaKey||R.ctrlKey)&&(R.preventDefault(),X()),R.key==="Escape"&&(R.preventDefault(),ne(null),G(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Plan:",V.start,"-",V.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!x&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Xt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:R=>{O.trim()&&(R.preventDefault(),X())},onClick:()=>{x||X()},disabled:!O.trim(),className:L("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",O.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Uo,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return e.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Plan"}),S?e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:N??S,children:N??S}):null]}),S?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Zl,{currentMode:D,onToggle:()=>q(D==="preview"?"edit":"preview")}),e.jsx(je,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(v),P(!0),B.current!==null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{P(!1)},1200)}catch{}},className:"h-5 w-5 p-0",title:"Copy plan contents","aria-label":"Copy plan contents",children:I?e.jsx(Pt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(za,{className:"h-4 w-4"})}),e.jsx(je,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(N??S),T(!0),F.current!==null&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{T(!1)},1200)}catch{}},className:"h-5 w-5 p-0",title:`Copy plan path (${N??S})`,"aria-label":`Copy plan path (${N??S})`,children:j?e.jsx(Pt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Al,{className:"h-4 w-4"})})]}):null]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(gt,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:k?e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Loading…"}):e.jsx("div",{className:"relative h-full",children:e.jsx("div",{className:"h-full",style:{"--oc-plan-comment-pad":V?x?"calc(var(--oc-keyboard-inset, 0px) + 140px)":"140px":"0px"},children:e.jsx("div",{className:"h-full oc-plan-editor",children:D==="preview"?e.jsx("div",{className:"h-full overflow-auto p-3",children:e.jsx(ls,{fallback:e.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[e.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:e.jsx(Nr,{content:v,className:"typography-markdown-body"})})}):e.jsx(Xl,{value:v,onChange:()=>{},readOnly:!0,className:"h-full [&_.cm-scroller]:pb-[var(--oc-plan-comment-pad)]",extensions:Z,highlightLines:V?{start:Math.min(V.start,V.end),end:Math.max(V.start,V.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(R,de,we)=>{if(!(we instanceof MouseEvent)||we.button!==0)return!1;we.preventDefault();const xe=R.state.doc.lineAt(de.from).number;if(x&&V&&!we.shiftKey){const Pe=Math.min(V.start,V.end,xe),H=Math.max(V.start,V.end,xe);return ne({start:Pe,end:H}),$.current=!1,W.current=null,!0}if($.current=!0,W.current=xe,V&&we.shiftKey){const Pe=Math.min(V.start,xe),H=Math.max(V.end,xe);ne({start:Pe,end:H})}else ne({start:xe,end:xe});return!0},mouseover:(R,de,we)=>{if(!(we instanceof MouseEvent)||we.buttons!==1||!$.current||W.current===null)return!1;const xe=R.state.doc.lineAt(de.from).number,Pe=Math.min(W.current,xe),H=Math.max(W.current,xe);return ne({start:Pe,end:H}),!1},mouseup:()=>($.current=!1,W.current=null,!1)}}})})})})})}),V&&D!=="preview"&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex flex-col justify-end",style:{paddingBottom:x?"var(--oc-keyboard-inset, 0px)":"0px"},children:e.jsx("div",{className:L("pointer-events-auto pb-2 transition-none w-full flex justify-center",x&&g?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:x&&!g&&h>0?`${h}px`:"16px"},"data-keyboard-avoid":"true",children:z()})})]})},Wu=12,XS=[{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"}],ZS=({isActive:t,burstKey:r=0,className:s,durationMs:n=900,bursts:o=XS,onComplete:a})=>{const l=Ae.useRef(!1);Ae.useEffect(()=>{!t&&l.current&&a?.(),t&&(l.current=!0)},[t,a]);const c=Ae.useMemo(()=>Array.from({length:Wu},(d,u)=>{const m=Math.PI*2*u/Wu;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return t?e.jsx("div",{className:L("fireworks-overlay pointer-events-none",s),"aria-hidden":"true","data-burst-key":r,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:c.map((m,f)=>{const p=m.x*d.radius,h=m.y*d.radius,g={"--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:g},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},eN=({durationMs:t=3400}={})=>{const[r,s]=Ae.useState({isActive:!1,cycle:0}),n=Ae.useRef(null),o=Ae.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Ae.useCallback(()=>{o(),s(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ae.useCallback(()=>{o(),s(c=>({isActive:!0,cycle:c.cycle+1})),n.current=window.setTimeout(()=>{s(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},t)},[o,t]);return Ae.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:l,dismissFireworks:a}},sh=i.createContext(void 0),Uu=({children:t})=>{const{isActive:r,burstKey:s,triggerFireworks:n,dismissFireworks:o}=eN(),a=i.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(sh.Provider,{value:a,children:[t,e.jsx(ZS,{isActive:r,burstKey:s})]})},tN=()=>{const t=i.useContext(sh);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},oo=is()(hs(qs((t,r)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:s=>{t({selectedProfileId:s})},loadProfiles:async()=>{t({isLoading:!0});const s=r().profiles;try{const n=await Hb();return t({profiles:n,isLoading:!1}),!0}catch(n){return console.error("Failed to load git identity profiles:",n),t({profiles:s,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const s=await qb();if(s&&s.userName&&s.userEmail){const n={id:"global",name:"Global Identity",userName:s.userName,userEmail:s.userEmail,authType:s.sshCommand?"ssh":void 0,sshKey:s.sshCommand?s.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"house"};t({globalIdentity:n})}else t({globalIdentity:null});return!0}catch(s){return console.error("Failed to load global git identity:",s),t({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const s=await Gb();return t({discoveredCredentials:s}),!0}catch(s){return console.error("Failed to discover git credentials:",s),t({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const s=n=>{if(typeof n!="string")return null;const o=n.trim();return o.length>0?o:null};try{let n=null;if(ms()){const o=await Br();n=s(o?.defaultGitIdentityId)}else{const o=Ps()?.settings;if(o)try{const l=(await o.load())?.settings||{};n=s(l.defaultGitIdentityId)}catch{}if(n===null)try{const a=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(a.ok){const l=await a.json().catch(()=>null);n=s(l?.defaultGitIdentityId)}}catch{}}return t({defaultGitIdentityId:n}),!0}catch(n){return console.error("Failed to load default git identity setting:",n),!1}},setDefaultGitIdentityId:async s=>{try{const n=typeof s=="string"?s.trim():"",o=n.length>0?n:"";return await cs({defaultGitIdentityId:o}),t({defaultGitIdentityId:o.length>0?o:null}),!0}catch(n){return console.error("Failed to save default git identity setting:",n),!1}},createProfile:async s=>{try{const n={...s,id:s.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:s.color||"keyword",icon:s.icon||"branch"};return await Wb(n),await r().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(s,n)=>{try{const o=r().profiles.find(l=>l.id===s);if(!o)throw new Error("Profile not found");const a={...o,...n};return await Ub(s,a),await r().loadProfiles(),!0}catch(o){return console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async s=>{try{return await Vb(s),r().selectedProfileId===s&&t({selectedProfileId:null}),await r().loadProfiles(),!0}catch(n){return console.error("Failed to delete git identity profile:",n),!1}},getProfileById:s=>{const{profiles:n,globalIdentity:o}=r();return s==="global"?o||void 0:n.find(a=>a.id===s)},getUnimportedCredentials:()=>{const{profiles:s,discoveredCredentials:n}=r();return n.filter(o=>!s.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Ks(()=>Ss()),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=oo);const ll="/api",sN=()=>(ll.startsWith("/"),ll);function rN(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}async function nN(t,r){const s=rN();if(s?.execCommands)return s.execCommands(t,r);const n=await fetch(`${sN()}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:t,cwd:r,background:!1})});if(!n.ok){const a=await n.json().catch(()=>({error:n.statusText}));throw new Error(a.error||"Command exec failed")}const o=await n.json().catch(()=>null);return{success:!!o?.success,results:Array.isArray(o?.results)?o.results:[]}}async function Zt(t,r){const s=await nN([t],r),n=s.results[0];return n||{command:t,success:s.success}}const Os=t=>{const r=t.trim();return r?`'${r.replace(/'/g,"'\\''")}'`:"''"},ao=t=>(t||"").split(/\r?\n/).map(r=>r.trim()).filter(Boolean),Ho=t=>!!t.success,io=t=>(t.stdout||"").trim(),lo=t=>(t.stderr||"").trim();async function oN(t,r){const s=r.trim();if(!s||s==="HEAD")return"HEAD";const n=await Zt(`git show-ref --verify --quiet ${Os(`refs/heads/${s}`)} && echo ok || echo missing`,t);if(io(n)==="ok")return s;if(s.startsWith("remotes/")){const l=s.slice(8).split("/"),c=l[0]||"origin",d=l.slice(1).join("/");if(d)return await Zt(`git branch --track ${Os(d)} ${Os(`${c}/${d}`)}`,t),d}const o=await Zt(`git show-ref --verify --quiet ${Os(`refs/remotes/origin/${s}`)} && echo ok || echo missing`,t);return io(o)==="ok"&&await Zt(`git branch --track ${Os(s)} ${Os(`origin/${s}`)}`,t),s}async function So(t){const r=t.repoRoot,s=t.sourceBranch.trim(),n=t.targetBranch.trim();if(!s||!n)return{repoRoot:r,sourceBranch:s,targetBranch:n,commits:[]};const o=await oN(r,n),a=await Zt(`git cherry ${Os(o)} ${Os(s)}`,r),l=ao(a.stdout),c=new Set;for(const f of l){const p=f.match(/^\+\s+([0-9a-f]{7,40})\b/i);p&&c.add(p[1])}const d=await Zt(`git rev-list --reverse ${Os(`${o}..${s}`)}`,r),m=ao(d.stdout).filter(f=>c.has(f));return{repoRoot:r,sourceBranch:s,targetBranch:o,commits:m}}async function aN(t,r){const s=await Zt('mkdir -p "$HOME/.config/openchamber/tmp" && mktemp -d "$HOME/.config/openchamber/tmp/oc-integrate-XXXXXX"',t),n=io(s);if(!n)throw new Error(lo(s)||"Failed to create temp directory");const o=await Zt(`git worktree add --force ${Os(n)} ${Os(r)}`,t);if(!Ho(o))throw new Error(lo(o)||"Failed to create temp worktree");return n}async function ai(t,r){await Zt(`git worktree remove --force ${Os(r)}`,t).catch(()=>{}),await Zt("git worktree prune",t).catch(()=>{})}async function iN(t){const r=await Zt("git rev-parse --abbrev-ref --symbolic-full-name @{u}",t),s=io(r);if(!s)return;await Zt("git fetch",t);const n=await Zt(`git merge --ff-only ${Os(s)}`,t);if(!Ho(n))throw new Error(lo(n)||"Fast-forward failed")}async function ii(t){const r=await Zt("git status --porcelain",t),s=await Zt("git diff --name-only --diff-filter=U",t),n=await Zt("git diff",t),o=await Zt("git show --no-patch --pretty=fuller CHERRY_PICK_HEAD",t),a=await Zt("git show CHERRY_PICK_HEAD",t);return{statusPorcelain:r.stdout||"",unmergedFiles:ao(s.stdout),diff:n.stdout||n.stderr||"",currentPatchMeta:o.stdout||o.stderr||"",currentPatch:a.stdout||a.stderr||""}}async function lN(t){return ii(t)}async function cN(t){const r=await Zt("git rev-parse --verify --quiet CHERRY_PICK_HEAD && echo yes || echo no",t);return io(r)==="yes"}async function dN(t){if(t.commits.length===0)return{kind:"noop",reason:"No commits to move"};const r=await aN(t.repoRoot,t.targetBranch);let s=[];try{await iN(r);const n=await Zt("git status --porcelain",r);if(io(n))throw new Error("Target branch has local changes; abort integration and retry");for(s=[...t.commits];s.length>0;){const o=s[0],a=await Zt(`git cherry-pick ${Os(o)}`,r);if(Ho(a)){s.shift();continue}const l=await Zt("git diff --name-only --diff-filter=U",r);if(ao(l.stdout).length>0){const d=await ii(r);return{kind:"conflict",state:{repoRoot:t.repoRoot,tempWorktreePath:r,sourceBranch:t.sourceBranch,targetBranch:t.targetBranch,remainingCommits:s,currentCommit:o},details:d}}throw new Error(lo(a)||"Cherry-pick failed")}return await ai(t.repoRoot,r),{kind:"success",moved:t.commits.length}}catch(n){throw await ai(t.repoRoot,r).catch(()=>{}),n}}async function uN(t){await Zt("git cherry-pick --abort",t.tempWorktreePath).catch(()=>{}),await ai(t.repoRoot,t.tempWorktreePath)}async function mN(t){const r=await Zt("git cherry-pick --continue",t.tempWorktreePath);if(!Ho(r)){const a=await Zt("git diff --name-only --diff-filter=U",t.tempWorktreePath);if(ao(a.stdout).length>0){const c=await ii(t.tempWorktreePath);return{kind:"conflict",state:t,details:c}}throw new Error(lo(r)||"Cherry-pick continue failed")}const s=t.tempWorktreePath,n=[...t.remainingCommits];n.length>0&&n[0]===t.currentCommit&&n.shift();const o=[...n];for(;o.length>0;){const a=o[0],l=await Zt(`git cherry-pick ${Os(a)}`,s);if(Ho(l)){o.shift();continue}const c=await Zt("git diff --name-only --diff-filter=U",s);if(ao(c.stdout).length>0){const u=await ii(s);return{kind:"conflict",state:{repoRoot:t.repoRoot,tempWorktreePath:s,sourceBranch:t.sourceBranch,targetBranch:t.targetBranch,remainingCommits:o,currentCommit:a},details:u}}throw new Error(lo(l)||"Cherry-pick failed")}return await ai(t.repoRoot,t.tempWorktreePath),{kind:"success",moved:n.length}}const fN=({repoRoot:t,sourceBranch:r,worktreeMetadata:s,localBranches:n,defaultTargetBranch:o,onRefresh:a})=>{const l=be(C=>C.currentSessionId),c=Me(C=>C.setActiveMainTab),[d,u]=Ae.useState(!0),[m,f]=Ae.useState(o);Ae.useEffect(()=>{f(o)},[o]);const p=!!(t&&r&&m&&m!=="HEAD"&&r!==m),[h,g]=Ae.useState({kind:"idle"}),[x,b]=Ae.useState(!1),[y,w]=Ae.useState([]),S=Ae.useMemo(()=>l?`openchamber.integrate.conflict:${l}`:null,[l]);Ae.useEffect(()=>{if(!S||typeof window>"u")return;const C=window.localStorage.getItem(S);if(C)try{const j=JSON.parse(C);if(!j?.tempWorktreePath||j.repoRoot!==t){window.localStorage.removeItem(S);return}(async()=>{if(!await cN(j.tempWorktreePath).catch(()=>!1)){window.localStorage.removeItem(S);return}const I=await lN(j.tempWorktreePath).catch(()=>null);I&&g({kind:"conflict",state:j,details:I})})()}catch{window.localStorage.removeItem(S)}},[S,t]),Ae.useEffect(()=>{if(!p){g({kind:"idle"});return}let C=!1;return g({kind:"loading"}),(async()=>{try{const j=await So({repoRoot:t,sourceBranch:r,targetBranch:m});if(C)return;if(g({kind:"ready",plan:j}),j.commits.length>0){const P=j.commits.slice(-50).reverse().map(B=>JSON.stringify(B)).join(" "),E=((await Zt(`git show -s --format=%H%x09%h%x09%s ${P}`,t)).stdout||"").split(/\r?\n/).filter(Boolean),F=[];for(const B of E){const[V,ne,O]=B.split(" ");!V||!ne||F.push({sha:V,short:ne,subject:O||""})}C||(w(F),b(!1))}else C||(w([]),b(!1))}catch{C||g({kind:"idle"})}})(),()=>{C=!0}},[p,t,r,m]);const M=Ae.useCallback(C=>{l&&be.getState().setWorktreeMetadata(l,{...s,createdFromBranch:C})},[l,s]),N=Ae.useCallback(async C=>{if(c("chat"),!l){U.error("No active session",{description:"Open a chat session first."});return}const{currentProviderId:j,currentModelId:T,currentAgentName:I,currentVariant:P}=Ze.getState(),D=St.getState().lastUsedProvider,E=j||D?.providerID,F=T||D?.modelID;if(!E||!F){U.error("No model selected");return}const B=`Resolve cherry-pick conflicts and keep intent of commit ${C.state.currentCommit} onto branch ${C.state.targetBranch}. After edits, report if I can continue process.`,V=`Worktree commit integration is in progress.
|
|
203
|
+
- Repo root: ${C.state.repoRoot}
|
|
204
|
+
- Temp target worktree: ${C.state.tempWorktreePath}
|
|
205
|
+
- Source branch: ${C.state.sourceBranch}
|
|
206
|
+
- Target branch: ${C.state.targetBranch}
|
|
207
|
+
|
|
208
|
+
Goal:
|
|
209
|
+
- Resolve conflicts inside the temp target worktree directory.
|
|
210
|
+
- Do NOT change intent of the commit being applied.
|
|
211
|
+
- After edits, say whether I can click "Continue".
|
|
212
|
+
`,ne=`Cherry-pick conflict context (JSON)
|
|
213
|
+
${JSON.stringify({repoRoot:C.state.repoRoot,tempWorktreePath:C.state.tempWorktreePath,sourceBranch:C.state.sourceBranch,targetBranch:C.state.targetBranch,currentCommit:C.state.currentCommit,remainingCommits:C.state.remainingCommits,statusPorcelain:C.details.statusPorcelain,unmergedFiles:C.details.unmergedFiles,currentPatchMeta:C.details.currentPatchMeta,currentPatch:C.details.currentPatch,diff:C.details.diff},null,2)}`;St.getState().sendMessage(B,E,F,I??void 0,l,void 0,null,[{text:V,synthetic:!0},{text:ne,synthetic:!0}],P).catch(O=>{const G=O instanceof Error?O.message:String(O);U.error("Failed to send message",{description:G})})},[l,c]),v=Ae.useCallback(async()=>{if(h.kind==="ready"){if(h.plan.commits.length===0){U.message("No commits to move");return}g({kind:"running",plan:h.plan});try{const C=await dN(h.plan);if(C.kind==="success"){U.success("Commits moved",{description:`${C.moved} commit${C.moved===1?"":"s"} into ${h.plan.targetBranch}`});const j=await So(h.plan);g({kind:"ready",plan:j}),a?.();return}C.kind==="conflict"&&(U.error("Cherry-pick conflict",{description:"Resolve conflicts, then Continue."}),g({kind:"conflict",state:C.state,details:C.details}),S&&typeof window<"u"&&window.localStorage.setItem(S,JSON.stringify(C.state)))}catch(C){const j=C instanceof Error?C.message:String(C);U.error("Failed to move commits",{description:j});const T=await So({repoRoot:t,sourceBranch:r,targetBranch:m}).catch(()=>null);g(T?{kind:"ready",plan:T}:{kind:"idle"})}}},[h,a,t,r,m,S]),A=Ae.useCallback(async()=>{if(h.kind==="conflict")try{await uN(h.state),U.message("Cherry-pick aborted"),S&&typeof window<"u"&&window.localStorage.removeItem(S)}finally{const C=await So({repoRoot:t,sourceBranch:r,targetBranch:m}).catch(()=>null);g(C?{kind:"ready",plan:C}:{kind:"idle"})}},[h,t,r,m,S]),k=Ae.useCallback(async()=>{if(h.kind==="conflict")try{const C=await mN(h.state);if(C.kind==="success"){U.success("Cherry-pick finished");const j=await So({repoRoot:t,sourceBranch:r,targetBranch:m}).catch(()=>null);g(j?{kind:"ready",plan:j}:{kind:"idle"}),S&&typeof window<"u"&&window.localStorage.removeItem(S),a?.();return}C.kind==="conflict"&&(g({kind:"conflict",state:C.state,details:C.details}),S&&typeof window<"u"&&window.localStorage.setItem(S,JSON.stringify(C.state)))}catch(C){const j=C instanceof Error?C.message:String(C);U.error("Cherry-pick continue failed",{description:j})}},[h,t,r,m,a,S]);return!t||!r?null:e.jsxs(En,{open:d,onOpenChange:u,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(go,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx($x,{className:"size-4 text-muted-foreground"}),e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:"Re-integrate commits"}),h.kind==="ready"&&h.plan.commits.length>0?e.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:[h.plan.commits.length," to move"]}):null]}),e.jsx("div",{className:"flex items-center gap-2",children:h.kind==="loading"||h.kind==="running"?e.jsx(Ct,{className:"size-4 animate-spin text-muted-foreground"}):null})]}),e.jsx(In,{children:e.jsx("div",{className:"border-t border-border/40",children:e.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Move commits"}),e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[r," → ",m]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsxs(je,{variant:"outline",size:"sm",className:"gap-1.5",children:["Target",e.jsx("span",{className:"max-w-[160px] truncate font-mono text-xs text-muted-foreground",children:m}),e.jsx(Ut,{className:"size-4 opacity-60"})]})}),e.jsx(os,{align:"end",className:"w-72 p-0 max-h-(--radix-dropdown-menu-content-available-height) flex flex-col overflow-hidden",children:e.jsxs(ki,{className:"h-full min-h-0",children:[e.jsx(Ci,{placeholder:"Search branches..."}),e.jsxs(Mi,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Di,{children:"No branches found."}),e.jsx(Qr,{heading:"Local branches",children:n.map(C=>e.jsx(vs,{value:C,onSelect:()=>{f(C),M(C)},children:C},C))})]})]})})]}),h.kind==="ready"?e.jsx(je,{size:"sm",onClick:()=>{v()},disabled:!p||h.plan.commits.length===0,children:"Move"}):h.kind==="loading"?e.jsx(je,{size:"sm",variant:"outline",disabled:!0,children:"Checking…"}):h.kind==="running"?e.jsx(je,{size:"sm",variant:"outline",disabled:!0,children:"Moving…"}):null]}),h.kind==="ready"&&h.plan.commits.length===0&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:"No commits to move."}),h.kind==="ready"&&h.plan.commits.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"typography-meta text-foreground",children:["Commits to move",e.jsxs("span",{className:"text-muted-foreground",children:[" (",h.plan.commits.length,")"]})]}),y.length>0&&h.plan.commits.length>5&&e.jsx("button",{type:"button",onClick:()=>b(C=>!C),className:"typography-micro text-muted-foreground hover:text-foreground",children:x?"Show less":"Show all"})]}),e.jsxs("div",{className:"space-y-1",children:[(x?y:y.slice(0,5)).map(C=>e.jsxs("div",{className:"flex items-baseline gap-2 min-w-0",children:[e.jsx("span",{className:"font-mono text-xs text-muted-foreground flex-shrink-0",children:C.short}),e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:C.subject||C.sha})]},C.sha)),y.length===0&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Preview unavailable."}),h.plan.commits.length>y.length&&e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["Showing first ",y.length," commits."]})]})]}),h.kind==="conflict"&&e.jsxs("div",{className:"rounded-md border border-border/60 bg-background/60 p-3 space-y-2",children:[e.jsxs("div",{className:"typography-meta text-foreground",children:["Conflicts in ",h.details.unmergedFiles.length," files"]}),e.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:["Current commit: ",e.jsx("span",{className:"font-mono",children:h.state.currentCommit.slice(0,7)})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[h.details.unmergedFiles.slice(0,6).map(C=>e.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:C},C)),h.details.unmergedFiles.length>6&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",h.details.unmergedFiles.length-6," more"]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(je,{size:"sm",variant:"ghost",className:"h-7 px-2 py-0 typography-meta",onClick:()=>{A()},children:"Abort"}),e.jsx(je,{size:"sm",variant:"secondary",className:"h-7 px-2 py-0 typography-meta",onClick:()=>{N({state:h.state,details:h.details})},children:"Resolve with AI"}),e.jsx(je,{size:"sm",className:"h-7 px-2 py-0 typography-meta",onClick:()=>{k()},children:"Continue"})]})]})]})})})]})},pN=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),hN=({currentBranch:t,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:o,onCreate:a,disabled:l=!1})=>{const[c,d]=i.useState(!1),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,g]=i.useState(""),[x,b]=i.useState(!1),y=i.useRef(null),w=i.useMemo(()=>pN(h),[h]),S=i.useMemo(()=>{const C=u.toLowerCase();return C?r.filter(j=>j.toLowerCase().includes(C)):r},[u,r]),M=i.useMemo(()=>{const C=u.toLowerCase();return C?s.filter(j=>j.toLowerCase().includes(C)):s},[u,s]),N=C=>{if(C===t){d(!1);return}o(C),d(!1),m("")},v=()=>{p(!0),setTimeout(()=>y.current?.focus(),50)},A=async()=>{if(!(!w||x)){b(!0);try{await a(w),g(""),p(!1),d(!1)}finally{b(!1)}}},k=()=>{g(""),p(!1)};return i.useEffect(()=>{c||(m(""),p(!1),g(""))},[c]),e.jsxs(rs,{open:c,onOpenChange:d,children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ns,{asChild:!0,children:e.jsxs(je,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:l,children:[e.jsx(Vt,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:t||"Detached HEAD"}),e.jsx(Ut,{className:"size-4 opacity-60"})]})})}),e.jsxs(ct,{sideOffset:8,children:["Switch branch (",r.length," local · ",s.length," remote)"]})]}),e.jsx(os,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(ki,{className:"h-full min-h-0",children:[e.jsx(Ci,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(Mi,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Di,{children:"No branches found."}),e.jsx(Qr,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:y,placeholder:"New branch name",value:h,onChange:C=>g(C.target.value),onKeyDown:C=>{C.key==="Enter"?(C.preventDefault(),A()):C.key==="Escape"&&(C.preventDefault(),k())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:A,disabled:!w||x,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:x?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(us,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:k,disabled:x,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(ss,{className:"size-4"})})]}):e.jsxs(vs,{onSelect:v,children:[e.jsx(us,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(si,{}),e.jsxs(Qr,{heading:"Local branches",children:[S.map(C=>e.jsxs(vs,{onSelect:()=>N(C),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:C}),(n?.[C]?.ahead||n?.[C]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[C].ahead||0," ahead ·"," ",n[C].behind||0," behind"]})]}),t===C&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${C}`)),S.length===0&&e.jsx(vs,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(si,{}),e.jsxs(Qr,{heading:"Remote branches",children:[M.map(C=>e.jsx(vs,{onSelect:()=>N(C),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:C})},`remote-${C}`)),M.length===0&&e.jsx(vs,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},gN=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),xN=({currentBranch:t,onRename:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(t||""),[l,c]=i.useState(!1),d=i.useRef(null),u=()=>{!t||!r||(a(t),n(!0),setTimeout(()=>d.current?.focus(),0))},m=async()=>{if(!t||!r||!o.trim())return;const h=gN(o);if(h===t){n(!1);return}c(!0);try{await r(t,h),n(!1),a("")}finally{c(!1)}},f=()=>{n(!1),a("")},p=h=>{h.key==="Enter"?(h.preventDefault(),m()):h.key==="Escape"&&(h.preventDefault(),f())};return s?e.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:e.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:h=>{h.preventDefault(),m()},children:[e.jsx(Vt,{className:"size-4 text-primary"}),e.jsx("input",{ref:d,value:o,onChange:h=>a(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:p,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:l,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:l?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(Pt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:l,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(ss,{className:"size-4"})})]})}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 h-8",children:[e.jsx(Vt,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate typography-ui-label font-normal text-foreground",children:t||"Detached HEAD"})]}),r&&t&&e.jsx(je,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(mo,{className:"size-4"})})]})},yN=({syncAction:t,onFetch:r,onPull:s,onPush:n,disabled:o})=>{const a=o||t!==null;return e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(je,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[t==="fetch"?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(Xr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(ct,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(je,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:s,disabled:a,children:[t==="pull"?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(fo,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(ct,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(je,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[t==="push"?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(Jn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(ct,{sideOffset:8,children:"Push changes"})]})]})},bN={branch:Vt,briefcase:mc,house:uc,graduation:dc,code:tr,heart:lf,user:sr},wN={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 rh(t){return t&&wN[t]||"var(--primary)"}const Vu=({icon:t,className:r,colorToken:s})=>{const n=bN[t??"branch"]??sr;return e.jsx(n,{className:r,style:{color:rh(s)}})},vN=({activeProfile:t,identities:r,onSelect:s,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(rs,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(ns,{asChild:!0,children:e.jsxs(je,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:rh(t?.color)},disabled:o,children:[n?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(Vu,{icon:t?.icon,colorToken:t?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:t?.name||"No identity"}),e.jsx(Ut,{className:"size-4 opacity-60"})]})})}),e.jsxs(ct,{sideOffset:8,className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:t?.userName||"Unknown user"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:t?.userEmail||"No email configured"})]})]}),e.jsx(os,{align:"end",className:"w-64",children:r.length===0?e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):r.map(a=>e.jsx(Nt,{onSelect:()=>s(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Vu,{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))})]})},jN=({status:t,localBranches:r,remoteBranches:s,branchInfo:n,syncAction:o,onFetch:a,onPull:l,onPush:c,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:h,isApplyingIdentity:g,isWorktreeMode:x})=>t?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[x?e.jsx(xN,{currentBranch:t.current,onRename:m}):e.jsx(hN,{currentBranch:t.current,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:d,onCreate:u}),(!!t.tracking||t.ahead>0||t.behind>0)&&e.jsxs(dt,{delayDuration:800,children:[e.jsx(ut,{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(Jn,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:t.ahead})]}),!!t.tracking&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(fo,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:t.behind})]})]})}),e.jsx(ct,{sideOffset:8,children:t.tracking?`Upstream: ${t.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(yN,{syncAction:o,onFetch:a,onPull:l,onPush:c,disabled:!t}),e.jsx("div",{className:"flex-1"}),e.jsx(vN,{activeProfile:f,identities:p,onSelect:h,isApplying:g})]}):null,SN=({behind:t,onPull:r,isPulling:s})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx(oc,{className:"size-10 text-emerald-500/60 mb-4"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:"Working tree clean"}),e.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:"All changes have been committed"}),t>0&&e.jsxs(je,{variant:"outline",onClick:r,disabled:s,children:[s?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(fo,{className:"size-4"}),"Pull ",t," commit",t===1?"":"s"]})]}),nh={"?":{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"}},NN=nh.M;function kN(t){const r=t.index?.trim(),s=t.working_dir?.trim();return r&&r!=="?"?r.charAt(0):s?s.charAt(0):r?.charAt(0)||s?.charAt(0)||"M"}function CN(t){const r=kN(t);return nh[r]??NN}const MN=i.memo(function({file:r,checked:s,onToggle:n,onViewDiff:o,onRevert:a,isReverting:l,stats:c}){const d=Ae.useMemo(()=>CN(r),[r]),u=d.description,m=c?.insertions??0,f=c?.deletions??0,p=Ae.useCallback(x=>{x.key===" "?(x.preventDefault(),n()):x.key==="Enter"&&(x.preventDefault(),o())},[n,o]),h=Ae.useCallback(x=>{x.preventDefault(),x.stopPropagation(),n()},[n]),g=Ae.useCallback(x=>{x.preventDefault(),x.stopPropagation(),a()},[a]);return e.jsx("li",{children:e.jsxs("div",{className:"group flex items-center gap-2 px-3 py-1.5 hover:bg-sidebar/40 cursor-pointer",role:"button",tabIndex:0,onClick:o,onKeyDown:p,children:[e.jsx("button",{type:"button",onClick:h,"aria-pressed":s,"aria-label":`Select ${r.path}`,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s?e.jsx(Sn,{className:"size-4 text-primary"}):e.jsx(Nn,{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(dt,{delayDuration:200,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:g,disabled:l,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:l?e.jsx(Ct,{className:"size-3.5 animate-spin"}):e.jsx(Zn,{className:"size-3.5"})})}),e.jsx(ct,{sideOffset:8,children:"Revert changes"})]})]})})}),DN=({changeEntries:t,selectedPaths:r,diffStats:s,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:l,onViewDiff:c,onRevertFile:d})=>{const u=r.size,m=t.length;return e.jsxs("section",{className:"flex flex-col rounded-xl border border-border/60 bg-background/70",children:[e.jsxs("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Changes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[u,"/",m]}),m>0&&e.jsxs(e.Fragment,{children:[e.jsx(je,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(je,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:l,disabled:u===0,children:"None"})]})]})]}),e.jsx(gt,{outerClassName:"flex-1 min-h-0 max-h-[30vh]",className:"w-full",children:e.jsx("ul",{className:"divide-y divide-border/60",children:t.map(f=>e.jsx(MN,{file:f,checked:r.has(f.path),stats:s?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>c(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function Cn({className:t,variant:r,...s}){return e.jsx(je,{variant:r,size:"sm",className:L("h-7 px-2 py-0",t),...s})}const cl=38,Gu=200,AN=({value:t,onChange:r,placeholder:s="Commit message",disabled:n=!1})=>{const o=i.useRef(null);return i.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${cl}px`;const l=Math.min(Math.max(a.scrollHeight,cl),Gu);a.style.height=`${l}px`},[t]),e.jsx(Fs,{ref:o,value:t,onChange:a=>r(a.target.value),placeholder:s,rows:1,disabled:n,className:L("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:cl,maxHeight:Gu}})},EN=({highlights:t,onInsert:r,onClear:s})=>{if(t.length===0)return null;const n=()=>{r(),s()};return e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground",children:"AI highlights"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(fo,{className:"size-4"})})}),e.jsx(ct,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:t.map((o,a)=>e.jsx("li",{className:"typography-meta text-foreground",children:o},a))})]})},IN=({selectedCount:t,commitMessage:r,onCommitMessageChange:s,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:l,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f,gitmojiEnabled:p,onOpenGitmojiPicker:h})=>{const g=t>0,x=r.trim()&&g&&m===null,{isMobile:b}=qt();return e.jsxs(En,{open:g,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:g?`${t} file${t===1?"":"s"} selected`:"No files selected"})]}),e.jsx(In,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(EN,{highlights:n,onInsert:o,onClear:a}),e.jsx(AN,{value:r,onChange:s,placeholder:"Commit message",disabled:m!==null}),p&&e.jsxs(je,{variant:"outline",size:"sm",onClick:h,className:"w-fit",type:"button",children:[e.jsx(Bx,{className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"@container/commit-actions flex items-center gap-2 min-w-0",children:[e.jsxs(je,{variant:"outline",size:"sm",onClick:l,disabled:c||m!==null||t===0||f,type:"button","aria-label":"Generate",className:"commit-actions__btn",children:[c?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(cc,{className:"size-4 text-primary"}),e.jsx("span",{className:"commit-actions__label",children:"Generate"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Cn,{variant:"outline",onClick:d,disabled:!x||c,className:"commit-actions__btn whitespace-nowrap","aria-label":"Commit",children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"size-4 animate-spin"}),e.jsx("span",{className:"commit-actions__label",children:"Committing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(oc,{className:"size-4"}),e.jsx("span",{className:"commit-actions__label",children:"Commit"})]})}),b?e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{variant:"default",size:"sm",onClick:u,disabled:!x||c,className:"h-7 w-7 p-0","aria-label":"Commit & Push",children:m==="commitAndPush"?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(Jn,{className:"size-4"})})}),e.jsx(ct,{side:"top",children:e.jsx("p",{children:"Commit & Push"})})]}):e.jsx(Cn,{variant:"default",onClick:u,disabled:!x||c,className:"commit-actions__btn","aria-label":"Commit & Push",children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"size-4 animate-spin"}),e.jsx("span",{className:"commit-actions__label commit-actions__label--long",children:"Pushing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Jn,{className:"size-4"}),e.jsx("span",{className:"commit-actions__label commit-actions__label--long",children:"Commit & Push"})]})})]})]})})]})};function qu(t){const r=new Date(t);return Number.isNaN(r.getTime())?t:r.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function PN(t){switch(t){case"A":return"text-emerald-500";case"D":return"text-red-500";case"M":return"text-amber-500";case"R":return"text-blue-500";default:return"text-muted-foreground"}}const TN=({entry:t,isExpanded:r,onToggle:s,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:s,className:L("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",r?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[e.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:t.message}),e.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[e.jsx("span",{className:"truncate min-w-[3ch]",title:t.author_name,children:t.author_name}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("span",{className:"truncate min-w-0",title:qu(t.date),children:qu(t.date)})]}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:l=>{l.stopPropagation(),a(t.hash)},children:e.jsx(rr,{className:"size-3"})})}),e.jsx(ct,{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(Ct,{className:"size-4 animate-spin text-muted-foreground"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Loading files..."})]}):n.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:"No files"}):e.jsx("ul",{className:"space-y-0.5 py-2",children:n.map(l=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:L("font-semibold w-3 text-center",PN(l.changeType)),children:l.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:l.path,children:l.path}),!l.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",l.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",l.deletions]})]}),l.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},l.path))})})]}),FN=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],RN=({log:t,isLogLoading:r,logMaxCount:s,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:l,loadingCommitHashes:c,onCopyHash:d})=>{const[u,m]=i.useState(!0);return t?e.jsxs(En,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(go,{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(As,{value:String(s),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Es,{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(kn,{placeholder:"Commits"})}),e.jsx(Is,{children:FN.map(f=>e.jsx(Bt,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(di,{className:"size-4 text-muted-foreground"}):e.jsx(Ut,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(In,{children:e.jsx(gt,{outerClassName:"min-h-0 max-h-[50vh]",className:"w-full",children:t.all.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"No commits found"})}):e.jsx("ul",{className:"divide-y divide-border/60",children:t.all.map(f=>e.jsx(TN,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:l.get(f.hash)??[],isLoadingFiles:c.has(f.hash),onCopyHash:d},f.hash))})})})]}):null},LN=t=>{switch(t){case"success":return"bg-[color:var(--status-success)]";case"failure":return"bg-[color:var(--status-error)]";case"pending":return"bg-[color:var(--status-warning)]";default:return"bg-muted-foreground/40"}},Ku=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase()),dl=new Map,Yu=async t=>{if(typeof window>"u")return;const r=window.opencodeDesktop;if(r?.openExternal)try{const s=await r.openExternal(t);if(s&&typeof s=="object"&&"success"in s&&s.success===!0)return}catch{}try{window.open(t,"_blank","noopener,noreferrer")}catch{}},ON=({directory:t,branch:r,baseBranch:s})=>{const{github:n}=Hs(),o=Bs(fe=>fe.status),a=Bs(fe=>fe.hasChecked),l=Me(fe=>fe.setSettingsDialogOpen),c=Me(fe=>fe.setSidebarSection),d=Me(fe=>fe.setActiveMainTab),u=be(fe=>fe.currentSessionId),m=i.useCallback(()=>{c("settings"),l(!0)},[l,c]),f=i.useMemo(()=>`${t}::${r}`,[t,r]),p=i.useMemo(()=>dl.get(f)??null,[f]),[h,g]=i.useState(p?.isOpen??!0),[x,b]=i.useState(!1),[y,w]=i.useState(null),[S,M]=i.useState(null),[N,v]=i.useState(()=>p?.title??Ku(r)),[A,k]=i.useState(()=>p?.body??""),[C,j]=i.useState(()=>p?.draft??!1),[T,I]=i.useState("squash"),[P,D]=i.useState(!1),[E,F]=i.useState(!1),[B,V]=i.useState(!1),[ne,O]=i.useState(!1),[G,K]=i.useState(!1),[q,$]=i.useState(null),[W,Y]=i.useState(!1),X=!!(t&&r&&s&&r!==s),Z=y?.pr??null,z=i.useCallback(async()=>{if(!n?.prContext){U.error("GitHub runtime API unavailable");return}if(Z){K(!0),Y(!0);try{const fe=await n.prContext(t,Z.number,{includeDiff:!1,includeCheckDetails:!0});$(fe)}catch(fe){const oe=fe instanceof Error?fe.message:String(fe);U.error("Failed to load check details",{description:oe})}finally{Y(!1)}}},[t,n,Z]),R=i.useCallback(fe=>{const oe=fe.status||"unknown",Q=fe.conclusion??void 0,re=Q?`${oe} / ${Q}`:oe,ue=fe.app?.name||fe.app?.slug;return e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground truncate",children:fe.name}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:ue?`${ue} · ${re}`:re}),fe.output?.summary?e.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap line-clamp-4 mt-2",children:fe.output.summary}):null,fe.job?.steps&&fe.job.steps.length>0?e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Steps"}),e.jsx("div",{className:"space-y-1",children:fe.job.steps.map((he,Ge)=>{const qe=(he.conclusion||"").toLowerCase(),et=qe&&!["success","neutral","skipped"].includes(qe);return e.jsxs("div",{className:"typography-micro flex items-center gap-2 rounded px-2 py-1 "+(et?"bg-destructive/10 text-destructive":"text-muted-foreground"),children:[e.jsx("span",{className:"truncate",children:he.name}),he.conclusion?e.jsx("span",{className:"ml-auto flex-shrink-0",children:he.conclusion}):null]},`${he.name}-${Ge}`)})})]}):null]}),fe.detailsUrl?e.jsx(je,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:e.jsxs("a",{href:fe.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Open"]})}):null]})},[]),de=i.useCallback(async()=>{if(d("chat"),!n?.prContext){U.error("GitHub runtime API unavailable");return}if(!t||!Z)return;if(!u){U.error("No active session",{description:"Open a chat session first."});return}const{currentProviderId:fe,currentModelId:oe,currentAgentName:Q,currentVariant:re}=Ze.getState(),ue=St.getState().lastUsedProvider,he=fe||ue?.providerID,Ge=oe||ue?.modelID;if(!he||!Ge){U.error("No model selected");return}try{const qe=await n.prContext(t,Z.number,{includeDiff:!1,includeCheckDetails:!0}),rt=(qe.checkRuns??[]).filter(He=>{const Se=typeof He.conclusion=="string"?He.conclusion.toLowerCase():"";return Se?!["success","neutral","skipped"].includes(Se):!1});if(rt.length===0){U.message("No failed checks");return}const vt="Review these PR failed checks and propose likely fixes. Do not implement until I confirm.",Ce=`Use the attached checks payload.
|
|
214
|
+
- Summarize what is failing.
|
|
215
|
+
- Identify likely root cause(s).
|
|
216
|
+
- Propose a minimal fix plan and verification steps.
|
|
217
|
+
- No speculation: ask for missing info if needed.`,pe=`GitHub PR failed checks (JSON)
|
|
218
|
+
${JSON.stringify({repo:qe.repo??null,pr:qe.pr??null,failedChecks:rt},null,2)}`;St.getState().sendMessage(vt,he,Ge,Q??void 0,u,void 0,null,[{text:Ce,synthetic:!0},{text:pe,synthetic:!0}],re).catch(He=>{const Se=He instanceof Error?He.message:String(He);U.error("Failed to send message",{description:Se})})}catch(qe){const et=qe instanceof Error?qe.message:String(qe);U.error("Failed to load checks",{description:et})}},[u,t,n,Z,d]),we=i.useCallback(async()=>{if(d("chat"),!n?.prContext){U.error("GitHub runtime API unavailable");return}if(!t||!Z)return;if(!u){U.error("No active session",{description:"Open a chat session first."});return}const{currentProviderId:fe,currentModelId:oe,currentAgentName:Q,currentVariant:re}=Ze.getState(),ue=St.getState().lastUsedProvider,he=fe||ue?.providerID,Ge=oe||ue?.modelID;if(!he||!Ge){U.error("No model selected");return}try{const qe=await n.prContext(t,Z.number,{includeDiff:!1,includeCheckDetails:!1}),et=qe.issueComments??[],rt=qe.reviewComments??[];if(et.length+rt.length===0){U.message("No PR comments");return}const Ce="Review these PR comments and propose the required changes and next actions. Do not implement until I confirm.",pe=`Use the attached comments payload.
|
|
219
|
+
- Identify required vs optional changes.
|
|
220
|
+
- Call out intent/implementation mismatch if present.
|
|
221
|
+
- Propose a minimal plan and verification steps.
|
|
222
|
+
- No speculation: ask for missing info if needed.`,He=`GitHub PR comments (JSON)
|
|
223
|
+
${JSON.stringify({repo:qe.repo??null,pr:qe.pr??null,issueComments:et,reviewComments:rt},null,2)}`;St.getState().sendMessage(Ce,he,Ge,Q??void 0,u,void 0,null,[{text:pe,synthetic:!0},{text:He,synthetic:!0}],re).catch(Se=>{const ke=Se instanceof Error?Se.message:String(Se);U.error("Failed to send message",{description:ke})})}catch(qe){const et=qe instanceof Error?qe.message:String(qe);U.error("Failed to load PR comments",{description:et})}},[u,t,n,Z,d]),xe=i.useCallback(async()=>{if(X){if(a&&o?.connected===!1){w({connected:!1}),M(null),b(!1);return}if(!n?.prStatus){w(null),M("GitHub runtime API unavailable");return}b(!0),M(null);try{const fe=await n.prStatus(t,r);w(fe),fe.connected===!1&&M(null)}catch(fe){const oe=fe instanceof Error?fe.message:String(fe);M(oe||"Failed to load PR status")}finally{b(!1)}}},[r,X,t,n,a,o]);i.useEffect(()=>{const fe=dl.get(f)??null;v(fe?.title??Ku(r)),k(fe?.body??""),j(fe?.draft??!1),g(fe?.isOpen??!0),xe()},[r,xe,f]),i.useEffect(()=>{a&&o?.connected===!1&&(w({connected:!1}),M(null))},[a,o]),i.useEffect(()=>{!t||!r||dl.set(f,{title:N,body:A,draft:C,isOpen:h})},[f,N,A,C,h,t,r]);const Pe=i.useCallback(async()=>{if(!P&&t){D(!0);try{const fe=await $b(t,{base:s,head:r});fe.title?.trim()&&v(fe.title.trim()),fe.body?.trim()&&k(fe.body.trim()),U.success("PR description generated")}catch(fe){const oe=fe instanceof Error?fe.message:String(fe);U.error("Failed to generate description",{description:oe})}finally{D(!1)}}},[s,r,t,P]),H=i.useCallback(async()=>{if(!n?.prCreate){U.error("GitHub runtime API unavailable");return}const fe=N.trim();if(!fe){U.error("Title is required");return}F(!0);try{const oe=await n.prCreate({directory:t,title:fe,head:r,base:s,...A.trim()?{body:A}:{},draft:C});U.success("PR created"),w(Q=>Q&&{...Q,pr:oe}),await xe()}catch(oe){const Q=oe instanceof Error?oe.message:String(oe);U.error("Failed to create PR",{description:Q})}finally{F(!1)}},[s,A,r,t,C,n,xe,N]),ye=i.useCallback(async fe=>{if(!n?.prMerge){U.error("GitHub runtime API unavailable");return}V(!0);try{const oe=await n.prMerge({directory:t,number:fe.number,method:T});oe.merged?U.success("PR merged"):U.message("PR not merged",{description:oe.message||"Not mergeable"}),await xe()}catch(oe){const Q=oe instanceof Error?oe.message:String(oe);U.error("Merge failed",{description:Q}),fe.url&&Yu(fe.url)}finally{V(!1)}},[t,n,T,xe]),J=i.useCallback(async fe=>{if(!n?.prReady){U.error("GitHub runtime API unavailable");return}O(!0);try{await n.prReady({directory:t,number:fe.number}),U.success("Marked ready for review"),await xe()}catch(oe){const Q=oe instanceof Error?oe.message:String(oe);U.error("Failed to mark ready",{description:Q}),fe.url&&Yu(fe.url)}finally{O(!1)}},[t,n,xe]);if(!X)return null;const ce=y?.repo?.url||null,ge=y?.checks??null,ee=!!y?.canMerge,me=!!y?.connected,le=a&&y?.connected===!1;return e.jsxs(En,{open:h,onOpenChange:g,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(go,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ha,{className:"size-4 text-muted-foreground"}),e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:"Pull Request"}),Z?e.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",Z.number]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[x?e.jsx(Ct,{className:"size-4 animate-spin text-muted-foreground"}):null,ge?e.jsxs("span",{className:"inline-flex items-center gap-2 typography-micro text-muted-foreground",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${LN(ge.state)}`}),ge.total>0?`${ge.success}/${ge.total} checks`:`${ge.state} checks`]}):null]})]}),e.jsx(In,{children:e.jsx("div",{className:"border-t border-border/40",children:e.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[le?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground",children:"GitHub not connected. Connect your GitHub account in settings."}),e.jsx(je,{variant:"outline",size:"sm",onClick:m,className:"w-fit",children:"Open settings"})]}):null,S?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"PR status unavailable"}),e.jsx("div",{className:"typography-meta text-muted-foreground break-words",children:S}),ce?e.jsx(je,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:e.jsxs("a",{href:ce,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Open Repo"]})}):null]}):null,Z?e.jsx("div",{className:"flex flex-col gap-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground truncate",children:Z.title}),e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[Z.state,Z.draft?" (draft)":"",Z.mergeable===!1?" · not mergeable":"",typeof Z.mergeableState=="string"&&Z.mergeableState?` · ${Z.mergeableState}`:""]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[ge?e.jsxs(je,{variant:"outline",size:"sm",onClick:z,disabled:W,children:[W?e.jsx(Ct,{className:"size-4 animate-spin"}):null,"Check details"]}):null,ge?.failure?e.jsx(je,{variant:"outline",size:"sm",onClick:de,children:"Send failed checks to chat"}):null,e.jsx(je,{variant:"outline",size:"sm",onClick:we,children:"Send PR comments to chat"})]}),ee&&Z.draft?e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Draft PRs must be marked ready before merge."}):null,ee?null:e.jsx("div",{className:"typography-micro text-muted-foreground",children:"No merge permission; use Open in GitHub."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:Z.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Open"]})}),ee&&Z.draft&&Z.state==="open"?e.jsxs(je,{variant:"outline",size:"sm",onClick:()=>J(Z),disabled:ne||B,children:[ne?e.jsx(Ct,{className:"size-4 animate-spin"}):null,"Ready"]}):null,ee?e.jsxs(e.Fragment,{children:[e.jsxs("select",{className:"h-8 rounded-md border border-border bg-background px-2 typography-meta",value:T,onChange:fe=>I(fe.target.value),disabled:B||Z.state!=="open",children:[e.jsx("option",{value:"squash",children:"Squash"}),e.jsx("option",{value:"merge",children:"Merge"}),e.jsx("option",{value:"rebase",children:"Rebase"})]}),e.jsxs(je,{size:"sm",onClick:()=>ye(Z),disabled:B||ne||Z.state!=="open"||Z.draft,children:[B?e.jsx(Ct,{className:"size-4 animate-spin"}):null,"Merge"]})]}):null]})]})}):e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Create PR"}),e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[r," → ",s]})]}),ce?e.jsx(je,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ce,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xs,{className:"size-4"}),"Repo"]})}):null]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Title"}),e.jsx(wt,{value:N,onChange:fe=>v(fe.target.value),placeholder:"PR title"})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Description"}),e.jsx(Fs,{value:A,onChange:fe=>k(fe.target.value),className:"min-h-[110px] bg-background/80",placeholder:"What changed and why"})]}),e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":C,onClick:()=>j(fe=>!fe),onKeyDown:fe=>{(fe.key===" "||fe.key==="Enter")&&(fe.preventDefault(),j(oe=>!oe))},children:[e.jsx("button",{type:"button",onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),j(oe=>!oe)},"aria-label":"Toggle draft PR",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:C?e.jsx(Sn,{className:"size-4 text-primary"}):e.jsx(Nn,{className:"size-4"})}),e.jsx("span",{className:"typography-ui-label text-foreground select-none",children:"Draft"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(je,{variant:"outline",size:"sm",onClick:Pe,disabled:P||E,children:[P?e.jsx(Ct,{className:"size-4 animate-spin"}):e.jsx(cc,{className:"size-4 text-primary"}),"Generate"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(je,{size:"sm",onClick:H,disabled:E||!me,children:[E?e.jsx(Ct,{className:"size-4 animate-spin"}):null,"Create PR"]})]})]})]})})}),e.jsx(fs,{open:G,onOpenChange:K,children:e.jsxs(ps,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(bs,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-5 w-5"}),"Check Details"]}),e.jsx(Ns,{children:Z?`PR #${Z.number}`:"Pull request"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[W?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):null,W?null:e.jsx("div",{className:"space-y-3",children:Array.isArray(q?.checkRuns)&&q?.checkRuns.length>0?q.checkRuns.map((fe,oe)=>e.jsx("div",{className:"rounded-md border border-border/60 p-3",children:R(fe)},`${fe.name}-${oe}`)):e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No check details available."})})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx("div",{className:"flex-1"}),e.jsx(je,{variant:"outline",onClick:()=>K(!1),children:"Close"})]})]})})]})},oh="gitmojiCache",_N=1e3*60*60*24*7,ah="1",$N="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Qu={feat:":sparkles:",feature:":sparkles:",fix:":bug:",bug:":bug:",hotfix:":ambulance:",docs:":memo:",documentation:":memo:",style:":lipstick:",refactor:":recycle:",perf:":zap:",performance:":zap:",test:":white_check_mark:",tests:":white_check_mark:",build:":construction_worker:",ci:":green_heart:",chore:":wrench:",revert:":rewind:",wip:":construction:",security:":lock:",release:":bookmark:",merge:":twisted_rightwards_arrows:",mv:":truck:",move:":truck:",rename:":truck:",remove:":fire:",delete:":fire:",add:":sparkles:",create:":sparkles:",implement:":sparkles:",update:":recycle:",improve:":zap:",optimize:":zap:",upgrade:":arrow_up:",downgrade:":arrow_down:",deploy:":rocket:",init:":tada:",initial:":tada:"},ih=t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.emoji=="string"&&typeof r.code=="string"&&typeof r.description=="string"},BN=()=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(oh);if(!t)return null;const r=JSON.parse(t);return!r||r.version!==ah||typeof r.fetchedAt!="number"||!Array.isArray(r.gitmojis)?null:{gitmojis:r.gitmojis.filter(ih),fetchedAt:r.fetchedAt,version:r.version}}catch{return null}},zN=t=>{if(!(typeof window>"u"))try{const r={gitmojis:t,fetchedAt:Date.now(),version:ah};localStorage.setItem(oh,JSON.stringify(r))}catch{return}},HN=t=>Date.now()-t.fetchedAt<_N,WN=(t,r)=>{const s=t.toLowerCase(),n=/^([a-z]+)(?:\(.*\))?!?:/,o=s.match(n);if(o){const c=o[1],d=Qu[c];if(d)return r.find(u=>u.code===d)||null}const a=s.split(" ")[0],l=Qu[a];return l&&r.find(c=>c.code===l)||null},Ju=new Map,UN=()=>{const{git:t}=Hs(),r=Qo(),{currentSessionId:s,worktreeMetadata:n}=be(),o=s?n.get(s)??void 0:void 0,{profiles:a,globalIdentity:l,defaultGitIdentityId:c,loadProfiles:d,loadGlobalIdentity:u,loadDefaultGitIdentityId:m}=oo(),f=sp(r??null),p=ep(r??null),h=tp(r??null),g=rv(r??null),x=nv(r??null),b=ds(Ie=>Ie.isLoadingStatus),y=ds(Ie=>Ie.isLoadingLog),{setActiveDirectory:w,fetchAll:S,fetchStatus:M,fetchBranches:N,fetchLog:v,fetchIdentity:A,setLogMaxCount:k}=ds(),C=i.useMemo(()=>r?Ju.get(r)??null:null,[r]),j=Ze(Ie=>Ie.settingsGitmojiEnabled),T=Ft(Ie=>Ie.getActiveProject()),I=i.useMemo(()=>{const Ie=T?.worktreeDefaults?.baseBranch;return typeof Ie=="string"&&Ie.trim().length>0?Ie.trim():"main"},[T?.worktreeDefaults?.baseBranch]),[P,D]=i.useState(C?.commitMessage??""),[E,F]=i.useState(!1),[B,V]=i.useState(null),[ne,O]=i.useState(null),[G,K]=i.useState(25),[q,$]=i.useState(!1),{triggerFireworks:W}=tN(),Y=i.useRef(new Map),X=i.useRef(0),Z=i.useCallback(()=>{X.current+=1,$(!0)},[]),z=i.useCallback(()=>{X.current=Math.max(0,X.current-1),X.current===0&&$(!1)},[]),[R,de]=i.useState(()=>new Set(C?.selectedPaths??[])),[we,xe]=i.useState(!1),[Pe,H]=i.useState(new Set),[ye,J]=i.useState(!1),[ce,ge]=i.useState(C?.generatedHighlights??[]),ee=o?.projectDirectory||null,me=p?.current||null,le=i.useMemo(()=>{const Ie=o?.createdFromBranch;if(typeof Ie=="string"&&Ie.trim().length>0)return Ie.trim();const Te=T?.worktreeDefaults?.baseBranch;return typeof Te=="string"&&Te.trim().length>0?Te.trim():"main"},[o?.createdFromBranch,T?.worktreeDefaults?.baseBranch]),fe=i.useCallback(()=>{ge([])},[]),[oe,Q]=i.useState(new Set),[re,ue]=i.useState(new Map),[he,Ge]=i.useState(new Set),[qe,et]=i.useState(null),[rt,vt]=i.useState([]),[Ce,pe]=i.useState(""),He=i.useCallback(Ie=>{navigator.clipboard.writeText(Ie).then(()=>{U.success("Commit hash copied")}).catch(()=>{U.error("Failed to copy")})},[]),Se=i.useCallback(Ie=>{Q(Te=>{const Le=new Set(Te);return Le.has(Ie)?Le.delete(Ie):Le.add(Ie),Le})},[]);i.useEffect(()=>{if(!r||!t)return;const Ie=Array.from(oe).filter(Te=>!re.has(Te)&&!he.has(Te));if(Ie.length!==0){Ge(Te=>{const Le=new Set(Te);for(const te of Ie)Le.add(te);return Le});for(const Te of Ie)t.getCommitFiles(r,Te).then(Le=>{ue(te=>new Map(te).set(Te,Le.files))}).catch(Le=>{console.error("Failed to fetch commit files:",Le),ue(te=>new Map(te).set(Te,[]))}).finally(()=>{Ge(Le=>{const te=new Set(Le);return te.delete(Te),te})})}},[oe,r,t,re,he]),i.useEffect(()=>{r&&Ju.set(r,{directory:r,selectedPaths:Array.from(R),commitMessage:P,generatedHighlights:ce})},[P,r,R,ce]),i.useEffect(()=>{d(),u(),m()},[d,u,m]),i.useEffect(()=>{if(!r||!t?.getRemoteUrl){et(null);return}t.getRemoteUrl(r).then(et).catch(()=>et(null))},[r,t]),i.useEffect(()=>{if(!j){vt([]);return}let Ie=!1;const Te=BN();return Te&&(vt(Te.gitmojis),HN(Te))?()=>{Ie=!0}:((async()=>{try{const te=await fetch($N);if(!te.ok)throw new Error(`Failed to load gitmojis: ${te.statusText}`);const se=await te.json(),ie=Array.isArray(se.gitmojis)?se.gitmojis.filter(ih):[];Ie||(vt(ie),zN(ie))}catch(te){Ie||console.warn("Failed to load gitmoji list:",te)}})(),()=>{Ie=!0})},[j]),i.useEffect(()=>{r&&(w(r),ds.getState().directories.get(r)?.status||S(r,t,{force:!0}))},[r,w,S,t]);const ke=i.useCallback(async(Ie=!0)=>{if(r)try{await Promise.all([M(r,t),N(r,t)])}catch(Te){if(Ie){const Le=Te instanceof Error?Te.message:"Failed to refresh repository state";U.error(Le)}}},[r,t,M,N]),Xe=i.useCallback(async()=>{r&&await v(r,t,G)},[r,t,v,G]),at=i.useCallback(async()=>{r&&await A(r,t)},[r,t,A]);i.useEffect(()=>{if(!r||!t?.hasLocalIdentity||f!==!0)return;const Ie=typeof c=="string"?c.trim():"";if(!Ie||Ie==="global"||Y.current.get(r)===Ie)return;let Le=!1;return(async()=>{try{const se=await t.hasLocalIdentity?.(r);if(Le||se===!0)return;Z(),await t.setGitIdentity(r,Ie),Y.current.set(r,Ie),await at()}catch(se){console.warn("Failed to auto-apply default git identity:",se)}finally{Le||z()}})(),()=>{Le=!0}},[Z,r,c,z,t,f,at]);const We=i.useMemo(()=>{if(!p)return[];const Ie=p.files??[],Te=new Map;for(const Le of Ie)Te.set(Le.path,Le);return Array.from(Te.values()).sort((Le,te)=>Le.path.localeCompare(te.path))},[p]);i.useEffect(()=>{if(!p||We.length===0){de(new Set),xe(!1);return}de(Ie=>{const Te=new Set,Le=Ie??new Set;for(const te of We)Le.has(te.path)?Te.add(te.path):we||Te.add(te.path);return Te})},[p,We,we]);const Be=async Ie=>{if(r){V(Ie);try{if(Ie==="fetch")await t.gitFetch(r),U.success("Fetched latest updates");else if(Ie==="pull"){const Te=await t.gitPull(r);U.success(`Pulled ${Te.files.length} file${Te.files.length===1?"":"s"}`)}else Ie==="push"&&(await t.gitPush(r),U.success("Pushed to remote"));await ke(!1),await Xe()}catch(Te){const Le=Te instanceof Error?Te.message:`Failed to ${Ie==="pull"?"pull":Ie}`;U.error(Le)}finally{V(null)}}},Ve=async(Ie={})=>{if(!r)return;if(!P.trim()){U.error("Please enter a commit message");return}const Te=Array.from(R).sort();if(Te.length===0){U.error("Select at least one file to commit");return}const Le=Ie.pushAfter?"commitAndPush":"commit";O(Le);try{await t.createGitCommit(r,P.trim(),{files:Te}),U.success("Commit created successfully"),D(""),de(new Set),xe(!1),fe(),await ke(),Ie.pushAfter?(await t.gitPush(r),U.success("Pushed to remote"),W(),await ke(!1)):await ke(!1),await Xe()}catch(te){const se=te instanceof Error?te.message:"Failed to create commit";U.error(se)}finally{O(null)}},mt=i.useCallback(async()=>{if(r){if(R.size===0){U.error("Select at least one file to describe");return}J(!0);try{const{message:Ie}=await t.generateCommitMessage(r,Array.from(R)),Te=Ie.subject?.trim()??"",Le=Array.isArray(Ie.highlights)?Ie.highlights:[];if(Te){let te=Te;if(j&&rt.length>0){const se=WN(Te,rt);if(se){const{code:ie,emoji:Ee}=se;!Te.startsWith(ie)&&!Te.startsWith(Ee)&&(te=`${ie} ${Te}`)}}D(te)}ge(Le),U.success("Commit message generated")}catch(Ie){const Te=Ie instanceof Error?Ie.message:"Failed to generate commit message";U.error(Te)}finally{J(!1)}}},[r,R,t,j,rt]),ft=async Ie=>{if(!r||!p)return;const Te=p.current??null;try{await t.createBranch(r,Ie,Te??"HEAD"),U.success(`Created branch ${Ie}`);let Le=!1;try{await t.checkoutBranch(r,Ie),await t.gitPush(r,{remote:"origin",branch:Ie,options:["--set-upstream"]}),Le=!0}catch(te){const se=te instanceof Error?te.message:"Unable to push new branch to origin.";U.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",se]})})}finally{if(Te)try{await t.checkoutBranch(r,Te)}catch(te){console.warn("Failed to restore original branch after creation:",te)}}await ke(),await Xe(),Le&&U.success(`Upstream set for ${Ie}`)}catch(Le){const te=Le instanceof Error?Le.message:"Failed to create branch";throw U.error(te),Le}},Ke=async(Ie,Te)=>{if(r)try{await t.renameBranch(r,Ie,Te),U.success(`Renamed branch ${Ie} to ${Te}`),await ke(),await Xe()}catch(Le){const te=Le instanceof Error?Le.message:`Failed to rename branch ${Ie} to ${Te}`;U.error(te)}},lt=async Ie=>{if(!r)return;const Te=Ie.replace(/^remotes\//,"");if(p?.current!==Te)try{await t.checkoutBranch(r,Te),U.success(`Checked out ${Te}`),await ke(),await Xe()}catch(Le){const te=Le instanceof Error?Le.message:`Failed to checkout ${Te}`;U.error(te)}},jt=async Ie=>{if(r){Z();try{await t.setGitIdentity(r,Ie.id),U.success(`Applied "${Ie.name}" to repository`),await at()}catch(Te){const Le=Te instanceof Error?Te.message:"Failed to apply git identity";U.error(Le)}finally{z()}}},yt=i.useMemo(()=>h?.all?h.all.filter(Ie=>!Ie.startsWith("remotes/")).sort():[],[h]),Mt=i.useMemo(()=>h?.all?h.all.filter(Ie=>Ie.startsWith("remotes/")).map(Ie=>Ie.replace(/^remotes\//,"")).sort():[],[h]),es=i.useMemo(()=>{const Ie=new Map;l&&Ie.set(l.id,l);let Te=null;if(qe)try{let Le=qe.trim();Le.startsWith("git@")&&(Le=`https://${Le.slice(4).replace(":","/")}`),Le.endsWith(".git")&&(Le=Le.slice(0,-4));const te=new URL(Le);Te=te.hostname+te.pathname}catch{}for(const Le of a){if(Le.authType!=="token"){Ie.set(Le.id,Le);continue}const te=Le.host;if(!te){Ie.set(Le.id,Le);continue}if(!te.includes("/")){Ie.set(Le.id,Le);continue}Te&&Te===te&&Ie.set(Le.id,Le)}return Array.from(Ie.values())},[a,l,qe]),Ht=i.useMemo(()=>{if(x?.userName&&x?.userEmail){const Ie=a.find(Te=>Te.userName===x.userName&&Te.userEmail===x.userEmail);return Ie||(l&&l.userName===x.userName&&l.userEmail===x.userEmail?l:{id:"local-config",name:x.userName,userName:x.userName,userEmail:x.userEmail,sshKey:x.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return l??null},[x,a,l]),Wt=We.length,kt=R.size,gs=b||B!==null||ne!==null,Qt=Wt>0,Tt=Ie=>{de(Te=>{const Le=new Set(Te);return Le.has(Ie)?Le.delete(Ie):Le.add(Ie),Le}),xe(!0)},Kt=()=>{const Ie=new Set(We.map(Te=>Te.path));de(Ie),xe(!0)},Rt=()=>{de(new Set),xe(!0)},_t=i.useCallback(async Ie=>{if(r){H(Te=>{const Le=new Set(Te);return Le.add(Ie),Le});try{await t.revertGitFile(r,Ie),U.success(`Reverted ${Ie}`),await ke(!1)}catch(Te){const Le=Te instanceof Error?Te.message:"Failed to revert changes";U.error(Le)}finally{H(Te=>{const Le=new Set(Te);return Le.delete(Ie),Le})}}},[r,ke,t]),Yt=i.useCallback(()=>{if(ce.length===0)return;const Ie=ce.map(Te=>Te.trim()).filter(Boolean);if(Ie.length===0){fe();return}D(Te=>{const Le=Te.trim(),te=Le.length>0?`
|
|
224
|
+
|
|
225
|
+
`:"";return`${Le}${te}${Ie.join(`
|
|
226
|
+
`)}`.trim()})},[ce,fe]),Gt=i.useCallback((Ie,Te)=>{const Le=Te||Ie;D(te=>{const se=te.trimStart();return se.startsWith(Ie)||Te&&se.startsWith(Te)?te:`${Le.endsWith(" ")?Le:`${Le} `}${te}`.trimStart()}),pe(""),F(!1)},[]),It=i.useCallback(Ie=>{K(Ie),r&&(k(r,Ie),v(r,t,Ie))},[r,k,v,t]);return r?b&&f===null?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ct,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):f===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Vt,{className:"mb-3 size-6 text-muted-foreground"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:"Not a Git repository"}),e.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:"Choose a different directory or initialize Git to use this workspace."})]}):e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background","data-keyboard-avoid":"true",children:[e.jsx(jN,{status:p,localBranches:yt,remoteBranches:Mt,branchInfo:h?.branches,syncAction:B,onFetch:()=>Be("fetch"),onPull:()=>Be("pull"),onPush:()=>Be("push"),onCheckoutBranch:lt,onCreateBranch:ft,onRenameBranch:Ke,activeIdentityProfile:Ht,availableIdentities:es,onSelectIdentity:jt,isApplyingIdentity:q,isWorktreeMode:!!o}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"p-3",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[Qt?e.jsx(DN,{changeEntries:We,selectedPaths:R,diffStats:p?.diffStats,revertingPaths:Pe,onToggleFile:Tt,onSelectAll:Kt,onClearSelection:Rt,onViewDiff:Ie=>Me.getState().navigateToDiff(Ie),onRevertFile:_t}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(SN,{behind:p?.behind??0,onPull:()=>Be("pull"),isPulling:B==="pull"})}),We.length>0&&e.jsx(IN,{selectedCount:kt,commitMessage:P,onCommitMessageChange:D,generatedHighlights:ce,onInsertHighlights:Yt,onClearHighlights:fe,onGenerateMessage:mt,isGeneratingMessage:ye,onCommit:()=>Ve({pushAfter:!1}),onCommitAndPush:()=>Ve({pushAfter:!0}),commitAction:ne,isBusy:gs,gitmojiEnabled:j,onOpenGitmojiPicker:()=>F(!0)})]}),o&&ee&&me?e.jsx(fN,{repoRoot:ee,sourceBranch:me,worktreeMetadata:o,localBranches:yt,defaultTargetBranch:le,onRefresh:()=>{r&&(M(r,t),N(r,t),v(r,t,G))}}):null,r&&p?.current&&p?.tracking?e.jsx(ON,{directory:r,branch:p.current,baseBranch:I}):null,e.jsx(RN,{log:g,isLogLoading:y,logMaxCount:G,onLogMaxCountChange:It,expandedCommitHashes:oe,onToggleCommit:Se,commitFilesMap:re,loadingCommitHashes:he,onCopyHash:He})]})}),e.jsx(fs,{open:E,onOpenChange:F,children:e.jsxs(ps,{className:"max-w-md p-0 overflow-hidden",children:[e.jsx(bs,{className:"px-4 pt-4",children:e.jsx(ws,{children:"Pick a gitmoji"})}),e.jsxs(ki,{className:"h-[420px]",children:[e.jsx(Ci,{placeholder:"Search gitmojis...",value:Ce,onValueChange:pe}),e.jsxs(Mi,{children:[e.jsx(Di,{children:"No gitmojis found."}),e.jsx(Qr,{children:(rt.length===0?[]:rt.filter(Ie=>{const Te=Ce.trim().toLowerCase();return Te?Ie.emoji.includes(Te)||Ie.code.toLowerCase().includes(Te)||Ie.description.toLowerCase().includes(Te):!0})).map(Ie=>e.jsxs(vs,{onSelect:()=>Gt(Ie.emoji,Ie.code),children:[e.jsx("span",{className:"text-lg",children:Ie.emoji}),e.jsx("span",{className:"typography-ui-label text-foreground",children:Ie.code}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:Ie.description})]},Ie.code))})]})]})]})})]}):e.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"Select a session or directory to view repository details."})})},VN=1e6;function cn(t){let r=t.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const ya=t=>({directory:t,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),Xu=is((t,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:s=>{const n=cn(s);return r().sessions.get(n)},setTerminalSession:(s,n)=>{const o=cn(s);t(a=>{const l=new Map(a.sessions),c=l.get(o),u=!c||c.terminalSessionId!==n.sessionId?ya(o):c??ya(o);return l.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:l}})},setConnecting:(s,n)=>{const o=cn(s);t(a=>{const l=new Map(a.sessions),c=l.get(o)??ya(o);return l.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(s,n)=>{if(!n)return;const o=cn(s);t(a=>{const l=new Map(a.sessions),c=l.get(o)??ya(o),d=a.nextChunkId,u={id:d,data:n},m=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>VN&&m.length>1;){const h=m.shift();if(!h)break;f-=h.data.length}const p=m.map(h=>h.data).join("");return l.set(o,{...c,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:l,nextChunkId:d+1}})},clearTerminalSession:s=>{const n=cn(s);t(o=>{const a=new Map(o.sessions),l=a.get(n);return l&&a.set(n,{...l,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:s=>{const n=cn(s);t(o=>{const a=new Map(o.sessions),l=a.get(n);return l?(a.set(n,{...l,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:s=>{const n=cn(s);t(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{t({sessions:new Map,nextChunkId:1})}})),lh=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),GN=[{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'}],qN=[{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'}],ch=t=>Object.fromEntries(t.map(r=>[r.id,r])),Zu=ch(GN),un=ch(qN),KN="ibm-plex-sans",_a="ibm-plex-mono";function YN(t){const{colors:r}=t,s=r.syntax.base;return{background:r.surface.background,foreground:s.foreground,cursor:r.interactive.cursor,cursorAccent:r.surface.background,selectionBackground:r.interactive.selection,selectionForeground:r.interactive.selectionForeground,selectionInactiveBackground:r.interactive.selection+"50",black:r.surface.muted,red:r.status.error,green:r.status.success,yellow:r.status.warning,blue:s.function,magenta:s.keyword,cyan:s.type,white:s.foreground,brightBlack:s.comment,brightRed:r.status.error,brightGreen:r.status.success,brightYellow:r.status.warning,brightBlue:s.function,brightMagenta:s.keyword,brightCyan:s.type,brightWhite:r.surface.elevatedForeground}}function QN(t,r,s,n){const a=`${t}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!0,fontSize:r,lineHeight:1.15,fontFamily:a,allowTransparency:!1,theme:{background:s.background,foreground:s.foreground,cursor:s.cursor,cursorAccent:s.cursorAccent,selectionBackground:s.selectionBackground,selectionForeground:s.selectionForeground,black:s.black,red:s.red,green:s.green,yellow:s.yellow,blue:s.blue,magenta:s.magenta,cyan:s.cyan,white:s.white,brightBlack:s.brightBlack,brightRed:s.brightRed,brightGreen:s.brightGreen,brightYellow:s.brightYellow,brightBlue:s.brightBlue,brightMagenta:s.brightMagenta,brightCyan:s.brightCyan,brightWhite:s.brightWhite},scrollback:5e4,ghostty:n}}let ul=null;function JN(){return ul||(ul=Wx.load()),ul}function XN(t){if(typeof window>"u")return null;const r=[t,...Array.from(t.querySelectorAll("*"))];let s=null;for(const n of r){const a=window.getComputedStyle(n).overflowY;if(!(a!=="auto"&&a!=="scroll")){if(n.scrollHeight-n.clientHeight>2)return n;s||(s=n)}}return s}const sc=i.forwardRef(({sessionKey:t,chunks:r,onInput:s,onResize:n,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d},u)=>{const m=i.useRef(null),f=i.useRef(null),p=i.useRef(null),h=i.useRef(null),g=i.useRef(s),x=i.useRef(n),b=i.useRef(null),y=i.useRef(""),w=i.useRef(null),S=i.useRef(!1),M=i.useRef(null),N=i.useRef(null),v=i.useRef(null),A=i.useRef(0),k=i.useRef(null),[,C]=i.useReducer(O=>O+1,0),[j,T]=i.useReducer(O=>O+1,0);g.current=s,x.current=n;const I=i.useCallback((O,G)=>{const K=k.current,q=m.current;if(!K||!q)return;const $=q.getBoundingClientRect(),W=$.left+$.width/2,Y=$.top+$.height-12,X=typeof O=="number"?O:W,Z=typeof G=="number"?G:Y,z=8,R=Math.max(z,Math.min($.width-z,X-$.left)),de=Math.max(z,Math.min($.height-z,Z-$.top));K.style.left=`${R}px`,K.style.top=`${de}px`,K.style.bottom="";try{K.focus({preventScroll:!0})}catch{try{K.focus()}catch{}}},[]),P=i.useCallback(async()=>{if(typeof window>"u"||typeof document>"u")return;const O=window.getSelection();if(!O)return;const G=O.toString();if(!G.trim())return;const K=m.current;if(!K)return;const q=O.anchorNode,$=O.focusNode;if(!(q&&!K.contains(q))&&!($&&!K.contains($))){try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(G);return}}catch{}try{const W=document.createElement("textarea");W.value=G,W.style.position="fixed",W.style.opacity="0",document.body.appendChild(W),W.focus(),W.select(),document.execCommand("copy"),document.body.removeChild(W)}catch{}}},[]),D=i.useCallback(()=>{y.current="",w.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(w.current),w.current=null,S.current=!1,M.current=null},[]),E=i.useCallback(()=>{const O=h.current,G=p.current,K=m.current;if(!O||!G||!K)return;const q=K.getBoundingClientRect();if(!(q.width<24||q.height<24))try{O.fit();const $={cols:G.cols,rows:G.rows},W=b.current;(!W||W.cols!==$.cols||W.rows!==$.rows)&&(b.current=$,x.current($.cols,$.rows))}catch{}},[]),F=i.useCallback(()=>{if(S.current)return;const O=p.current;if(!O){D();return}if(!y.current)return;const G=y.current;y.current="",S.current=!0,O.write(G,()=>{S.current=!1,y.current&&(typeof window<"u"?w.current=window.requestAnimationFrame(()=>{w.current=null,F()}):F())})},[D]),B=i.useCallback(()=>{w.current===null&&(typeof window<"u"?w.current=window.requestAnimationFrame(()=>{w.current=null,F()}):F())},[F]),V=i.useCallback(O=>{O&&(y.current+=O,B())},[B]),ne=i.useCallback(()=>{if(N.current?.(),N.current=null,v.current!==null&&typeof window<"u"&&(window.clearTimeout(v.current),v.current=null),!d){A.current=0;return}const O=m.current;if(!O)return;const G=p.current;if(!G)return;A.current=0;const K=2.2,q=2.8,$=25,W=.25,Y=8,X=.05,Z=.015,z={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},R=()=>typeof performance<"u"?performance.now():Date.now(),de=Math.max(12,Math.round(l*1.35));let we=0;const xe=le=>{if(!le)return!1;const fe=G.getViewportY(),oe=we+le,Q=Math.trunc(oe/de);return we=oe-Q*de,Q!==0&&G.scrollLines(Q),G.getViewportY()!==fe},Pe=()=>{z.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(z.rafId),z.rafId=null},H={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const le=Object.assign(z,{pointerId:null,startX:null,startY:null,moved:!1}),fe=6,oe=he=>{if(he.pointerType==="touch"){Pe(),le.pointerId=he.pointerId,le.startX=he.clientX,le.startY=he.clientY,le.moved=!1,le.lastY=he.clientY,le.lastTime=R(),le.velocity=0;try{O.setPointerCapture(he.pointerId)}catch{}}},Q=he=>{if(he.pointerType!=="touch"||le.pointerId!==he.pointerId)return;if(le.startX!==null&&le.startY!==null&&!le.moved){const Se=he.clientX-le.startX,ke=he.clientY-le.startY;Math.hypot(Se,ke)>=fe&&(le.moved=!0)}if(le.lastY===null){le.lastY=he.clientY,le.lastTime=R();return}const Ge=le.lastY,qe=le.lastTime??R(),et=R();le.lastY=he.clientY,le.lastTime=et;const rt=Ge-he.clientY;if(Math.abs(rt)<1)return;const vt=Math.max(et-qe,8),Ce=K+Math.min(q,Math.abs(rt)/$),pe=rt*Ce,He=pe/vt;le.velocity=le.velocity*(1-W)+He*W,le.velocity>Y?le.velocity=Y:le.velocity<-Y&&(le.velocity=-Y),le.moved&&(he.cancelable&&he.preventDefault(),he.stopPropagation()),xe(pe)},re=he=>{if(he.pointerType!=="touch"||le.pointerId!==he.pointerId)return;const Ge=!le.moved;le.pointerId=null,le.startX=null,le.startY=null,le.moved=!1,le.lastY=null,le.lastTime=null;try{O.releasePointerCapture(he.pointerId)}catch{}if(Ge){I(he.clientX,he.clientY);return}if(typeof window>"u")return;if(Math.abs(le.velocity)<X){le.velocity=0;return}let qe=R();const et=()=>{const rt=R(),vt=Math.max(rt-qe,8);qe=rt;const Ce=xe(le.velocity*vt)??!1,pe=Math.sign(le.velocity),He=Math.max(0,Math.abs(le.velocity)-Z*vt);if(le.velocity=He*pe,!Ce||He<=X){Pe(),le.velocity=0;return}le.rafId=window.requestAnimationFrame(et)};le.rafId=window.requestAnimationFrame(et)};O.addEventListener("pointerdown",oe,H),O.addEventListener("pointermove",Q,H),O.addEventListener("pointerup",re,H),O.addEventListener("pointercancel",re,H);const ue=O.style.touchAction;O.style.touchAction="manipulation",N.current=()=>{Pe(),v.current!==null&&typeof window<"u"&&(window.clearTimeout(v.current),v.current=null),A.current=0,O.removeEventListener("pointerdown",oe,H),O.removeEventListener("pointermove",Q,H),O.removeEventListener("pointerup",re,H),O.removeEventListener("pointercancel",re,H),O.style.touchAction=ue};return}const J=6,ce=le=>{le.touches.length===1&&(Pe(),z.lastY=le.touches[0].clientY,z.lastTime=R(),z.velocity=0,z.startX=le.touches[0].clientX,z.startY=le.touches[0].clientY,z.didMove=!1)},ge=le=>{if(le.touches.length!==1){z.lastY=null,z.lastTime=null,z.velocity=0,z.startX=null,z.startY=null,z.didMove=!1,Pe();return}const fe=le.touches[0].clientX,oe=le.touches[0].clientY;if(z.startX!==null&&z.startY!==null&&!z.didMove){const vt=fe-z.startX,Ce=oe-z.startY;Math.hypot(vt,Ce)>=J&&(z.didMove=!0)}if(z.lastY===null){z.lastY=oe,z.lastTime=R();return}const Q=z.lastY,re=z.lastTime??R(),ue=R();z.lastY=oe,z.lastTime=ue;const he=Q-oe;if(Math.abs(he)<1)return;const Ge=Math.max(ue-re,8),qe=K+Math.min(q,Math.abs(he)/$),et=he*qe,rt=et/Ge;z.velocity=z.velocity*(1-W)+rt*W,z.velocity>Y?z.velocity=Y:z.velocity<-Y&&(z.velocity=-Y),z.didMove&&(le.preventDefault(),le.stopPropagation()),xe(et)},ee=le=>{const fe=!z.didMove;z.lastY=null,z.lastTime=null;const oe=z.velocity;if(z.startX=null,z.startY=null,z.didMove=!1,fe){const ue=le.changedTouches?.[0];I(ue?.clientX,ue?.clientY);return}if(typeof window>"u")return;if(Math.abs(oe)<X){z.velocity=0;return}let Q=R();const re=()=>{const ue=R(),he=Math.max(ue-Q,8);Q=ue;const Ge=xe(z.velocity*he)??!1,qe=Math.sign(z.velocity),et=Math.max(0,Math.abs(z.velocity)-Z*he);if(z.velocity=et*qe,!Ge||et<=X){Pe(),z.velocity=0;return}z.rafId=window.requestAnimationFrame(re)};z.rafId=window.requestAnimationFrame(re)};O.addEventListener("touchstart",ce,H),O.addEventListener("touchmove",ge,H),O.addEventListener("touchend",ee,H),O.addEventListener("touchcancel",ee,H);const me=O.style.touchAction;O.style.touchAction="manipulation",N.current=()=>{Pe(),v.current!==null&&typeof window<"u"&&(window.clearTimeout(v.current),v.current=null),A.current=0,O.removeEventListener("touchstart",ce,H),O.removeEventListener("touchmove",ge,H),O.removeEventListener("touchend",ee,H),O.removeEventListener("touchcancel",ee,H),O.style.touchAction=me}},[d,I,l]);return i.useEffect(()=>{let O=!1,G=null,K=null,q=[];const $=m.current;return $?($.tabIndex=0,(async()=>{try{const Y=await JN();if(O)return;const X=QN(a,l,o,Y),Z=new zx(X),z=new Hx;G=Z,p.current=Z,h.current=z,Z.loadAddon(z),Z.open($),T();const R=XN($);R?(R.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=R,C()):f.current=null,E(),ne(),Z.focus(),q=[Z.onData(de=>{g.current(de)})],K=new ResizeObserver(()=>{E()}),K.observe($),typeof window<"u"&&window.setTimeout(()=>{E()},0)}catch{}})(),()=>{O=!0,N.current?.(),N.current=null,q.forEach(Y=>Y.dispose()),K?.disconnect(),G?.dispose(),p.current=null,h.current=null,f.current=null,b.current=null,D()}):void 0},[E,a,l,ne,o,D]),i.useEffect(()=>{const O=p.current;O&&(O.reset(),D(),b.current=null,E(),O.focus())},[t,j,E,D]),i.useEffect(()=>(ne(),()=>{N.current?.(),N.current=null}),[ne,t]),i.useEffect(()=>{const O=p.current;if(!O)return;if(r.length===0){M.current!==null&&(O.reset(),D(),E());return}const G=M.current;let K;if(G===null)K=r;else{const q=r.findIndex($=>$.id===G);K=q>=0?r.slice(q+1):r}K.length>0&&V(K.map(q=>q.data).join("")),M.current=r[r.length-1].id},[r,j,V,E,D]),i.useImperativeHandle(u,()=>({focus:()=>{if(d){I();return}p.current?.focus()},clear:()=>{const O=p.current;O&&(O.reset(),D(),E())},fit:()=>{E()}}),[d,I,E,D]),e.jsxs("div",{ref:m,className:L("relative h-full w-full terminal-viewport-container",c),style:{backgroundColor:o.background},onClick:O=>{d?I(O.clientX,O.clientY):p.current?.focus()},onMouseUp:()=>{P()},onTouchEnd:()=>{P()},children:[d?e.jsx("textarea",{ref:k,inputMode:"text",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,"aria-hidden":"true",style:{position:"absolute",left:0,top:0,width:1,height:1,opacity:0,zIndex:1,background:"transparent",color:"transparent",caretColor:"transparent",resize:"none",overflow:"hidden",whiteSpace:"nowrap",border:"none",padding:0,margin:0,outline:"none"},onInput:O=>{const G=String(O.currentTarget.value||"");if(!G)return;const K=G.replace(/\r\n|\r|\n/g,"\r");g.current(K),O.currentTarget.value=""},onKeyDown:O=>{O.key==="Backspace"&&(O.currentTarget.value||g.current(""))}}):null,f.current&&!d?e.jsx(kc,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});sc.displayName="TerminalViewport";const em=13,ZN={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},ba={ctrl:"5",cmd:"3"},ek={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},tk=(t,r)=>{if(r)switch(t){case"arrow-up":return`\x1B[1;${ba[r]}A`;case"arrow-down":return`\x1B[1;${ba[r]}B`;case"arrow-right":return`\x1B[1;${ba[r]}C`;case"arrow-left":return`\x1B[1;${ba[r]}D`}return ZN[t]??null},sk=()=>{const{terminal:t}=Hs(),{currentTheme:r}=Hr(),{monoFont:s}=lh(),{isMobile:n,hasTouchInput:o}=qt(),{currentSessionId:a,newSessionDraft:l}=be(),c=a!==null||l?.open===!0,d=Qo()??null,{homeDirectory:u}=xt(),m=i.useMemo(()=>d?u?d===u?"~":d.startsWith(u+"/")?"~"+d.slice(u.length):d:d:"",[d,u]),f=Xu(),p=f.sessions,h=f.setTerminalSession,g=f.setConnecting,x=f.appendToBuffer,b=f.clearTerminalSession,y=f.removeTerminalSession,w=f.clearBuffer,S=i.useMemo(()=>{if(d)return p.get(d)},[p,d]),M=S?.terminalSessionId??null,N=S?.bufferChunks??[],v=S?.bufferLength??0,A=S?.isConnecting??!1,k=M,[C,j]=i.useState(null),[T,I]=i.useState(!1),[P,D]=i.useState(null),[E,F]=i.useState(!1),B=i.useRef(null),V=i.useRef(null),ne=i.useRef(k),O=i.useRef(d),G=i.useRef(null),q=Me(ge=>ge.activeMainTab)==="terminal";i.useEffect(()=>{ne.current=k},[k]),i.useEffect(()=>{O.current=d},[d]),i.useEffect(()=>{!n&&P!==null&&D(null)},[n,P,D]),i.useEffect(()=>{!k&&P!==null&&D(null)},[k,P,D]);const $=i.useCallback(()=>{B.current?.(),B.current=null,V.current=null},[]);i.useEffect(()=>()=>{$(),ne.current=null},[$]);const W=i.useCallback(ge=>{if(V.current===ge)return;$();const ee=t.connect(ge,{onEvent:me=>{const le=O.current;if(le)switch(me.type){case"connected":{(me.runtime||me.ptyBackend)&&console.log(`[Terminal] connected runtime=${me.runtime??"unknown"} pty=${me.ptyBackend??"unknown"}`),g(le,!1),j(null),I(!1),G.current?.focus();break}case"reconnecting":{const fe=me.attempt??0,oe=me.maxAttempts??3;j(`Reconnecting (${fe}/${oe})...`),I(!1);break}case"data":{me.data&&x(le,me.data);break}case"exit":{const fe=typeof me.exitCode=="number"?me.exitCode:null,oe=typeof me.signal=="number"?me.signal:null;x(le,`\r
|
|
227
|
+
[Process exited${fe!==null?` with code ${fe}`:""}${oe!==null?` (signal ${oe})`:""}]\r
|
|
228
|
+
`),b(le),g(le,!1),j("Terminal session ended"),I(!1),$();break}}},onError:(me,le)=>{const fe=O.current;if(!fe)return;const oe=le?`Connection failed: ${me.message}`:me.message||"Terminal stream connection error";j(oe),I(!!le),le&&(g(fe,!1),$(),y(fe))}},ek);B.current=()=>{ee.close(),V.current=null},V.current=ge},[x,b,$,y,g,t,j]);i.useEffect(()=>{let ge=!1;if(!d){j(c?"No working directory available for terminal.":"Select a session to open the terminal."),$();return}return(async()=>{const me=d;if(!O.current||O.current!==me)return;let fe=Xu.getState().getTerminalSession(me)?.terminalSessionId??null;if(!fe){j(null),I(!1),g(me,!0);try{const oe=await t.createSession({cwd:me});if(ge){try{await t.close(oe.sessionId)}catch{}return}h(me,oe),fe=oe.sessionId}catch(oe){ge||(j(oe instanceof Error?oe.message:"Failed to start terminal session"),I(!0),g(me,!1));return}}!fe||ge||(ne.current=fe,W(fe))})(),()=>{ge=!0,ne.current=null,$()}},[c,d,k,y,g,h,W,$,t]);const Y=i.useCallback(async()=>{if(!d||E)return;F(!0),j(null),I(!1),$();const ge=ne.current;try{if(t.restartSession&&ge){const ee=await t.restartSession(ge,{cwd:d});h(d,ee),ne.current=ee.sessionId,W(ee.sessionId)}else{if(ge)try{await t.close(ge)}catch{}y(d)}}catch(ee){j(ee instanceof Error?ee.message:"Failed to restart terminal"),I(!0)}finally{F(!1)}},[d,E,$,t,h,W,y]),X=i.useCallback(async()=>{if(d&&!E){F(!0),j(null),I(!1),$();try{t.forceKill&&await t.forceKill({cwd:d})}catch{}y(d),w(d),G.current?.clear(),await new Promise(ge=>setTimeout(ge,100));try{g(d,!0);const ge=await t.createSession({cwd:d});h(d,ge),ne.current=ge.sessionId,W(ge.sessionId)}catch(ge){j(ge instanceof Error?ge.message:"Failed to create terminal"),I(!0),g(d,!1)}finally{F(!1)}}},[d,E,$,t,y,w,g,h,W]),Z=i.useCallback(()=>{if(!d)return;w(d),G.current?.clear(),G.current?.focus();const ge=ne.current;ge&&t.sendInput(ge,"\f").catch(ee=>{j(ee instanceof Error?ee.message:"Failed to refresh prompt")})},[w,d,j,t]),z=i.useCallback(ge=>{if(!ge)return;let ee=ge,me=!1;if(P&&ge.length>0){const fe=ge[0];if(fe.length===1&&/[a-zA-Z]/.test(fe)){const oe=fe.toUpperCase();(P==="ctrl"||P==="cmd")&&(ee=String.fromCharCode(oe.charCodeAt(0)&31),me=!0)}me||(me=!0)}const le=ne.current;le&&(t.sendInput(le,ee).catch(fe=>{j(fe instanceof Error?fe.message:"Failed to send input")}),me&&(D(null),G.current?.focus()))},[P,D,t]),R=i.useCallback((ge,ee)=>{const me=ne.current;me&&t.resize({sessionId:me,cols:ge,rows:ee}).catch(()=>{})},[t]),de=i.useCallback(ge=>{D(ee=>ee===ge?null:ge),G.current?.focus()},[D]),we=i.useCallback(ge=>{const ee=tk(ge,P);ee&&(z(ee),D(null),G.current?.focus())},[P,z,D]);i.useEffect(()=>{if(!n||!P||!k)return;const ge=ee=>{if(ee.repeat)return;const me=ee.key;if(!me||me==="Control"||me==="Meta"||me==="Alt"||me==="Shift")return;const le=me.length===1?me.toLowerCase():me,fe=ee.code??"",oe=fe.startsWith("Key")&&fe.length===4?fe.slice(3).toUpperCase():null,Q=me.length===1&&/[a-zA-Z]/.test(me)?me.toUpperCase():oe,re={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(le in re){ee.preventDefault(),ee.stopPropagation(),we(re[le]);return}if(P==="ctrl"&&Q&&Q.length===1&&Q>="A"&&Q<="Z"){const ue=String.fromCharCode(Q.charCodeAt(0)&31);ee.preventDefault(),ee.stopPropagation(),z(ue),D(null),G.current?.focus()}};return window.addEventListener("keydown",ge),()=>{window.removeEventListener("keydown",ge)}},[P,we,z,n,D,k]);const xe=i.useMemo(()=>{const ge=un[_a].stack;if(typeof window>"u")return(un[s]??un[_a]).stack;const me=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return me&&me.trim().length>0?me.trim():(un[s]??un[_a]).stack??ge},[s]),Pe=i.useMemo(()=>YN(r),[r]),H=i.useMemo(()=>`${d??"no-dir"}::${k??"pending"}`,[d,k]);i.useEffect(()=>{if(!q)return;const ge=G.current;if(!ge)return;const ee=()=>{ge.fit()};if(typeof window<"u"){const me=window.requestAnimationFrame(()=>{ee(),ge.focus()}),le=[220,400].map(fe=>window.setTimeout(ee,fe));return()=>{window.cancelAnimationFrame(me),le.forEach(fe=>window.clearTimeout(fe))}}ee()},[q,H,k]);const ye=C?.includes("Reconnecting"),J=C?ye?e.jsx(Ux,{size:20,className:"text-amber-400"}):e.jsx(ss,{size:20,className:"text-destructive"}):k&&!A&&!E?e.jsx(ka,{size:20,className:"text-emerald-400"}):A||E?e.jsx(Dl,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Dl,{size:20,className:"text-muted-foreground"});if(!c)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(!d)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:Y,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const ce=!k||A||E;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:m})}),e.jsxs("div",{className:"flex items-center gap-2",children:[J,e.jsxs(je,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:Z,disabled:!v,title:"Clear output",type:"button",children:[e.jsx(zs,{size:16}),"Clear"]}),e.jsxs(je,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:Y,disabled:E,title:"Restart terminal session",type:"button",children:[e.jsx(Ls,{size:16,className:L((A||E)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(je,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>we("esc"),disabled:ce,children:"Esc"}),e.jsxs(je,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>we("tab"),disabled:ce,children:[e.jsx(Zc,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(je,{type:"button",size:"sm",variant:P==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>de("ctrl"),disabled:ce,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(je,{type:"button",size:"sm",variant:P==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>de("cmd"),disabled:ce,children:[e.jsx(Dn,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(je,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>we("arrow-up"),disabled:ce,children:[e.jsx(Jn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(je,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>we("arrow-left"),disabled:ce,children:[e.jsx(cf,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(je,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>we("arrow-down"),disabled:ce,children:[e.jsx(fo,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(je,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>we("arrow-right"),disabled:ce,children:[e.jsx(Zc,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(je,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>we("enter"),disabled:ce,children:[e.jsx(Zn,{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:q?n?e.jsx(sc,{ref:ge=>{G.current=ge},sessionKey:H,chunks:N,onInput:z,onResize:R,theme:Pe,fontFamily:xe,fontSize:em,enableTouchScroll:o},H):e.jsx(gt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(sc,{ref:ge=>{G.current=ge},sessionKey:H,chunks:N,onInput:z,onResize:R,theme:Pe,fontFamily:xe,fontSize:em,enableTouchScroll:o},H)}):null}),C&&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:C}),T&&e.jsx(je,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:X,disabled:E,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},rk=t=>t.slice().sort((r,s)=>r.type!==s.type?r.type==="directory"?-1:1:r.name.localeCompare(s.name)),ar=t=>t.replace(/\\/g,"/"),nk=new Set(["node_modules"]),ok=t=>nk.has(t),ak=t=>{const r=ar(t);return r==="node_modules"||r.endsWith("/node_modules")||r.includes("/node_modules/")},No=2e5,ik=new Set(["js","jsx","ts","tsx","mjs","cjs","mts","cts","html","htm","xhtml","css","scss","sass","less","styl","stylus","vue","svelte","astro","sh","bash","zsh","fish","ps1","psm1","bat","cmd","py","pyw","pyx","pxd","pxi","rb","erb","rake","gemspec","php","phtml","php3","php4","php5","phps","java","kt","kts","scala","sc","groovy","gradle","c","h","cpp","cc","cxx","hpp","hxx","hh","m","mm","cs","fs","fsx","fsi","go","rs","swift","dart","lua","pl","pm","pod","r","R","rmd","jl","hs","lhs","ex","exs","erl","hrl","clj","cljs","cljc","edn","lisp","cl","el","scm","ss","rkt","ml","mli","re","rei","nim","zig","v","cr","main.kts","sql","psql","plsql","graphql","gql","sol","asm","s","S","mk","nix","tf","tfvars","pp","ansible"]),lk=new Set(["json","jsonc","json5","jsonl","ndjson","geojson","yaml","yml","toml","xml","xsl","xslt","xsd","dtd","plist","ini","cfg","conf","config","env","properties","csv","tsv","lock"]),ck=new Set(["png","jpg","jpeg","gif","svg","webp","ico","icns","bmp","tiff","tif","psd","ai","eps","raw","cr2","nef","heic","heif","avif","jxl"]),dk=new Set(["md","mdx","markdown","mdown","mkd","txt","text","rtf","doc","docx","odt","pdf","rst","adoc","asciidoc","org","tex","latex","bib"]),tm=t=>{const r=t?.toLowerCase();return r&&ik.has(r)?e.jsx(tr,{className:"h-4 w-4 flex-shrink-0 text-blue-500"}):r&&lk.has(r)?e.jsx(tr,{className:"h-4 w-4 flex-shrink-0 text-yellow-500"}):r&&ck.has(r)?e.jsx(Dr,{className:"h-4 w-4 flex-shrink-0 text-green-500"}):r&&dk.has(r)?e.jsx(Qn,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(Qn,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})},_n=t=>{if(!t)return!1;const r=t.toLowerCase().split(".").pop();return r==="md"||r==="markdown"},uk=()=>{const{files:t,runtime:r}=Hs(),{currentTheme:s}=Hr();i.useMemo(()=>Pi(s),[s]);const{isMobile:n,screenWidth:o}=qt(),a=Vo(),l=xi(),c=Qo()??"",d=ar(c),u=yi(Ne=>Ne.searchFiles),[m,f]=i.useState(""),p=Ii(m,200),h=i.useRef(null),[g,x]=i.useState(!1),[b,y]=i.useState(n),[w,S]=i.useState(!1),[M,N]=i.useState(new Set),[v,A]=i.useState({}),k=i.useRef(new Set),C=i.useRef(new Set),[j,T]=i.useState([]),[I,P]=i.useState(!1),[D,E]=i.useState(null),[F,B]=i.useState(""),[V,ne]=i.useState(!1),[O,G]=i.useState(null),[K,q]=i.useState(""),[$,W]=i.useState(""),[Y,X]=i.useState(!1),[Z,z]=i.useState(!1),R=i.useRef(null),de=i.useRef(null),we=i.useRef(!1),xe=i.useRef(null),Pe=i.useRef(null),[H,ye]=i.useState(null),[J,ce]=i.useState(null),[ge,ee]=i.useState(""),[me,le]=i.useState(!1),[fe,oe]=i.useState(null),[Q,re]=i.useState(!1),[ue,he]=i.useState(!1),[Ge,qe]=i.useState("edit"),et=!!t.writeFile,rt=!!t.createDirectory,vt=!!t.rename,Ce=!!t.delete,pe=i.useCallback((Ne,_)=>{ye(Ne),ce(_),ee(Ne==="rename"&&_.name||""),le(!1)},[]),[He,Se]=i.useState(null),[ke,Xe]=i.useState(""),at=i.useRef(!1),We=i.useRef(null),Be=be(Ne=>Ne.sendMessage),Ve=be(Ne=>Ne.currentSessionId),{currentProviderId:mt,currentModelId:ft,currentAgentName:Ke,currentVariant:lt}=Ze(),jt=tt(Ne=>Ne.getSessionAgentSelection),yt=tt(Ne=>Ne.getAgentModelForSession),Mt=tt(Ne=>Ne.getAgentModelVariantForSession),es=Me(Ne=>Ne.setActiveMainTab),Ht=Me(Ne=>Ne.setMainTabGuard),{inputBarOffset:Wt,isKeyboardOpen:kt}=Me();i.useEffect(()=>{const Ne=()=>{at.current=!1,We.current=null};return document.addEventListener("mouseup",Ne),()=>document.removeEventListener("mouseup",Ne)},[]),i.useEffect(()=>{Se(null),Xe(""),Ht(null),W(""),X(!1)},[D?.path,Ht]),i.useEffect(()=>()=>{xe.current!==null&&window.clearTimeout(xe.current),Pe.current!==null&&window.clearTimeout(Pe.current)},[]),i.useEffect(()=>{if(!He)return;const Ne=ve=>{const ae=ve.target;document.querySelector("[data-comment-ui]")?.contains(ae)||ae.closest(".cm-gutterElement")||ae.closest("[data-sonner-toast]")||ae.closest("[data-sonner-toaster]")||(Se(null),Xe(""))},_=setTimeout(()=>{document.addEventListener("click",Ne)},100);return()=>{clearTimeout(_),document.removeEventListener("click",Ne)}},[He]);const gs=i.useCallback((Ne,_)=>{const ve=Ne.split(`
|
|
229
|
+
`),ae=Math.max(1,_.start),Fe=Math.min(ve.length,_.end);return ae>Fe?"":ve.slice(ae-1,Fe).join(`
|
|
230
|
+
`)},[]),Qt=i.useCallback(async()=>{if(!He||!ke.trim()||!D)return;if(!Ve){U.error("Select a session to send comment");return}const Ne=jt(Ve)||Ke,_=Ne?yt(Ve,Ne):null,ve=_?.providerId||mt,ae=_?.modelId||ft;if(!ve||!ae){U.error("Select a model to send comment");return}const Fe=Ne&&ve&&ae?Mt(Ve,Ne,ve,ae)??lt:lt,$e=gs(F,He),Ue=Ar(D.path)||"text",Je=D.name,ot=He.start,Et=He.end,it=`Comment on \`${Je}\` lines ${ot}-${Et}:
|
|
231
|
+
\`\`\`${Ue}
|
|
232
|
+
${$e}
|
|
233
|
+
\`\`\`
|
|
234
|
+
|
|
235
|
+
${ke}`;Xe(""),Se(null),es("chat"),Be(it,ve,ae,Ne,void 0,void 0,void 0,Fe).catch(ts=>{console.error("Failed to send comment",ts)})},[He,ke,D,F,Ve,mt,ft,Ke,lt,gs,Be,es,jt,yt,Mt]),Tt=i.useCallback((Ne,_)=>{const ve=_.filter(ae=>ae&&typeof ae.name=="string"&&ae.name.length>0).filter(ae=>a||!ae.name.startsWith(".")).filter(ae=>l||!ok(ae.name)).map(ae=>{const Fe=ae.name,$e=ar(ae.path||`${Ne}/${Fe}`),Ue=ae.isDirectory?"directory":"file",Je=Ue==="file"&&Fe.includes(".")?Fe.split(".").pop()?.toLowerCase():void 0;return{name:Fe,path:$e,type:Ue,extension:Je}});return rk(ve)},[l,a]),Kt=i.useCallback(async Ne=>{const _=ar(Ne.trim());if(_&&!(k.current.has(_)||C.current.has(_))){C.current=new Set(C.current),C.current.add(_);try{const ve=!l;let ae;r.isDesktop?ae=(await t.listDirectory(_,{respectGitignore:ve})).entries.map(Ue=>({name:Ue.name,path:Ue.path,isDirectory:Ue.isDirectory})):ae=(await Oe.listLocalDirectory(_,{respectGitignore:ve})).map(Ue=>({name:Ue.name,path:Ue.path,isDirectory:Ue.isDirectory}));const Fe=Tt(_,ae);k.current=new Set(k.current),k.current.add(_),A($e=>({...$e,[_]:Fe}))}catch{A(ve=>({...ve,[_]:ve[_]??[]}))}finally{C.current=new Set(C.current),C.current.delete(_)}}},[t,Tt,r.isDesktop,l]),Rt=i.useCallback(async()=>{const Ne=ar(c.trim());Ne&&(k.current=new Set,C.current=new Set,N(new Set),A({}),await Kt(Ne))},[c,Kt]);i.useEffect(()=>{c&&(Rt(),E(null),B(""),G(null),q(""),x(!1))},[c,Rt]),i.useEffect(()=>{c&&Rt()},[c,Rt,l]);const _t="openchamber:files:md-viewer-mode";i.useEffect(()=>{try{const Ne=localStorage.getItem(_t);if(Ne){const _=JSON.parse(Ne);(_==="preview"||_==="edit")&&qe(_)}}catch{}},[]);const Yt=i.useCallback(Ne=>{qe(Ne);try{localStorage.setItem(_t,JSON.stringify(Ne))}catch{}},[]),Gt=i.useCallback(()=>Ge,[Ge]),It=i.useCallback(async Ne=>{if(Ne?.preventDefault(),!(!J||!H)){le(!0);try{if(H==="createFile"){if(!ge.trim())throw new Error("Filename is required");const _=J.path,ve=_?`${_}/`:"",ae=ar(`${ve}${ge.trim()}`);if(!t.writeFile)throw new Error("Write not supported");(await t.writeFile(ae,"")).success&&(U.success("File created"),await Rt())}else if(H==="createFolder"){if(!ge.trim())throw new Error("Folder name is required");const _=J.path,ve=_?`${_}/`:"",ae=ar(`${ve}${ge.trim()}`);(await t.createDirectory(ae)).success&&(U.success("Folder created"),await Rt())}else if(H==="rename"){if(!ge.trim())throw new Error("Name is required");const _=J.path,ve=_.split("/").slice(0,-1).join("/"),ae=ve?`${ve}/`:"",Fe=ar(`${ae}${ge.trim()}`);t.rename?(await t.rename(_,Fe)).success&&(U.success("Renamed successfully"),await Rt(),D?.path===_&&E(null)):U.error("Rename not supported")}else H==="delete"&&(t.delete?(await t.delete(J.path)).success&&(U.success("Deleted successfully"),await Rt(),(D?.path===J.path||D?.path.startsWith(J.path+"/"))&&(E(null),B(""))):U.error("Delete not supported"));ye(null)}catch(_){U.error(_ instanceof Error?_.message:"Operation failed")}finally{le(!1)}}},[H,J,ge,t,Rt,D]),Ie=i.useCallback((Ne,_)=>{const ve=Ne.trim().toLowerCase();if(!ve)return 0;const ae=_.toLowerCase();let Fe=0,$e=-1,Ue=0;for(let Je=0;Je<ve.length;Je+=1){const ot=ve[Je];if(!ot||ot===" ")continue;const Et=ae.indexOf(ot,$e+1);if(Et===-1)return null;const it=Et-$e-1;if(it===0?Ue+=1:Ue=0,Fe+=10,Fe+=Math.max(0,18-Et),Fe-=Math.max(0,it),Et===0)Fe+=12;else{const ts=ae[Et-1];(ts==="/"||ts==="_"||ts==="-"||ts==="."||ts===" ")&&(Fe+=10)}Fe+=Ue>0?12:0,$e=Et}return Fe+=Math.max(0,24-Math.round(ae.length/3)),Fe},[]);i.useEffect(()=>{c&&Rt()},[c,Rt,l]),i.useEffect(()=>{if(!c){T([]),P(!1);return}const Ne=p.trim();if(!Ne){T([]),P(!1);return}const _=Ne.toLowerCase();let ve=!1;return P(!0),u(c,Ne,150,{includeHidden:a,respectGitignore:!l}).then(ae=>{if(ve)return;const $e=ae.filter(Je=>l||!ak(Je.path)).map(Je=>{const ot=Je.relativePath||Je.name||Je.path,Et=Ie(_,ot);return Et===null?null:{hit:Je,score:Et,labelLength:ot.length}}).filter(Boolean);$e.sort((Je,ot)=>ot.score-Je.score||Je.labelLength-ot.labelLength||Je.hit.path.localeCompare(ot.hit.path));const Ue=$e.map(({hit:Je})=>({name:Je.name,path:ar(Je.path),type:"file",extension:Je.extension,relativePath:Je.relativePath}));T(Ue)}).catch(()=>{ve||T([])}).finally(()=>{ve||P(!1)}),()=>{ve=!0}},[c,p,Ie,u,a,l]);const Te=i.useCallback(async Ne=>{if(t.readFile)return(await t.readFile(Ne)).content??"";const _=await fetch(`/api/fs/read?path=${encodeURIComponent(Ne)}`);if(!_.ok){const ve=await _.json().catch(()=>({error:_.statusText}));throw new Error(ve.error||"Failed to read file")}return _.text()},[t]),Le=i.useMemo(()=>F.length>No?`${F.slice(0,No)}
|
|
236
|
+
|
|
237
|
+
… truncated …`:F,[F]),te=i.useMemo(()=>$!==Le,[$,Le]),se=i.useCallback(async()=>{if(!D||!t.writeFile){U.error("Saving not supported");return}if(te){X(!0);try{if(!(await t.writeFile(D.path,$))?.success)throw new Error("Failed to write file");B($)}catch(Ne){U.error(Ne instanceof Error?Ne.message:"Save failed")}finally{X(!1)}}},[$,t,te,D]);i.useEffect(()=>{if(!te){Ht(null);return}const Ne=_=>we.current?(we.current=!1,!0):(z(!0),de.current=_,!1);return Ht(Ne),()=>{Me.getState().mainTabGuard===Ne&&Ht(null)}},[te,Ht]),i.useEffect(()=>{const Ne=_=>{$s(_)&&_.key.toLowerCase()==="s"&&(_.preventDefault(),Y||se())};return window.addEventListener("keydown",Ne),()=>window.removeEventListener("keydown",Ne)},[Y,se]);const ie=i.useCallback(async Ne=>{if(we.current)we.current=!1;else if(te){z(!0),R.current=Ne;return}E(Ne),G(null),q("");const _=zo(Ne.path);n&&x(!0);const ve=Ne.path.toLowerCase().endsWith(".svg");if(r.isDesktop&&_&&!ve){B(""),ne(!0);return}if(!r.isDesktop&&_&&!ve){B(""),ne(!1);return}ne(!0);try{const ae=await Te(Ne.path);B(ae),W(ae.length>No?`${ae.slice(0,No)}
|
|
238
|
+
|
|
239
|
+
… truncated …`:ae)}catch(ae){B(""),W(""),G(ae instanceof Error?ae.message:"Failed to read file")}finally{ne(!1)}},[te,n,Te,r.isDesktop]),Ee=i.useCallback(()=>{const Ne=R.current,_=de.current;if(R.current=null,de.current=null,we.current=!0,z(!1),W(Le),Ne){ie(Ne);return}_&&(Ht(null),Me.getState().setActiveMainTab(_))},[Le,ie,Ht]),Re=i.useCallback(async()=>{const Ne=R.current,_=de.current;if(R.current=null,de.current=null,we.current=!0,z(!1),await se(),Ne){await ie(Ne);return}_&&(Ht(null),Me.getState().setActiveMainTab(_))},[ie,se,Ht]),Ye=i.useCallback(async Ne=>{const _=ar(Ne);N(ve=>{const ae=new Set(ve);return ae.has(_)?ae.delete(_):ae.add(_),ae}),k.current.has(_)||await Kt(_)},[Kt]),bt=i.useCallback((Ne,_)=>{const ve=v[Ne]??[];return ve.map((ae,Fe)=>{const $e=ae.type==="directory",Ue=$e&&M.has(ae.path),Je=D?.path===ae.path,ot=$e&&C.current.has(ae.path),Et=Fe===ve.length-1;return e.jsxs("li",{className:"relative",children:[_>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Et&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),e.jsxs("div",{className:"group relative flex items-center",onContextMenu:it=>{!vt&&!et&&!rt&&!Ce||(it.preventDefault(),oe(ae.path))},children:[e.jsxs("button",{type:"button",onClick:()=>{$e?Ye(ae.path):ie(ae)},className:L("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",Je?"bg-accent/70":"hover:bg-accent/40"),children:[$e?ot?e.jsx(Ct,{className:"h-4 w-4 flex-shrink-0 animate-spin"}):Ue?e.jsx(Vx,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):e.jsx(Gx,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):tm(ae.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:ae.path,children:ae.name})]}),(vt||et||rt||Ce)&&e.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 focus-within:opacity-100",children:e.jsxs(rs,{open:fe===ae.path,onOpenChange:it=>oe(it?ae.path:null),children:[e.jsx(ns,{asChild:!0,children:e.jsx(je,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(qx,{className:"h-4 w-4"})})}),e.jsxs(os,{align:"end",onCloseAutoFocus:()=>oe(null),children:[vt&&e.jsxs(Nt,{onClick:it=>{it.stopPropagation(),pe("rename",ae)},children:[e.jsx(mo,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(Nt,{onClick:it=>{it.stopPropagation(),navigator.clipboard.writeText(ae.path),U.success("Path copied")},children:[e.jsx(rr,{className:"mr-2 h-4 w-4"})," Copy Path"]}),$e&&(et||rt)&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),et&&e.jsxs(Nt,{onClick:it=>{it.stopPropagation(),pe("createFile",ae)},children:[e.jsx(ed,{className:"mr-2 h-4 w-4"})," New File"]}),rt&&e.jsxs(Nt,{onClick:it=>{it.stopPropagation(),pe("createFolder",ae)},children:[e.jsx(Cl,{className:"mr-2 h-4 w-4"})," New Folder"]})]}),Ce&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),e.jsxs(Nt,{onClick:it=>{it.stopPropagation(),pe("delete",ae)},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]})})]}),$e&&Ue&&e.jsx("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:bt(ae.path,_+1)})]},ae.path)})},[v,M,ie,D?.path,Ye,pe,et,rt,vt,Ce,fe,oe]),pt=!!(D?.path&&zo(D.path)),Jt=!!(D?.path&&D.path.toLowerCase().endsWith(".svg")),Lt=i.useMemo(()=>{if(!D?.path)return"";const Ne=ar(D.path);if(d&&Ne.startsWith(d)){const _=Ne.slice(d.length);return _.startsWith("/")?_.slice(1):_}return Ne},[D?.path,d]),ks=!!(D&&(!pt||Jt)&&F.length>0),Cs=!!(D&&Lt.length>0),Dt=!!(D&&!pt&&t.writeFile&&F.length<=No),Ot=i.useMemo(()=>{if(!D?.path)return[ec(s)];const Ne=[ec(s)],_=th(D.path);return _&&Ne.push(_),b&&Ne.push(fn.lineWrapping),Ne},[s,D?.path,b]),as=D?.path&&pt?r.isDesktop?Jt?`data:${zl(D.path)};utf8,${encodeURIComponent(F)}`:K:Jt?`data:${zl(D.path)};utf8,${encodeURIComponent(F)}`:`/api/fs/raw?path=${encodeURIComponent(D.path)}`:"";i.useEffect(()=>{let Ne=!1;return(async()=>{if(!r.isDesktop||!D?.path||!pt||Jt){q("");return}G(null);try{if(t.readFileBinary){const $e=await t.readFileBinary(D.path);Ne||q($e.dataUrl);return}const ae=(await js(()=>import("./vendor-.bun-Bui932eM.js").then($e=>$e.dk),__vite__mapDeps([0,1]))).convertFileSrc;if(!ae)return;const Fe=ae(D.path,"asset");Ne||q(Fe)}catch(ve){Ne||(q(""),G(ve instanceof Error?ve.message:"Failed to read file"))}finally{Ne||ne(!1)}})(),()=>{Ne=!0}},[t,pt,Jt,r.isDesktop,D?.path]);const hr=()=>e.jsx(fs,{open:!!H,onOpenChange:Ne=>!Ne&&ye(null),children:e.jsxs(ps,{children:[e.jsxs(bs,{children:[e.jsxs(ws,{children:[H==="createFile"&&"Create File",H==="createFolder"&&"Create Folder",H==="rename"&&"Rename",H==="delete"&&"Delete"]}),e.jsxs(Ns,{children:[H==="createFile"&&`Create a new file in ${J?.path??"root"}`,H==="createFolder"&&`Create a new folder in ${J?.path??"root"}`,H==="rename"&&`Rename ${J?.name}`,H==="delete"&&`Are you sure you want to delete ${J?.name}? This action cannot be undone.`]})]}),H!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(wt,{value:ge,onChange:Ne=>ee(Ne.target.value),placeholder:H==="rename"?"New name":"Name",onKeyDown:Ne=>{Ne.key==="Enter"&&It()},autoFocus:!0})}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"outline",onClick:()=>ye(null),disabled:me,children:"Cancel"}),e.jsx(je,{variant:H==="delete"?"destructive":"default",onClick:()=>{It()},disabled:me||H!=="delete"&&!ge.trim(),children:me?e.jsx(Ct,{className:"animate-spin"}):H==="delete"?"Delete":"Confirm"})]})]})}),De=()=>!He||!D?null:e.jsx("div",{"data-comment-ui":!0,className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-background flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Fs,{value:ke,onChange:Ne=>{Xe(Ne.target.value);const _=Ne.target;_.style.height="auto";const ae=20*5+8;_.style.height=`${Math.min(_.scrollHeight,ae)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!n,rows:1,onKeyDown:Ne=>{Ne.key==="Enter"&&(Ne.metaKey||Ne.ctrlKey)&&(Ne.preventDefault(),Qt()),Ne.key==="Escape"&&(Ne.preventDefault(),Se(null),Xe(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[D.name,":",He.start,"-",He.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!n&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Xt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:Ne=>{ke.trim()&&(Ne.preventDefault(),Qt())},onClick:()=>{n||Qt()},disabled:!ke.trim(),className:L("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",ke.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Uo,{className:"h-[18px] w-[18px]"})})]})]})]})}),ze=e.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[e.jsx(fs,{open:Z,onOpenChange:Ne=>{Ne||z(!0)},children:e.jsxs(ps,{showCloseButton:!1,className:"max-w-md",children:[e.jsxs(bs,{children:[e.jsx(ws,{children:"Unsaved changes"}),e.jsx(Ns,{children:"Save your edits before continuing?"})]}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"outline",onClick:()=>{Re()},disabled:Y,className:"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]",children:"Save changes"}),e.jsx(je,{variant:"destructive",onClick:Ee,children:"Discard"})]})]})}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[n&&g&&e.jsx("button",{type:"button",onClick:()=>x(!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(ac,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label font-medium truncate",children:D?D.name:"Select a file"}),D&&!n&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:Lt,children:Lt})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[Dt&&e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{se()},disabled:!te||Y,className:"h-5 w-5 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Xt()}+S)`,"aria-label":`Save (${Xt()}+S)`,children:Y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(td,{className:"h-4 w-4"})}),Dt&&D&&!pt&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),D&&!pt&&e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>y(!b),className:L("h-5 w-5 p-0 transition-opacity",b?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:b?"Disable line wrap":"Enable line wrap",children:e.jsx(Nl,{className:"size-4"})}),(ks||Cs||D&&_n(D.path))&&(Dt||D&&!pt)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),D&&_n(D.path)&&e.jsx(Zl,{currentMode:Gt(),onToggle:()=>Yt(Gt()==="preview"?"edit":"preview")}),ks&&e.jsx(je,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(F),re(!0),xe.current!==null&&window.clearTimeout(xe.current),xe.current=window.setTimeout(()=>{re(!1)},1200)}catch{U.error("Copy failed")}},className:"h-5 w-5 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:Q?e.jsx(Pt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(za,{className:"h-4 w-4"})}),Cs&&e.jsx(je,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(Lt),he(!0),Pe.current!==null&&window.clearTimeout(Pe.current),Pe.current=window.setTimeout(()=>{he(!1)},1200)}catch{U.error("Copy failed")}},className:"h-5 w-5 p-0",title:`Copy file path (${Lt})`,"aria-label":`Copy file path (${Lt})`,children:ue?e.jsx(Pt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Al,{className:"h-4 w-4"})}),D&&!n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>S(!w),className:"h-5 w-5 p-0",title:w?"Exit fullscreen":"Fullscreen","aria-label":w?"Exit fullscreen":"Fullscreen",children:w?e.jsx(sd,{className:"h-4 w-4"}):e.jsx(Kx,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(gt,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:D?V?e.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):O?e.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:O}):pt?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("img",{src:as,alt:D?.name??"Image",className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"})}):D&&_n(D.path)&&Gt()==="preview"?e.jsxs("div",{className:"h-full overflow-auto p-3",children:[F.length>500*1024&&e.jsxs("div",{className:"mb-3 rounded-md border border-warning/20 bg-warning/10 px-3 py-2 text-sm text-warning",children:["⚠️ This file is large (",Math.round(F.length/1024),"KB). Preview may be limited."]}),e.jsx(ls,{fallback:e.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[e.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:e.jsx(Nr,{content:F,className:"typography-markdown-body"})})]}):e.jsx("div",{className:"h-full",children:e.jsx(Xl,{value:$,onChange:W,extensions:Ot,className:"h-full",highlightLines:He?{start:Math.min(He.start,He.end),end:Math.max(He.start,He.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(Ne,_,ve)=>{if(!(ve instanceof MouseEvent)||ve.button!==0)return!1;ve.preventDefault();const ae=Ne.state.doc.lineAt(_.from).number;if(n&&He&&!ve.shiftKey){const Fe=Math.min(He.start,He.end,ae),$e=Math.max(He.start,He.end,ae);return Se({start:Fe,end:$e}),at.current=!1,We.current=null,!0}if(at.current=!0,We.current=ae,He&&ve.shiftKey){const Fe=Math.min(He.start,ae),$e=Math.max(He.end,ae);Se({start:Fe,end:$e})}else Se({start:ae,end:ae});return!0},mouseover:(Ne,_,ve)=>{if(!(ve instanceof MouseEvent)||ve.buttons!==1||!at.current||We.current===null)return!1;const ae=Ne.state.doc.lineAt(_.from).number,Fe=Math.min(We.current,ae),$e=Math.max(We.current,ae);return Se({start:Fe,end:$e}),!1},mouseup:()=>(at.current=!1,We.current=null,!1)}}})}):e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}),He&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex flex-col justify-end",style:{paddingBottom:n?"var(--oc-keyboard-inset, 0px)":"0px"},children:e.jsx("div",{className:L("pointer-events-auto pb-2 transition-none w-full flex justify-center",n&&kt?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:n&&!kt&&Wt>0?`${Wt}px`:"16px"},"data-keyboard-avoid":"true",children:De()})})]}),_e=!!(d&&v[d]),st=e.jsxs("section",{className:L("flex min-h-0 flex-col overflow-hidden",n?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[e.jsx("div",{className:L("flex flex-col gap-2 py-2",n?"px-3":"px-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Vs,{className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(wt,{ref:h,value:m,onChange:Ne=>f(Ne.target.value),placeholder:"Search files…",className:"h-8 pl-8 pr-8 typography-meta"}),m.trim().length>0&&e.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{f(""),h.current?.focus()},children:e.jsx(ss,{className:"h-4 w-4"})})]}),e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>pe("createFile",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File",children:e.jsx(ed,{className:"h-4 w-4"})}),e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>pe("createFolder",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder",children:e.jsx(Cl,{className:"h-4 w-4"})}),e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{Rt()},className:"h-8 w-8 p-0 flex-shrink-0",children:e.jsx(Xr,{className:"h-4 w-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:L("py-2",n?"px-3":"px-2"),children:e.jsx("ul",{className:"flex flex-col",children:I?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Searching…"]}):j.length>0?j.map(Ne=>{const _=D?.path===Ne.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{ie(Ne)},className:L("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",_?"bg-accent/70":"hover:bg-accent/40"),children:[tm(Ne.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:Ne.path,children:Ne.relativePath??Ne.path})]})},Ne.path)}):_e?bt(d,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading…"})})})]}),nt=w&&D&&e.jsxs("div",{className:"absolute inset-0 z-50 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-4 py-2 flex-shrink-0",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label font-medium truncate",children:D.name}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:Lt,children:Lt})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[Dt&&e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{se()},disabled:!te||Y,className:"h-6 w-6 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Xt()}+S)`,"aria-label":`Save (${Xt()}+S)`,children:Y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(td,{className:"h-4 w-4"})}),Dt&&!pt&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),!pt&&e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>y(!b),className:L("h-6 w-6 p-0 transition-opacity",b?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:b?"Disable line wrap":"Enable line wrap",children:e.jsx(Nl,{className:"size-4"})}),(ks||Cs||_n(D.path))&&(Dt||!pt)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),_n(D.path)&&e.jsx(Zl,{currentMode:Gt(),onToggle:()=>Yt(Gt()==="preview"?"edit":"preview")}),ks&&e.jsx(je,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(F),re(!0),xe.current!==null&&window.clearTimeout(xe.current),xe.current=window.setTimeout(()=>{re(!1)},1200)}catch{U.error("Copy failed")}},className:"h-6 w-6 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:Q?e.jsx(Pt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(za,{className:"h-4 w-4"})}),Cs&&e.jsx(je,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(Lt),he(!0),Pe.current!==null&&window.clearTimeout(Pe.current),Pe.current=window.setTimeout(()=>{he(!1)},1200)}catch{U.error("Copy failed")}},className:"h-6 w-6 p-0",title:`Copy file path (${Lt})`,"aria-label":`Copy file path (${Lt})`,children:ue?e.jsx(Pt,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Al,{className:"h-4 w-4"})}),e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),e.jsx(je,{variant:"ghost",size:"sm",onClick:()=>S(!1),className:"h-6 w-6 p-0",title:"Exit fullscreen","aria-label":"Exit fullscreen",children:e.jsx(sd,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(gt,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:V?e.jsxs("div",{className:"p-4 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):O?e.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:O}):pt?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("img",{src:as,alt:D.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"})}):_n(D.path)&&Gt()==="preview"?e.jsxs("div",{className:"h-full overflow-auto p-4",children:[F.length>500*1024&&e.jsxs("div",{className:"mb-3 rounded-md border border-warning/20 bg-warning/10 px-3 py-2 text-sm text-warning",children:["This file is large (",Math.round(F.length/1024),"KB). Preview may be limited."]}),e.jsx(ls,{fallback:e.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[e.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:e.jsx(Nr,{content:F,className:"typography-markdown-body"})})]}):e.jsx("div",{className:"h-full",children:e.jsx(Xl,{value:$,onChange:W,extensions:Ot,className:"h-full"})})})})]});return e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[hr(),nt,n?g?ze:st:e.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[o>=1024&&e.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:st}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:ze})]})]})},dh=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:lc},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Cr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:Dn},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:Qm},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:eo},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Vt},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:wn}],mk={},fk={},pk={};dh.forEach(t=>{mk[t.id]=t.label,fk[t.id]=t.description,pk[t.id]=t});const hk=t=>{if(!Array.isArray(t))return[];const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},gk=t=>{const r=new Map;for(const s of t)!s.permission||s.permission==="invalid"||s.pattern&&r.set(`${s.permission}::${s.pattern}`,s);return Array.from(r.values())},sm=t=>{const r=gk(hk(t));if(r.length===0)return;const s={};for(const o of r)o.permission&&((s[o.permission]||={})[o.pattern]=o.action);const n={};for(const[o,a]of Object.entries(s)){const l=Object.keys(a);if(l.length===1&&l[0]==="*"){n[o]=a["*"];continue}n[o]=a}return Object.keys(n).length>0?n:void 0},xk=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedAgentName:a,agents:l,setSelectedAgent:c,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=on(),{setSidebarOpen:p}=Me(),{isMobile:h}=qt(),[g,x]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||x(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=g?"bg-transparent":b?"bg-background":"bg-sidebar",w=()=>{const I="new-agent";let P=I,D=1;for(;l.some(E=>E.name===P);)P=`${I}-${D}`,D++;d({name:P,scope:"user"}),c(P),t?.(),h&&p(!1)},S=async I=>{if(pn(I)){U.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${I.name}"?`)&&(await m(I.name)?U.success(`Agent "${I.name}" deleted successfully`):U.error("Failed to delete agent"))},M=async I=>{pn(I)&&window.confirm(`Are you sure you want to reset agent "${I.name}" to its default configuration?`)&&(await m(I.name)?U.success(`Agent "${I.name}" reset to default`):U.error("Failed to reset agent"))},N=I=>{const P=I.name;let D=1,E=`${P}-copy`;for(;l.some(ne=>ne.name===E);)D++,E=`${P}-copy-${D}`;const F=I,B=I.model?.providerID&&I.model?.modelID?`${I.model.providerID}/${I.model.modelID}`:null,V=I;d({name:E,scope:F.scope||"user",description:I.description,model:B,temperature:I.temperature,top_p:I.topP,prompt:I.prompt,mode:I.mode,permission:sm(I.permission),disable:V.disable}),c(E),h&&p(!1)},v=I=>{o(I.name),s(I)},A=async()=>{if(!r)return;const I=n.trim().replace(/\s+/g,"-");if(!I){U.error("Agent name is required");return}if(I===r.name){s(null);return}if(l.some(F=>F.name===I)){U.error("An agent with this name already exists");return}const P=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,D=r;await u({name:I,description:r.description,model:P,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:sm(r.permission),disable:D.disable,scope:D.scope})?await m(r.name)?(U.success(`Agent renamed to "${I}"`),c(I)):U.error("Failed to remove old agent after rename"):U.error("Failed to rename agent"),s(null)},k=I=>{switch(I){case"primary":return e.jsx(jn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(uf,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(df,{className:"h-3 w-3 text-primary"});default:return null}},C=l.filter(I=>!If(I)),j=C.filter(pn),T=C.filter(I=>!pn(I));return e.jsxs("div",{className:L("flex h-full flex-col",y),children:[e.jsx("div",{className:L("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",C.length]}),e.jsx(je,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(us,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:C.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(To,{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:[j.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Agents"}),j.map(I=>e.jsx(rm,{agent:I,isSelected:a===I.name,onSelect:()=>{c(I.name),t?.(),h&&p(!1)},onReset:()=>M(I),onDuplicate:()=>N(I),getAgentModeIcon:k},I.name))]}),T.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"}),T.map(I=>e.jsx(rm,{agent:I,isSelected:a===I.name,onSelect:()=>{c(I.name),t?.(),h&&p(!1)},onRename:()=>v(I),onDelete:()=>S(I),onDuplicate:()=>N(I),getAgentModeIcon:k},I.name))]})]})}),e.jsx(fs,{open:r!==null,onOpenChange:I=>!I&&s(null),children:e.jsxs(ps,{children:[e.jsxs(bs,{children:[e.jsx(ws,{children:"Rename Agent"}),e.jsxs(Ns,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(wt,{value:n,onChange:I=>o(I.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:I=>{I.key==="Enter"&&A()}}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cn,{onClick:A,children:"Rename"})]})]})})]})},rm=({agent:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:l,getAgentModeIcon:c})=>{const d=t;return e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:s,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t.name}),c(t.mode),(d.scope||pn(t))&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:pn(t)?"system":d.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsx(je,{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(sn,{className:"h-3.5 w-3.5"})})}),e.jsxs(os,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(mo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),l()},children:[e.jsx(rr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Ts({className:t,variant:r,...s}){return e.jsx(je,{variant:r,size:"sm",className:L("h-6 px-2 text-xs",t),...s})}const yk=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),bk=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=yk.format(t);return r.endsWith(".0")?r.slice(0,-2):r},Bc=({providerId:t,modelId:r,onChange:s,className:n,allowedProviderIds:o})=>{const{providers:a,modelsMetadata:l}=Ze(),c=Me($=>$.isMobile),{toggleFavoriteModel:d,isFavoriteModel:u,addRecentModel:m}=Me(),{favoriteModelsList:f,recentModelsList:p}=Fc(),{isMobile:h}=qt(),g=c||h,[x,b]=i.useState(!1),[y,w]=i.useState(new Set),[S,M]=i.useState(!1),[N,v]=i.useState(""),[A,k]=i.useState(0),C=i.useRef([]),j=i.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),T=i.useMemo(()=>j?a.filter($=>j.has(String($.id))):a,[a,j]),I=()=>b(!1),P=$=>{w(W=>{const Y=new Set(W);return Y.has($)?Y.delete($):Y.add($),Y})};i.useEffect(()=>{S||(v(""),k(0))},[S]),i.useEffect(()=>{k(0)},[N]);const D=$=>{const W=$?.name||$?.id||"",Y=String(W);return Y.length>40?Y.substring(0,37)+"...":Y},E=($,W)=>{const Y=`${$}/${W}`;return l.get(Y)},F=($,W)=>{s($,W),$&&W&&m($,W),M(!1)},B=($,W)=>{if(!N.trim())return!0;const Y=N.toLowerCase();return $.toLowerCase().includes(Y)||W.toLowerCase().includes(Y)},V=($,W,Y,X,Z,z)=>{const R=E(W,Y),de=bk(R?.limit?.context),we=t===W&&r===Y,xe=u(W,Y),Pe=X==="fav"||X==="recent";return e.jsxs("div",{ref:H=>{C.current[Z]=H},className:L("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",z?"bg-accent":"hover:bg-accent/50"),onClick:()=>F(W,Y),onMouseEnter:()=>k(Z),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[Pe&&e.jsx(ys,{providerId:W,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:D($)}),de?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:de}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[we&&e.jsx(Pt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),d(W,Y)},className:L("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",xe?"text-yellow-500":"text-muted-foreground"),"aria-label":xe?"Unfavorite":"Favorite",title:xe?"Remove from favorites":"Add to favorites",children:xe?e.jsx(Fr,{className:"h-3.5 w-3.5"}):e.jsx(Gn,{className:"h-3.5 w-3.5"})})]})]},`${X}-${W}-${Y}`)},ne=f.filter(({model:$,providerID:W})=>{if(j&&!j.has(W))return!1;const X=a.find(z=>z.id===W)?.name||W,Z=D($);return B(Z,X)}),O=p.filter(({model:$,providerID:W})=>{if(j&&!j.has(W))return!1;const X=a.find(z=>z.id===W)?.name||W,Z=D($);return B(Z,X)}),G=T.map($=>{const Y=(Array.isArray($.models)?$.models:[]).filter(X=>{const Z=D(X);return B(Z,$.name||$.id||"")});return{...$,models:Y}}).filter($=>$.models.length>0),K=ne.length>0||O.length>0||G.length>0,q=()=>g?e.jsx(Ws,{open:x,onClose:I,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[f.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Favorites"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:$,providerID:W,modelID:Y})=>{const X=W===t&&Y===r;return e.jsxs("div",{className:L("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",X?"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:()=>{F(W,Y),I()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{providerId:W,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:D($)})]})}),e.jsx("button",{onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),d(W,Y)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-yellow-500 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Unfavorite",children:e.jsx(Fr,{className:"h-4 w-4"})})]},`fav-mobile-${W}-${Y}`)})})]}),p.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Recents"}),e.jsx("div",{className:"border-t border-border/20",children:p.map(({model:$,providerID:W,modelID:Y})=>{const X=W===t&&Y===r;return e.jsxs("div",{className:L("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",X?"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:()=>{F(W,Y),I()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{providerId:W,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:D($)})]})}),e.jsx("button",{onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),d(W,Y)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Favorite",children:e.jsx(Gn,{className:"h-4 w-4"})})]},`recent-mobile-${W}-${Y}`)})})]}),T.map($=>{const W=Array.isArray($.models)?$.models:[];if(W.length===0)return null;const Y=$.id===t,X=y.has($.id);return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left",onClick:()=>P($.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{providerId:$.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:$.name}),Y&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),X?e.jsx(Ut,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(er,{className:"h-3 w-3 text-muted-foreground"})]}),X&&e.jsx("div",{className:"border-t border-border/20",children:W.map(Z=>{const z=$.id===t&&Z.id===r;return e.jsxs("div",{className:L("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",z?"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:()=>{F($.id,Z.id),I()},children:e.jsx("span",{className:"font-medium truncate",children:D(Z)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:R=>{R.preventDefault(),R.stopPropagation(),d($.id,Z.id)},className:L("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",u($.id,Z.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":u($.id,Z.id)?"Unfavorite":"Favorite",children:u($.id,Z.id)?e.jsx(Fr,{className:"h-4 w-4"}):e.jsx(Gn,{className:"h-4 w-4"})}),z&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},Z.id)})})]},$.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:()=>{F("",""),I()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[g?e.jsxs("button",{type:"button",onClick:()=>b(!0),className:L("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[t?e.jsx(ys,{providerId:t,className:"h-3.5 w-3.5"}):e.jsx(Tr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:t&&r?`${t}/${r}`:"Select model..."})]}),e.jsx(Ut,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(rs,{open:S,onOpenChange:M,children:[e.jsx(ns,{asChild:!0,children:e.jsxs("div",{className:L("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",n),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(ys,{providerId:t,className:"h-3 w-3 flex-shrink-0"}),e.jsx(Tr,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Tr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:t&&r?`${t}/${r}`:"Not selected"}),e.jsx(Ut,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(os,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const $=[];ne.forEach(({model:Z,providerID:z,modelID:R})=>{$.push({model:Z,providerID:z,modelID:R,section:"fav"})}),O.forEach(({model:Z,providerID:z,modelID:R})=>{$.push({model:Z,providerID:z,modelID:R,section:"recent"})}),G.forEach(Z=>{Z.models.forEach(z=>{$.push({model:z,providerID:Z.id,modelID:z.id,section:"provider"})})});const W=$.length,Y=Z=>{if(Z.key==="ArrowDown"){Z.preventDefault(),Z.stopPropagation();const z=(A+1)%Math.max(1,W);k(z),setTimeout(()=>{C.current[z]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Z.key==="ArrowUp"){Z.preventDefault(),Z.stopPropagation();const z=(A-1+Math.max(1,W))%Math.max(1,W);k(z),setTimeout(()=>{C.current[z]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Z.key==="Enter"){Z.preventDefault(),Z.stopPropagation();const z=$[A];z&&F(z.providerID,z.modelID)}else Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),M(!1))};let X=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(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(wt,{type:"text",placeholder:"Search models",value:N,onChange:Z=>v(Z.target.value),onKeyDown:Y,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(gt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:L("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>F("",""),children:[e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!t&&!r&&e.jsx(Pt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Ds,{}),!K&&N&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),ne.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Rr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),ne.map(({model:Z,providerID:z,modelID:R})=>{const de=X++;return V(Z,z,R,"fav",de,A===de)})]}),O.length>0&&e.jsxs(e.Fragment,{children:[ne.length>0&&e.jsx(Ds,{}),e.jsxs(Rr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(kr,{className:"h-4 w-4"}),"Recent"]}),O.map(({model:Z,providerID:z,modelID:R})=>{const de=X++;return V(Z,z,R,"recent",de,A===de)})]}),(ne.length>0||O.length>0)&&G.length>0&&e.jsx(Ds,{}),G.map((Z,z)=>e.jsxs(i.Fragment,{children:[z>0&&e.jsx(Ds,{}),e.jsxs(Rr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ys,{providerId:Z.id,className:"h-4 w-4 flex-shrink-0"}),Z.name]}),Z.models.map(R=>{const de=X++;return V(R,Z.id,R.id,"provider",de,A===de)})]},Z.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()})]}),q()]})},nm=["*","read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop","question","plan_enter","plan_exit"],$a=t=>t==="allow"||t==="ask"||t==="deny",mn=(t,r)=>`${t}::${r}`,Mn=t=>{const r=new Map;for(const s of t)!s.permission||s.permission==="invalid"||s.pattern&&$a(s.action)&&r.set(mn(s.permission,s.pattern),{permission:s.permission,pattern:s.pattern,action:s.action});return Array.from(r.values())},wa=t=>{const r=new Map;for(const s of Mn(t))r.set(mn(s.permission,s.pattern),s);return r},om=t=>[...t].sort((r,s)=>{const n=r.permission.localeCompare(s.permission);return n!==0?n:r.pattern.localeCompare(s.pattern)}),wk=(t,r)=>{const s=om(Mn(t)),n=om(Mn(r));return s.length!==n.length?!1:s.every((o,a)=>{const l=n[a];return o.permission===l.permission&&o.pattern===l.pattern&&o.action===l.action})},vk=t=>t.find(s=>s.permission==="*"&&s.pattern==="*")?.action??"allow",jk=(t,r)=>Mn(t).filter(s=>!(s.permission==="*"&&s.pattern==="*")).filter(s=>s.pattern!=="*"||s.action!==r),Sk=t=>{if($a(t))return[{permission:"*",pattern:"*",action:t}];if(!t||typeof t!="object"||Array.isArray(t))return[];const r=[];for(const[s,n]of Object.entries(t))if(s!=="__originalKeys"){if($a(n)){r.push({permission:s,pattern:"*",action:n});continue}if(n&&typeof n=="object"&&!Array.isArray(n))for(const[o,a]of Object.entries(n))$a(a)&&r.push({permission:s,pattern:o,action:a})}return r},Nk=(t,r)=>{const s=Mn(r),n={};for(const a of s)(n[a.permission]||={})[a.pattern]=a.action;const o={"*":t};for(const[a,l]of Object.entries(n))if(a!=="*"){if(Object.keys(l).length===1&&l["*"]){o[a]=l["*"];continue}o[a]=l}return o},kk=()=>{const{selectedAgentName:t,getAgentByName:r,createAgent:s,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:l}=on();Ze();const c=t?r(t):null,d=!!(a&&a.name===t&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,g]=i.useState(""),[x,b]=i.useState("subagent"),[y,w]=i.useState(""),[S,M]=i.useState(void 0),[N,v]=i.useState(void 0),[A,k]=i.useState(""),[C,j]=i.useState("allow"),[T,I]=i.useState([]),[P,D]=i.useState([]),[E,F]=i.useState(""),[B,V]=i.useState("*"),[ne,O]=i.useState(!1),[G,K]=i.useState(!1),q=i.useRef(null),$=xt(Q=>Q.currentDirectory??null),[W,Y]=i.useState([]),X=Bo(Q=>Q.permissions);i.useEffect(()=>{let Q=!1;return(async()=>{const ue=await Oe.listToolIds({directory:$});if(Q)return;const he=new Set(["write","patch","multiedit"]),Ge=ue.map(qe=>typeof qe=="string"?qe.trim():"").filter(Boolean).filter(qe=>qe!=="*").filter(qe=>qe!=="invalid").filter(qe=>!he.has(qe));Y(Array.from(new Set(Ge)).sort((qe,et)=>qe.localeCompare(et)))})(),()=>{Q=!0}},[$]);const Z=i.useMemo(()=>{const Q=new Set;for(const re of o){const ue=Mn(Array.isArray(re.permission)?re.permission:[]);for(const he of ue)he.permission&&he.permission!=="*"&&he.permission!=="invalid"&&Q.add(he.permission)}for(const re of X.values())for(const ue of re){const he=ue.permission?.trim();he&&he!=="invalid"&&Q.add(he)}for(const re of W)Q.add(re);return Array.from(Q).sort((re,ue)=>re.localeCompare(ue))},[o,X,W]),z=i.useMemo(()=>wa(T),[T]),R=i.useMemo(()=>wa(P),[P]),de=i.useCallback(Q=>R.get(mn(Q,"*"))?.action,[R]),we=i.useCallback(Q=>P.filter(re=>re.permission===Q&&re.pattern!=="*").sort((re,ue)=>re.pattern.localeCompare(ue.pattern)),[P]),xe=i.useMemo(()=>{const Q=new Set;for(const re of nm)Q.add(re);for(const re of Z)Q.add(re);return Array.from(Q).sort((re,ue)=>re.localeCompare(ue))},[Z]),Pe=i.useCallback(Q=>{const re=Q==="*"?C:de(Q)??C,ue=we(Q),he=!1,Ge=ue.reduce((et,rt)=>(et[rt.action]=(et[rt.action]??0)+1,et),{allow:0,ask:0,deny:0}),qe=["allow","ask","deny"].filter(et=>Ge[et]>0).map(et=>`${Ge[et]} ${et}`).join(", ");return{defaultAction:re,patternRulesCount:ue.length,patternSummary:qe,hasDefaultHint:he}},[we,de,C]),H=i.useMemo(()=>{const Q=new Set;for(const re of nm)Q.add(re);for(const re of Z)Q.add(re);return Array.from(Q).sort((re,ue)=>re.localeCompare(ue))},[Z]),ye=i.useCallback((Q,re,ue)=>{D(he=>{const Ge=wa(he);return Ge.set(mn(Q,re),{permission:Q,pattern:re,action:ue}),Array.from(Ge.values())})},[]),J=i.useCallback((Q,re)=>{D(ue=>{const he=wa(ue);return he.delete(mn(Q,re)),Array.from(he.values())})},[]),ce=i.useCallback((Q,re)=>{const ue=z.get(mn(Q,re));if(ue){ye(Q,re,ue.action);return}J(Q,re)},[z,J,ye]),ge=i.useCallback((Q,re,ue)=>{ye(Q,re,ue)},[ye]),ee=i.useCallback(Q=>{j(Q),D(re=>re.filter(ue=>!(ue.pattern==="*"&&ue.action===Q)))},[]),me=i.useCallback(Q=>{const re=E.trim();if(!re){U.error("Permission name is required");return}const ue=B.trim()||"*";if(re==="*"&&ue==="*"){ee(Q),F(""),V("*");return}ue==="*"&&re!=="*"&&Q===C?J(re,"*"):ye(re,ue,Q),F(""),V("*")},[C,E,B,J,ee,ye]),le=i.useCallback(Q=>Q==="*"?"Default":Q==="webfetch"?"WebFetch":Q==="websearch"?"WebSearch":Q==="codesearch"?"CodeSearch":Q==="doom_loop"?"Doom Loop":Q==="external_directory"?"External Directory":Q==="todowrite"?"TodoWrite":Q==="todoread"?"TodoRead":Q.split(/[_-]+/g).filter(Boolean).map(re=>re.charAt(0).toUpperCase()+re.slice(1)).join(" "),[]);i.useEffect(()=>{F(""),V("*");const Q=re=>{const ue=Mn(re),he=vk(ue),Ge=jk(ue,he);return j(he),I(Ge),D(Ge),{global:he,rules:Ge}};if(d&&a){const re=a.name||"",ue=a.scope||"user",he=a.description||"",Ge=a.mode||"subagent",qe=a.model||"",et=a.temperature,rt=a.top_p,vt=a.prompt||"";m(re),p(ue),g(he),b(Ge),w(qe),M(et),v(rt),k(vt);const Ce=Sk(a.permission),pe=Q(Ce);q.current={draftName:re,draftScope:ue,description:he,mode:Ge,model:qe,temperature:et,topP:rt,prompt:vt,globalPermission:pe.global,permissionRules:pe.rules};return}if(c&&t===c.name){const re=c.description||"",ue=c.mode||"subagent",he=c.model?.providerID&&c.model?.modelID?`${c.model.providerID}/${c.model.modelID}`:"",Ge=c.temperature,qe=c.topP,et=c.prompt||"";g(re),b(ue),w(he),M(Ge),v(qe),k(et);const rt=Q(Array.isArray(c.permission)?c.permission:[]);q.current={draftName:"",draftScope:"user",description:re,mode:ue,model:he,temperature:Ge,topP:qe,prompt:et,globalPermission:rt.global,permissionRules:rt.rules}}},[a,d,c,t]);const fe=i.useMemo(()=>{const Q=q.current;return Q?!!(d&&(u!==Q.draftName||f!==Q.draftScope)||h!==Q.description||x!==Q.mode||y!==Q.model||S!==Q.temperature||N!==Q.topP||A!==Q.prompt||C!==Q.globalPermission||!wk(P,Q.permissionRules)):!1},[h,u,f,C,d,x,y,P,A,S,N]),oe=async()=>{const Q=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!Q){U.error("Agent name is required");return}if(d&&o.some(re=>re.name===Q)){U.error("An agent with this name already exists");return}K(!0);try{const re=y.trim(),ue=Nk(C,P),he={name:Q,description:h.trim()||void 0,mode:x,model:re===""?null:re,temperature:S,top_p:N,prompt:A.trim()||void 0,permission:ue,scope:d?f:void 0};let Ge;d?(Ge=await s(he),Ge&&l(null)):Ge=await n(Q,he),Ge?U.success(d?"Agent created successfully":"Agent updated successfully"):U.error(d?"Failed to create agent":"Failed to update agent")}catch(re){console.error("Error saving agent:",re);const ue=re instanceof Error&&re.message?re.message:"An error occurred while saving";U.error(ue)}finally{K(!1)}};return t?e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Agent":t})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure agent identity and behavior mode"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"@"}),e.jsx(wt,{value:u,onChange:Q=>m(Q.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(As,{value:f,onValueChange:Q=>p(Q),children:[e.jsxs(Es,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(sr,{className:"h-4 w-4"}):e.jsx(Mr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Is,{align:"end",children:[e.jsx(Bt,{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(sr,{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(Bt,{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(Mr,{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(Fs,{value:h,onChange:Q=>g(Q.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(Ts,{variant:x==="primary"?"default":"outline",onClick:()=>b("primary"),className:L("gap-2",x==="primary"?void 0:"text-foreground"),children:[e.jsx(jn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Ts,{variant:x==="subagent"?"default":"outline",onClick:()=>b("subagent"),className:L("gap-2",x==="subagent"?void 0:"text-foreground"),children:[e.jsx(df,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Ts,{variant:x==="all"?"default":"outline",onClick:()=>b("all"),className:L("gap-2",x==="all"?void 0:"text-foreground"),children:[e.jsx(uf,{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(Bc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(Q,re)=>{w(Q&&re?`${Q}/${re}`:"")}})]}),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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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 re=Math.max(0,(S!==void 0?S:.7)-.1);M(parseFloat(re.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(xo,{className:"h-3.5 w-3.5"})}),e.jsx(wt,{type:"text",inputMode:"decimal",value:S!==void 0?S:"",onChange:Q=>{const re=Q.target.value;if(re===""){M(void 0);return}const ue=parseFloat(re);!isNaN(ue)&&ue>=0&&ue<=2&&M(ue)},onBlur:Q=>{const re=Q.target.value;if(re!==""){const ue=parseFloat(re);if(!isNaN(ue)){const he=Math.max(0,Math.min(2,ue));M(parseFloat(he.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 re=Math.min(2,(S!==void 0?S:.7)+.1);M(parseFloat(re.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(us,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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 re=Math.max(0,(N!==void 0?N:.9)-.1);v(parseFloat(re.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(xo,{className:"h-3.5 w-3.5"})}),e.jsx(wt,{type:"text",inputMode:"decimal",value:N!==void 0?N:"",onChange:Q=>{const re=Q.target.value;if(re===""){v(void 0);return}const ue=parseFloat(re);!isNaN(ue)&&ue>=0&&ue<=1&&v(ue)},onBlur:Q=>{const re=Q.target.value;if(re!==""){const ue=parseFloat(re);if(!isNaN(ue)){const he=Math.max(0,Math.min(1,ue));v(parseFloat(he.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 re=Math.min(1,(N!==void 0?N:.9)+.1);v(parseFloat(re.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(us,{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(Fs,{value:A,onChange:Q=>k(Q.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Tool Access"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"OpenCode v1.1.1+ configures tool access via the permissions below."})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>O(Q=>!Q),className:"h-8",children:ne?"Hide":"Edit"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:ne?"Set a global default; tools only saved when different from global.":"Summary shows default actions; edit to manage granular rules."})]}),ne?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"All Rules"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Each rule is shown as permission + pattern. Editing updates the action only."})]}),e.jsx("div",{className:"rounded-lg border border-border/40",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:"Global"}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:"*"})]}),e.jsxs(As,{value:C,onValueChange:Q=>ee(Q),children:[e.jsx(Es,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:C})}),e.jsxs(Is,{children:[e.jsx(Bt,{value:"allow",className:"pr-2 [&>span:first-child]:hidden",children:"Allow"}),e.jsx(Bt,{value:"ask",className:"pr-2 [&>span:first-child]:hidden",children:"Ask"}),e.jsx(Bt,{value:"deny",className:"pr-2 [&>span:first-child]:hidden",children:"Deny"})]})]})]})}),e.jsx("div",{className:"space-y-6",children:xe.filter(Q=>Q!=="*").map(Q=>{const re=le(Q),{defaultAction:ue,patternRulesCount:he,patternSummary:Ge}=Pe(Q),qe=de(Q),et=qe??"global",rt=we(Q),vt=["allow","ask","deny"].filter(Ce=>Ce!==C);return e.jsxs("div",{className:"rounded-lg border border-border/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:re}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:Q})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[he>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Global: ",ue]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:ue}),he>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Patterns: ",Ge]}):null]})]}),e.jsxs("div",{className:"space-y-2 border-t border-border/40 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Pattern"}),e.jsx("span",{className:"typography-micro font-mono text-foreground",children:"*"}),qe?e.jsxs(je,{size:"sm",variant:"outline",onClick:()=>ce(Q,"*"),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(xo,{className:"h-3 w-3"}),"Revert"]}):null]}),e.jsxs(As,{value:et,onValueChange:Ce=>{if(Ce==="global"){J(Q,"*");return}ye(Q,"*",Ce)},children:[e.jsx(Es,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:et==="global"?"Global":et})}),e.jsxs(Is,{children:[e.jsx(Bt,{value:"global",className:"pr-2 [&>span:first-child]:hidden",children:"Global"}),vt.map(Ce=>e.jsx(Bt,{value:Ce,className:"pr-2 [&>span:first-child]:hidden",children:Ce.charAt(0).toUpperCase()+Ce.slice(1)},Ce))]})]})]}),rt.map(Ce=>{const pe=mn(Ce.permission,Ce.pattern),He=z.get(pe),Se=!He,ke=!!(He&&He.action!==Ce.action);return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Pattern"}),e.jsx("span",{className:"typography-micro font-mono text-foreground",children:Ce.pattern}),Se?e.jsx("span",{className:"typography-micro text-emerald-500",children:"New"}):null,ke?e.jsx("span",{className:"typography-micro text-amber-500",children:"Modified"}):null,Se?e.jsxs(je,{size:"sm",variant:"outline",onClick:()=>J(Ce.permission,Ce.pattern),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(xo,{className:"h-3 w-3"}),"Remove"]}):ke?e.jsxs(je,{size:"sm",variant:"outline",onClick:()=>ce(Ce.permission,Ce.pattern),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(xo,{className:"h-3 w-3"}),"Revert"]}):null]}),e.jsxs(As,{value:Ce.action,onValueChange:Xe=>ge(Ce.permission,Ce.pattern,Xe),children:[e.jsx(Es,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:Ce.action})}),e.jsxs(Is,{children:[e.jsx(Bt,{value:"allow",className:"pr-2 [&>span:first-child]:hidden",children:"Allow"}),e.jsx(Bt,{value:"ask",className:"pr-2 [&>span:first-child]:hidden",children:"Ask"}),e.jsx(Bt,{value:"deny",className:"pr-2 [&>span:first-child]:hidden",children:"Deny"})]})]})]},pe)})]})]},Q)})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Add Rule"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose a permission key, set a pattern, and pick an action."}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs(As,{value:E,onValueChange:F,children:[e.jsx(Es,{className:"h-8 min-h-8 w-full sm:w-64",children:E?e.jsx("span",{className:"truncate",children:le(E)}):e.jsx("span",{className:"text-muted-foreground",children:"Permission…"})}),e.jsx(Is,{children:H.map(Q=>e.jsx(Bt,{value:Q,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:le(Q)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:Q})]})},Q))})]}),e.jsx(wt,{value:B,onChange:Q=>V(Q.target.value),placeholder:"Pattern (e.g. *)",className:"h-8 sm:w-64 font-mono"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(je,{size:"sm",variant:"outline",onClick:()=>me("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>me("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>me("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})]})]}):e.jsx("div",{className:"rounded-lg border border-border/40 divide-y divide-border/40",children:xe.map(Q=>{const{defaultAction:re,patternRulesCount:ue,patternSummary:he,hasDefaultHint:Ge}=Pe(Q),qe=le(Q),et=Ge?`${re} (env blocked)`:re;return e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:qe}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:Q})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[ue>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Global: ",et]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:et}),ue>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Patterns: ",he]}):null]})]},Q)})}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(je,{size:"sm",variant:"default",onClick:oe,disabled:G||!fe,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(pi,{className:"h-3 w-3"}),G?"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(To,{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"})]})})},Ck=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedCommandName:a,commands:l,setSelectedCommand:c,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=nn(),{setSidebarOpen:p}=Me(),{isMobile:h}=qt(),[g,x]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||x(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=g?"bg-transparent":b?"bg-background":"bg-sidebar",w=()=>{const j="new-command";let T=j,I=1;for(;l.some(P=>P.name===T);)T=`${j}-${I}`,I++;d({name:T,scope:"user"}),c(T),t?.(),h&&p(!1)},S=async j=>{if(Wn(j)){U.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${j.name}"?`)&&(await m(j.name)?U.success(`Command "${j.name}" deleted successfully`):U.error("Failed to delete command"))},M=async j=>{Wn(j)&&window.confirm(`Are you sure you want to reset command "${j.name}" to its default configuration?`)&&(await m(j.name)?U.success(`Command "${j.name}" reset to default`):U.error("Failed to reset command"))},N=j=>{const T=j.name;let I=1,P=`${T}-copy`;for(;l.some(D=>D.name===P);)I++,P=`${T}-copy-${I}`;d({name:P,scope:j.scope||"user",description:j.description,template:j.template,agent:j.agent,model:j.model,subtask:j.subtask}),c(P),h&&p(!1)},v=j=>{o(j.name),s(j)},A=async()=>{if(!r)return;const j=n.trim().replace(/\s+/g,"-");if(!j){U.error("Command name is required");return}if(j===r.name){s(null);return}if(l.some(I=>I.name===j)){U.error("A command with this name already exists");return}await u({name:j,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(U.success(`Command renamed to "${j}"`),c(j)):U.error("Failed to remove old command after rename"):U.error("Failed to rename command"),s(null)},k=l.filter(Wn),C=l.filter(j=>!Wn(j));return e.jsxs("div",{className:L("flex h-full flex-col",y),children:[e.jsx("div",{className:L("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",l.length]}),e.jsx(je,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(us,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(tn,{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:[k.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Commands"}),[...k].sort((j,T)=>j.name.localeCompare(T.name)).map(j=>e.jsx(am,{command:j,isSelected:a===j.name,onSelect:()=>{c(j.name),t?.(),h&&p(!1)},onReset:()=>M(j),onDuplicate:()=>N(j)},j.name))]}),C.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Commands"}),[...C].sort((j,T)=>j.name.localeCompare(T.name)).map(j=>e.jsx(am,{command:j,isSelected:a===j.name,onSelect:()=>{c(j.name),t?.(),h&&p(!1)},onRename:()=>v(j),onDelete:()=>S(j),onDuplicate:()=>N(j)},j.name))]})]})}),e.jsx(fs,{open:r!==null,onOpenChange:j=>!j&&s(null),children:e.jsxs(ps,{children:[e.jsxs(bs,{children:[e.jsx(ws,{children:"Rename Command"}),e.jsxs(Ns,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(wt,{value:n,onChange:j=>o(j.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:j=>{j.key==="Enter"&&A()}}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cn,{onClick:A,children:"Rename"})]})]})})]})},am=({command:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:l})=>e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:s,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-normal truncate text-foreground",children:["/",t.name]}),(t.scope||Wn(t))&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:Wn(t)?"system":t.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsx(je,{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(sn,{className:"h-3.5 w-3.5"})})}),e.jsxs(os,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(mo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),l()},children:[e.jsx(rr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),uh=({agentName:t,onChange:r,className:s})=>{const{loadAgents:n,getVisibleAgents:o}=on(),a=o(),l=Me(g=>g.isMobile),{isMobile:c}=qt(),d=l||c,[u,m]=i.useState(!1);i.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=g=>{r(g)},h=()=>d?e.jsx(Ws,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(g=>{const x=g.name===t;return e.jsxs("button",{type:"button",className:L("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",x?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(g.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:g.name}),g.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:g.description})]}),x&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},g.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:L("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",s),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(To,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:t||"Select agent..."})]}),e.jsx(Ut,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsxs("div",{className:L("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",s),children:[e.jsx(To,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:t||"Not selected"}),e.jsx(Ut,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(os,{className:"max-w-[300px]",children:[a.map(g=>e.jsx(Nt,{className:"typography-meta",onSelect:()=>p(g.name),children:e.jsx("span",{className:"font-medium",children:g.name})},g.name)),e.jsx(Nt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},Mk=()=>{const{selectedCommandName:t,getCommandByName:r,createCommand:s,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:l}=nn(),c=t?r(t):null,d=!!(a&&a.name===t&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,g]=i.useState(""),[x,b]=i.useState(""),[y,w]=i.useState(""),[S,M]=i.useState(""),[N,v]=i.useState(!1),[A,k]=i.useState(!1),C=i.useRef(null);i.useEffect(()=>{if(d&&a){const I=a.name||"",P=a.scope||"user",D=a.description||"",E=a.agent||"",F=a.model||"",B=a.template||"",V=a.subtask||!1;m(I),p(P),g(D),b(E),w(F),M(B),v(V),C.current={draftName:I,draftScope:P,description:D,agent:E,model:F,template:B,subtask:V}}else if(c){const I=c.description||"",P=c.agent||"",D=c.model||"",E=c.template||"",F=c.subtask||!1;g(I),b(P),w(D),M(E),v(F),C.current={draftName:"",draftScope:"user",description:I,agent:P,model:D,template:E,subtask:F}}},[c,d,t,o,a]);const j=i.useMemo(()=>{const I=C.current;return I?!!(d&&(u!==I.draftName||f!==I.draftScope)||h!==I.description||x!==I.agent||y!==I.model||S!==I.template||N!==I.subtask):!1},[x,h,u,f,d,y,N,S]),T=async()=>{const I=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!I){U.error("Command name is required");return}if(!S.trim()){U.error("Command template is required");return}if(d&&o.some(P=>P.name===I)){U.error("A command with this name already exists");return}k(!0);try{const P=x.trim(),D=y.trim(),E=S.trim(),F={name:I,description:h.trim()||void 0,agent:P===""?null:P,model:D===""?null:D,template:E,subtask:N,scope:d?f:void 0};let B;d?(B=await s(F),B&&l(null)):B=await n(I,F),B?U.success(d?"Command created successfully":"Command updated successfully"):U.error(d?"Failed to create command":"Failed to update command")}catch(P){console.error("Error saving command:",P),U.error("An error occurred while saving")}finally{k(!1)}};return t?e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Command":`/${t}`})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure command identity and metadata"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Command Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"/"}),e.jsx(wt,{value:u,onChange:I=>m(I.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(As,{value:f,onValueChange:I=>p(I),children:[e.jsxs(Es,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(sr,{className:"h-4 w-4"}):e.jsx(Mr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Is,{align:"end",children:[e.jsx(Bt,{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(sr,{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(Bt,{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(Mr,{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(Fs,{value:h,onChange:I=>g(I.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(uh,{agentName:x,onChange:I=>b(I)}),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(Bc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(I,P)=>{w(I&&P?`${I}/${P}`:"")}}),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:N,onChange:I=>v(I.target.checked),className:"sr-only"}),e.jsx("div",{className:L("w-5 h-5 rounded border-2 flex items-center justify-center",N?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:N&&e.jsx(Pt,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(Fs,{value:S,onChange:I=>M(I.target.value),placeholder:`Your command template here...
|
|
240
|
+
|
|
241
|
+
Use $ARGUMENTS to reference user input.
|
|
242
|
+
Use !\`shell command\` to inject shell output.
|
|
243
|
+
Use @filename to include file contents.`,rows:12,className:"font-mono typography-meta"}),e.jsxs("div",{className:"typography-meta text-muted-foreground/80 space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Template Features:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 ml-2",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"$ARGUMENTS"}),e.jsx("span",{children:"- User input after command"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["Replaced with everything the user types after the command name.",e.jsx("br",{}),'Example: "/deploy staging" makes $ARGUMENTS = "staging"']})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"!`command`"}),e.jsx("span",{children:"- Inject shell command output"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["Executes shell command and replaces this placeholder with its output.",e.jsx("br",{}),"Example: !`git branch --show-current` gets current branch name"]})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"@filename"}),e.jsx("span",{children:"- Include file contents"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(je,{size:"sm",variant:"default",onClick:T,disabled:A||!j,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(pi,{className:"h-3 w-3"}),A?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(tn,{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"})]})})},Dk=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedSkillName:a,skills:l,setSelectedSkill:c,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=mr(),{setSidebarOpen:h}=Me(),{isMobile:g}=qt(),[x,b]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||b(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const w=x?"bg-transparent":y?"bg-background":"bg-sidebar",S=()=>{const j="new-skill";let T=j,I=1;for(;l.some(P=>P.name===T);)T=`${j}-${I}`,I++;d({name:T,scope:"user",description:""}),c(T),t?.(),g&&h(!1)},M=async j=>{window.confirm(`Are you sure you want to delete skill "${j.name}"?`)&&(await m(j.name)?U.success(`Skill "${j.name}" deleted successfully`):U.error("Failed to delete skill"))},N=async j=>{const T=j.name;let I=1,P=`${T}-copy`;for(;l.some(E=>E.name===P);)I++,P=`${T}-copy-${I}`;const D=await p(j.name);if(!D){U.error("Failed to load skill details for duplication");return}d({name:P,scope:j.scope||"user",description:(D.sources.md.fields.includes("description"),""),instructions:""}),c(P),g&&h(!1)},v=j=>{o(j.name),s(j)},A=async()=>{if(!r)return;const j=n.trim().replace(/\s+/g,"-").toLowerCase();if(!j){U.error("Skill name is required");return}if(j===r.name){s(null);return}if(l.some(P=>P.name===j)){U.error("A skill with this name already exists");return}if(!await p(r.name)){U.error("Failed to load skill details"),s(null);return}await u({name:j,description:"Renamed skill",scope:r.scope})?await m(r.name)?(U.success(`Skill renamed to "${j}"`),c(j)):U.error("Failed to remove old skill after rename"):U.error("Failed to rename skill"),s(null)},k=l.filter(j=>j.scope==="project"),C=l.filter(j=>j.scope==="user");return e.jsxs("div",{className:L("flex h-full flex-col",w),children:[e.jsx("div",{className:L("border-b px-3",g?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",l.length]}),e.jsx(je,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:S,children:e.jsx(us,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(mf,{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:[k.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Project Skills"}),k.map(j=>e.jsx(im,{skill:j,isSelected:a===j.name,onSelect:()=>{c(j.name),t?.(),g&&h(!1)},onRename:()=>v(j),onDelete:()=>M(j),onDuplicate:()=>N(j)},j.name))]}),C.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"User Skills"}),C.map(j=>e.jsx(im,{skill:j,isSelected:a===j.name,onSelect:()=>{c(j.name),t?.(),g&&h(!1)},onRename:()=>v(j),onDelete:()=>M(j),onDuplicate:()=>N(j)},j.name))]})]})}),e.jsx(fs,{open:r!==null,onOpenChange:j=>!j&&s(null),children:e.jsxs(ps,{children:[e.jsxs(bs,{children:[e.jsx(ws,{children:"Rename Skill"}),e.jsxs(Ns,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(wt,{value:n,onChange:j=>o(j.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:j=>{j.key==="Enter"&&A()}}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cn,{onClick:A,children:"Rename"})]})]})})]})},im=({skill:t,isSelected:r,onSelect:s,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsx("button",{onClick:s,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t.name}),e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:t.scope}),t.source==="claude"&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"claude"})]})}),e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsx(je,{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(sn,{className:"h-3.5 w-3.5"})})}),e.jsxs(os,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(mo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(rr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function mh({tabs:t,value:r,onValueChange:s,className:n,isInteractive:o=!0,animate:a=!0}){const l=i.useRef(null),c=i.useRef(null),d=i.useCallback(()=>{const u=l.current,m=c.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:h}=m,g=Math.max(0,Math.min(100,p/f*100)),x=Math.max(0,Math.min(100,(p+h)/f*100));u.style.clipPath=`inset(0 ${Number(100-x).toFixed(2)}% 0 ${Number(g).toFixed(2)}% round 8px)`},[]);return i.useLayoutEffect(()=>{d()},[d,r,t.length]),i.useEffect(()=>{const u=l.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:L("relative isolate w-full",n),children:[e.jsx("div",{ref:l,"aria-hidden":!0,className:L("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:"flex h-9 items-center gap-1 rounded-lg bg-accent px-1.5 text-accent-foreground",children:t.map(u=>{const m=u.icon;return e.jsxs("div",{className:"flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold",children:[m?e.jsx(m,{className:"h-4 w-4"}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})}),e.jsx("div",{className:"relative z-20 flex h-9 items-center gap-1 rounded-lg bg-muted/20 px-1.5",children:t.map(u=>{const m=r===u.value,f=u.icon;return e.jsxs("button",{ref:m?c:null,type:"button",onClick:()=>{o&&s(u.value)},className:L("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:L("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const Ak=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,Ek=t=>{const r=t.trim(),s=r.match(/^git@github\.com:([^/\s]+)\/([^\s#]+)$/i);if(s)return`${s[1]}/${s[2].replace(/\.git$/i,"")}`;const n=r.match(/^https?:\/\/github\.com\/([^/\s]+)\/([^\s#]+)$/i);if(n)return`${n[1]}/${n[2].replace(/\.git$/i,"")}`;const o=r.match(/^([^/\s]+)\/([^/\s]+)(?:\/.+)?$/);return o?`${o[1]}/${o[2].replace(/\.git$/i,"")}`:r},Ik=async()=>{try{if(ms())return await Br();const t=Ps()?.settings;if(t)return(await t.load())?.settings||{};const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return r.ok?await r.json().catch(()=>null):null}catch{return null}},Pk=({open:t,onOpenChange:r})=>{const{scanRepo:s,loadCatalog:n,isScanning:o}=Go(),a=oo(j=>j.defaultGitIdentityId),l=oo(j=>j.loadDefaultGitIdentityId),[c,d]=i.useState(""),[u,m]=i.useState(""),[f,p]=i.useState(""),[h,g]=i.useState([]),[x,b]=i.useState(null),[y,w]=i.useState(!1),[S,M]=i.useState([]),[N,v]=i.useState(null);i.useEffect(()=>{t&&(d(""),m(""),p(""),b(null),w(!1),M([]),v(null),l(),(async()=>{const j=await Ik(),T=Array.isArray(j?.skillCatalogs)?j?.skillCatalogs:[];g(T||[])})())},[t,l]);const A=i.useMemo(()=>{const j=u.trim(),T=f.trim();return h.some(I=>{const P=(I.source||"").trim(),D=(I.subpath||"").trim();return P===j&&D===T})},[h,u,f]),k=async()=>{const j=u.trim();if(!j){U.error("Repository source is required");return}c.trim()||d(Ek(j)),w(!1),b(null);const T=await s({source:j,subpath:f.trim()||void 0,gitIdentityId:N||void 0});if(!T.ok){if(T.error?.kind==="authRequired"){if(zt()){U.error("Private repositories are not supported in VS Code yet");return}const P=T.error.identities||[];if(M(P),!N&&P.length>0){const D=a&&a!=="global"&&P.some(E=>E.id===a)?a:P[0].id;v(D)}U.error("Authentication required. Select a Git identity and scan again.");return}U.error(T.error?.message||"Failed to scan repository");return}const I=T.items?.length||0;if(b(I),I===0){U.error("No skills found in this repository"),w(!1);return}M([]),w(!0),U.success(`Found ${I} skill(s)`)},C=async()=>{const j=c.trim(),T=u.trim(),I=f.trim();if(!j){U.error("Catalog name is required");return}if(!T){U.error("Repository source is required");return}if(!y){U.error("Scan the repository before adding this catalog");return}if(A){U.error("This catalog already exists");return}const P={id:Ak(),label:j,source:T,...I?{subpath:I}:{},...N?{gitIdentityId:N}:{}},D=[...h,P];try{await cs({skillCatalogs:D}),g(D),U.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(E){U.error(E instanceof Error?E.message:"Failed to save catalog")}};return e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ps,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(bs,{children:[e.jsx(ws,{children:"Add skills catalog"}),e.jsxs(Ns,{children:["Add a Git repository as a new catalog source. OpenChamber will scan it for folders containing ",e.jsx("code",{className:"font-mono",children:"SKILL.md"}),"."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Catalog name"}),e.jsx(wt,{value:c,onChange:j=>d(j.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(wt,{value:u,onChange:j=>{m(j.target.value),w(!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(wt,{value:f,onChange:j=>{p(j.target.value),w(!1),b(null)},placeholder:"e.g. skills"})]}),S.length>0&&!zt()?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(As,{value:N||"",onValueChange:j=>v(j),children:[e.jsx(Es,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:S.find(j=>j.id===N)?.name||"Choose identity"})}),e.jsx(Is,{align:"start",children:S.map(j=>e.jsx(Bt,{value:j.id,className:"pr-2 [&>span:first-child]:hidden",children:j.name},j.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,x!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",x," skill(s) found"]}):null,A?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(je,{variant:"outline",onClick:()=>{k()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(Gm,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(je,{variant:"default",onClick:()=>{C()},disabled:!y||A||!c.trim()||!u.trim(),children:"Add catalog"})]})]})})},Tk=({open:t,onOpenChange:r,conflicts:s,onConfirm:n})=>{const[o,a]=i.useState({});i.useEffect(()=>{if(!t)return;const d={};for(const u of s)d[u.skillName]="skip";a(d)},[t,s]);const l=d=>{const u={};for(const m of s)u[m.skillName]=d;a(u)},c=s.length>0&&s.every(d=>o[d.skillName]);return e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ps,{className:"max-w-2xl",children:[e.jsxs(bs,{children:[e.jsx(ws,{children:"Skills already exist"}),e.jsx(Ns,{children:"Some selected skills are already installed in this scope. Choose whether to skip or overwrite them."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[s.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{variant:"outline",size:"sm",onClick:()=>l("skip"),children:"Skip all"}),e.jsx(je,{variant:"outline",size:"sm",onClick:()=>l("overwrite"),children:"Overwrite all"})]})]}),e.jsx("div",{className:"space-y-2",children:s.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label truncate",children:d.skillName}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Installed in ",d.scope," scope"]})]}),e.jsxs(As,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Es,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(Is,{align:"end",children:[e.jsx(Bt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Bt,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Cn,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},Fk=({open:t,onOpenChange:r,item:s})=>{const{installSkills:n,isInstalling:o}=Go(),[a,l]=i.useState("user"),[c,d]=i.useState(!1),[u,m]=i.useState([]),[f,p]=i.useState(null);i.useEffect(()=>{t&&(l("user"),d(!1),m([]),p(null))},[t]);const h=async g=>{const x={skillDir:g.skillDir};s?.clawdhub&&(x.clawdhub={slug:s.clawdhub.slug,version:s.clawdhub.version});const b=await n({source:g.source,subpath:g.subpath,gitIdentityId:s?.gitIdentityId,scope:g.scope,selections:[x],conflictPolicy:"prompt",conflictDecisions:g.conflictDecisions});if(b.ok){U.success("Skill installed successfully"),r(!1);return}if(b.error?.kind==="conflicts"){p({source:g.source,subpath:g.subpath,scope:g.scope,skillDir:g.skillDir}),m(b.error.conflicts),d(!0);return}if(b.error?.kind==="authRequired"){U.error(b.error.message||"Authentication required");return}U.error(b.error?.message||"Failed to install skill")};return s?e.jsxs(e.Fragment,{children:[e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ps,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(bs,{children:[e.jsx(ws,{children:"Install skill"}),e.jsxs(Ns,{children:["Install ",e.jsx("span",{className:"font-semibold text-foreground",children:s.skillName})," into user or project scope."]})]}),e.jsx("div",{className:"space-y-3",children:s.warnings?.length?e.jsxs("div",{className:"rounded-lg border bg-muted/30 px-3 py-2",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Warnings"}),e.jsx("ul",{className:"mt-1 space-y-1",children:s.warnings.map(g=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:g},g))})]}):null}),e.jsxs(Gs,{className:"flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-center",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(As,{value:a,onValueChange:g=>l(g),children:[e.jsx(Es,{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(sr,{className:"h-4 w-4"}):e.jsx(Mr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Is,{align:"start",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sr,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mr,{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(je,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(je,{className:"w-full sm:w-auto",variant:"default",disabled:o||!s.installable,onClick:()=>{h({source:s.repoSource,subpath:s.repoSubpath,scope:a,skillDir:s.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(Tk,{open:c,onOpenChange:d,conflicts:u,onConfirm:g=>{f&&(h({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:g}),d(!1))}})]}):null},Rk=async()=>{try{if(ms())return await Br();const t=Ps()?.settings;if(t)return(await t.load())?.settings||{};const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return r.ok?await r.json().catch(()=>null):null}catch{return null}},Lk=({mode:t,onModeChange:r})=>{const{sources:s,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:l,loadSource:c,loadMoreClawdHub:d,isLoadingCatalog:u,isLoadingSource:m,isLoadingMore:f,loadedSourceIds:p,clawdhubHasMoreBySource:h,lastCatalogError:g}=Go(),[x,b]=i.useState(""),[y,w]=i.useState(!1),[S,M]=i.useState(!1),[N,v]=i.useState(null),[A,k]=i.useState(!1);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{o&&(p[o]||c(o))},[o,p,c]);const C=i.useMemo(()=>o?n[o]||[]:[],[n,o]),j=i.useMemo(()=>{const F=x.trim().toLowerCase();return F?C.filter(B=>{const V=B.skillName.toLowerCase(),ne=(B.description||"").toLowerCase(),O=(B.frontmatterName||"").toLowerCase();return V.includes(F)||ne.includes(F)||O.includes(F)}):C},[C,x]),T=i.useMemo(()=>s.find(F=>F.id===o)||null,[s,o]),I=!!(o&&o.startsWith("custom:")),P=T?.source==="clawdhub:registry"||T?.sourceType==="clawdhub",D=!!(o&&(h[o]??!0)),E=async()=>{if(!(!o||!I)&&window.confirm("Remove this catalog?")){k(!0);try{const F=await Rk(),V=(Array.isArray(F?.skillCatalogs)?F?.skillCatalogs:[]).filter(ne=>ne.id!==o);await cs({skillCatalogs:V}),await l({refresh:!0})}finally{k(!1)}}};return e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(mh,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:t,onValueChange:r,animate:!1}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Skills Catalog"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Browse curated repositories and install skills into your OpenCode configuration."})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Source"}),e.jsxs(As,{value:o||"",onValueChange:F=>a(F),children:[e.jsx(Es,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:T?.label||"Select source"})}),e.jsx(Is,{align:"start",children:s.map(F=>e.jsx(Bt,{value:F.id,className:"pr-2 [&>span:first-child]:hidden",children:F.label},F.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(je,{type:"button",variant:"outline",onClick:()=>{o?c(o,{refresh:!0}):l({refresh:!0})},disabled:u||m,className:"gap-2",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Refresh"]}),I?e.jsxs(je,{type:"button",variant:"outline",onClick:()=>{E()},disabled:A,className:"gap-2",children:[e.jsx(zs,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(je,{type:"button",variant:"default",onClick:()=>w(!0),className:"gap-2",children:[e.jsx(us,{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(wt,{value:x,onChange:F=>b(F.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:u?"Loading…":`${j.length} skill(s)`})]}),g?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:g.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:j.length===0&&!m?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"})]}):m?e.jsx("div",{className:"py-10 text-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Loading skills…"})}):e.jsxs(e.Fragment,{children:[j.map(F=>{const B=F.installed?.isInstalled,V=F.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:F.skillName}),B?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,F.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"})]}),F.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:F.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),F.clawdhub?e.jsxs("div",{className:"typography-micro text-muted-foreground mt-1 flex items-center gap-3",children:[F.clawdhub.owner?e.jsxs("span",{children:["by ",F.clawdhub.owner]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),F.clawdhub.downloads?.toLocaleString()??0]}),(F.clawdhub.stars??0)>0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gn,{className:"h-3 w-3"}),F.clawdhub.stars]}):null,e.jsxs("span",{children:["v",F.clawdhub.version]})]}):null,F.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:F.warnings.join(" · ")}):null]}),e.jsx(je,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!F.installable,onClick:()=>{v(F),M(!0)},children:"Install"})]})},`${F.sourceId}:${F.skillDir}`)}),P&&D?e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(je,{type:"button",variant:"outline",onClick:()=>{d()},disabled:f||m,children:f?"Loading…":"Load more"})}):null]})}),e.jsx(Pk,{open:y,onOpenChange:w}),e.jsx(Fk,{open:S,onOpenChange:M,item:N})]})})},Ok=()=>{const{selectedSkillName:t,getSkillByName:r,getSkillDetail:s,createSkill:n,updateSkill:o,skills:a,skillDraft:l,setSkillDraft:c,setSelectedSkill:d}=mr(),u=t?r(t):null,m=!!(l&&l.name===t&&!u),f=!!(t&&!u&&!l),[p,h]=i.useState("manual");i.useEffect(()=>{!m&&p!=="manual"&&h("manual")},[m,p]),i.useEffect(()=>{f&&d(null)},[f,d]);const g=m?e.jsx(mh,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[x,b]=i.useState(""),[y,w]=i.useState("user"),[S,M]=i.useState(""),[N,v]=i.useState(""),[A,k]=i.useState([]),[C,j]=i.useState([]),[T,I]=i.useState(!1),[P,D]=i.useState(!1),[E,F]=i.useState(""),[B,V]=i.useState(""),[ne,O]=i.useState(!1),[G,K]=i.useState(""),[q,$]=i.useState(""),[W,Y]=i.useState(null),[X,Z]=i.useState(!1),[z,R]=i.useState(""),de=m?x.trim()!==""||S.trim()!==""||N.trim()!==""||C.length>0:S!==E||N!==B,we=W?q!==z:G.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&l)b(l.name||""),w(l.scope||"user"),M(l.description||""),v(l.instructions||""),F(""),V(""),k([]),j(l.pendingFiles||[]);else if(t&&u){D(!0);try{const ge=await s(t);if(ge){const ee=ge.sources.md;M(ee.description||""),v(ee.instructions||""),F(ee.description||""),V(ee.instructions||""),k(ee.supportingFiles||[])}}catch(ge){console.error("Failed to load skill details:",ge)}finally{D(!1)}}})()},[u,m,t,a,l,s,p]);const xe=async()=>{const ce=m?x.trim().replace(/\s+/g,"-").toLowerCase():t?.trim();if(!ce){U.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(ce)||ce.length>64){U.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!S.trim()){U.error("Description is required");return}if(m&&a.some(ge=>ge.name===ce)){U.error("A skill with this name already exists");return}I(!0);try{const ge={name:ce,description:S.trim(),instructions:N.trim()||void 0,scope:m?y:void 0,supportingFiles:m&&C.length>0?C:void 0};let ee;m?(ee=await n(ge),ee&&(c(null),j([]),d(ce))):(ee=await o(ce,ge),ee&&(F(S.trim()),V(N.trim()))),ee?U.success(m?"Skill created successfully":"Skill updated successfully"):U.error(m?"Failed to create skill":"Failed to update skill")}catch(ge){console.error("Error saving skill:",ge),U.error("An error occurred while saving")}finally{I(!1)}},Pe=()=>{Y(null),K(""),$(""),R(""),O(!0)},H=async ce=>{if(Y(ce),K(ce),m){const ee=C.find(me=>me.path===ce)?.content||"";$(ee),R(ee),O(!0);return}if(t){Z(!0),O(!0);try{const{readSupportingFile:ge}=mr.getState(),ee=await ge(t,ce);$(ee||""),R(ee||"")}catch{U.error("Failed to load file content"),$(""),R("")}finally{Z(!1)}}},ye=async()=>{if(!G.trim()){U.error("File name is required");return}const ce=G.trim(),ge=W!==null;if(m){if(ge)j(le=>le.map(fe=>fe.path===W?{path:ce,content:q}:fe)),U.success(`File "${ce}" updated`);else{if(C.some(le=>le.path===ce)){U.error("A file with this name already exists");return}j(le=>[...le,{path:ce,content:q}]),U.success(`File "${ce}" added`)}O(!1),Y(null);return}if(!t){U.error("No skill selected");return}const{writeSupportingFile:ee}=mr.getState();if(await ee(t,ce,q)){U.success(ge?`File "${ce}" updated`:`File "${ce}" created`),O(!1),Y(null);const le=await s(t);le&&k(le.sources.md.supportingFiles||[])}else U.error(ge?"Failed to update file":"Failed to create file")},J=async ce=>{if(m){j(ge=>ge.filter(ee=>ee.path!==ce)),U.success(`File "${ce}" removed`);return}if(t&&window.confirm(`Are you sure you want to delete "${ce}"?`)){const{deleteSupportingFile:ge}=mr.getState();if(await ge(t,ce)){U.success(`File "${ce}" deleted`);const me=await s(t);me&&k(me.sources.md.supportingFiles||[])}else U.error("Failed to delete file")}};return m&&p==="external"?e.jsx(Lk,{mode:p,onModeChange:h}):!t&&!l||f?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(mf,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a skill from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})}):P?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Loading skill details..."})})}):e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[m?g:null,e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:m?"New Skill":t}),u&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:[u.scope==="project"?"Project":"User"," skill",u.source==="claude"&&" (Claude-compatible)"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure skill identity and description"})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Skill Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wt,{value:x,onChange:ce=>b(ce.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(As,{value:y,onValueChange:ce=>w(ce),children:[e.jsxs(Es,{className:"!h-9 w-auto gap-1.5",children:[y==="user"?e.jsx(sr,{className:"h-4 w-4"}):e.jsx(Mr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:y})]}),e.jsxs(Is,{align:"end",children:[e.jsx(Bt,{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(sr,{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(Bt,{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(Mr,{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(Fs,{value:S,onChange:ce=>M(ce.target.value),placeholder:"Brief description of what this skill does...",rows:2,className:"max-h-32 resize-none"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The agent uses this to decide when to load the skill"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Instructions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Detailed instructions for the agent when this skill is loaded"})]}),e.jsx(Fs,{value:N,onChange:ce=>v(ce.target.value),placeholder:"Step-by-step instructions, guidelines, or reference content...",rows:12,className:"font-mono typography-meta max-h-80 resize-y"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Supporting Files"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Reference documentation, scripts, or templates"})]}),e.jsxs(je,{variant:"outline",size:"sm",onClick:Pe,className:"gap-1.5",children:[e.jsx(us,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const ce=m?C:A;return ce.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-2",children:m?'No files yet. Use "Add File" to include reference materials.':'No supporting files. Use "Add File" to include reference materials.'}):e.jsx("div",{className:"space-y-2",children:ce.map(ge=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg border bg-muted/30 hover:bg-muted/50 cursor-pointer transition-colors",onClick:()=>H(ge.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(vr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:ge.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(je,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:ee=>{ee.stopPropagation(),J(ge.path)},children:e.jsx(zs,{className:"h-3.5 w-3.5"})})]},ge.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(je,{size:"sm",variant:"default",onClick:xe,disabled:T||!de,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(pi,{className:"h-3 w-3"}),T?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(fs,{open:ne,onOpenChange:ce=>{O(ce),ce||Y(null)},children:e.jsxs(ps,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(bs,{className:"flex-shrink-0",children:[e.jsx(ws,{children:W?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ns,{children:W?"Modify the file content":"Create a new file in the skill directory"})]}),X?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(wt,{value:G,onChange:ce=>K(ce.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:W!==null}),!W&&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(Fs,{value:q,onChange:ce=>$(ce.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"ghost",onClick:()=>{O(!1),Y(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cn,{onClick:ye,disabled:X||!we,children:W?"Save Changes":"Create File"})]})]})})]})})},_k="__add_provider__",$k=({onItemSelect:t})=>{const r=Ze(u=>u.providers),s=Ze(u=>u.selectedProviderId),n=Ze(u=>u.setSelectedProvider),{isMobile:o}=qt(),[a,l]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||l(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":c?"bg-background":"bg-sidebar";return e.jsxs("div",{className:L("flex h-full flex-col",d),children:[e.jsx("div",{className:L("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(je,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(_k),t?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(us,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:r.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(eo,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No providers found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Check your OpenCode configuration"})]}):r.map(u=>{const m=Array.isArray(u.models)?u.models.length:0,f=u.id===s;return e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",f?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{type:"button",onClick:()=>{n(u.id),t?.()},className:"flex min-w-0 flex-1 items-center gap-2 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsx(ys,{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)})})]})},Bk=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),lm=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const r=Bk.format(t);return r.endsWith(".0")?r.slice(0,-2):r},$n="__add_provider__",co=t=>typeof t=="object"&&t!==null,cm=t=>{const r=typeof t.type=="string"?t.type:"",s=`${t.name??""} ${t.label??""}`.toLowerCase(),n=`${r} ${s}`.toLowerCase();return n.includes("oauth")?"oauth":n.includes("api")?"api":r.toLowerCase()},zk=t=>{if(!co(t))return{};const r={};for(const[s,n]of Object.entries(t))Array.isArray(n)&&(r[s]=n.filter(o=>co(o)));return r},Hk=t=>{if(typeof t=="string")return{id:t};if(!co(t))return null;const r=typeof t.id=="string"&&t.id||typeof t.providerID=="string"&&t.providerID||typeof t.slug=="string"&&t.slug||typeof t.name=="string"&&t.name;if(!r)return null;const s=typeof t.name=="string"?t.name:void 0;return{id:r,name:s}},Wk=t=>{let r=[];Array.isArray(t)?r=t:co(t)&&(Array.isArray(t.all)?r=t.all:Array.isArray(t.providers)&&(r=t.providers));const s=r.map(o=>Hk(o)).filter(o=>!!o),n=new Set;return s.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},Uk=()=>{const t=Ze(H=>H.providers),r=Ze(H=>H.selectedProviderId),s=Ze(H=>H.setSelectedProvider),n=Ze(H=>H.getModelMetadata),[o,a]=i.useState({}),[l,c]=i.useState(!1),[d,u]=i.useState({}),[m,f]=i.useState(null),[p,h]=i.useState(""),[g,x]=i.useState(null),[b,y]=i.useState({}),[w,S]=i.useState({}),[M,N]=i.useState([]),[v,A]=i.useState(!1),[k,C]=i.useState(null),[j,T]=i.useState(""),[I,P]=i.useState(""),[D,E]=i.useState(!1),[F,B]=i.useState({}),[V,ne]=i.useState(!1);i.useEffect(()=>{!r&&t.length>0&&s(t[0].id)},[t,r,s]),i.useEffect(()=>{let H=!0;return(async()=>{c(!0);try{const J=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!J.ok)throw new Error(`Auth methods request failed (${J.status})`);const ce=await J.json().catch(()=>({}));if(!H)return;a(zk(ce))}catch(J){if(!H)return;console.error("Failed to load provider auth methods:",J),U.error("Failed to load provider authentication methods")}finally{H&&c(!1)}})(),()=>{H=!1}},[]),i.useEffect(()=>{let H=!0;return(async()=>{A(!0),C(null);try{const J=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!J.ok)throw new Error(`Provider list request failed (${J.status})`);const ce=await J.json().catch(()=>({}));if(!H)return;N(Wk(ce))}catch(J){if(!H)return;console.error("Failed to load available providers:",J),C("Unable to load provider list")}finally{H&&A(!1)}})(),()=>{H=!1}},[]);const O=i.useMemo(()=>new Set(t.map(H=>H.id)),[t]),G=i.useMemo(()=>M.filter(H=>!O.has(H.id)),[M,O]);i.useEffect(()=>{if(r===$n){if(!j&&G.length>0){T(G[0].id);return}j&&!G.some(H=>H.id===j)&&T(G[0]?.id??"")}},[r,j,G]),i.useEffect(()=>{if(r===$n){ne(!0);return}ne(!1)},[r]),i.useEffect(()=>{if(!r||r===$n)return;let H=!1;return(async()=>{try{const J=await fetch(`/api/provider/${encodeURIComponent(r)}/source`,{method:"GET",headers:{Accept:"application/json"}}),ce=await J.json().catch(()=>null);if(!J.ok)throw new Error(ce?.error||"Failed to load provider sources");const ge=ce?.sources??ce?.data?.sources;!H&&ge&&B(ee=>({...ee,[r]:ge}))}catch(J){H||console.error("Failed to load provider sources:",J)}})(),()=>{H=!0}},[r]);const K=t.find(H=>H.id===r),q=r?F[r]:void 0,$=async H=>{const ye=d[H]?.trim()??"";if(!ye){U.error("API key is required");return}const J=`api:${H}`;f(J);try{const ce=await fetch(`/api/auth/${encodeURIComponent(H)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:ye})}),ge=await ce.json().catch(()=>null);if(!ce.ok){const ee=ge?.error||"Failed to save API key";throw new Error(ee)}U.success("API key saved"),u(ee=>({...ee,[H]:""})),await Do({scopes:["providers"],mode:"active"}),s(H)}catch(ce){console.error("Failed to save API key:",ce),U.error("Failed to save API key")}finally{f(null)}},W=async(H,ye)=>{const J=`oauth:${H}:${ye}`;f(J);try{const ce=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:ye})}),ge=await ce.json().catch(()=>null);if(!ce.ok){const re=ge?.error||"Failed to start OAuth flow";throw new Error(re)}const ee=co(ge)?ge:{},me=co(ee.data)?ee.data:ee,le=typeof me.url=="string"&&me.url||typeof me.verification_uri_complete=="string"&&me.verification_uri_complete||typeof me.verification_uri=="string"&&me.verification_uri||void 0,fe=typeof me.instructions=="string"&&me.instructions||typeof me.message=="string"&&me.message||void 0,oe=typeof me.user_code=="string"&&me.user_code||typeof me.code=="string"&&me.code||typeof me.userCode=="string"&&me.userCode||void 0;if(!le&&!fe&&!oe)throw new Error("No OAuth details returned");const Q=`${H}:${ye}`;S(re=>({...re,[Q]:{url:le,instructions:fe,userCode:oe}})),le&&window.open(le,"_blank","noopener,noreferrer"),x({providerId:H,methodIndex:ye}),U.message("Complete the OAuth flow in your browser")}catch(ce){console.error("Failed to start OAuth flow:",ce),U.error("Failed to start OAuth flow")}finally{f(null)}},Y=async(H,ye)=>{const J=`${H}:${ye}`,ce=b[J]?.trim(),ge=`oauth-complete:${H}:${ye}`;f(ge);try{const ee={method:ye};ce&&(ee.code=ce);const me=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ee)}),le=await me.json().catch(()=>null);if(!me.ok){const fe=le?.error||"Failed to complete OAuth flow";throw new Error(fe)}U.success("OAuth connection completed"),y(fe=>({...fe,[J]:""})),x(null),await Do({scopes:["providers"],mode:"active"}),s(H)}catch(ee){console.error("Failed to complete OAuth flow:",ee),U.error("Failed to complete OAuth flow")}finally{f(null)}},X=async H=>{try{await navigator.clipboard.writeText(H),U.success("OAuth link copied")}catch(ye){console.error("Failed to copy OAuth link:",ye),U.error("Failed to copy OAuth link")}},Z=async H=>{try{await navigator.clipboard.writeText(H),U.success("Device code copied")}catch(ye){console.error("Failed to copy device code:",ye),U.error("Failed to copy device code")}},z=async H=>{const ye=`disconnect:${H}`;f(ye);try{const J=await fetch(`/api/provider/${encodeURIComponent(H)}/auth?scope=all`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),ce=await J.json().catch(()=>null);if(!J.ok){const ge=ce?.error||"Failed to disconnect provider";throw new Error(ge)}U.success("Provider disconnected"),await Do({scopes:["providers"],mode:"active"})}catch(J){console.error("Failed to disconnect provider:",J),U.error("Failed to disconnect provider")}finally{f(null)}},R=r===$n;if(!R&&t.length===0)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(eo,{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(R)return e.jsx(gt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Connect provider"}),e.jsx("p",{className:"typography-body text-muted-foreground",children:"Choose a provider to connect and set up its authentication."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Provider"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select a provider that is not connected yet."})]}),v?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):k?e.jsx("p",{className:"typography-meta text-muted-foreground",children:k}):G.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(rs,{open:D,onOpenChange:H=>{E(H),H||P("")},children:[e.jsx(ns,{asChild:!0,children:e.jsxs("button",{type:"button",className:L("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:j?"text-foreground":"text-muted-foreground",children:j?G.find(H=>H.id===j)?.name||j:"Select provider"}),e.jsx(Ut,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(os,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:H=>H.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:H=>H.stopPropagation(),children:[e.jsx(Vs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:I,onChange:H=>P(H.target.value),onKeyDown:H=>H.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(gt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const H=G.filter(ye=>{const J=I.toLowerCase();return(ye.name||ye.id).toLowerCase().includes(J)||ye.id.toLowerCase().includes(J)});return H.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):H.map(ye=>e.jsxs(Nt,{onSelect:()=>{T(ye.id),E(!1),P("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:ye.name||ye.id}),j===ye.id&&e.jsx(Pt,{className:"h-4 w-4 text-primary"})]},ye.id))})()})]})]})]}),j&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),l?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(wt,{type:"password",value:d[j]??"",onChange:H=>u(ye=>({...ye,[j]:H.target.value})),placeholder:"sk-..."}),e.jsx(je,{size:"sm",onClick:()=>$(j),disabled:m===`api:${j}`,className:"h-8",children:m===`api:${j}`?"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 ye=(o[j]??[]).filter(J=>cm(J)==="oauth");return ye.length===0?null:e.jsx("div",{className:"space-y-3",children:ye.map((J,ce)=>{const ge=J.label||J.name||`OAuth method ${ce+1}`,ee=`${j}:${ce}`,me=g?.providerId===j&&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:ge}),(J.description||J.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(J.description||J.help)})]}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>W(j,ce),disabled:m===`oauth:${j}:${ce}`,className:"h-8",children:"Connect"})]}),w[ee]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:w[ee]?.instructions}),w[ee]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(wt,{value:w[ee]?.userCode,readOnly:!0}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>Z(w[ee]?.userCode??""),className:"h-8",children:"Copy code"})]}),w[ee]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(wt,{value:w[ee]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(je,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:w[ee]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>X(w[ee]?.url??""),className:"h-8",children:"Copy link"})]})]}),me&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(wt,{value:b[ee]??"",onChange:le=>y(fe=>({...fe,[ee]:le.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(je,{size:"sm",onClick:()=>Y(j,ce),disabled:m===`oauth-complete:${j}:${ce}`,className:"h-8",children:m===`oauth-complete:${j}:${ce}`?"Saving…":"Complete"})]})]},`${j}-${ge}`)})})})()]})]})]})});if(!K)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(eo,{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 de=Array.isArray(K.models)?K.models:[],xe=(o[K.id]??[]).filter(H=>cm(H)==="oauth"),Pe=de.filter(H=>{const ye=typeof H?.name=="string"?H.name:"",J=typeof H?.id=="string"?H.id:"",ce=p.trim().toLowerCase();return ce?ye.toLowerCase().includes(ce)||J.toLowerCase().includes(ce):!0});return e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{providerId:K.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:K.name||K.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",K.id]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),r!==$n&&e.jsx(je,{size:"sm",variant:"outline",onClick:()=>ne(H=>!H),className:"h-8",children:V?"Hide":"Reconnect"})]}),!V&&r!==$n?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Connected. Use Reconnect to update credentials."}):l?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(wt,{type:"password",value:d[K.id]??"",onChange:H=>u(ye=>({...ye,[K.id]:H.target.value})),placeholder:"sk-..."}),e.jsx(je,{size:"sm",onClick:()=>$(K.id),disabled:m===`api:${K.id}`,className:"h-8",children:m===`api:${K.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."})]}),xe.length>0&&e.jsx("div",{className:"space-y-3",children:xe.map((H,ye)=>{const J=H.label||H.name||`OAuth method ${ye+1}`,ce=`${K.id}:${ye}`,ge=g?.providerId===K.id&&g?.methodIndex===ye;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:J}),(H.description||H.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(H.description||H.help)})]}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>W(K.id,ye),disabled:m===`oauth:${K.id}:${ye}`,className:"h-8",children:"Connect"})]}),w[ce]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:w[ce]?.instructions}),w[ce]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(wt,{value:w[ce]?.userCode,readOnly:!0}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>Z(w[ce]?.userCode??""),className:"h-8",children:"Copy code"})]}),w[ce]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(wt,{value:w[ce]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(je,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:w[ce]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>X(w[ce]?.url??""),className:"h-8",children:"Copy link"})]})]}),ge&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(wt,{value:b[ce]??"",onChange:ee=>y(me=>({...me,[ce]:ee.target.value})),placeholder:"Paste authorization code"}),e.jsx(je,{size:"sm",onClick:()=>Y(K.id,ye),disabled:m===`oauth-complete:${K.id}:${ye}`,className:"h-8",children:m===`oauth-complete:${K.id}:${ye}`?"Saving…":"Complete"})]})]},`${K.id}-${J}`)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Connection"}),q&&(q.auth.exists||q.user.exists||q.project.exists||q.custom?.exists)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Configured in: ",[q.auth.exists?"auth credentials":null,q.user.exists?"user config":null,q.project.exists?"project config":null,q.custom?.exists?"custom config":null].filter(Boolean).join(", ")]}),e.jsx(je,{size:"sm",variant:"outline",onClick:()=>z(K.id),disabled:m===`disconnect:${K.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${K.id}`?"Disconnecting…":"Disconnect provider"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Models"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Browse and filter models exposed by this provider."})]}),e.jsx(wt,{value:p,onChange:H=>h(H.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:Pe.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):Pe.map(H=>{const ye=typeof H?.id=="string"?H.id:"",J=typeof H?.name=="string"?H.name:ye,ce=ye?n(K.id,ye):void 0,ge=lm(ce?.limit?.context),ee=lm(ce?.limit?.output),me=[];return ce?.tool_call&&me.push({key:"tools",icon:mi,label:"Tool calling"}),ce?.reasoning&&me.push({key:"reasoning",icon:Cr,label:"Reasoning"}),ce?.attachment&&me.push({key:"image",icon:Dr,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:J}),(ge||ee)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[ge?`${ge} ctx`:"",ge&&ee?" · ":"",ee?`${ee} out`:""]}),me.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:me.map(({key:le,icon:fe,label:oe})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:oe,"aria-label":oe,children:e.jsx(fe,{className:"h-3 w-3"})},le))})]},ye)})})]})]})})},Vk={branch:Vt,briefcase:mc,house:uc,graduation:dc,code:tr,heart:lf},Gk={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},qk=({onItemSelect:t})=>{const{selectedProfileId:r,defaultGitIdentityId:s,profiles:n,globalIdentity:o,setSelectedProfile:a,deleteProfile:l,loadProfiles:c,loadGlobalIdentity:d,loadDiscoveredCredentials:u,loadDefaultGitIdentityId:m,setDefaultGitIdentityId:f,getUnimportedCredentials:p}=oo(),{setSidebarOpen:h}=Me(),{isMobile:g}=qt(),[x,b]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||b(typeof window.opencodeDesktop<"u")},[]);const w=p();i.useEffect(()=>{c(),d(),u(),m()},[c,d,u,m]);const S=k=>{a(`import:${k.host}:${k.username}`),t?.(),g&&h(!1)},M=x?"bg-transparent":y?"bg-background":"bg-sidebar",N=()=>{a("new"),t?.(),g&&h(!1)},v=async k=>{window.confirm(`Are you sure you want to delete profile "${k.name}"?`)&&(await l(k.id)?U.success(`Profile "${k.name}" deleted successfully`):U.error("Failed to delete profile"))},A=async k=>{const C=s===k?null:k;if(!await f(C)){U.error("Failed to update default identity");return}U.success(C?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:L("flex h-full flex-col",M),children:[e.jsx("div",{className:L("border-b px-3",g?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",n.length]}),e.jsx(je,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:N,"aria-label":"Create new profile",children:e.jsx(us,{className:"size-4"})})]})}),e.jsxs(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"System Default"}),e.jsx(dm,{profile:o,isSelected:r==="global",isDefault:s==="global",onSelect:()=>{a("global"),t?.(),g&&h(!1)},onToggleDefault:()=>A("global"),onDelete:void 0,isReadOnly:!0})]}),n.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),n.length===0&&!o&&w.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Vt,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:n.map(k=>e.jsx(dm,{profile:k,isSelected:r===k.id,isDefault:s===k.id,onSelect:()=>{a(k.id),t?.(),g&&h(!1)},onToggleDefault:()=>A(k.id),onDelete:()=>v(k)},k.id))}),w.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Discovered Credentials"}),e.jsx("p",{className:"px-2 pb-2 typography-micro text-muted-foreground/60",children:"Found in ~/.git-credentials"}),w.map(k=>e.jsx(Yk,{credential:k,onImport:()=>S(k)},`${k.host}-${k.username}`))]})]})]})},dm=({profile:t,isSelected:r,isDefault:s=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:l=!1})=>{const c=Vk[t.icon||"branch"]||Vt,d=Gk[t.color||""],u=t.authType||"ssh";return e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:n,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(c,{className:"w-4 h-4 flex-shrink-0",style:{color:d}}),e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t.name}),e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:u}),s&&e.jsx("span",{className:"typography-micro text-primary bg-primary/12 px-1 rounded flex-shrink-0 leading-none pb-px border border-primary/25",children:"default"})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:u==="token"&&t.host?t.host:t.userEmail})]}),(o||!l&&a)&&e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsx(je,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100","aria-label":"Profile actions",children:e.jsx(sn,{className:"h-3.5 w-3.5"})})}),e.jsxs(os,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(Nt,{onClick:m=>{m.stopPropagation(),o()},children:s?"Unset default":"Set as default"}),!l&&a&&e.jsxs(Nt,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},Kk=t=>{const r=t.split("/");return r.length>=3?r[r.length-1]:t},Yk=({credential:t,onImport:r})=>{const s=Kk(t.host),n=t.host.includes("/");return e.jsx("div",{className:"group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 hover:dark:bg-accent/40 hover:bg-primary/6",children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:s})}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n?t.host:t.username})]}),e.jsxs(je,{size:"sm",variant:"ghost",onClick:r,className:"h-6 px-2 text-xs gap-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:[e.jsx(Zr,{className:"h-3 w-3"}),"Import"]})]})})},um=[{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)"}],Qk=[{key:"branch",Icon:Vt,label:"Branch"},{key:"briefcase",Icon:mc,label:"Work"},{key:"house",Icon:uc,label:"Personal"},{key:"graduation",Icon:dc,label:"School"},{key:"code",Icon:tr,label:"Code"}],Jk=()=>{const{selectedProfileId:t,getProfileById:r,createProfile:s,updateProfile:n,deleteProfile:o}=oo(),a=i.useMemo(()=>{if(t?.startsWith("import:")){const[,D,E]=t.split(":");return{host:D,username:E}}return null},[t]),l=i.useMemo(()=>t&&t!=="new"&&!a?r(t):null,[t,r,a]),c=t==="new"||a!==null,d=t==="global",[u,m]=i.useState(""),[f,p]=i.useState(""),[h,g]=i.useState(""),[x,b]=i.useState("ssh"),[y,w]=i.useState(""),[S,M]=i.useState(""),[N,v]=i.useState("keyword"),[A,k]=i.useState("branch"),[C,j]=i.useState(!1);i.useEffect(()=>{if(a){const D=a.host.split("/"),E=D.length>=3?D[D.length-1]:a.host;m(E),p(a.username),g(""),b("token"),w(""),M(a.host),v("string"),k("code")}else c?(m(""),p(""),g(""),b("ssh"),w(""),M(""),v("keyword"),k("branch")):l&&(m(l.name),p(l.userName),g(l.userEmail),b(l.authType||"ssh"),w(l.sshKey||""),M(l.host||""),v(l.color||"keyword"),k(l.icon||"branch"))},[l,c,t,a]);const T=async()=>{if(!f.trim()||!h.trim()){U.error("User name and email are required");return}if(x==="token"&&!S.trim()){U.error("Host is required for token-based authentication");return}j(!0);try{const D={name:u.trim()||f.trim(),userName:f.trim(),userEmail:h.trim(),authType:x,sshKey:x==="ssh"&&y.trim()||null,host:x==="token"&&S.trim()||null,color:N,icon:A};let E;if(c)E=await s(D);else if(t)E=await n(t,D);else return;E?U.success(c?"Profile created successfully":"Profile updated successfully"):U.error(c?"Failed to create profile":"Failed to update profile")}catch(D){console.error("Error saving profile:",D),U.error("An error occurred while saving")}finally{j(!1)}},I=async()=>{if(!(!t||c)&&confirm("Are you sure you want to delete this profile?"))try{await o(t)?U.success("Profile deleted successfully"):U.error("Failed to delete profile")}catch(D){console.error("Error deleting profile:",D),U.error("An error occurred while deleting")}},P=i.useMemo(()=>um.find(E=>E.key===N)?.cssVar||"var(--syntax-keyword)",[N]);return t?e.jsx(gt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:a?"Import Credential":c?"New Git Profile":d?"Global Identity":u||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:a?`Import token credential for ${a.host} - please fill in your email address`:c?"Create a new Git identity profile for your repositories":d?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!d&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Profile Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Basic profile settings and display name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Display Name"}),e.jsx(wt,{value:u,onChange:D=>m(D.target.value),placeholder:"Work Profile, Personal, etc."}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Friendly name to identify this profile (optional, defaults to user name)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Color"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:um.map(D=>e.jsx("button",{onClick:()=>v(D.key),className:L("w-8 h-8 rounded-lg border-2 transition-all",N===D.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:D.cssVar},title:D.label},D.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Icon"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Qk.map(D=>{const E=D.Icon;return e.jsx("button",{onClick:()=>k(D.key),className:L("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",A===D.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:D.label,children:e.jsx(E,{className:"w-4 h-4",style:{color:P}})},D.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(wt,{value:f,onChange:D=>p(D.target.value),placeholder:"John Doe",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.name configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Email ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(wt,{type:"email",value:h,onChange:D=>g(D.target.value),placeholder:"john@example.com",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Authentication Type",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["SSH: Uses SSH key for authentication",e.jsx("br",{}),"Token: Uses personal access token from ~/.git-credentials"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>b("ssh"),className:L("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",x==="ssh"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx(Yx,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>b("token"),className:L("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",x==="token"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx(Qx,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"Token (HTTPS)"})]})]})]}),x==="ssh"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["SSH Key Path",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["Path to SSH private key used for Git authentication.",e.jsx("br",{}),"This key will be used for SSH Git operations.",e.jsx("br",{}),"Common paths: ~/.ssh/id_rsa, ~/.ssh/id_ed25519"]})]})]}),e.jsx(wt,{value:y,onChange:D=>w(D.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),x==="token"&&!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Host ",e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["The Git host this credential applies to.",e.jsx("br",{}),"Token will be read from ~/.git-credentials for this host.",e.jsx("br",{}),"Examples: github.com, gitlab.com"]})]})]}),e.jsx(wt,{value:S,onChange:D=>M(D.target.value),placeholder:"github.com",required:!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git host for token authentication (from ~/.git-credentials)"})]}),!d&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!c&&e.jsxs(je,{size:"sm",variant:"destructive",onClick:I,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(zs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:L("flex gap-2",c&&"ml-auto"),children:e.jsxs(je,{size:"sm",variant:"default",onClick:T,disabled:C,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(pi,{className:"h-3 w-3"}),C?"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(sr,{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 ml(t,r,s){return Math.min(s,Math.max(r,t))}const gn=Ae.forwardRef(({value:t,onValueChange:r,min:s=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:l,onBlur:c,onKeyDown:d,disabled:u,...m},f)=>{const p=Ae.useRef(null);Ae.useImperativeHandle(f,()=>p.current);const[h,g]=Ae.useState(()=>String(t));Ae.useEffect(()=>{document.activeElement!==p.current&&g(String(t))},[t]);const x=Ae.useCallback(()=>{p.current?.focus()},[]),b=Ae.useCallback(j=>{const T=ml(j,s,n);r(T),g(String(T))},[n,s,r]),y=Ae.useCallback(()=>{const j=Number(h);return Number.isFinite(j)?j:t},[h,t]),w=Ae.useCallback(()=>{b(y()+o),x()},[b,y,x,o]),S=Ae.useCallback(()=>{b(y()-o),x()},[b,y,x,o]),M=j=>{const T=j.target.value;g(T);const I=Number(T);Number.isFinite(I)&&r(ml(I,s,n))},N=j=>{const T=Number(h);if(!Number.isFinite(T))g(String(t));else{const I=ml(T,s,n);I!==T&&r(I),g(String(I))}c?.(j)},v=j=>{if(j.key==="ArrowUp"){j.preventDefault(),w();return}if(j.key==="ArrowDown"){j.preventDefault(),S();return}d?.(j)},A=y(),k=u||A<=s,C=u||A>=n;return e.jsxs("div",{className:L("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",l),children:[e.jsx("input",{...m,ref:p,type:"number",inputMode:"numeric",min:Number.isFinite(s)?s:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:h,onChange:M,onBlur:N,onKeyDown:v,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:L("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:C,onClick:w,className:L("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(di,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:k,onClick:S,className:L("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(Ut,{className:"h-3.5 w-3.5"})})]})]})});gn.displayName="NumberInput";const Xk=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],mm=[{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"}],fm=[{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."}],pm=[{id:"single",label:"Single file",description:"Show one file at a time in the Diff tab."},{id:"stacked",label:"All files",description:"Stack all changed files together in the Diff tab."}],zc=({visibleSettings:t})=>{const{isMobile:r}=qt(),s=Vo(),n=Me(j=>j.showReasoningTraces),o=Me(j=>j.setShowReasoningTraces),a=Me(j=>j.showTextJustificationActivity),l=Me(j=>j.setShowTextJustificationActivity),c=Me(j=>j.toolCallExpansion),d=Me(j=>j.setToolCallExpansion),u=Me(j=>j.fontSize),m=Me(j=>j.setFontSize),f=Me(j=>j.padding),p=Me(j=>j.setPadding),h=Me(j=>j.cornerRadius),g=Me(j=>j.setCornerRadius),x=Me(j=>j.inputBarOffset),b=Me(j=>j.setInputBarOffset),y=Me(j=>j.diffLayoutPreference),w=Me(j=>j.setDiffLayoutPreference),S=Me(j=>j.diffViewMode),M=Me(j=>j.setDiffViewMode),N=wr(j=>j.queueModeEnabled),v=wr(j=>j.setQueueMode),{themeMode:A,setThemeMode:k}=Hr(),C=j=>t?t.includes(j):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[C("theme")&&!zt()&&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:Xk.map(j=>e.jsx(Ts,{variant:A===j.value?"default":"outline",className:L(A===j.value?void 0:"text-foreground"),onClick:()=>k(j.value),children:j.label},j.value))})]}),C("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:u,onChange:j=>m(Number(j.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(gn,{value:u,onValueChange:m,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>m(100),disabled:u===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset font size",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]})]}),C("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:f,onChange:j=>p(Number(j.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"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:f}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>p(100),disabled:f===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(Ls,{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:f,onChange:j=>p(Number(j.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(gn,{value:f,onValueChange:p,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>p(100),disabled:f===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(Ls,{className:"h-3.5 w-3.5"})})]})]}),C("cornerRadius")&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Input Field Corner Radius"})}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"32",step:"1",value:h,onChange:j=>g(Number(j.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Corner radius in pixels"}),e.jsxs("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:[h,"px"]}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>g(12),disabled:h===12,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset corner radius",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"0",max:"32",step:"1",value:h,onChange:j=>g(Number(j.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Corner radius in pixels"}),e.jsx(gn,{value:h,onValueChange:g,min:0,max:32,step:1,"aria-label":"Corner radius in pixels"}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>g(12),disabled:h===12,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset corner radius",title:"Reset",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})]})]}),C("inputBarOffset")&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Input Bar Offset"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Raise the input bar to avoid screen obstructions."})]}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"100",step:"5",value:x,onChange:j=>b(Number(j.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Input bar offset in pixels"}),e.jsxs("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:[x,"px"]}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>b(0),disabled:x===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(Ls,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"0",max:"100",step:"5",value:x,onChange:j=>b(Number(j.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Input bar offset in pixels"}),e.jsx(gn,{value:x,onValueChange:b,min:0,max:100,step:5,"aria-label":"Input bar offset in pixels"}),e.jsx(Ts,{type:"button",variant:"ghost",onClick:()=>b(0),disabled:x===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(Ls,{className:"h-3.5 w-3.5"})})]})]}),C("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:mm.find(j=>j.value===c)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:mm.map(j=>e.jsx(Ts,{variant:c===j.value?"default":"outline",className:L(c===j.value?void 0:"text-foreground"),onClick:()=>d(j.value),children:j.label},j.value))})]}),C("diffLayout")&&!r&&!zt()&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff layout (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose the default layout for file diffs. You can still override layout per file from the Diff tab."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:fm.map(j=>e.jsx(Ts,{variant:y===j.id?"default":"outline",className:L(y===j.id?void 0:"text-foreground"),onClick:()=>w(j.id),children:j.label},j.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:fm.find(j=>j.id===y)?.description})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff view (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose whether the Diff tab defaults to a single file or all files."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:pm.map(j=>e.jsx(Ts,{variant:S===j.id?"default":"outline",className:L(S===j.id?void 0:"text-foreground"),onClick:()=>M(j.id),children:j.label},j.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:pm.find(j=>j.id===S)?.description})]})]}),C("dotfiles")&&!zt()&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Hidden files (Chat)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Show or hide dotfiles in file lists and directory pickers."})]}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx("div",{className:"flex gap-1 w-fit",children:[{id:"hide",label:"Hide",value:!1},{id:"show",label:"Show",value:!0}].map(j=>e.jsx(Ts,{variant:s===j.value?"default":"outline",className:L(s===j.value?void 0:"text-foreground"),onClick:()=>gc(j.value),children:j.label},j.id))})})]}),C("reasoning")&&e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:n,onChange:j=>o(j.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),C("textJustificationActivity")&&e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:a,onChange:j=>l(j.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show text justification in activity"})]}),C("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:N,onChange:j=>v(j.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Queue messages by default"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5",children:N?`Enter queues messages, ${Xt()}+Enter sends immediately.`:`Enter sends immediately, ${Xt()}+Enter queues messages.`})]})]})},hm="https://github.com/btriapitsyn/openchamber",Zk=800,fh=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),o=hi(),{isMobile:a}=qt(),l=o.info?.currentVersion||"unknown",c=i.useRef(!1);i.useEffect(()=>{if(o.checking)n(!0),c.current=!0;else if(s){const u=setTimeout(()=>{n(!1),c.current&&!o.available&&!o.error&&(U.success("You are on the latest version"),c.current=!1)},Zk);return()=>clearTimeout(u)}},[o.checking,s,o.available,o.error]);const d=o.checking||s;return a?e.jsxs("div",{className:"w-full space-y-2",children:[e.jsxs("button",{onClick:()=>Do(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ls,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["v",l]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:L("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(Zr,{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:hm,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Kr,{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(ff,{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(El,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Ul,{open:t,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]}):e.jsxs("div",{className:"w-full space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"About OpenChamber"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Version"}),e.jsx("div",{className:"typography-ui-header font-mono",children:l})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Na,{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:L("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(Zr,{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:L("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:hm,target:"_blank",rel:"noopener noreferrer",className:L("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Kr,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:L("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(El,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Ul,{open:t,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]})},eC=1440*60*1e3,ph=5,gm=1440*60*1e3,fl=t=>t.time?.updated??t.time?.created??0,xm=({sessions:t,currentSessionId:r,cutoffDays:s,keepRecent:n=ph,now:o=Date.now()})=>{if(!Array.isArray(t)||s<=0)return[];const a=o-s*eC,l=[...t].sort((d,u)=>fl(u)-fl(d)),c=new Set(l.slice(0,n).map(d=>d.id));return l.filter(d=>{if(!d?.id||c.has(d.id)||d.id===r||d.share)return!1;const u=fl(d);return u?u<a:!1}).map(d=>d.id)},hh=t=>{const r=t?.autoRun!==!1,s=be(x=>x.sessions),n=be(x=>x.currentSessionId),o=be(x=>x.isLoading),a=be(x=>x.deleteSessions),l=Me(x=>x.autoDeleteEnabled),c=Me(x=>x.autoDeleteAfterDays),d=Me(x=>x.autoDeleteLastRunAt),u=Me(x=>x.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),h=i.useMemo(()=>c<=0?[]:xm({sessions:s,currentSessionId:n,cutoffDays:c}),[c,n,s]),g=i.useCallback(async({force:x=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!l||c<=0)&&!x)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const b=Date.now();if(!x&&d&&b-d<gm)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(s.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const y=xm({sessions:s,currentSessionId:n,cutoffDays:c,now:b});if(y.length===0)return u(b),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(y,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[c,l,d,n,a,o,s,u]);return i.useEffect(()=>{if(!r||!l||c<=0||o||s.length===0)return;const x=Date.now();d&&x-d<gm||g()},[c,l,d,r,o,s.length,g]),{candidates:h,isRunning:m,runCleanup:g,keepRecentCount:ph}},pl=1,hl=365,gh=()=>{const{isMobile:t}=qt(),r=Me(p=>p.autoDeleteEnabled),s=Me(p=>p.autoDeleteAfterDays),n=Me(p=>p.setAutoDeleteEnabled),o=Me(p=>p.setAutoDeleteAfterDays),[a,l]=i.useState(String(s));i.useEffect(()=>{l(String(s))},[s]);const{candidates:c,isRunning:d,runCleanup:u}=hh({autoRun:!1}),m=c.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){U.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&U.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&U.error(`Failed to delete ${p.failedIds.length} session${p.failedIds.length===1?"":"s"}`)},[u]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session retention"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["Automatically delete inactive sessions based on their last activity.",e.jsx("br",{}),"You can also run a one-time cleanup without enabling auto-cleanup.",e.jsx("br",{}),"Keeps the most recent 5 sessions, and never deletes shared sessions."]})]})]})}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:r,onChange:p=>n(p.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Enable auto-cleanup"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[t?e.jsx("input",{type:"number",inputMode:"numeric",value:a,onChange:p=>{const h=p.target.value;if(l(h),h.trim()==="")return;const g=Number(h);if(!Number.isFinite(g))return;const x=Math.min(hl,Math.max(pl,Math.round(g)));o(x)},onBlur:()=>{if(a.trim()===""){l(String(s));return}const p=Number(a);if(!Number.isFinite(p)){l(String(s));return}const h=Math.min(hl,Math.max(pl,Math.round(p)));o(h),l(String(h))},"aria-label":"Retention period in days",className:"h-8 w-16 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(gn,{value:s,onValueChange:o,min:pl,max:hl,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(Ts,{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]})]})},tC=10,sC=500,rC=20,nC=500,oC=30,aC=1e3,iC=()=>{const{isMobile:t}=qt(),r=Me(h=>h.memoryLimitHistorical),s=Me(h=>h.memoryLimitViewport),n=Me(h=>h.memoryLimitActiveSession),o=Me(h=>h.setMemoryLimitHistorical),a=Me(h=>h.setMemoryLimitViewport),l=Me(h=>h.setMemoryLimitActiveSession),[c,d]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let g=null;if(ms())g=await Br();else{const x=Ps()?.settings;if(x)try{const y=(await x.load())?.settings;y&&(g={memoryLimitHistorical:typeof y.memoryLimitHistorical=="number"?y.memoryLimitHistorical:void 0,memoryLimitViewport:typeof y.memoryLimitViewport=="number"?y.memoryLimitViewport:void 0,memoryLimitActiveSession:typeof y.memoryLimitActiveSession=="number"?y.memoryLimitActiveSession:void 0})}catch{}if(!g){const b=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});b.ok&&(g=await b.json())}}g&&(typeof g.memoryLimitHistorical=="number"&&o(g.memoryLimitHistorical),typeof g.memoryLimitViewport=="number"&&a(g.memoryLimitViewport),typeof g.memoryLimitActiveSession=="number"&&l(g.memoryLimitActiveSession))}catch(g){console.warn("Failed to load memory limits settings:",g)}finally{d(!1)}})()},[o,a,l]);const u=i.useCallback(async(h,g)=>{try{if(await cs({[h]:g}),!ms()){const x=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({[h]:g})});x.ok||console.warn(`Failed to save ${h} to server:`,x.status,x.statusText)}}catch(x){console.warn(`Failed to save ${h}:`,x)}},[]),m=i.useCallback(h=>{o(h),u("memoryLimitHistorical",h)},[o,u]),f=i.useCallback(h=>{a(h),u("memoryLimitViewport",h)},[a,u]),p=i.useCallback(h=>{l(h),u("memoryLimitActiveSession",h)},[l,u]);return c?null:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Message Memory"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["Control how many messages are kept in memory for performance optimization.",e.jsx("br",{}),"Lower values use less memory but may require reloading older messages."]})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(gl,{label:"Initial load limit",description:"Messages loaded when opening a session",value:r,defaultValue:hn.HISTORICAL_MESSAGES,min:tC,max:sC,onChange:m,isMobile:t}),e.jsx(gl,{label:"Background trim limit",description:"Max messages kept when switching away",value:s,defaultValue:hn.VIEWPORT_MESSAGES,min:rC,max:nC,onChange:f,isMobile:t}),e.jsx(gl,{label:"Active session limit",description:"Max messages for active session",value:n,defaultValue:Ol,min:oC,max:aC,onChange:p,isMobile:t})]})]})},gl=({label:t,description:r,value:s,defaultValue:n,min:o,max:a,onChange:l,isMobile:c})=>{const[d,u]=i.useState(String(s));i.useEffect(()=>{u(String(s))},[s]);const m=i.useCallback(h=>{const g=h.target.value;if(u(g),g.trim()==="")return;const x=Number(g);if(!Number.isFinite(x))return;const b=Math.min(a,Math.max(o,Math.round(x)));l(b)},[o,a,l]),f=i.useCallback(()=>{if(d.trim()===""){u(String(s));return}const h=Number(d);if(!Number.isFinite(h)){u(String(s));return}const g=Math.min(a,Math.max(o,Math.round(h)));l(g),u(String(g))},[d,s,o,a,l]),p=s===n;return e.jsx("div",{className:"flex flex-col gap-1",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:t}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:r})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!p&&e.jsxs("span",{className:"typography-meta text-muted-foreground/60",children:["(default: ",n,")"]}),c?e.jsx("input",{type:"number",inputMode:"numeric",value:d,onChange:m,onBlur:f,"aria-label":t,className:"h-8 w-20 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(gn,{value:s,onValueChange:l,min:o,max:a,step:10,"aria-label":t})]})]})})},ym="opencode",bm="big-pickle",lC=(t,r)=>{if(t){const o=t.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(r.find(o=>o.id===ym)?.models.some(o=>o.id===bm))return{providerId:ym,modelId:bm};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},xh=()=>{const t=Ze(T=>T.setProvider),r=Ze(T=>T.setModel),s=Ze(T=>T.setAgent),n=Ze(T=>T.setCurrentVariant),o=Ze(T=>T.setSettingsDefaultModel),a=Ze(T=>T.setSettingsDefaultVariant),l=Ze(T=>T.setSettingsDefaultAgent),c=Ze(T=>T.settingsAutoCreateWorktree),d=Ze(T=>T.setSettingsAutoCreateWorktree),u=Ze(T=>T.providers),[m,f]=i.useState(),[p,h]=i.useState(),[g,x]=i.useState(),[b,y]=i.useState(!0),w=i.useMemo(()=>lC(m,u),[m,u]),S=i.useMemo(()=>zt(),[]);i.useEffect(()=>{(async()=>{try{let I=null;if(ms())I=await Br();else{const P=Ps()?.settings;if(P)try{const E=(await P.load())?.settings;E&&(I={defaultModel:typeof E.defaultModel=="string"?E.defaultModel:void 0,defaultVariant:typeof E.defaultVariant=="string"?E.defaultVariant:void 0,defaultAgent:typeof E.defaultAgent=="string"?E.defaultAgent:void 0})}catch{}if(!I){const D=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});D.ok&&(I=await D.json())}}if(I){const P=typeof I.defaultModel=="string"&&I.defaultModel.trim().length>0?I.defaultModel.trim():void 0,D=typeof I.defaultVariant=="string"&&I.defaultVariant.trim().length>0?I.defaultVariant.trim():void 0,E=typeof I.defaultAgent=="string"&&I.defaultAgent.trim().length>0?I.defaultAgent.trim():void 0;P!==void 0&&f(P),D!==void 0&&h(D),E!==void 0&&x(E)}}catch(I){console.warn("Failed to load defaults settings:",I)}finally{y(!1)}})()},[]);const M=i.useCallback(async(T,I)=>{const P=T&&I?`${T}/${I}`:void 0;f(P),h(void 0),a(void 0),n(void 0),o(P),T&&I&&u.find(E=>E.id===T)&&(t(T),r(I));try{if(await cs({defaultModel:P??"",defaultVariant:""}),!ms()){const D=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:P})});D.ok||console.warn("Failed to save default model to server:",D.status,D.statusText)}}catch(D){console.warn("Failed to save default model:",D)}},[u,n,t,r,o,a]),N="__default__",v=i.useCallback(async T=>{const I=T===N?void 0:T||void 0;h(I),a(I),n(I);try{await cs({defaultVariant:I??""})}catch(P){console.warn("Failed to save default variant:",P)}},[n,a]),A=i.useCallback(async T=>{const I=T||void 0;x(I),l(I),T&&s(T);try{await cs({defaultAgent:I??""})}catch(P){console.warn("Failed to save default agent:",P)}},[s,l]),k=i.useMemo(()=>{if(!w.providerId||!w.modelId)return[];const P=u.find(D=>D.id===w.providerId)?.models.find(D=>D.id===w.modelId)?.variants;return P?Object.keys(P):[]},[w.modelId,w.providerId,u]),C=k.length>0;i.useEffect(()=>{!C&&p&&(h(void 0),a(void 0),n(void 0),cs({defaultVariant:""}).catch(()=>{}))},[p,n,a,C]);const j=i.useCallback(async T=>{const I=T.target.checked;d(I);try{await cs({autoCreateWorktree:I})}catch(P){console.warn("Failed to save auto create worktree setting:",P)}},[d]);return b?null:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session Defaults"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ct,{sideOffset:8,className:"max-w-xs",children:"Configure default behaviors for new sessions."})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default model"}),e.jsx(Bc,{providerId:w.providerId,modelId:w.modelId,onChange:M})]}),C&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default thinking"}),e.jsxs(As,{value:p??N,onValueChange:v,children:[e.jsx(Es,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(kn,{placeholder:"Thinking"})}),e.jsxs(Is,{children:[e.jsx(Bt,{value:N,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),k.map(T=>e.jsx(Bt,{value:T,className:"pr-2 [&>span:first-child]:hidden",children:T},T))]})]})]}),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(uh,{agentName:g||"",onChange:A})]})]}),(w.providerId||g)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",w.providerId&&e.jsxs("span",{className:"text-foreground",children:[w.providerId,"/",w.modelId,C?` (${p??"default"})`:""]}),w.providerId&&g&&" / ",g&&e.jsx("span",{className:"text-foreground",children:g})]}),!S&&e.jsxs("div",{className:"pt-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:c,onChange:j}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Always create worktree for new sessions"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5 mt-1",children:c?`New session (Worktree): ${Xt()} + N • New session (Standard): Shift + ${Xt()} + N`:`New session (Standard): ${Xt()} + N • New session (Worktree): Shift + ${Xt()} + N`})]})]})},cC=()=>{const t=Ze(l=>l.settingsGitmojiEnabled),r=Ze(l=>l.setSettingsGitmojiEnabled),s=xi(),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let c=null;if(ms())c=await Br();else{const d=Ps()?.settings;if(d)try{const m=(await d.load())?.settings;m&&(c={gitmojiEnabled:typeof m.gitmojiEnabled=="boolean"?m.gitmojiEnabled:void 0})}catch{}if(!c){const u=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});u.ok&&(c=await u.json())}}c&&typeof c.gitmojiEnabled=="boolean"&&r(c.gitmojiEnabled)}catch(c){console.warn("Failed to load git settings:",c)}finally{o(!1)}})()},[r]);const a=i.useCallback(async l=>{const c=l.target.checked;r(c);try{await cs({gitmojiEnabled:c})}catch(d){console.warn("Failed to save gitmoji setting:",d)}},[r]);return n?null:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit Messages"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ct,{sideOffset:8,className:"max-w-xs",children:"Configure how commit messages are generated."})]})]})}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:t,onChange:a}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Enable gitmoji picker"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5",children:"Adds a gitmoji selector to the Git commit message input."})]})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Files Overview"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Show gitignored files in the Files browser pane only."})]}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:s,onChange:l=>bf(l.target.checked)}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Display gitignored files"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5",children:"Toggles gitignored files in the Files tree and search results."})]})})]})},dC=()=>{const t=Ft(O=>O.getActiveProject()),r=Ft(O=>O.updateWorktreeDefaults),s=t?.path??null,n=t?.worktreeDefaults,o=tp(s),{sessions:a,getWorktreeMetadata:l}=be(),c=xt(O=>O.homeDirectory),[d,u]=i.useState(n?.baseBranch??"HEAD"),[m,f]=i.useState([]),[p,h]=i.useState(!1),[g,x]=i.useState(!1),[b,y]=i.useState(null),[w,S]=i.useState(null),[M,N]=i.useState([]),[v,A]=i.useState(!1),k=i.useMemo(()=>!t?.id||!s?null:{id:t.id,path:s},[t?.id,s]),C=i.useCallback(async()=>{if(!(!k||b===!1))try{const O=await _o(k);N(O)}catch{}},[k,b]);i.useEffect(()=>{if(!s)return;let O=!1;return x(!0),y(null),S(null),(async()=>{try{const G=await zr(s);if(O||(y(G),!G))return;const K=await wc(s);if(O)return;S({all:K.all,current:K.current})}catch{}finally{O||x(!1)}})(),()=>{O=!0}},[s]),i.useEffect(()=>{if(!k){N([]),A(!1);return}if(b===!1){N([]),A(!1);return}let O=!1;return A(!0),N([]),(async()=>{try{const G=await _o(k);if(O)return;N(G)}catch{}finally{O||A(!1)}})(),()=>{O=!0}},[k,b]),i.useEffect(()=>{if(!k)return;let O=!1;return h(!0),(async()=>{try{const G=await ho(k);O||f(G.length>0?G:[""])}catch{O||f([""])}finally{O||h(!1)}})(),()=>{O=!0}},[k]),i.useEffect(()=>{u(n?.baseBranch??"HEAD")},[n]);const j=w??o,T=i.useMemo(()=>{const O=[],G=j?.current?`Current (HEAD: ${j.current})`:"Current (HEAD)";return O.push({value:"HEAD",label:G,group:"special"}),j&&(j.all.filter($=>!$.startsWith("remotes/")).sort(($,W)=>$.localeCompare(W)).forEach($=>{O.push({value:$,label:$,group:"local"})}),j.all.filter($=>$.startsWith("remotes/")).map($=>$.replace(/^remotes\//,"")).sort(($,W)=>$.localeCompare(W)).forEach($=>{O.push({value:$,label:$,group:"remote"})})),O},[j]),I=i.useCallback(O=>{u(O),t?.id&&r(t.id,{baseBranch:O})},[t?.id,r]),P=i.useCallback((O,G)=>{f(K=>{const q=[...K];return q[O]=G,q})},[]),D=i.useCallback(()=>{f(O=>[...O,""])},[]),E=i.useCallback(async O=>{if(!k)return;const G=O.filter(K=>K.trim().length>0);await Wf(k,G)},[k]),F=i.useCallback(O=>{f(G=>{const K=G.filter((q,$)=>$!==O);return E(K),K.length>0?K:[""]})},[E]),B=i.useCallback(()=>{E(m)},[E,m]),V=i.useCallback(O=>{const G=O.path.replace(/\\/g,"/").replace(/\/+$/,""),K=a.filter(Z=>{if(l(Z.id)?.path===O.path)return!0;const R=Z.directory;return!!(R&&R.replace(/\\/g,"/").replace(/\/+$/,"")===G)}),q=new Set(K.map(Z=>Z.id)),$=Z=>{const z=a.filter(de=>{const we=de.parentID;return we&&Z.has(we)});if(z.length===0)return[];const R=new Set(z.map(de=>de.id));return[...z,...$(R)]},W=$(q),Y=new Set,X=[...K,...W].filter(Z=>Y.has(Z.id)?!1:(Y.add(Z.id),!0));no.requestDelete({sessions:X,mode:"worktree",worktree:O})},[a,l]),ne=i.useMemo(()=>a.map(O=>O.id).join(","),[a]);return i.useEffect(()=>{b&&s&&C()},[ne,b,s,C]),s?b===!1?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Worktree settings are only available for Git repositories."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Base branch"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ct,{sideOffset:8,className:"max-w-xs",children:"Default branch to create new worktrees from."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default branch for new worktree branches"})]}),g?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs(As,{value:d,onValueChange:I,children:[e.jsx(Es,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(kn,{placeholder:"Select a branch"})}),e.jsxs(Is,{children:[e.jsxs(bn,{children:[e.jsx(Yn,{children:"Default"}),T.filter(O=>O.group==="special").map(O=>e.jsx(Bt,{value:O.value,children:O.label},O.value))]}),T.some(O=>O.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(ni,{}),e.jsxs(bn,{children:[e.jsx(Yn,{children:"Local branches"}),T.filter(O=>O.group==="local").map(O=>e.jsx(Bt,{value:O.value,children:O.label},O.value))]})]}),T.some(O=>O.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(ni,{}),e.jsxs(bn,{children:[e.jsx(Yn,{children:"Remote branches"}),T.filter(O=>O.group==="remote").map(O=>e.jsx(Bt,{value:O.value,children:O.label},O.value))]})]})]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Setup commands"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Run automatically inside the new worktree directory when a worktree is created.",e.jsx("br",{}),"Use ",e.jsx("code",{className:"font-mono text-xs bg-sidebar-accent/50 px-1 rounded",children:"$ROOT_PROJECT_PATH"})," for the project root."]})]}),p?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[m.map((O,G)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(wt,{value:O,onChange:K=>P(G,K.target.value),onBlur:B,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{F(G)},className:"flex-shrink-0 flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(ss,{className:"h-4 w-4"})})]},G)),e.jsxs("button",{type:"button",onClick:D,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(us,{className:"h-3.5 w-3.5"}),"Add command"]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Existing worktrees"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["SDK worktrees live outside the repo (OpenCode-managed). Legacy ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})," worktrees are still supported. Deleting a worktree also removes linked sessions."]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Manage worktrees for this project"})]}),v?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):M.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"No worktrees found for this project"}):e.jsx("div",{className:"space-y-1",children:M.map(O=>e.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-sidebar-accent/30 transition-colors group",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("p",{className:"typography-meta text-foreground truncate min-w-0",children:O.label||O.branch||"Detached HEAD"}),e.jsx("span",{className:"typography-micro text-muted-foreground/60 px-1.5 py-[1px] rounded bg-sidebar-accent/40 flex-shrink-0 self-center leading-none",children:O.source==="sdk"?"OpenCode":"OpenChamber"})]}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:O.source==="sdk"?Yr(O.path,c):O.relativePath||O.path})]}),e.jsx("button",{type:"button",onClick:()=>V(O),className:"flex-shrink-0 flex h-7 w-7 items-center justify-center rounded text-muted-foreground/50 hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover:opacity-100 transition-opacity focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete worktree ${O.branch||O.label}`,children:e.jsx(zs,{className:"h-4 w-4"})})]},O.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},uC=()=>{const t=Me(v=>v.nativeNotificationsEnabled),r=Me(v=>v.setNativeNotificationsEnabled),s=Me(v=>v.notificationMode),n=Me(v=>v.setNotificationMode),[o,a]=i.useState("default"),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,f]=i.useState(!1);i.useEffect(()=>{typeof Notification<"u"&&a(Notification.permission);const v=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;c(v),(async()=>{if(!v){u(!1);return}try{const k=await navigator.serviceWorker.getRegistration();if(!k){u(!1);return}const C=await k.pushManager.getSubscription();u(!!C)}catch{u(!1)}})()},[]);const p=async v=>{if(v&&typeof Notification<"u"&&Notification.permission==="default")try{const A=await Notification.requestPermission();a(A),A==="granted"?r(!0):U.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(A){console.error("Failed to request notification permission:",A),U.error("Failed to request notification permission")}else r(!!(v&&o==="granted"))},h=typeof Notification<"u"&&Notification.permission==="granted",g=v=>{const A="=".repeat((4-v.length%4)%4),k=(v+A).replace(/-/g,"+").replace(/_/g,"/"),C=atob(k),j=new Uint8Array(C.length);for(let T=0;T<C.length;T+=1)j[T]=C.charCodeAt(T);return j},x=async(v,A,k)=>{let C=null;const j=new Promise((T,I)=>{C=setTimeout(()=>{I(new Error(k))},A)});try{return await Promise.race([v,j])}finally{C&&clearTimeout(C)}},b=async v=>{if(v.active)return;const A=v.installing||v.waiting;A&&A.state!=="activated"&&await x(new Promise(k=>{const C=()=>{A.state==="activated"&&(A.removeEventListener("statechange",C),k())};A.addEventListener("statechange",C),C()}),15e3,"Service worker activation timed out")},y=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const v=[{label:"no-options",opts:null},{label:"scope-root",opts:{scope:"/"}},{label:"type-classic",opts:{type:"classic"}},{label:"type-classic-scope",opts:{type:"classic",scope:"/"}},{label:"updateViaCache-none",opts:{type:"classic",updateViaCache:"none",scope:"/"}}];let A=null;for(const k of v)try{const C=k.opts?navigator.serviceWorker.register("/sw.js",k.opts):navigator.serviceWorker.register("/sw.js");return await x(C,1e4,`Service worker registration timed out (${k.label})`)}catch(C){A=C}throw A instanceof Error?A:new Error("Service worker registration failed")},w=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const v=await navigator.serviceWorker.getRegistration();if(v)return v;const A=await y();try{await A.update()}catch{}return await b(A),A},S=v=>{const A=v,k=[`type=${typeof v}`,`toString=${String(v)}`,`name=${String(A?.name??"")}`,`message=${String(A?.message??"")}`];let C="";try{C=JSON.stringify(v)}catch{}return{summary:k.filter(Boolean).join(" | "),json:C,stack:typeof A?.stack=="string"?A.stack:""}},M=async()=>{if(!l){U.error("Push notifications not supported");return}const v=Ps();if(!v?.push){U.error("Push API not available");return}f(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const D=await Notification.requestPermission();if(a(D),D!=="granted"){U.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){U.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}const A=await v.push.getVapidPublicKey();if(!A?.publicKey){U.error("Failed to load push key");return}const k=await w();await b(k);const C=await k.pushManager.getSubscription();if(!("pushManager"in k)||!k.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const T=(C??await x(k.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:g(A.publicKey)}),15e3,"Push subscription timed out")).toJSON(),I=T.keys;if(!T.endpoint||!I?.p256dh||!I.auth)throw new Error("Push subscription missing keys");if(!(await x(v.push.subscribe({endpoint:T.endpoint,keys:{p256dh:I.p256dh,auth:I.auth},origin:typeof window<"u"?window.location.origin:void 0}),15e3,"Push subscribe request timed out"))?.ok){U.error("Failed to enable background notifications");return}u(!0),U.success("Background notifications enabled")}catch(A){console.error("[Push] Enable failed:",A);const k=S(A);U.error("Failed to enable background notifications",{description:k.summary})}finally{f(!1)}},N=async()=>{if(!l){u(!1);return}const v=Ps();if(!v?.push){U.error("Push API not available");return}f(!0);try{const k=await(await w()).pushManager.getSubscription();if(!k){u(!1);return}const C=k.endpoint;await k.unsubscribe(),await v.push.unsubscribe({endpoint:C}),u(!1),U.success("Background notifications disabled")}finally{f(!1)}};return ur()?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Foreground Notifications"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Uses the browser Notification API while OpenChamber is open."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Enable foreground notifications"}),e.jsx(yn,{checked:t&&h,onCheckedChange:p,className:"data-[state=checked]:bg-status-info"})]}),t&&h&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Notify even when visible"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"When off, only notifies when the tab is hidden or the window is not focused."})]}),e.jsx(yn,{checked:s==="always",onCheckedChange:v=>n(v?"always":"hidden-only"),className:"data-[state=checked]:bg-status-info"})]}),o==="denied"&&e.jsx("p",{className:"typography-micro text-destructive",children:"Notification permission denied. Enable notifications in your browser settings."}),o==="granted"&&!t&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Permission granted, but foreground notifications are disabled."}),e.jsxs("div",{className:"space-y-1 pt-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Background Notifications (Push)"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Uses push notifications; works when OpenChamber is closed."})]}),l?e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Desktop Chrome/Edge and Android support push in the browser. iOS requires an installed PWA."}):e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Push not supported in this browser."}),l&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Enable background notifications"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Opens chat with /?session=<id> deep link."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&e.jsx("div",{className:"text-muted-foreground",children:e.jsx(yp,{size:"sm"})}),e.jsx(yn,{checked:d,disabled:m,onCheckedChange:v=>{v?M():N()},className:"data-[state=checked]:bg-status-info"})]})]})]}):null},mC=()=>{const t=Ps()?.github,r=Bs(v=>v.status),s=Bs(v=>v.isLoading),n=Bs(v=>v.hasChecked),o=Bs(v=>v.refreshStatus),a=Bs(v=>v.setStatus),l=i.useCallback(async v=>{if(typeof window>"u")return;const A=window.opencodeDesktop;if(A?.openExternal)try{const k=await A.openExternal(v);if(k&&typeof k=="object"&&"success"in k&&k.success===!0)return}catch{}try{window.open(v,"_blank","noopener,noreferrer")}catch{}},[]),[c,d]=i.useState(!1),[u,m]=i.useState(null),[f,p]=i.useState(null),h=i.useRef(null),g=i.useCallback(()=>{h.current!=null&&(window.clearInterval(h.current),h.current=null),p(null)},[]);i.useEffect(()=>((async()=>{try{n||await o(t)}catch(v){console.warn("Failed to load GitHub auth status:",v)}})(),()=>{g()}),[n,o,t,g]);const x=i.useCallback(async()=>{d(!0);try{const v=t?await t.authStart():await(async()=>{const k=await fetch("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),C=await k.json().catch(()=>null);if(!k.ok||!C||!("deviceCode"in C))throw new Error(C?.error||k.statusText);return C})();m(v),p(Math.max(1,v.interval)*1e3);const A=v.verificationUriComplete||v.verificationUri;l(A)}catch(v){console.error("Failed to start GitHub connect:",v),Qs.error("Failed to start GitHub connect")}finally{d(!1)}},[l,t]),b=i.useCallback(async v=>{if(t)return t.authComplete(v);const A=await fetch("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:v})}),k=await A.json().catch(()=>null);if(!A.ok||!k)throw new Error(k?.error||A.statusText);return k},[t]);i.useEffect(()=>{if(!(!u?.deviceCode||!f)&&h.current==null)return h.current=window.setInterval(()=>{(async()=>{try{const v=await b(u.deviceCode);if(v.connected){Qs.success("GitHub connected"),m(null),g(),await o(t,{force:!0});return}v.status==="slow_down"&&p(A=>A?A+5e3:5e3),(v.status==="expired_token"||v.status==="access_denied")&&(Qs.error(v.error||"GitHub authorization failed"),m(null),g())}catch(v){console.warn("GitHub polling failed:",v)}})()},f),()=>{h.current!=null&&(window.clearInterval(h.current),h.current=null)}},[u,f,b,o,t,g]);const y=i.useCallback(async()=>{d(!0);try{if(g(),m(null),t)await t.authDisconnect();else{const v=await fetch("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}});if(!v.ok)throw new Error(v.statusText)}Qs.success("GitHub disconnected"),await o(t,{force:!0})}catch(v){console.error("Failed to disconnect GitHub:",v),Qs.error("Failed to disconnect GitHub")}finally{d(!1)}},[o,t,g]),w=i.useCallback(async v=>{if(v){d(!0);try{const A=t?await t.authActivate(v):await(async()=>{const k=await fetch("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:v})}),C=await k.json().catch(()=>null);if(!k.ok||!C)throw new Error(C?.error||k.statusText);return C})();a(A),Qs.success("GitHub account switched")}catch(A){console.error("Failed to switch GitHub account:",A),Qs.error("Failed to switch GitHub account")}finally{d(!1)}}},[t,a]);if(s)return null;const S=!!r?.connected,M=r?.user,N=r?.accounts??[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"GitHub"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Connect a GitHub account for in-app PR and issue workflows."})]}),S?e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border bg-background/50 px-4 py-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-4",children:[M?.avatarUrl?e.jsx("img",{src:M.avatarUrl,alt:M.login?`${M.login} avatar`:"GitHub avatar",className:"h-14 w-14 shrink-0 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-14 w-14 shrink-0 rounded-full border border-border/60 bg-muted"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-header font-semibold text-foreground truncate",children:M?.name?.trim()||M?.login||"GitHub"}),M?.email?e.jsx("div",{className:"typography-body text-muted-foreground truncate",children:M.email}):null,e.jsxs("div",{className:"mt-1 flex items-center gap-2 typography-meta text-muted-foreground truncate",children:[e.jsx(Kr,{className:"h-4 w-4"}),e.jsx("span",{className:"font-mono",children:M?.login||"unknown"})]}),r?.scope?e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:["Scopes: ",r.scope]}):null]})]}),e.jsx(je,{variant:"outline",onClick:y,disabled:c,children:"Disconnect"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-background/50 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Not connected"}),e.jsx(je,{onClick:x,disabled:c,children:"Connect"})]}),S?e.jsx("div",{className:"flex justify-end",children:e.jsx(je,{variant:"ghost",onClick:x,disabled:c,children:"Add account"})}):null,N.length>1?e.jsxs("div",{className:"space-y-2 rounded-lg border bg-background/50 p-3",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Accounts"}),e.jsx("div",{className:"space-y-2",children:N.map(v=>{const A=v.user,k=!!v.current;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-border/40 bg-background/70 px-3 py-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[A?.avatarUrl?e.jsx("img",{src:A.avatarUrl,alt:A.login?`${A.login} avatar`:"GitHub avatar",className:"h-8 w-8 shrink-0 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/60 bg-muted",children:e.jsx(Kr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground truncate",children:A?.name?.trim()||A?.login||"GitHub"}),A?.login?e.jsx("div",{className:"typography-micro text-muted-foreground truncate font-mono",children:A.login}):null]})]}),k?e.jsx("span",{className:"typography-micro text-primary",children:"Active"}):e.jsx(je,{size:"sm",variant:"ghost",onClick:()=>w(v.id),disabled:c,children:"Use"})]},v.id)})})]}):null,u?e.jsxs("div",{className:"space-y-3 rounded-lg border bg-background/50 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Authorize OpenChamber"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:"In GitHub, enter this code:"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-mono text-lg tracking-widest text-foreground",children:u.userCode}),e.jsx(je,{variant:"outline",asChild:!0,children:e.jsx("a",{href:u.verificationUriComplete||u.verificationUri,target:"_blank",rel:"noopener noreferrer",children:"Open GitHub"})})]}),e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Waiting for approval… (auto-refresh)"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(je,{variant:"ghost",disabled:c,onClick:()=>{g(),m(null)},children:"Cancel"})})]}):null]})},fC=({section:t})=>{const{isMobile:r}=qt(),s=r&&ur();if(!t)return e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"openchamber-page-body mx-auto max-w-3xl space-y-3 p-3 sm:space-y-6 sm:p-6",children:[e.jsx(zc,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(xh,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gh,{})}),s&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(fh,{})})]})});const n=()=>{switch(t){case"visual":return e.jsx(pC,{});case"chat":return e.jsx(hC,{});case"sessions":return e.jsx(gC,{});case"git":return e.jsx(xC,{});case"github":return e.jsx(yC,{});case"notifications":return e.jsx(bC,{});default:return null}};return e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsx("div",{className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})})},pC=()=>e.jsx(zc,{visibleSettings:["theme","fontSize","spacing","cornerRadius","inputBarOffset"]}),hC=()=>e.jsx(zc,{visibleSettings:["toolOutput","diffLayout","dotfiles","reasoning","textJustificationActivity","queueMode"]}),gC=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(xh,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gh,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(iC,{})})]}),xC=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(cC,{}),e.jsxs("div",{className:"border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1 mb-4",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Worktree"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Configure worktree branch defaults and manage existing worktrees."})]}),e.jsx(dC,{})]})]}),yC=()=>zt()?null:e.jsx(mC,{}),bC=()=>e.jsx(uC,{}),wC=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]},{id:"git",label:"Git",items:["Commit Messages","Worktree"],hideInVSCode:!0},{id:"github",label:"GitHub",items:["Connect","PRs","Issues"],hideInVSCode:!0},{id:"notifications",label:"Notifications",items:["Native"],webOnly:!0}],vC=({selectedSection:t,onSelectSection:r})=>{const{isMobile:s}=qt(),n=s&&ur(),[o,a]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=i.useMemo(()=>zt(),[]),c=i.useMemo(()=>ur(),[]);i.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=i.useMemo(()=>wC.filter(m=>!(m.webOnly&&!c||m.hideInVSCode&&l)),[c,l]),u=o?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:L("flex h-full flex-col",u),children:[e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:d.map(m=>{const f=t===m.id;return e.jsx("div",{className:L("group relative rounded-md px-1.5 py-1 transition-all duration-200",f?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{onClick:()=>r(m.id),className:"w-full text-left flex flex-col gap-0 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"typography-ui-label font-normal text-foreground",children:m.label}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 leading-tight",children:m.items.join(" · ")})]})},m.id)})}),n&&e.jsx("div",{className:"border-t px-3 py-4",children:e.jsx(fh,{})})]})},jC=t=>{let r=dh.filter(o=>o.id!=="sessions");t&&(r=r.filter(o=>o.id!=="git-identities"));const s=r.find(o=>o.id==="settings"),n=r.filter(o=>o.id!=="settings");return s?[s,...n]:r},xl=200,yl=500,SC=264,NC=940,rc=({onClose:t,forceMobile:r})=>{const s=qt(),n=r??s.isMobile,o=Me(R=>R.sidebarSection),a=Me(R=>R.setSidebarSection),l=i.useMemo(()=>o!=="sessions"?o:"settings",[o]),c=i.useCallback(R=>{a(R)},[a]),[d,u]=i.useState("visual"),[m,f]=i.useState(!1),[p,h]=i.useState(()=>typeof window<"u"?Math.min(yl,Math.max(xl,Math.floor(window.innerWidth*.2))):SC),[g,x]=i.useState(!1),[b,y]=i.useState(!1),[w,S]=i.useState(0),M=i.useRef(null),N=i.useRef(0),v=i.useRef(p),[A,k]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),C=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),j=i.useMemo(()=>zt(),[]),T=i.useMemo(()=>jC(j),[j]);i.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{const R=M.current;if(!R)return;const de=new ResizeObserver(we=>{for(const xe of we)S(xe.contentRect.width)});return de.observe(R),S(R.clientWidth),()=>de.disconnect()},[]);const I=Ft(R=>R.projects),P=Ft(R=>R.activeProjectId),D=Ft(R=>R.setActiveProject),E=i.useMemo(()=>[...I].sort((R,de)=>(R.label||R.path).localeCompare(de.label||de.path)),[I]),F=i.useMemo(()=>E.length===0?null:E.find(R=>R.id===P)??E[0],[P,E]),B=i.useCallback(R=>R.replace(/[-_]/g," ").replace(/\b\w/g,de=>de.toUpperCase()),[]),V=i.useMemo(()=>{if(!F)return"Project";const R=F.label&&F.label.trim().length>0?F.label:F.path.split("/").filter(Boolean).pop()||F.path;return B(R)},[F,B]),ne=E.length>0&&!j,O=w===0||w>=NC;i.useEffect(()=>{if(l==="agents"){setTimeout(()=>{on.getState().loadAgents()},0);return}if(l==="commands"){setTimeout(()=>{nn.getState().loadCommands()},0);return}l==="skills"&&(mr.getState().loadSkills(),Go.getState().loadCatalog())},[P,l]),i.useEffect(()=>{if(typeof window>"u")return;const R=()=>{if(!g){const de=Math.min(yl,Math.max(xl,Math.floor(window.innerWidth*.2)));h(de)}};return window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[g]),i.useEffect(()=>{if(!b)return;const R=we=>{const xe=we.clientX-N.current,Pe=Math.min(yl,Math.max(xl,v.current+xe));h(Pe),x(!0)},de=()=>y(!1);return window.addEventListener("pointermove",R),window.addEventListener("pointerup",de,{once:!0}),()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",de)}},[b]);const G=R=>{y(!0),N.current=R.clientX,v.current=p,R.preventDefault()},K=i.useCallback(async R=>{if(!R.target.closest("button, a, input, select, textarea")&&R.button===0&&A)try{const{getCurrentWindow:de}=await js(async()=>{const{getCurrentWindow:xe}=await import("./vendor-.bun-Bui932eM.js").then(Pe=>Pe.dl);return{getCurrentWindow:xe}},__vite__mapDeps([0,1]));await de().startDragging()}catch(de){console.error("Failed to start window dragging:",de)}},[A]),q=i.useCallback(async R=>{if(R.button===0&&A)try{const{getCurrentWindow:de}=await js(async()=>{const{getCurrentWindow:xe}=await import("./vendor-.bun-Bui932eM.js").then(Pe=>Pe.dl);return{getCurrentWindow:xe}},__vite__mapDeps([0,1]));await de().startDragging()}catch(de){console.error("Failed to start window dragging:",de)}},[A]),$=i.useCallback(R=>{c(R),f(!1)},[c]),W=i.useCallback(()=>{n&&f(!0)},[n]),Y=()=>{switch(l){case"settings":return e.jsx(vC,{selectedSection:d,onSelectSection:R=>{u(R),W()}});case"agents":return e.jsx(xk,{onItemSelect:W});case"commands":return e.jsx(Ck,{onItemSelect:W});case"skills":return e.jsx(Dk,{onItemSelect:W});case"providers":return e.jsx($k,{onItemSelect:W});case"git-identities":return e.jsx(qk,{onItemSelect:W});default:return null}},X=()=>{switch(l){case"agents":return e.jsx(kk,{});case"commands":return e.jsx(Mk,{});case"skills":return e.jsx(Ok,{});case"providers":return e.jsx(Uk,{});case"git-identities":return e.jsx(Jk,{});case"settings":return e.jsx(fC,{section:d});default:return null}},Z=Xt(),z=i.useMemo(()=>A&&C?"pl-[5.75rem]":"",[A,C]);return e.jsxs("div",{ref:M,className:L("flex h-full flex-col overflow-hidden bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:K,className:L("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&z,A?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80"),style:{borderColor:"var(--interactive-border)"},children:[n&&m&&e.jsx("button",{type:"button",onClick:()=>f(!1),"aria-label":"Back",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(ac,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:L("flex items-center",n?"gap-1":"h-full"),children:e.jsx("div",{className:L("flex items-center gap-1",!n&&"p-1 bg-background/50 rounded-lg"),children:T.map(({id:R,label:de,icon:we})=>{const xe=l===R,Pe=we;return n?e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{onClick:()=>$(R),className:L("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",xe?"bg-secondary text-foreground shadow-sm":"text-muted-foreground"),"aria-pressed":xe,"aria-label":de,children:e.jsx(Pe,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(ct,{children:e.jsx("p",{children:de})})]},R):e.jsxs("button",{onClick:()=>$(R),onMouseDown:xe?q:void 0,className:L("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",xe?"app-region-drag bg-secondary text-foreground shadow-sm":"app-region-no-drag text-muted-foreground hover:bg-secondary/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-pressed":xe,"aria-label":de,children:[e.jsx(Pe,{className:"h-4 w-4",weight:"regular"}),O&&e.jsx("span",{children:de})]},R)})})}),(t||ne)&&e.jsxs("div",{className:L("flex items-center gap-2",n?"":"pr-3"),children:[ne&&e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:V,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(Mr,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:V,className:L("flex h-9 max-w-[18rem] items-center gap-1.5 bg-transparent px-2 text-foreground outline-none hover:text-foreground/80 focus-visible:ring-2 focus-visible:ring-ring",!n&&"app-region-no-drag"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:V}),e.jsx(Ut,{className:"size-4 opacity-50"})]})}),e.jsx(os,{align:"end",className:"w-auto",children:e.jsx(Va,{value:F?.id??"",onValueChange:R=>{R&&D(R)},children:E.map(R=>{const de=R.label?.trim()?R.label.trim():R.path.split("/").filter(Boolean).pop()||R.path,we=B(de);return e.jsx(Ga,{value:R.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:we})},R.id)})})})]}),t&&e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,"aria-label":"Close settings",className:L("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(ss,{className:"h-5 w-5"})})}),e.jsx(ct,{children:e.jsxs("p",{children:["Close Settings (",Z,"+,)"]})})]})]})]}),e.jsx("div",{className:"flex flex-1 overflow-hidden",children:n?m?e.jsx("div",{className:"flex-1 overflow-hidden bg-background","data-keyboard-avoid":"true",children:e.jsx(ls,{children:X()})}):e.jsx("div",{className:L("flex-1 overflow-hidden",j?"bg-background":"bg-sidebar"),children:e.jsx(ls,{children:Y()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:L("relative overflow-hidden border-r",A?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":j?"bg-background":"bg-sidebar",b?"transition-none":""),style:{width:`${p}px`,minWidth:`${p}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:L("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:G,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(ls,{children:Y()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(ls,{children:X()})})]})})]})},kC=()=>{const{isSidebarOpen:t,activeMainTab:r,setIsMobile:s,isSessionSwitcherOpen:n,isSettingsDialogOpen:o,setSettingsDialogOpen:a,isMultiRunLauncherOpen:l,setMultiRunLauncherOpen:c,multiRunLauncherPrefillPrompt:d}=Me(),{isMobile:u}=qt();Fj({enabled:!0});const m=hi(g=>g.checkForUpdates);i.useEffect(()=>{const g=setTimeout(()=>{m()},3e3);return()=>clearTimeout(g)},[m]),i.useEffect(()=>{Me.getState().isMobile!==u&&s(u)},[u,s]),i.useEffect(()=>{if(typeof window>"u")return;let g;const x=()=>{g!==void 0&&window.clearTimeout(g),g=window.setTimeout(()=>{Me.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",x),()=>{window.removeEventListener("resize",x),g!==void 0&&window.clearTimeout(g)}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const g=document.documentElement;let x=0,b=!1,y=0,w=null;const S=Me.getState().setKeyboardOpen,M=()=>{w&&(w.style.setProperty("--oc-keyboard-avoid-offset","0px"),w.removeAttribute("data-keyboard-avoid-active"),w=null)},N=T=>{if(!T)return null;const I=T.closest("[data-keyboard-avoid]");if(I)return I;if(T.classList.contains("overlay-scrollbar-container")){const P=T.parentElement;if(P instanceof HTMLElement)return P}return T},v=()=>{x=0,b=!0,g.style.setProperty("--oc-keyboard-inset","0px"),S(!1)},A=()=>{const T=window.visualViewport,I=T?Math.round(T.height):window.innerHeight,P=T?Math.max(0,Math.round(T.offsetTop)):0;g.style.setProperty("--oc-visual-viewport-offset-top",`${P}px`);const D=document.activeElement,E=D?.tagName,B=E==="INPUT"||E==="TEXTAREA"||E==="SELECT"||!!D?.isContentEditable,V=Math.round(g.clientHeight||window.innerHeight),ne=I+P,O=Math.max(0,V-ne),K=O>=(B?120:180)?O:0;if(b)K===0&&(b=!1),x=0;else if(x===0)K>0&&B&&(x=K);else{const Y=!B&&I>y+6;K===0?(x=0,S(!1)):Y?v():(K>0&&B||K>x)&&(x=K,S(!0))}g.style.setProperty("--oc-keyboard-inset",`${x}px`),y=I;const $=/iPad|iPhone|iPod/.test(navigator.userAgent)&&x>0?34:0;g.style.setProperty("--oc-keyboard-home-indicator",`${$}px`);const W=B?N(D):null;if(!u||!W||!D)M();else{W!==w&&(M(),w=W);const Y=P+I,Z=D.getBoundingClientRect().bottom-Y,z=8,R=Math.max(x,K),de=Z>z&&R>0?Math.min(Z,R):0,we=w;we&&(we.style.setProperty("--oc-keyboard-avoid-offset",`${de}px`),we.setAttribute("data-keyboard-avoid-active","true"))}if(u&&B){const Y=document.scrollingElement;Y&&Y.scrollTop!==0&&(Y.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};A();const k=window.visualViewport;k?.addEventListener("resize",A),k?.addEventListener("scroll",A),window.addEventListener("resize",A),window.addEventListener("orientationchange",A);const C=T=>{const I=T.target;if(!I)return;const P=I.tagName;(P==="INPUT"||P==="TEXTAREA"||P==="SELECT"||I.isContentEditable)&&(b=!1),A()};document.addEventListener("focusin",C,!0);const j=T=>{const I=T.target;if(!I)return;const P=I.tagName;if(P==="INPUT"||P==="TEXTAREA"||P==="SELECT"||I.isContentEditable){const E=T.relatedTarget,F=E?.tagName;if(F==="INPUT"||F==="TEXTAREA"||F==="SELECT"||E?.isContentEditable)return;v()}};return document.addEventListener("focusout",j,!0),()=>{k?.removeEventListener("resize",A),k?.removeEventListener("scroll",A),window.removeEventListener("resize",A),window.removeEventListener("orientationchange",A),document.removeEventListener("focusin",C,!0),document.removeEventListener("focusout",j,!0),M()}},[u]);const f=i.useMemo(()=>{switch(r){case"plan":return e.jsx(JS,{});case"git":return e.jsx(UN,{});case"diff":return e.jsx($v,{});case"terminal":return e.jsx(sk,{});case"files":return e.jsx(uk,{});default:return null}},[r]),p=r==="chat",h=o&&!u;return e.jsx(kj,{children:e.jsxs("div",{className:L("main-content-safe-area h-[100dvh]",u?"flex flex-col":"flex","bg-background"),children:[e.jsx(rj,{}),e.jsx(aj,{}),e.jsx(wj,{}),u?e.jsxs(e.Fragment,{children:[!(o||l)&&e.jsx(Yd,{}),e.jsx("div",{className:L("flex flex-1 overflow-hidden",(o||l)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:n?e.jsx("div",{className:"flex-1 overflow-hidden bg-sidebar",children:e.jsx(ls,{children:e.jsx(ri,{mobileVariant:!0})})}):e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:L("absolute inset-0",!p&&"invisible"),children:e.jsx(ls,{children:e.jsx(Io,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:f})})]})}),l&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(ls,{children:e.jsx(mu,{initialPrompt:d,onCreated:()=>c(!1),onCancel:()=>c(!1)})})}),o&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(ls,{children:e.jsx(rc,{onClose:()=>a(!1)})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:L("absolute inset-0 flex flex-col",(h||l)&&"invisible"),children:[e.jsx(Yd,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx(Xv,{isOpen:t,isMobile:u,children:e.jsx(ri,{})}),e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:L("absolute inset-0",!p&&"invisible"),children:e.jsx(ls,{children:e.jsx(Io,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:f})})]})]})]}),l&&e.jsx("div",{className:L("absolute inset-0 z-10 bg-background"),children:e.jsx(ls,{children:e.jsx(mu,{initialPrompt:d,onCreated:()=>c(!1),onCancel:()=>c(!1)})})})]}),h&&e.jsx("div",{className:L("absolute inset-0 z-10 bg-background"),children:e.jsx(ls,{children:e.jsx(rc,{onClose:()=>a(!1)})})})]})]})})},CC=550,MC=1400,DC=280,AC=()=>{const t=Hs(),r=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),s=i.useMemo(()=>{const P=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof P=="string"&&P.trim().length>0?P.trim():null},[]),n=i.useRef(!1),[o,a]=i.useState("sessions"),[l,c]=i.useState(0),d=i.useRef(null),u=be(P=>P.currentSessionId),m=be(P=>P.sessions),f=i.useMemo(()=>u?m.find(P=>P.id===u)?.title||"Session":null,[u,m]),p=be(P=>!!P.newSessionDraft?.open),h=be(P=>P.openNewSessionDraft),[g,x]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),b=Ze(P=>P.isInitialized),y=Ze(P=>P.initializeApp),w=be(P=>P.loadSessions),S=be(P=>P.loadMessages),M=be(P=>P.messages),[N,v]=i.useState(()=>b),[A,k]=i.useState(!1),C=i.useRef(0);i.useEffect(()=>{u&&a("chat")},[u]),i.useEffect(()=>{const P=t.vscode;P&&P.executeCommand("openchamber.setActiveSession",u,f)},[f,u,t.vscode]),i.useEffect(()=>{r!=="editor"&&!u&&!p&&o==="chat"&&a("sessions")},[u,p,o,r]);const j=i.useCallback(()=>{a("sessions")},[]);i.useEffect(()=>{const P=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(P==="connected"||P==="connecting"||P==="error"||P==="disconnected")&&x(P);const D=E=>{const B=E.detail?.status;(B==="connected"||B==="connecting"||B==="error"||B==="disconnected")&&x(B)};return window.addEventListener("openchamber:connection-status",D),()=>window.removeEventListener("openchamber:connection-status",D)},[]),i.useEffect(()=>{const P=D=>{const F=D.detail?.view;F==="settings"?a("settings"):F==="chat"?a("chat"):F==="sessions"&&a("sessions")};return window.addEventListener("openchamber:navigate",P),()=>window.removeEventListener("openchamber:navigate",P)},[]),i.useEffect(()=>{(async()=>{if(A||N||g!=="connected")return;const D=Date.now();if(!(D-C.current<750)){C.current=D,k(!0);try{const E=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();E&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:b}),b||await y();const F=Ze.getState();if(!F.isInitialized||!F.isConnected||F.providers.length===0||F.agents.length===0)return;await w();const B=be.getState().error;if(E&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:F.providers.length,agents:F.agents.length,sessions:be.getState().sessions.length,sessionsError:B}),typeof B=="string"&&B.length>0)return;v(!0)}catch{}finally{k(!1)}}})()},[g,b,N,y,A,w]),i.useEffect(()=>{if(r==="editor"&&!n.current&&!(!N||g!=="connected")){if(!s){n.current=!0,h();return}m.some(P=>P.id===s)&&(n.current=!0,be.getState().setCurrentSession(s))}},[g,N,s,h,m,r]),i.useEffect(()=>{(async()=>{if(!N||g!=="connected"||o!=="chat"||p||!u)return;if(!(M.has(u)&&(M.get(u)?.length||0)>0))try{await S(u)}catch{}})()},[g,u,o,N,S,M,p]),i.useEffect(()=>{const P=d.current;if(!P)return;const D=new ResizeObserver(E=>{for(const F of E)c(F.contentRect.width)});return D.observe(P),c(P.clientWidth),()=>D.disconnect()},[]);const T=l>0&&l<CC,I=l>=MC;return i.useEffect(()=>{I&&o==="sessions"&&r==="sidebar"&&a("chat")},[I,o,r]),e.jsx("div",{ref:d,className:"h-full w-full bg-background text-foreground flex flex-col",children:r==="editor"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(va,{title:m.find(P=>P.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{children:e.jsx(Io,{})})})]}):o==="settings"?e.jsx(rc,{onClose:()=>a(I?"chat":"sessions"),forceMobile:T}):I?e.jsxs("div",{className:"flex h-full",children:[e.jsx("div",{className:"h-full border-r border-border overflow-hidden flex-shrink-0",style:{width:DC},children:e.jsx(ri,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(va,{title:p&&!u?"New session":m.find(P=>P.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{children:e.jsx(Io,{})})})]})]}):o==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(va,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ri,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>a("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(va,{title:p&&!u?"New session":m.find(P=>P.id===u)?.title||"Chat",showBack:!0,onBack:j,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{children:e.jsx(Io,{})})})]})})},va=({title:t,showBack:r,onBack:s,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:l,showContextUsage:c})=>{const{getCurrentModel:d}=Ze(),u=be(x=>x.getContextUsage),m=d(),f=m?.limit&&typeof m.limit=="object"?m.limit:null,p=typeof f?.context=="number"?f.context:0,h=typeof f?.output=="number"?f.output:0,g=u(p,h);return e.jsxs("div",{className:"flex items-center gap-1.5 pl-1 pr-2 py-1 border-b border-border bg-background shrink-0",children:[r&&s&&e.jsx("button",{onClick:s,className:"inline-flex h-7 w-7 items-center justify-center text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:e.jsx(cf,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:t,children:t}),n&&e.jsx("button",{onClick:n,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"New session",children:e.jsx(us,{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(To,{className:"h-5 w-5"})}),l&&e.jsx(Wl,{headerIconButtonClass:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"}),o&&e.jsx("button",{onClick:o,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Settings",children:e.jsx(wn,{className:"h-5 w-5"})}),c&&g&&g.totalTokens>0&&e.jsx(Bl,{totalTokens:g.totalTokens,percentage:g.percentage,contextLimit:g.contextLimit,outputLimit:g.outputLimit??0,size:"compact"})]})},wm=".openchamber",ja=t=>{const r=Ft.getState(),s=r.activeProjectId,n=s?r.projects.find(o=>o.id===s)?.path:void 0;return typeof n=="string"&&n.trim().length>0?n:t?$t(t):null},$t=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},vm=t=>{const r=$t(t);return!r||r==="/"?`/${wm}`:`${r}/${wm}`},EC=(t,r)=>{const s=$t(t);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const l=$t(o);if(l)return l}const a=typeof n.name=="string"?n.name.trim():"";return!a||!s?null:`${s}/${a}`}).filter(n=>!!n)},IC=async t=>{const r=$t(t);if(!r)return[];try{const n=(await Oe.listLocalDirectory(r)).filter(o=>o.isDirectory);return EC(r,n)}catch{return[]}},jm=(t,r)=>{const s=$t(t),n=$t(r);if(!s||!n)return!1;if(s===n)return!0;const o=n==="/"?"/":`${n}/`;return s.startsWith(o)},yh=async(t,r)=>{const s=$t(r);if(!s)return s;try{const n=await t.path.get({directory:s});return $t(n.data?.directory??"")||s}catch{return s}},bh=async(t,r)=>{const s=$t(r);if(!s)return[];const n=await yh(t,s),o=l=>l.filter(c=>{const d=$t(c.directory??"");return d?jm(d,s)||n!==s&&jm(d,n):!1}),a=async l=>{const c=await t.session.list({directory:l});return Array.isArray(c.data)?c.data:[]};try{const l=o(await a(s));if(l.length>0)return l}catch{}if(n&&n!==s)try{const l=o(await a(n));if(l.length>0)return l}catch{}try{const l=await t.session.list(void 0),c=Array.isArray(l.data)?l.data:[];return o(c)}catch{return[]}},PC=async(t,r)=>{const s=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&s.set($t(o.path),o.worktreeMetadata)});const n=Array.from(new Set(t.sessions.map(o=>$t(o.path)))).filter(Boolean).filter(o=>!s.has(o));if(n.length===0)return s;try{const o=await vi(r),a=new Map(o.map(l=>[$t(l.worktree),l]));n.forEach(l=>{const c=a.get(l);c&&s.set(l,ji(r,c))})}catch{}return s},bl=async t=>{const{apiClient:r,group:s,projectDirectory:n,worktreePaths:o}=t,a=await PC(s,n),l=be.getState(),c=Array.from(new Set(o.map(p=>$t(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<c.length;){const p=c[u];u+=1;const h=s.sessions.filter(w=>$t(w.path)===p).map(w=>w.id),g=l.getSessionsByDirectory(p),x=Array.isArray(g)?g.map(w=>w.id):[];let b=[];if(x.length===0)try{b=(await bh(r,p)).map(S=>S.id)}catch{b=[]}const y=Array.from(new Set([...x,...b,...h].filter(Boolean)));m.push({worktreePath:p,sessionIds:y,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,c.length)},f)),m};function TC(t){if(!t)return null;const r=t.split("/");if(r.length<3)return null;const s=r[0];if(!s||s.includes(" "))return null;const n=r[1];if(!n)return null;const o=r[r.length-1],a=parseInt(o,10),l=r.length>=4&&!isNaN(a)&&String(a)===o,c=l?r.slice(2,-1):r.slice(2);if(c.length===0)return null;const d=c.join("/");return{groupSlug:s,provider:n,model:d,index:l?a:1}}const Jr=is()(hs((t,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const s=xt.getState().currentDirectory,n=ja(s);if(!n){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=$t(n),c={id:Ft.getState().projects.find(u=>$t(u.path)===o)?.id??`path:${o}`,path:o},d=r().groups;t({isLoading:!0,error:null});try{const u=Oe.getApiClient(),m=await yh(u,o),f=m&&m!==o?{...c,path:m}:null,p=await _o(c).catch(()=>[]),h=f?await _o(f).catch(()=>[]):[],g=new Set;[...p,...h].forEach(k=>{k?.path&&g.add($t(k.path))});let x=new Map,b=[];try{b=await vi(o),x=new Map(b.map(k=>[$t(k.worktree),k]))}catch{console.debug("Failed to list git worktrees")}const y=async()=>{try{const C=await u.session.list({directory:o}),j=Array.isArray(C.data)?C.data:[];if(j.some(T=>{const I=$t(T.directory??"");return I?g.has(I):!1}))return j}catch{}const k=await u.session.list(void 0);return Array.isArray(k.data)?k.data:[]},w=async k=>{const C=new Map,j=5;let T=0;const I=async()=>{for(;T<k.length;){const P=k[T];T+=1;const D=$t(P);if(D)try{(await bh(u,D)).forEach(F=>C.set(F.id,F))}catch(E){console.debug("Failed to fetch sessions from worktree:",D,E)}}};return await Promise.all(Array.from({length:Math.min(j,k.length)},I)),Array.from(C.values())};let M=(await y()).filter(k=>{const C=$t(k.directory??"");return C?g.has(C):!1});if(M.length===0){const k=new Set;g.forEach(j=>k.add(j)),b.map(j=>$t(j.worktree)).filter(Boolean).forEach(j=>k.add(j));const C=[vm(o),vm(m)].map(j=>$t(j)).filter(Boolean);await Promise.all(Array.from(new Set(C)).map(async j=>{(await IC(j)).forEach(I=>k.add(I))})),k.size>0&&(M=await w(Array.from(k)))}const N=new Map;for(const k of M){const C=k.time?.updated??0;N.set(k.id,typeof C=="number"?C:0)}const v=new Map;for(const k of M){const C=TC(k.title);if(!C)continue;const j=$t(k.directory),T=x.get(j),I={id:k.id,path:j,providerId:C.provider,modelId:C.model,instanceNumber:C.index,branch:T?.branch??"",displayLabel:`${C.provider}/${C.model}`,worktreeMetadata:T?ji(o,T):void 0},P=v.get(C.groupSlug);P?P.push(I):v.set(C.groupSlug,[I])}const A=Array.from(v.entries()).map(([k,C])=>{const j=C.reduce((T,I)=>{const P=N.get(I.id)??0;return Math.max(T,P)},0);return{name:k,sessions:C.sort((T,I)=>{const P=T.providerId.localeCompare(I.providerId);if(P!==0)return P;const D=T.modelId.localeCompare(I.modelId);return D!==0?D:T.instanceNumber-I.instanceNumber}),lastActive:j||Date.now(),sessionCount:C.length}});A.sort((k,C)=>k.name.localeCompare(C.name)),t({groups:A,isLoading:!1,error:null})}catch(u){console.error("Failed to load agent groups:",u),t({groups:d.length>0?d:[],isLoading:!1,error:u instanceof Error?u.message:"Failed to load agent groups"})}},selectGroup:s=>{const{groups:n}=r(),o=n.find(a=>a.name===s);t({selectedGroupName:s,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:s=>{t({selectedSessionId:s})},deleteGroup:async s=>{const n=r().groups.find(l=>l.name===s);if(!n)return!1;const o=xt.getState().currentDirectory,a=ja(o);if(!a)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const l=Oe.getApiClient(),c=await bl({apiClient:l,group:n,projectDirectory:$t(a),worktreePaths:n.sessions.map(f=>f.path)}),d=be.getState(),u=new Set;c.forEach(({worktreePath:f,sessionIds:p,metadata:h})=>{p.forEach(g=>{u.add(g),h&&(d.setWorktreeMetadata(g,h),d.setSessionDirectory(g,f))})});const{failedIds:m}=await d.deleteSessions(Array.from(u),{archiveWorktree:!0,silent:!0});return m.length>0&&t({error:"Failed to delete some sessions"}),r().selectedGroupName===s&&t({selectedGroupName:null,selectedSessionId:null}),await r().loadGroups(),m.length===0}catch(l){return t({error:l instanceof Error?l.message:"Failed to delete group"}),!1}finally{t({isLoading:!1})}},deleteGroupWorktree:async(s,n)=>{const o=r().groups.find(d=>d.name===s);if(!o)return!1;const a=$t(n);if(!a)return!1;const l=xt.getState().currentDirectory,c=ja(l);if(!c)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const d=Oe.getApiClient(),u=await bl({apiClient:d,group:o,projectDirectory:$t(c),worktreePaths:[a]}),m=be.getState(),f=new Set;u.forEach(({worktreePath:g,sessionIds:x,metadata:b})=>{x.forEach(y=>{f.add(y),b&&(m.setWorktreeMetadata(y,b),m.setSessionDirectory(y,g))})});const{failedIds:p}=await m.deleteSessions(Array.from(f),{archiveWorktree:!0,silent:!0});p.length>0&&t({error:"Failed to delete some sessions"}),await r().loadGroups();const h=r().groups.find(g=>g.name===s);if(!h)return r().selectedGroupName===s&&t({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===s){const g=r().selectedSessionId,x=new Set(h.sessions.map(b=>b.id));(!g||!x.has(g))&&t({selectedSessionId:h.sessions[0]?.id??null})}return p.length===0}catch(d){return t({error:d instanceof Error?d.message:"Failed to delete worktree"}),!1}finally{t({isLoading:!1})}},keepOnlyGroupWorktree:async(s,n)=>{const o=r().groups.find(m=>m.name===s);if(!o)return!1;const a=$t(n);if(!a)return!1;const c=Array.from(new Set(o.sessions.map(m=>$t(m.path)).filter(Boolean))).filter(m=>m!==a);if(c.length===0)return!0;const d=xt.getState().currentDirectory,u=ja(d);if(!u)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const m=Oe.getApiClient(),f=await bl({apiClient:m,group:o,projectDirectory:$t(u),worktreePaths:c}),p=be.getState(),h=new Set;f.forEach(({worktreePath:x,sessionIds:b,metadata:y})=>{b.forEach(w=>{h.add(w),y&&(p.setWorktreeMetadata(w,y),p.setSessionDirectory(w,x))})});const{failedIds:g}=await p.deleteSessions(Array.from(h),{archiveWorktree:!0,silent:!0});if(g.length>0&&t({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===s){const x=r().groups.find(y=>y.name===s),b=x?.sessions.find(y=>$t(y.path)===a)??x?.sessions[0]??null;t({selectedSessionId:b?.id??null})}return g.length===0}catch(m){return t({error:m instanceof Error?m.message:"Failed to remove other worktrees"}),!1}finally{t({isLoading:!1})}},getSelectedGroup:()=>{const{groups:s,selectedGroupName:n}=r();return n?s.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:s}=r(),n=r().getSelectedGroup();return!n||!s?null:n.sessions.find(o=>o.id===s)??null},clearError:()=>{t({error:null})}}),{name:"agent-groups-store"})),FC=t=>{const s=Date.now()-t,n=Math.floor(s/(60*1e3)),o=Math.floor(s/(3600*1e3)),a=Math.floor(s/(1440*60*1e3));return n<1?"now":n<60?`${n}m`:o<24?`${o}h`:`${a}d`},RC=({group:t,isSelected:r,onSelect:s})=>{const[n,o]=i.useState(!1),[a,l]=i.useState(!1),[c,d]=i.useState(!1),u=Jr(f=>f.deleteGroup),m=i.useCallback(async()=>{if(c)return;if(d(!0),U.info(`Deleting "${t.name}"...`),await u(t.name))U.success(`Deleted "${t.name}"`);else{const p=Jr.getState().error;U.error(p||`Failed to delete "${t.name}"`)}d(!1),l(!1)},[u,t.name,c]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1.5 cursor-pointer",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),onClick:s,children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col gap-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-micro text-muted-foreground/60 flex items-center gap-1",children:[e.jsx(Vt,{className:"h-3 w-3"}),t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:FC(t.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(rs,{open:n,onOpenChange:o,children:[e.jsx(ns,{asChild:!0,children:e.jsx("button",{type:"button",className:L("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","opacity-0 group-hover:opacity-100",n&&"opacity-100"),"aria-label":"Group menu",onClick:f=>f.stopPropagation(),children:e.jsx(sn,{className:"h-3.5 w-3.5"})})}),e.jsx(os,{align:"end",className:"min-w-[140px]",children:e.jsx(Nt,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),l(!0)},children:"Delete"})})]})})]})}),e.jsx(fs,{open:a,onOpenChange:l,children:e.jsxs(ps,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(bs,{children:[e.jsx(ws,{children:"Delete agent group"}),e.jsxs(Ns,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"outline",onClick:()=>l(!1),disabled:c,children:"Cancel"}),e.jsx(je,{variant:"destructive",onClick:()=>{m()},disabled:c,children:c?"Deleting…":"Delete"})]})]})})]})},LC=({className:t,selectedGroupName:r,onGroupSelect:s,onNewAgent:n})=>{const[o,a]=i.useState(""),[l,c]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Jr(),f=xt(b=>b.currentDirectory);i.useEffect(()=>{f&&m()},[f,m]);const p=5,h=i.useMemo(()=>{if(!o.trim())return d;const b=o.toLowerCase();return d.filter(y=>y.name.toLowerCase().includes(b))},[o,d]),g=l?h:h.slice(0,p),x=h.length-p;return e.jsxs("div",{className:L("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",t),children:[e.jsx("div",{className:"px-2.5 pt-3 pb-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Vs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(wt,{value:o,onChange:b=>a(b.target.value),placeholder:"Search Agent Groups...",className:"pl-8 h-8 rounded-lg border-border/40 bg-background/50 typography-meta"})]})}),e.jsx("div",{className:"px-2.5 pb-2",children:e.jsxs(je,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(us,{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(Ut,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium text-muted-foreground uppercase tracking-wider",children:"Agent Groups"}),u&&e.jsx("span",{className:"typography-micro text-muted-foreground/50 ml-auto",children:"Loading..."})]}),e.jsxs(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[g.map(b=>e.jsx(RC,{group:b,isSelected:r===b.name,onSelect:()=>s?.(b.name)},b.name)),!l&&x>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 (",x,")"]}),l&&h.length>p&&e.jsx("button",{type:"button",onClick:()=>c(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&h.length===0&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:o.trim()?"No groups found":"No agent groups yet"}),!o.trim()&&e.jsx("p",{className:"typography-micro text-muted-foreground/60 mt-1",children:"Create a new agent group to get started"})]})]})]})},OC=10*1024*1024,_C=5,$C=({className:t,onCreateGroup:r,isCreating:s=!1})=>{const[n,o]=i.useState(""),[a,l]=i.useState(""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState("HEAD"),[h,g]=i.useState([]),[x,b]=i.useState(!1),[y,w]=i.useState([]),[S,M]=i.useState(!1),[N,v]=i.useState(!1),A=i.useRef(null),k=i.useRef(null),C=xt(Y=>Y.currentDirectory??null),{isGitRepository:j,isLoading:T}=Rc(C),I=i.useMemo(()=>{if(typeof window>"u")return null;const Y=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof Y=="string"&&Y.trim().length>0?Y.trim():null},[]),P=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),D=Ft(Y=>Y.activeProjectId),E=Ft(Y=>Y.projects),F=i.useMemo(()=>{if(P&&I)return{id:`vscode:${I}`,path:I};if(D){const Y=E.find(X=>X.id===D);if(Y?.path)return{id:Y.id,path:Y.path}}return C?{id:`path:${C}`,path:C}:null},[D,E,C,I,P]);i.useEffect(()=>{if(!F)return;let Y=!1;return v(!0),(async()=>{try{const X=await ho(F);Y||w(X)}catch{}finally{Y||v(!1)}})(),()=>{Y=!0}},[F]);const B=i.useCallback(Y=>{c.length>=_C||d(X=>[...X,Y])},[c.length]),V=i.useCallback(Y=>{d(X=>X.filter((Z,z)=>z!==Y))},[]),ne=i.useCallback((Y,X)=>{d(Z=>Z.map((z,R)=>R===Y?X:z))},[]),O=async Y=>{const X=Y.target.files;if(!X)return;let Z=0;for(let z=0;z<X.length;z++){const R=X[z];if(R.size>OC){U.error(`File "${R.name}" is too large (max 10MB)`);continue}try{const de=await new Promise((xe,Pe)=>{const H=new FileReader;H.onload=()=>xe(H.result),H.onerror=Pe,H.readAsDataURL(R)}),we={id:oi(),filename:R.name,mimeType:R.type||"application/octet-stream",size:R.size,dataUrl:de};g(xe=>[...xe,we]),Z++}catch(de){console.error("File attach failed",de),U.error(`Failed to attach "${R.name}"`)}}Z>0&&U.success(`Attached ${Z} file${Z>1?"s":""}`),A.current&&(A.current.value="")},G=Y=>{g(X=>X.filter(Z=>Z.id!==Y))},K=x||s,q=!!(n.trim()&&a.trim()&&c.length>=1&&j&&!T),$=async Y=>{if(Y.preventDefault(),!(!q||K)){b(!0);try{const X=c.map(({providerID:R,modelID:de,displayName:we,variant:xe})=>({providerID:R,modelID:de,displayName:we,variant:xe})),Z=h.length>0?h.map(R=>({mime:R.mimeType,filename:R.filename,url:R.dataUrl})):void 0,z=y.filter(R=>R.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:X,agent:u||void 0,worktreeBaseBranch:f,files:Z,setupCommands:z.length>0?z:void 0}),o(""),l(""),d([]),m(""),g([]),p("HEAD")}catch(X){console.error("Failed to create agent group:",X),U.error("Failed to create agent group")}finally{b(!1)}}},W=Y=>{Tc(Y)||Y.key==="Enter"&&!Y.shiftKey&&(Y.preventDefault(),q&&!K&&$(Y))};return e.jsx("div",{className:L("flex flex-col items-center justify-center h-full w-full p-4",t),children:e.jsxs("form",{onSubmit:$,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(wt,{id:"group-name",value:n,onChange:Y=>o(Y.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(Vt,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(Np,{directory:C,value:f,onChange:p}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from ",e.jsx("code",{className:"font-mono text-xs",children:f})]})]}),e.jsxs(En,{open:S,onOpenChange:M,children:[e.jsxs(go,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",y.filter(Y=>Y.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",y.filter(Y=>Y.trim()).length," configured)"]})]}),e.jsx(Ut,{className:L("h-4 w-4 text-muted-foreground transition-transform duration-200",S&&"rotate-180")})]}),e.jsx(In,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_PROJECT_PATH"})," for project root."]}),N?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[y.map((Y,X)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(wt,{value:Y,onChange:Z=>{const z=[...y];z[X]=Z.target.value,w(z)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const Z=y.filter((z,R)=>R!==X);w(Z)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(ss,{className:"h-4 w-4"})})]},X)),e.jsxs("button",{type:"button",onClick:()=>w([...y,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(us,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(kp,{value:u,onChange:m}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Models"}),e.jsx(Sp,{selectedModels:c,onAdd:B,onRemove:V,onUpdate:ne,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(Fs,{ref:k,id:"prompt",value:a,onChange:Y=>l(Y.target.value),onKeyDown:W,placeholder:"Ask anything...",className:"min-h-[100px] max-h-[300px] resize-none border-0 bg-transparent px-4 py-3 typography-markdown focus-visible:ring-0 focus-visible:ring-offset-0"}),h.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:h.map(Y=>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:[Y.mimeType.startsWith("image/")?e.jsx(Dr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(vr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:Y.filename,children:Y.filename}),e.jsx("button",{type:"button",onClick:()=>G(Y.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(ss,{className:"h-3.5 w-3.5"})})]},Y.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:A,type:"file",multiple:!0,className:"hidden",onChange:O,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>A.current?.click(),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors","aria-label":"Add attachment",children:e.jsx(qm,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[c.length," model",c.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!q||K,className:L("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",q?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:K?e.jsx(Jx,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Uo,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},BC=({group:t,className:r})=>{const{selectedSessionId:s,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Jr(),{setCurrentSession:l,currentSessionId:c}=be(),[d,u]=i.useState(null),[m,f]=i.useState(!1),p=i.useMemo(()=>s?t.sessions.find(S=>S.id===s)??t.sessions[0]??null:t.sessions[0]??null,[t.sessions,s]),h=i.useCallback(S=>{n(S.id),l(S.id)},[n,l]);i.useEffect(()=>{if(t.sessions.length>0){const S=s?t.sessions.find(M=>M.id===s)??t.sessions[0]:t.sessions[0];S&&(S.id!==c&&l(S.id),s||n(S.id))}},[t.name,t.sessions,s,c,n,l]);const g=p?.id===c,x=i.useCallback(()=>{if(!p?.path){U.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{U.success("Worktree path copied")}).catch(()=>{U.error("Failed to copy path")})},[p?.path]),b=i.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),y=i.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),w=i.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(U.info("Removing worktree..."),await o(t.name,d.path))U.success("Worktree removed");else{const M=Jr.getState().error;U.error(M||"Failed to remove worktree");return}else if(U.info("Removing other worktrees..."),await a(t.name,d.path))U.success("Removed other worktrees");else{const M=Jr.getState().error;U.error(M||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,t.name,m,a,d]);return e.jsxs("div",{className:L("flex h-full flex-col bg-background",r),children:[e.jsxs("div",{className:"flex-shrink-0 border-b border-border/30 px-4 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"typography-heading-lg text-foreground truncate",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{children:"·"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vt,{className:"h-3.5 w-3.5"}),p?.worktreeMetadata?.label||p?.branch||"No branch"]})]})]})}),t.sessions.length>0&&e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsxs(je,{variant:"outline",className:"w-full justify-between h-10 px-3",children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:p&&e.jsxs(e.Fragment,{children:[e.jsx(ys,{providerId:p.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsx("span",{className:"truncate typography-body",children:p.modelId}),p.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",p.instanceNumber]})]})}),e.jsx(Ut,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(os,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:t.sessions.map(S=>e.jsxs(Nt,{onClick:()=>h(S),className:"flex items-center gap-2 py-2",children:[e.jsx(ys,{providerId:S.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate typography-body",children:S.modelId}),S.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",S.instanceNumber]})]}),S.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(Vt,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:S.worktreeMetadata?.label||S.branch})]})]}),p?.id===S.id&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},S.id))})]})}),e.jsxs(rs,{children:[e.jsx(ns,{asChild:!0,children:e.jsx(je,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(sn,{className:"h-4 w-4"})})}),e.jsxs(os,{align:"end",className:"min-w-[220px]",children:[e.jsx(Nt,{onSelect:S=>{S.preventDefault(),b()},variant:"destructive",children:"Remove this worktree"}),e.jsx(Nt,{onSelect:S=>{S.preventDefault(),y()},children:"Leave this one, remove others"}),e.jsxs(Nt,{onClick:S=>{S.stopPropagation(),x()},disabled:!p?.path,children:[e.jsx(rr,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(fs,{open:!!d,onOpenChange:S=>{S||u(null)},children:e.jsxs(ps,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(bs,{children:[e.jsx(ws,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(Ns,{children:d?.kind==="remove"?e.jsxs(e.Fragment,{children:["Remove ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label}),"? This deletes all sessions in that worktree and removes the worktree itself."]}):e.jsxs(e.Fragment,{children:["Keep ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label})," and remove the other worktrees in ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"."]})})]}),e.jsxs(Gs,{children:[e.jsx(je,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(je,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{w()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?g?e.jsx(Zp,{sessionId:p.id,children:e.jsx(Xp,{})}):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(ys,{providerId:p.providerId,className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel}),e.jsx("span",{children:"·"}),e.jsx("span",{className:"font-mono text-xs truncate",children:p.path})]})}),e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center p-8",children:[e.jsxs("p",{className:"typography-body text-muted-foreground mb-2",children:["Loading session for ",e.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground/60",children:["Session ID: ",p.id]})]})})]}):e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx("p",{className:"typography-body text-muted-foreground",children:"No sessions in this group"})})})]})},zC=({className:t})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[s,n]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=Ze(S=>S.isInitialized),a=Ze(S=>S.initializeApp),l=be(S=>S.loadSessions),c=xt(S=>S.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Jr(),{createMultiRun:h,isLoading:g}=Eo();i.useEffect(()=>{if(!r)return;const S=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(S==="connected"||S==="connecting"||S==="error"||S==="disconnected")&&n(S);const M=N=>{const A=N.detail?.status;(A==="connected"||A==="connecting"||A==="error"||A==="disconnected")&&n(A)};return window.addEventListener("openchamber:connection-status",M),()=>window.removeEventListener("openchamber:connection-status",M)},[r]),i.useEffect(()=>{if(!r||s!=="connected")return;const S=Date.now();if(S-d.current<750)return;d.current=S;const M=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof M=="string"&&M.trim().length>0)try{c(M,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const v=Ze.getState();if(!v.isInitialized||!v.isConnected||v.providers.length===0||v.agents.length===0)return;await l(),xs()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:v.providers.length,agents:v.agents.length,sessions:be.getState().sessions.length})}catch{}})()},[s,o,a,r,l,c]);const x=i.useCallback(S=>{m(S)},[m]),b=i.useCallback(()=>{m(null)},[m]),y=i.useCallback(async S=>{U.info(`Creating agent group "${S.name}" with ${S.models.length} model(s)...`);const M=await h(S);if(M){U.success(`Agent group "${S.name}" created with ${M.sessionIds.length} session(s)`);const N=M.groupSlug,v=async(A=6)=>{for(let k=0;k<A;k+=1){if(await p(),Jr.getState().groups.some(j=>j.name===N))return!0;await new Promise(j=>setTimeout(j,500))}return!1};try{await be.getState().loadSessions()}catch{}await v(),m(N)}else{const N=Eo.getState().error;U.error(N||"Failed to create agent group")}},[h,p,m]),w=f();return e.jsxs("div",{className:L("flex h-full w-full bg-background",t),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(LC,{selectedGroupName:u,onGroupSelect:x,onNewAgent:b})}),e.jsx("div",{className:"flex-1 min-w-0",children:w?e.jsx(BC,{group:w}):e.jsx($C,{onCreateGroup:y,isCreating:g})})]})},HC=(t=5e3)=>{const[r,s]=Ae.useState(null);return Ae.useEffect(()=>{if(!ms())return;let n=!1,o=null;const a=async()=>{const l=await by();n||(s(l),o=setTimeout(a,t))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[t]),r},WC=({onClose:t})=>{const{sessions:r,messages:s,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:l}=be(),c=HC(4e3),d=i.useMemo(()=>{let f=0;return s.forEach(p=>{f+=p.length}),f},[s]),u=i.useMemo(()=>r.map(f=>{const p=s.get(f.id)?.length||0,h=n.get(f.id);return{id:f.id,title:f.title||"Untitled",messageCount:p,isStreaming:h?.isStreaming||!1,isZombie:h?.isZombie||!1,backgroundCount:h?.backgroundMessageCount||0,lastAccessed:h?.lastAccessedAt||0,isCurrent:f.id===o}}).sort((f,p)=>p.lastAccessed-f.lastAccessed),[r,s,n,o]),m=s.size;return e.jsxs(Pc,{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(Xx,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),t&&e.jsx(je,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:t,children:e.jsx(ss,{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," / ",Pr.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:[Pr.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:[Pr.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:[Pr.ZOMBIE_TIMEOUT/1e3/60," minutes"]})]})]}),e.jsxs("div",{className:"border-t pt-2",children:[e.jsx("div",{className:"typography-meta font-semibold mb-1",children:"Sessions in Memory:"}),e.jsx(gt,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:u.map(f=>e.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${f.isCurrent?"bg-primary/10":"bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("span",{className:"truncate",children:f.title}),f.isStreaming&&e.jsx(Zx,{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>Pr.VIEWPORT_MESSAGES?"text-warning":""}`,children:[f.messageCount," msgs"]}),f.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",f.backgroundCount]})]})]},f.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(je,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(zs,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(ct,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{l()},children:"Evict LRU"})}),e.jsx(ct,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(je,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[MemoryDebug] Session store state:",{sessions:r.map(f=>({id:f.id,title:f.title})),currentSessionId:o,cachedSessions:Array.from(s.keys()),memoryStates:Object.fromEntries(n)})},children:"Log State"})}),e.jsx(ct,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},UC="openchamber-message-cursors",uo="cursors",VC=1,wh="openchamber.messageCursors",Hc=()=>typeof window<"u",Wc=()=>Hc()&&typeof indexedDB<"u",vh=()=>Wc()?new Promise((t,r)=>{const s=indexedDB.open(UC,VC);s.onupgradeneeded=()=>{const n=s.result;n.objectStoreNames.contains(uo)||n.createObjectStore(uo)},s.onerror=()=>{r(s.error??new Error("Failed to open IndexedDB"))},s.onsuccess=()=>{t(s.result)}}):Promise.reject(new Error("IndexedDB not supported")),jh=()=>{if(!Hc())return{};try{const t=window.localStorage.getItem(wh);if(!t)return{};const r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},GC=t=>{if(Hc())try{window.localStorage.setItem(wh,JSON.stringify(t))}catch{}},qC=async(t,r,s)=>{if(!t||!r)return;if(Wc())try{const o=await vh();await new Promise((a,l)=>{const c=o.transaction(uo,"readwrite");c.objectStore(uo).put({messageId:r,completedAt:s},t),c.oncomplete=()=>a(),c.onerror=()=>l(c.error??new Error("Cursor write failed")),c.onabort=()=>l(c.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=jh();n[t]={messageId:r,completedAt:s},GC(n)},KC=async t=>{if(!t)return null;if(Wc())try{const s=await vh(),n=await new Promise((o,a)=>{const l=s.transaction(uo,"readonly"),d=l.objectStore(uo).get(t);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),l.onerror=()=>a(l.error??new Error("Cursor read failed")),l.onabort=()=>a(l.error??new Error("Cursor read aborted"))});return s.close(),n}catch{}return jh()[t]??null},YC=50,QC=750,Sm=new WeakMap,Nm=t=>{if(!t||!Array.isArray(t))return 0;const r=Sm.get(t);if(r!==void 0)return r;let s=0;for(let n=0;n<t.length;n++){const o=t[n];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(s+=a.length)}}return Sm.set(t,s),s},JC=10,km=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.indexOf("_"),n=s>=0?r.slice(s+1):r;return!n||n.length<JC?null:n},Cm=(t,r)=>{const s=km(t),n=km(r);return!s||!n||s.length!==n.length?!0:s>n},nc=new Map,wl=(t,r)=>{const s=`${t}:${r}`,n=nc.get(s);if(n&&n.sessionId===t)return n.message;const l=(be.getState().messages.get(t)||[]).find(c=>c.info.id===r)||null;return nc.set(s,{sessionId:t,message:l}),l},XC=t=>{const r=t.split(/[-_]/),s=[];let n=0;for(;n<r.length;){const o=r[n];if(/^\d+$/.test(o)&&n+1<r.length&&/^\d+$/.test(r[n+1])){const a=`${o}.${r[n+1]}`;s.push(a),n+=2;continue}s.push(o),n+=1}return s.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")},ZC=()=>{const{addStreamingPart:t,completeStreamingMessage:r,updateMessageInfo:s,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:l,currentSessionId:c,applySessionMetadata:d,getWorktreeMetadata:u,loadMessages:m,loadSessions:f,updateSession:p,removeSessionFromStore:h}=be(),{checkConnection:g}=Ze(),x=Me(Ce=>Ce.nativeNotificationsEnabled),b=Me(Ce=>Ce.notificationMode),y=xt(Ce=>Ce.currentDirectory),w=i.useMemo(()=>{if(!c)return;try{const He=u?.(c);if(He?.path)return He.path}catch(He){console.warn("Failed to inspect worktree metadata for session directory:",He)}const pe=be.getState().sessions.find(He=>He.id===c);if(pe&&typeof pe.directory=="string"&&pe.directory.trim().length>0)return pe.directory.trim()},[c,u]),S=i.useMemo(()=>{if(w&&w.length>0)return w;if(typeof y=="string"&&y.trim().length>0)return y.trim()},[w,y]);i.useEffect(()=>{let Ce=!1;const pe=async()=>{try{const Se=await Oe.listPendingPermissions();if(Ce||Se.length===0)return;for(const ke of Se)o(ke)}catch{}},He=async()=>{try{const ke=Ft.getState().projects.map(Ve=>Ve.path),at=be.getState().sessions.map(Ve=>Ve.directory),We=[S,...ke,...at],Be=await Oe.listPendingQuestions({directories:We});if(Ce||Be.length===0)return;for(const Ve of Be)a(Ve)}catch{}};return pe(),He(),()=>{Ce=!0}},[o,a,S]);const M=i.useCallback(Ce=>{if(typeof Ce!="string")return null;const pe=Ce.trim();if(!pe)return null;const He=pe.replace(/\\/g,"/");return He.length>1?He.replace(/\/+$/,""):He},[]),N=i.useCallback(Ce=>{if(!Ce)return null;try{const Se=u?.(Ce),ke=M(Se?.path??null);if(ke)return ke}catch{}const He=be.getState().sessions.find(Se=>Se.id===Ce);return M(He?.directory??null)},[u,M]),v=Me(Ce=>Ce.setEventStreamStatus),A=i.useRef(null),k=i.useCallback((Ce,pe)=>{const He=pe??null,Se=A.current;if(!(Se&&Se.status===Ce&&Se.hint===He)){if(A.current={status:Ce,hint:He},xs()){const Xe={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[Ce]??"[INFO]",at=He?`${Xe} SSE ${Ce}: ${He}`:`${Xe} SSE ${Ce}`;console.info(at)}v(Ce,He)}},[v]),C=i.useCallback((Ce,pe,He)=>{if(!Ce)return Promise.resolve();const Se=Date.now();if(O.current)return O.current;if(Se-G.current<QC)return Promise.resolve();const ke=m(Ce,He).catch(Xe=>{console.warn(`[useEventStream] Failed to resync messages (${pe}):`,Xe)}).finally(()=>{O.current=null,G.current=Date.now()});return O.current=ke,ke},[m]),j=i.useCallback(async Ce=>{xs()&&console.info("[useEventStream] Bootstrapping state:",Ce);try{await Promise.all([f(),c?C(c,Ce,1/0):Promise.resolve()])}catch(pe){console.warn("[useEventStream] Bootstrap failed:",Ce,pe)}},[c,f,C]),T=i.useCallback((Ce,pe,He)=>{xs()&&console.debug(`[MessageTracker] ${Ce}: ${pe}`,He)},[]),I=i.useCallback(Ce=>{xs()&&console.debug(`[MessageTracker] ${Ce}: reported`)},[]),P=i.useRef(null),D=i.useRef(null),E=i.useRef(0);i.useRef(new Set);const F=i.useRef(new Set),B=i.useRef(new Map),V=i.useRef(null),ne=i.useRef(!1),O=i.useRef(null),G=i.useRef(0),K=i.useRef(new Set),q=i.useRef(new Set),$=i.useRef(new Set),W=i.useRef(new Set),Y=i.useRef(new Set),X=i.useRef(new Map),Z=i.useCallback(()=>{if(typeof document>"u")return"visible";const Ce=document.visibilityState;return Ce==="hidden"&&document.hasFocus()?"visible":Ce},[]),z=i.useRef(Z()),R=i.useRef(typeof navigator>"u"?!0:navigator.onLine),de=i.useRef(!1),we=i.useRef(null),xe=i.useRef(null),Pe=i.useRef(Date.now()),H=i.useRef(!1),ye=i.useCallback(Ce=>{const pe=Date.now();pe-Pe.current>25e3&&(j(Ce),Pe.current=pe)},[j]);i.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(H.current=!0)},[]);const J=i.useRef(new Map),ce=i.useRef(new Map),ge=i.useRef(0),ee=i.useRef(null),me=i.useRef(c),le=i.useRef(null),fe=i.useRef(null);i.useEffect(()=>{me.current=c},[c]);const oe=i.useCallback((Ce,pe)=>{if(!Ce)return;const He=Date.now(),Se=B.current,ke=Se.get(Ce);if(ke&&He-ke<3e3)return;Se.set(Ce,He);const Xe=at=>{if(typeof pe=="string"&&pe.trim().length>0)return pe.trim();try{const Ve=u?.(at);if(Ve?.path)return Ve.path}catch{}const Be=be.getState().sessions.find(Ve=>Ve.id===at);return Be&&typeof Be.directory=="string"&&Be.directory.trim().length>0?Be.directory.trim():null};setTimeout(async()=>{try{const at=Xe(Ce),We=at?await Oe.withDirectory(at,()=>Oe.getSession(Ce)):await Oe.getSession(Ce);if(We){const Be={};typeof We.title=="string"&&We.title.length>0&&(Be.title=We.title),We.summary!==void 0&&(Be.summary=We.summary),Object.keys(Be).length>0&&d(Ce,Be)}}catch(at){console.warn("Failed to refresh session metadata:",at)}},100)},[d,u]),Q=i.useCallback((Ce,pe)=>{if(be.getState().sessionActivityPhase?.get(Ce)===pe){ce.current=new Map(be.getState().sessionActivityPhase??new Map);return}const Se=J.current.get(Ce);Se&&(clearTimeout(Se),J.current.delete(Ce));const ke=new Map(be.getState().sessionActivityPhase??new Map);if(ke.set(Ce,pe),ce.current=ke,be.setState({sessionActivityPhase:ke}),pe==="cooldown"){const Xe=setTimeout(()=>{if(J.current.delete(Ce),be.getState().sessionActivityPhase?.get(Ce)==="cooldown"){const We=new Map(be.getState().sessionActivityPhase??new Map);We.set(Ce,"idle"),ce.current=We,be.setState({sessionActivityPhase:We})}},2e3);J.current.set(Ce,Xe)}},[]),re=i.useCallback(async()=>{const Ce=Date.now();if(ee.current)return ee.current;if(Ce-ge.current<1500)return;ge.current=Ce;const pe=Se=>{const ke=new Set,Xe=be.getState().sessions,at=new Set(Xe.map(Be=>Be.id));for(const[Be,Ve]of Object.entries(Se)){if(!Be||!Ve)continue;ke.add(Be);const mt=Ve.type==="busy"||Ve.type==="retry"?"busy":"idle";Q(Be,mt)}const We=be.getState().sessionActivityPhase;if(We)for(const[Be,Ve]of We.entries())at.has(Be)&&(Ve==="busy"||Ve==="cooldown")&&!ke.has(Be)&&Q(Be,"idle")},He=(async()=>{try{if(ur()){const mt=await Oe.getWebServerSessionActivity();if(mt&&Object.keys(mt).length>0){pe(mt);return}}const Se=await Oe.getGlobalSessionStatus();if(Se&&Object.keys(Se).length>0){pe(Se);return}const ke=new Set,Xe=be.getState().sessions;for(const mt of Xe){const ft=N(mt.id);ft&&ke.add(ft)}const at=M(S??null);at&&ke.add(at);const We=Array.from(ke);if(We.length===0){const mt=await Oe.getSessionStatus();mt&&pe(mt);return}const Be=await Promise.allSettled(We.map(mt=>Oe.getSessionStatusForDirectory(mt))),Ve={};for(const mt of Be)mt.status!=="fulfilled"||!mt.value||Object.assign(Ve,mt.value);if(Object.keys(Ve).length===0&&Array.from(be.getState().sessionActivityPhase?.values?.()??[]).some(ft=>ft==="busy"||ft==="cooldown")&&!await Oe.checkHealth().catch(()=>!1))return;pe(Ve)}catch{}})().finally(()=>{ee.current=null});return ee.current=He,He},[S,M,N,Q]);i.useEffect(()=>{const Ce=c??null,pe=le.current,He=N(Ce),Se=fe.current;pe&&Ce&&pe!==Ce&&Se&&He&&Se!==He&&re(),le.current=Ce,fe.current=He},[c,re,N]);const ue=i.useCallback(Ce=>{if(Pe.current=Date.now(),xs()&&console.debug("[useEventStream] Received event:",Ce.type,Ce.properties),!Ce.properties)return;const pe=Ce.properties;if(!new Set(["session.abort","session.error"]).has(Ce.type)){const Se=(typeof pe.session=="object"&&pe.session!==null?pe.session:null)||(typeof pe.sessionInfo=="object"&&pe.sessionInfo!==null?pe.sessionInfo:null);if(Se){const ke=Se,Xe=typeof ke.id=="string"&&ke.id.length>0?ke.id:typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof pe.sessionID=="string"&&pe.sessionID.length>0?pe.sessionID:typeof pe.id=="string"&&pe.id.length>0?pe.id:void 0;if(Xe){const at=typeof ke.title=="string"?ke.title:typeof pe.title=="string"?pe.title:void 0,We=typeof ke.summary=="object"&&ke.summary!==null?ke.summary:typeof pe.summary=="object"&&pe.summary!==null?pe.summary:void 0;if(at!==void 0||We!==void 0){const Be={};at!==void 0&&(Be.title=at),We!==void 0&&(Be.summary=We),d(Xe,Be)}}}}switch(Ce.type){case"server.connected":g();break;case"global.disposed":case"server.instance.disposed":{j("server_disposed_event");break}case"openchamber:session-activity":{const Se=typeof pe.sessionId=="string"?pe.sessionId:null,ke=typeof pe.phase=="string"?pe.phase:null;Se&&(ke==="idle"||ke==="busy"||ke==="cooldown")&&(Q(Se,ke),oe(Se,typeof pe.directory=="string"?pe.directory:null));break}case"mcp.tools.changed":{const Se=typeof pe.directory=="string"?pe.directory:S;ko.getState().refresh({directory:Se??null,silent:!0});break}case"session.status":if(H.current)break;{const Se=typeof pe.sessionID=="string"?pe.sessionID:null,ke=typeof pe.status=="object"&&pe.status!==null?pe.status:null,Xe=typeof ke?.type=="string"?ke.type:null;Se&&Xe&&(Q(Se,Xe==="busy"||Xe==="retry"?"busy":"idle"),oe(Se,typeof pe.directory=="string"?pe.directory:null))}break;case"message.part.updated":{const Se=typeof pe.part=="object"&&pe.part!==null?pe.part:null;if(!Se)break;const ke=Se,Xe=typeof pe.info=="object"&&pe.info!==null?pe.info:pe,at=typeof Xe.sessionID=="string"?Xe.sessionID:null,We=typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof at=="string"&&at.length>0?at:typeof pe.sessionID=="string"&&pe.sessionID.length>0?pe.sessionID:null,Be=typeof Xe.id=="string"?Xe.id:null,Ve=typeof ke.messageID=="string"&&ke.messageID.length>0?ke.messageID:typeof Be=="string"&&Be.length>0?Be:typeof pe.messageID=="string"&&pe.messageID.length>0?pe.messageID:null;if(!We||!Ve){xs()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:ke.sessionID??at??pe.sessionID,messageID:ke.messageID??Be??pe.messageID});break}const mt=We,ft=Ve,Ke=be.getState().sessionMemoryState.get(mt)?.trimmedHeadMaxId;if(Ke&&!Cm(ft,Ke)){xs()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:mt,messageId:ft,trimmedHeadMaxId:Ke});break}let lt="assistant";if(Xe&&typeof Xe.role=="string")lt=Xe.role;else{const yt=wl(mt,ft);if(yt){const Mt=yt.info.role;typeof Mt=="string"&&(lt=Mt)}}if(T(ft,"part_received",{role:lt}),lt==="user"&&ke.synthetic===!0){T(ft,"skipped_synthetic_user_part");break}const jt={...Se,type:Se.type||"text"};T(ft,"addStreamingPart_called"),t(mt,ft,jt,lt);break}case"message.updated":{const Se=typeof pe.info=="object"&&pe.info!==null?pe.info:pe,ke=Se,Xe=typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof pe.sessionID=="string"&&pe.sessionID.length>0?pe.sessionID:null,at=typeof ke.id=="string"&&ke.id.length>0?ke.id:typeof pe.messageID=="string"&&pe.messageID.length>0?pe.messageID:null;if(!Xe||!at){xs()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:ke.sessionID??pe.sessionID,messageID:ke.id??pe.messageID});break}const We=Xe,Be=at,Ve=be.getState().sessionMemoryState.get(We)?.trimmedHeadMaxId;if(Ve&&!Cm(Be,Ve)){xs()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:We,messageId:Be,trimmedHeadMaxId:Ve});break}if(H.current&&xs())try{const _t=pe.parts||ke.parts||[],Gt=(Array.isArray(_t)?_t.filter(It=>It?.type==="text"):[]).map(It=>{const Ie=It;return typeof Ie?.text=="string"?Ie.text:typeof Ie?.content=="string"?Ie.content:""}).join(`
|
|
244
|
+
`);console.info("[STREAM-TRACE] message.updated",{messageId:Be,role:ke.role,status:ke.status,textLen:Gt.length,textPreview:Gt.slice(0,120),partsCount:Array.isArray(_t)?_t.length:0})}catch{}if(T(Be,"message_updated",{role:ke.role}),ke.role==="user"){const _t=pe.parts||ke.parts,Yt=Array.isArray(_t)?_t:[],Gt=wl(We,Be),It=(()=>{const se=ke.agent;if(typeof se=="string"&&se.trim().length>0)return se.trim();const ie=ke.mode;return typeof ie=="string"&&ie.trim().length>0?ie.trim():""})(),Ie=(()=>{const ie=ke.time?.created;return typeof ie=="number"?ie:null})(),Te=Yt.length>0&&Yt.every(se=>se?.synthetic===!0),Le=(()=>{if(!It)return!1;if(Te&&(It==="plan"||It==="build"))return!0;const se=X.current.get(We);return se?Ie===null?!1:Be===se.messageId?!0:Ie>=se.created:!0})();if(It&&Le)try{const se=Ze.getState().agents;if(Array.isArray(se)&&se.some(ie=>ie?.name===It)){const ie=tt.getState();if(ie.saveSessionAgentSelection(We,It),X.current.set(We,{created:Ie??Date.now(),messageId:Be}),me.current===We)try{Ze.getState().setAgent(It)}catch{}const Ee=ke.model,Re=typeof Ee?.providerID=="string"?Ee.providerID:null,Ye=typeof Ee?.modelID=="string"?Ee.modelID:null;if(Re&&Ye){ie.saveSessionModelSelection(We,Re,Ye),ie.saveAgentModelForSession(We,It,Re,Ye);const bt=typeof ke.variant=="string"?ke.variant:void 0;if(bt&&ie.saveAgentModelVariantForSession(We,It,Re,Ye,bt),me.current===We)try{Ze.getState().setProvider(Re),Ze.getState().setModel(Ye)}catch{}}}}catch{}if(Te&&(It==="plan"||It==="build")&&me.current===We){const se=`${We}:${Be}:${It}`;Y.current.has(se)||(Y.current.add(se),js(async()=>{const{toast:ie}=await import("./vendor-.bun-Bui932eM.js").then(Ee=>Ee.dj);return{toast:ie}},__vite__mapDeps([0,1])).then(({toast:ie})=>{ie.info(It==="plan"?"Plan mode active":"Build mode active",{description:It==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const te={...Se,userMessageMarker:!0,clientRole:"user",...It?{mode:It}:{}};if(s(We,Be,te),!Gt&&Yt.length===0){const se=`${We}:${Be}`;F.current.has(se)||(F.current.add(se),Oe.getSessionMessages(We,50).then(ie=>{be.getState().syncMessages(We,ie)}).catch(()=>{}))}if(Yt.length>0)for(let se=0;se<Yt.length;se++){const ie=Yt[se];if(ie.synthetic===!0){const Ye=ie.text,bt=typeof Ye=="string"?Ye.trim():"";if(!(bt.startsWith("User has requested to enter plan mode")||bt.startsWith("The plan at ")))continue}const Re={...ie,type:ie?.type||"text",sessionID:ie?.sessionID||We,messageID:ie?.messageID||Be};t(We,Be,Re,"user")}T(Be,"user_message_created_from_event",{partsCount:Yt.length});break}const mt=wl(We,Be),ft=Nm(mt?.parts||[]),Ke=mt?.info?.finish==="stop",lt=pe.parts||ke.parts,jt=Array.isArray(lt)?lt:[],yt=jt.length>0,es=typeof(ke.time||{})?.completed=="number";if(!yt&&!es)break;const Ht=Se.finish,Wt=typeof Ht=="string"?Ht:null,kt=Wt==="stop";if(ke.role==="assistant"&&yt){const _t=Nm(jt);if(ft>0&&_t+YC<ft&&!kt){T(Be,"skipped_shrinking_update",{incomingLen:_t,existingLen:ft});break}if(H.current){const Gt=ft>0&&_t<ft,It=jt.some(Te=>{if(!Te||Te.type!=="text")return!1;const Le=Te;return typeof Le.text=="string"&&Le.text.length>0});if(Gt&&!(kt&&It)){T(Be,"desktop_shrinking_update_suppressed",{incomingLen:_t,existingLen:ft});break}}}if(s(We,Be,Se),yt&&ke.role!=="user"){const Gt=(be.getState().messages.get(We)||[]).find(Te=>Te.info.id===Be),It=!Gt||Gt.parts.length===0;T(Be,It?"server_parts_injected":"server_parts_refreshed",{count:jt.length});const Ie=H.current&&ke.role==="assistant"?jt.filter(Te=>Te?.type!=="text"):jt;for(let Te=0;Te<Ie.length;Te++){const Le=Ie[Te],te={...Le,type:Le?.type||"text",sessionID:Le?.sessionID||We,messageID:Le?.messageID||Be};t(We,Be,te,ke.role),T(Be,`server_part_${Te}`)}}const gs=Se.time,Qt=gs?.completed,Tt=typeof Qt=="number"&&Number.isFinite(Qt),Kt=Wt==="stop"||Ke;if(Se.role==="assistant"&&(Tt||Kt)&&Se.role==="assistant"){const Yt=be.getState().messages.get(We)||[];let Gt=null,It="";for(let ie=0;ie<Yt.length;ie++){const Ee=Yt[ie];Ee.info.role==="assistant"&&Ee.info.id>It&&(It=Ee.info.id,Gt=Ee.info.id)}if(c===We&&Be!==Gt)break;if(!Kt&&H.current){T(Be,"desktop_completion_without_stop");break}const Te=Tt?Qt:Date.now();if(Tt||s(We,Be,{...Se,time:{...gs??{},completed:Te}}),T(Be,"completed",{timeCompleted:Te}),I(Be),qC(We,Be,Te),r(We,Be),Wt==="stop"&&ur()&&x&&(b==="always"||z.current==="hidden")){const Ee=$.current;if(!Ee.has(Be)){Ee.add(Be);const Re=Ps();if(Re?.notifications){const Ye=ke.mode||"agent",bt=ke.modelID||"assistant",pt=`${Ye.charAt(0).toUpperCase()+Ye.slice(1)} agent is ready`,Jt=`${XC(bt)} completed the task`;Re.notifications.notifyAgentCompletion({title:pt,body:Jt,tag:Be})}}}H.current||Wt==="stop"&&be.getState().sessionActivityPhase?.get(We)==="busy"&&Q(We,"cooldown");const Le=Se.sessionID,te=typeof Le=="string"&&Le.length>0?Le:We;oe(te,typeof pe.directory=="string"?pe.directory:null),Se.summary&&typeof te=="string"&&n(te,null)}break}case"session.created":case"session.updated":{const Se=typeof pe.info=="object"&&pe.info!==null?pe.info:typeof pe.sessionInfo=="object"&&pe.sessionInfo!==null?pe.sessionInfo:typeof pe.session=="object"&&pe.session!==null?pe.session:pe,ke=typeof Se.id=="string"&&Se.id.length>0?Se.id:typeof Se.sessionID=="string"&&Se.sessionID.length>0?Se.sessionID:typeof pe.sessionID=="string"&&pe.sessionID.length>0?pe.sessionID:typeof pe.id=="string"&&pe.id.length>0?pe.id:void 0;if(ke){const Xe=typeof Se.time=="object"&&Se.time!==null?Se.time:typeof pe.time=="object"&&pe.time!==null?pe.time:null,at=Xe&&typeof Xe.compacting=="number"?Xe.compacting:null;n(ke,at);const We=typeof Se.directory=="string"?Se.directory:typeof pe.directory=="string"?pe.directory:null,Be={...Se,id:ke,...We?{directory:We}:{}};p(Be)}break}case"session.deleted":{const Se=typeof pe.sessionID=="string"?pe.sessionID:typeof pe.id=="string"?pe.id:null;Se&&h(Se);break}case"session.abort":{const Se=typeof pe.sessionID=="string"&&pe.sessionID.length>0?pe.sessionID:null,ke=typeof pe.messageID=="string"&&pe.messageID.length>0?pe.messageID:null;Se&&ke&&r(Se,ke);break}case"permission.asked":{if(!("sessionID"in pe)||typeof pe.sessionID!="string")break;const Se=pe;o(Se);const ke=`${Se.sessionID}:${Se.id}`;K.current.has(ke)||setTimeout(()=>{if(me.current===Se.sessionID||!be.getState().permissions.get(Se.sessionID)?.some(Be=>Be.id===Se.id))return;K.current.add(ke);const We=be.getState().sessions.find(Be=>Be.id===Se.sessionID)?.title||"Session";if(js(async()=>{const{toast:Be}=await import("./vendor-.bun-Bui932eM.js").then(Ve=>Ve.dj);return{toast:Be}},__vite__mapDeps([0,1])).then(({toast:Be})=>{Be.warning("Permission required",{description:We,action:{label:"Open",onClick:()=>{Me.getState().setActiveMainTab("chat"),be.getState().setCurrentSession(Se.sessionID)}}})}),ur()&&x&&(b==="always"||z.current==="hidden")){const Ve=Ps();Ve?.notifications&&Ve.notifications.notifyAgentCompletion({title:"Permission required",body:We,tag:`permission-${ke}`})}},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in pe)||typeof pe.sessionID!="string")break;const Se=pe;a(Se);const ke=`${Se.sessionID}:${Se.id}`;if(ur()&&x&&(b==="always"||z.current==="hidden")){const at=W.current;if(!at.has(ke)){at.add(ke);const We=Ps();if(We?.notifications){const Be=Array.isArray(Se.questions)?Se.questions[0]:void 0,Ve=typeof Be?.header=="string"?Be.header.trim():"",mt=typeof Be?.question=="string"?Be.question.trim():"",ft=/plan\s*mode/i.test(Ve)?"Switch to plan mode":/build\s*agent/i.test(Ve)?"Switch to build mode":Ve||"Input needed",Ke=mt||"Agent is waiting for your response";We.notifications.notifyAgentCompletion({title:ft,body:Ke,tag:ke})}}}q.current.has(ke)||setTimeout(()=>{if(me.current===Se.sessionID||!be.getState().questions.get(Se.sessionID)?.some(Be=>Be.id===Se.id))return;q.current.add(ke);const We=be.getState().sessions.find(Be=>Be.id===Se.sessionID)?.title||"Session";js(async()=>{const{toast:Be}=await import("./vendor-.bun-Bui932eM.js").then(Ve=>Ve.dj);return{toast:Be}},__vite__mapDeps([0,1])).then(({toast:Be})=>{Be.info("Input needed",{description:We,action:{label:"Open",onClick:()=>{Me.getState().setActiveMainTab("chat"),be.getState().setCurrentSession(Se.sessionID)}}})})},0);break}case"question.replied":{const Se=typeof pe.sessionID=="string"?pe.sessionID:null,ke=typeof pe.requestID=="string"?pe.requestID:null;Se&&ke&&l(Se,ke);break}case"question.rejected":{const Se=typeof pe.sessionID=="string"?pe.sessionID:null,ke=typeof pe.requestID=="string"?pe.requestID:null;Se&&ke&&l(Se,ke);break}case"todo.updated":{const Se=typeof pe.sessionID=="string"?pe.sessionID:null,ke=Array.isArray(pe.todos)?pe.todos:null;Se&&ke&&Qj(Se,ke);break}}},[c,x,b,t,r,s,o,a,l,g,oe,n,d,T,I,Q,p,h,j,S]),he=i.useCallback(()=>{const Ce=Z();return z.current=Ce,Ce==="visible"&&R.current},[Z]),Ge=i.useCallback(()=>{xs()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:H.current,hasUnsubscribe:!!P.current,currentSessionId:me.current,effectiveDirectory:S,onlineStatus:R.current,visibilityState:z.current,lastEventTimestamp:Pe.current,reconnectAttempts:E.current})},[S]),qe=i.useCallback(async()=>!0,[]),et=i.useCallback(()=>{if(ne.current){xs()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(ne.current=!0,D.current&&(clearTimeout(D.current),D.current=null),P.current){const Ce=P.current;P.current=null;try{Ce()}catch(pe){console.warn("[useEventStream] Error during unsubscribe:",pe)}}ne.current=!1},[]),rt=i.useCallback(async Ce=>{if(Ge(),!he()){de.current=!0,R.current?k("paused","Paused while hidden"):k("offline","Waiting for network");return}H.current&&(await qe()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),Ce?.resetAttempts&&(E.current=0),et(),Pe.current=Date.now(),k("connecting",null),xs()&&console.info("[useEventStream] Starting event stream...");const pe=Se=>{console.warn("Event stream error:",Se)},He=()=>{const Se=de.current;if(E.current=0,de.current=!1,Pe.current=Date.now(),k("connected",null),g(),re(),Se)j("sse_reconnected");else{const ke=me.current;ke&&setTimeout(()=>{C(ke,"sse_reconnected",1/0).then(()=>oe(ke)).catch(Xe=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Xe)})},0)}};if(xs()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:S,isCleaningUp:ne.current}),ne.current){xs()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Se=Oe.subscribeToGlobalEvents(Xe=>{const at=Xe.payload,We=Xe.payload,Be=typeof We.properties=="object"&&We.properties!==null?We.properties:{},Ve=Xe.directory&&Xe.directory!=="global"?{...Be,directory:Xe.directory}:Be;ue({type:typeof at.type=="string"?at.type:"",properties:Ve})},pe,He),ke=()=>{try{Se()}catch(Xe){console.warn("[useEventStream] Error during unsubscribe:",Xe)}};ne.current?ke():P.current=ke}catch(Se){console.error("[useEventStream] Error during subscription:",Se),pe(Se)}},[he,et,k,g,C,oe,ue,S,re,qe,Ge,j]),vt=i.useCallback(Ce=>{if(!he()){de.current=!0,et(),R.current?k("paused","Paused while hidden"):k("offline","Waiting for network");return}const pe=E.current+1;E.current=pe;const He=Ce??`Retrying (${pe})`;k("reconnecting",He);const Se=pe<=3?Math.min(1e3*Math.pow(2,pe-1),8e3):Math.min(2e3*Math.pow(2,pe-3),32e3),ke=Math.floor(Math.random()*250),Xe=Se+ke;D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{rt({resetAttempts:!1})},Xe)},[he,et,k,rt]);i.useEffect(()=>{const Ce=J.current;typeof window<"u"&&(window.__messageTracker=T);let pe=null;H.current&&typeof window<"u"&&(pe=Ve=>{const mt=typeof Ve.detail?.sessionId=="string"?Ve.detail.sessionId:null,ft=typeof Ve.detail?.phase=="string"?Ve.detail.phase:null;mt&&(ft==="idle"||ft==="busy"||ft==="cooldown")&&(Q(mt,ft),oe(mt))},window.addEventListener("openchamber:session-activity",pe));const He=()=>{we.current&&(clearTimeout(we.current),we.current=null)},Se=()=>{we.current||(we.current=setTimeout(()=>{const Ve=Z();z.current=Ve,Ve!=="visible"?(et(),de.current=!0,k("paused","Paused while hidden")):He()},5e3))},ke=()=>{if(z.current=Z(),z.current==="visible"){if(He(),ye("visibility_restore"),de.current||!P.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ve=me.current;Ve&&(C(Ve,"visibility_restore",_l()).catch(()=>{}),oe(Ve)),re(),k("connecting","Resuming stream"),rt({resetAttempts:!0})}}else k("paused","Paused while hidden"),Se()},Xe=()=>{if(z.current=Z(),z.current==="visible"&&(He(),ye("window_focus"),de.current||!P.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ve=me.current;Ve&&(oe(Ve),C(Ve,"window_focus",_l()).then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(mt=>console.warn("[useEventStream] Failed to refresh messages:",mt))),re(),k("connecting","Resuming stream"),rt({resetAttempts:!0})}},at=()=>{R.current=!0,ye("network_restored"),(de.current||!P.current)&&(k("connecting","Network restored"),rt({resetAttempts:!0}))},We=()=>{R.current=!1,de.current=!0,k("offline","Waiting for network"),et()};typeof document<"u"&&document.addEventListener("visibilitychange",ke),typeof window<"u"&&(window.addEventListener("online",at),window.addEventListener("offline",We),window.addEventListener("focus",Xe));const Be=setTimeout(()=>{rt({resetAttempts:!0})},100);return xe.current&&clearInterval(xe.current),xe.current=setInterval(()=>{if(!he())return;const Ve=Date.now();Array.from(be.getState().sessionActivityPhase?.values?.()??[]).some(ft=>ft==="busy"||ft==="cooldown")&&re(),Ve-Pe.current>45e3&&Promise.resolve().then(async()=>{try{await Oe.checkHealth()?Pe.current=Date.now():vt("Refreshing stalled stream")}catch(ft){console.warn("Health check after stale stream failed:",ft),vt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Be),pe&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",pe),typeof document<"u"&&document.removeEventListener("visibilitychange",ke),typeof window<"u"&&(window.removeEventListener("online",at),window.removeEventListener("offline",We),window.removeEventListener("focus",Xe)),He(),xe.current&&(clearInterval(xe.current),xe.current=null),Ce.forEach(Ve=>clearTimeout(Ve)),Ce.clear(),nc.clear(),$.current.clear(),W.current.clear(),de.current=!1,z.current=Z(),R.current=typeof navigator>"u"?!0:navigator.onLine,et(),V.current&&(clearTimeout(V.current),V.current=null),k("idle",null)}},[S,T,Z,et,k,rt,vt,m,oe,Q,re,he,f,ye,C])},eM=()=>{const{openNewSessionDraft:t,abortCurrentOperation:r,armAbortPrompt:s,clearAbortPrompt:n,currentSessionId:o}=be(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=Me(),{themeMode:p,setThemeMode:h}=Hr(),{working:g}=Rp(),x=i.useRef(null),b=i.useRef(null),y=i.useRef(!1),w=i.useCallback(()=>{b.current&&(clearTimeout(b.current),b.current=null),x.current=null,n()},[n]);i.useEffect(()=>{const S=M=>{if($s(M)&&M.key==="k"&&(M.preventDefault(),a()),$s(M)&&M.shiftKey&&M.key.toLowerCase()==="l"){const v=Ps()?.diagnostics;if(!v||(M.preventDefault(),y.current))return;y.current=!0,v.downloadLogs().then(({fileName:A,content:k})=>{const C=A||"openchamber.log",j=new Blob([k],{type:"text/plain;charset=utf-8"}),T=URL.createObjectURL(j),I=document.createElement("a");I.href=T,I.download=C,document.body.appendChild(I),I.click(),document.body.removeChild(I),URL.revokeObjectURL(T)}).finally(()=>{y.current=!1});return}if($s(M)&&M.key==="."&&(M.preventDefault(),l()),$s(M)&&M.key.toLowerCase()==="n"){M.preventDefault();const N=zt(),v=Ze.getState().settingsAutoCreateWorktree;if(N?!1:v?!M.shiftKey:M.shiftKey){u("chat"),d(!1),Ai();return}u("chat"),d(!1),t()}if($s(M)&&M.key==="/"){M.preventDefault();const N=["light","dark","system"],A=(N.indexOf(p)+1)%N.length;h(N[A])}if($s(M)&&!M.shiftKey&&M.key.toLowerCase()==="t"){M.preventDefault();const{isTimelineDialogOpen:N,setTimelineDialogOpen:v}=Me.getState();v(!N);return}if($s(M)&&!M.shiftKey&&M.key===","){M.preventDefault();const{isSettingsDialogOpen:N}=Me.getState();m(!N);return}if($s(M)&&!M.shiftKey&&M.key.toLowerCase()==="l"){M.preventDefault();const{isMobile:N,isSessionSwitcherOpen:v}=Me.getState();N?d(!v):c();return}if($s(M)&&!M.shiftKey&&M.key.toLowerCase()==="i"){M.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if($s(M)&&M.shiftKey&&M.key.toLowerCase()==="m"){const{isSettingsDialogOpen:N,isCommandPaletteOpen:v,isHelpDialogOpen:A,isSessionSwitcherOpen:k,isAboutDialogOpen:C,activeMainTab:j,isModelSelectorOpen:T}=Me.getState();if(N||v||A||k||C||!(j==="chat"))return;M.preventDefault(),f(!T);return}if($s(M)&&M.shiftKey&&M.key.toLowerCase()==="t"){const{isSettingsDialogOpen:N,isCommandPaletteOpen:v,isHelpDialogOpen:A,isSessionSwitcherOpen:k,isAboutDialogOpen:C,activeMainTab:j}=Me.getState();if(N||v||A||k||C||!(j==="chat"))return;const P=Ze.getState();if(P.getCurrentModelVariants().length===0)return;M.preventDefault(),P.cycleCurrentVariant();const E=Ze.getState().currentVariant,F=be.getState(),B=F.currentSessionId,V=Ze.getState().currentAgentName,ne=Ze.getState().currentProviderId,O=Ze.getState().currentModelId;B&&V&&ne&&O&&F.saveAgentModelVariantForSession(B,V,ne,O,E);return}if(M.key==="Escape"){const{isSettingsDialogOpen:N,isCommandPaletteOpen:v,isHelpDialogOpen:A,isSessionSwitcherOpen:k,isAboutDialogOpen:C,activeMainTab:j}=Me.getState();if(N){M.preventDefault(),m(!1),w();return}if(v||A||k||C||!(j==="chat")){w();return}const P=o;if(!(g.canAbort&&!!P)){w();return}const E=Date.now(),F=x.current;if(F&&E<F){M.preventDefault(),w(),r();return}M.preventDefault();const B=s(3e3)??E+3e3;x.current=B,b.current&&clearTimeout(b.current);const V=Math.max(B-E,0);b.current=setTimeout(()=>{x.current&&Date.now()>=x.current&&w()},V||0);return}};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[t,r,a,l,c,d,u,m,f,h,p,g,s,w,o]),i.useEffect(()=>()=>{w()},[w])},Mm="openchamber:menu-action",tM=t=>{const{openNewSessionDraft:r}=be(),{toggleCommandPalette:s,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=Me(),{addProject:u}=Ft(),{requestAccess:m,startAccessing:f}=Ei(),{setThemeMode:p}=Hr(),h=i.useRef(!1),g=i.useCallback(()=>{ms()?m("").then(async x=>{if(!x.success||!x.path){x.error&&x.error!=="Directory selection cancelled"&&U.error("Failed to select directory",{description:x.error});return}const b=await f(x.path);if(!b.success){U.error("Failed to open directory",{description:b.error||"Desktop could not grant file access."});return}u(x.path,{id:x.projectId})||U.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(x=>{console.error("Desktop: Error selecting directory:",x),U.error("Failed to select directory")}):no.requestDirectoryDialog()},[u,m,f]);i.useEffect(()=>{const x=b=>{switch(b.detail){case"about":d(!0);break;case"settings":c(!0);break;case"command-palette":s();break;case"new-session":l("chat"),a(!1),r();break;case"new-worktree-session":l("chat"),a(!1),Ai();break;case"change-workspace":g();break;case"open-git-tab":{const{activeMainTab:w}=Me.getState();l(w==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:w}=Me.getState();l(w==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:w}=Me.getState();l(w==="terminal"?"chat":"terminal");break}case"theme-light":p("light");break;case"theme-dark":p("dark");break;case"theme-system":p("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":t?.();break;case"help-dialog":n();break;case"download-logs":{const S=Ps()?.diagnostics;if(!S||h.current)break;h.current=!0,S.downloadLogs().then(({fileName:M,content:N})=>{const v=M||"openchamber.log",A=new Blob([N],{type:"text/plain;charset=utf-8"}),k=URL.createObjectURL(A),C=document.createElement("a");C.href=k,C.download=v,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(k),U.success("Logs saved",{description:`Downloaded to ~/Downloads/${v}`})}).catch(()=>{U.error("Failed to download logs")}).finally(()=>{h.current=!1});break}}};return window.addEventListener(Mm,x),()=>window.removeEventListener(Mm,x)},[r,s,n,o,a,l,c,d,p,t,g])},sM=t=>t.role==="assistant",Dm=t=>{const r=t.info;if(!sM(r))return;const s=r.time?.completed;return typeof s=="number"?s:void 0},Ba=t=>{if(!t)return!1;if(t.role==="user")return!0;const r=t;return r.clientRole==="user"?!0:!!r.userMessageMarker},Am=t=>(Array.isArray(t?.parts)?t.parts:[]).map(n=>dn(n)).join(" ").replace(/\s+/g," ").trim(),rM=(t,r)=>{if(!t||!Ba(t.info))return-1;const s=Am(t),n=typeof t.info?.time?.created=="number"?t.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((l,c)=>{if(!Ba(l.info))return;const d=Am(l),u=!!(s&&d&&d===s),m=typeof l.info?.time?.created=="number"?l.info.time.created:void 0,f=typeof n=="number"&&typeof m=="number"?Math.abs(m-n):null;if(u){const p=typeof f=="number"?f:0;p<a&&(o=c,a=p);return}!s&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=c,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(l=>{if(!Ba(l.info))return!1;const c=typeof l.info?.time?.created=="number"?l.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},nM=()=>{const{currentSessionId:t,messages:r,streamingMessageIds:s}=be(),n=i.useMemo(()=>t?s.get(t)??null:null,[t,s]),o=i.useRef(void 0),a=i.useRef(0),l=i.useCallback(async()=>{if(!t||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=r.get(t)||[],u=be.getState().sessionMemoryState.get(t),m=Ja(),f=u?.isStreaming?m.VIEWPORT_MESSAGES:m.HISTORICAL_MESSAGES,p=f+m.FETCH_BUFFER,h=await Oe.getSessionMessages(t,p),g=await KC(t);if(!h)return;const x=d[d.length-1];if(x){const b=h.findIndex(S=>S.info.id===x.info.id),w=b===-1?rM(x,h):b;if(w!==-1)if(w<h.length-1){const S=h.slice(w+1);console.log(`[SYNC] Found ${S.length} new messages to append`);const M=[...d,...S],{syncMessages:N}=be.getState();N(t,M)}else{const S=h[w],M=d[d.length-1],N=Dm(S),v=Dm(M);if(N&&!v){console.log("[SYNC] Last message completed on server");const A=[...d.slice(0,-1),S],{syncMessages:k}=be.getState();k(t,A)}}else if(Ba(x.info)){const S=h.slice(-f);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:M}=be.getState();M(t,S)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(g){const b=h.findIndex(y=>y.info.id===g.messageId);if(b!==-1){if(b<h.length-1){const w=h.slice(b+1).slice(-f);if(w.length>0){console.log(`[SYNC] Restoring ${w.length} messages after cursor`);const{syncMessages:S}=be.getState();S(t,w)}}}else if(h.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const y=h.slice(-f),{syncMessages:w}=be.getState();w(t,y)}}else if(h.length>0){const b=h.slice(-f);console.log(`[SYNC] Loading last ${b.length} messages`);const{syncMessages:y}=be.getState();y(t,b)}}catch(d){console.debug("Background sync failed:",d)}}},[t,r,n]);i.useEffect(()=>{const c=()=>{console.log("[FOCUS] Window focused - checking for updates"),l()};return window.addEventListener("focus",c),()=>window.removeEventListener("focus",c)},[l]),i.useEffect(()=>{if(!t||n)return;const c=()=>{document.visibilityState==="visible"&&l(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[t,n,l]),i.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),l())};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[l])},oM=()=>{i.useEffect(()=>{let t=!1;return(async()=>{try{const s=await Oe.getGlobalSessionStatus();if(t||!s)return;const n=new Map;Object.entries(s).forEach(([o,a])=>{if(!o||!a)return;const l=a,c=l.type==="busy"||l.type==="retry"?"busy":"idle";n.set(o,c)}),n.size>0&&be.setState({sessionActivityPhase:n})}catch{}})(),()=>{t=!0}},[])},aM=["chat","git","diff","terminal","files"],iM=["settings","agents","commands","skills","providers","git-identities"],Zs={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function Em(t){const r=lM();return{sessionId:cM(r),tab:dM(r),settingsSection:uM(r),diffFile:mM(r)}}function lM(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function cM(t){const r=t.get(Zs.SESSION);return!r||r.trim().length===0?null:r.trim()}function dM(t){const r=t.get(Zs.TAB);if(!r)return null;const s=r.toLowerCase().trim();return aM.includes(s)?s:null}function uM(t){const r=t.get(Zs.SETTINGS);if(!r)return null;const s=r.toLowerCase().trim();return iM.includes(s)?s:s==="openchamber"||s==="general"||s==="preferences"?"settings":null}function mM(t){const r=t.get(Zs.FILE);if(!r||r.trim().length===0)return null;try{return decodeURIComponent(r.trim())}catch{return r.trim()}}function Im(){if(typeof window>"u")return!1;try{const t=new URLSearchParams(window.location.search);return t.has(Zs.SESSION)||t.has(Zs.TAB)||t.has(Zs.SETTINGS)||t.has(Zs.FILE)}catch{return!1}}const fM="chat";function Sh(t){const r=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&r.set(Zs.SESSION,t.sessionId),t.isSettingsOpen){const s=t.settingsSection==="sessions"?"settings":t.settingsSection;return r.set(Zs.SETTINGS,s),r}return t.tab!==fM&&r.set(Zs.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&r.set(Zs.FILE,t.diffFile),r}function pM(t,r){const s=typeof window<"u"?window.location.pathname:"/",n=t.toString();return n?`${s}?${n}`:s}function hM(t){if(typeof window>"u")return!0;try{const r=new URLSearchParams(window.location.search),s=Sh(t),n=[...r.entries()].sort((a,l)=>a[0].localeCompare(l[0])),o=[...s.entries()].sort((a,l)=>a[0].localeCompare(l[0]));if(n.length!==o.length)return!1;for(let a=0;a<n.length;a++)if(n[a][0]!==o[a][0]||n[a][1]!==o[a][1])return!1;return!0}catch{return!0}}function gM(t,r={}){if(!(typeof window>"u")&&!xM()&&!(!r.force&&hM(t)))try{const s=Sh(t),n=pM(s);r.replace?window.history.replaceState({...window.history.state,route:t},"",n):window.history.pushState({route:t},"",n)}catch{}}function xM(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function yM(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function bM(){const t=i.useMemo(()=>yM(),[]),r=i.useRef(!1),s=i.useRef(!1),n=be(f=>f.setCurrentSession),o=Me(f=>f.setActiveMainTab),a=Me(f=>f.setSettingsDialogOpen),l=Me(f=>f.setSidebarSection),c=Me(f=>f.navigateToDiff),d=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=be.getState().currentSessionId;f.sessionId!==p&&await n(f.sessionId)}if(f.settingsSection){l(f.settingsSection),a(!0);return}Me.getState().isSettingsDialogOpen&&a(!1),f.tab&&o(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&c(f.diffFile)}finally{s.current=!1}}},[n,o,a,l,c]),u=i.useCallback(()=>{const f=be.getState(),p=Me.getState();return{sessionId:f.currentSessionId,tab:p.activeMainTab,isSettingsOpen:p.isSettingsDialogOpen,settingsSection:p.sidebarSection,diffFile:p.pendingDiffFile}},[]),m=i.useCallback((f={})=>{if(t||s.current)return;const p=u();gM(p,f)},[t,u]);i.useEffect(()=>{if(r.current||(r.current=!0,!Im()))return;const f=Em();(async()=>(await d(f),t||m({replace:!0})))()},[d,t,m]),i.useEffect(()=>{if(t)return;let f=be.getState().currentSessionId;return be.subscribe(h=>{const g=h.currentSessionId;g===f||s.current||(f=g,m())})},[t,m]),i.useEffect(()=>{if(t)return;let f=Me.getState().activeMainTab,p=Me.getState().isSettingsDialogOpen,h=Me.getState().sidebarSection,g=Me.getState().pendingDiffFile;return Me.subscribe(b=>{if(s.current)return;const y=b.activeMainTab!==f,w=b.isSettingsDialogOpen!==p,S=b.sidebarSection!==h,M=b.pendingDiffFile!==g&&b.activeMainTab==="diff";f=b.activeMainTab,p=b.isSettingsDialogOpen,h=b.sidebarSection,g=b.pendingDiffFile,(y||w||S||M)&&m()})},[t,m]),i.useEffect(()=>{if(typeof window>"u"||t)return;const f=()=>{const p=Em();if(Im())d(p);else{const h=Me.getState();h.isSettingsDialogOpen&&a(!1),h.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[d,t,o,a])}const wM=1e4,Pm=()=>{if(typeof document>"u")return"visible";const t=document.visibilityState;return t==="hidden"&&document.hasFocus()?"visible":t},Tm=t=>{if(!ur())return;const r=Ps();r?.push?.setVisibility&&r.push.setVisibility({visible:t})},vM=()=>{i.useEffect(()=>{if(!ur()||typeof document>"u")return;const t=()=>{Tm(Pm()==="visible")},r=()=>{Pm()==="visible"&&Tm(!0)};t();const s=window.setInterval(r,wM);return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),window.addEventListener("blur",t),()=>{window.clearInterval(s),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t),window.removeEventListener("blur",t)}},[])};function jM(){const{git:t}=Hs(),r=xt(m=>m.currentDirectory),{currentSessionId:s,sessions:n,worktreeMetadata:o}=be(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=ds(),u=i.useMemo(()=>{const m=s?o.get(s)??void 0:void 0,p=n.find(h=>h.id===s)?.directory??null;return m?.path??p??r??null},[s,n,o,r]);i.useEffect(()=>{if(!u||!t){c();return}return a(u),d(u,t),l(t),()=>{c()}},[u,t,a,l,c,d])}function SM({children:t}){return jM(),e.jsx(e.Fragment,{children:t})}const NM=()=>{const[{isUpdating:t,message:r},s]=i.useState(()=>By());return i.useEffect(()=>$y(s),[]),t?e.jsxs("div",{className:"fixed inset-0 z-[9999] flex flex-col items-center justify-center gap-6 backdrop-blur-md",children:[e.jsx(Oc,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Nh={getLastAssistantMessage(){const t=be.getState(),r=t.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const s=t.messages.get(r);if(!s||s.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=s.length-1;n>=0;n--){const o=s[n];if(o.info.role==="assistant"){const a=o.parts.map(p=>{const h={id:p.id,type:p.type};return p.type==="text"?(h.text=p.text,h.textLength=p.text?.length||0):p.type==="tool"?(h.tool=p.tool,h.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(h.isStepMarker=!0),h}),l=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),c=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!l&&!c&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:l,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!l&&!c}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!l&&!c&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(t,r=80){return!t||typeof t!="string"||t.length<=r?t:t.substring(0,r)+"…"},truncateMessages(t){return t.map(r=>({...r,parts:(r.parts||[]).map(s=>{const n={...s};return"text"in s&&(n.text=this.truncateString(s.text)),"textPreview"in s&&(n.textPreview=this.truncateString(s.textPreview)),s.state&&(n.state={...s.state},"output"in s.state&&(n.state.output=this.truncateString(s.state.output)),"error"in s.state&&(n.state.error=this.truncateString(s.state.error)),s.state.metadata&&"preview"in s.state.metadata&&(n.state.metadata={...s.state.metadata,preview:this.truncateString(s.state.metadata.preview)})),n})}))},getAllMessages(t=!1){const r=be.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),[];const n=r.messages.get(s)||[];return console.log(`[MESSAGES] Total messages in session: ${n.length}`),n.forEach((o,a)=>{console.log(`[${a}] ${o.info.role} - ${o.info.id} - ${o.parts.length} parts`)}),t?this.truncateMessages(n):n},async getAppStatus(){const t=xt.getState(),r=be.getState(),s=Ft.getState(),n=t.currentDirectory||null,o=Oe.getDirectory()??null,a=r.sessions||[],l=new Set,c={};a.forEach(k=>{const C=k.directory;typeof C=="string"&&C.trim().length>0?(l.add(C),c[C]=(c[C]??0)+1):c["(none)"]=(c["(none)"]??0)+1});const d=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(k){return{available:!1,error:k instanceof Error?k.message:String(k)}}})(),u=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,m=typeof window<"u"?window.__OPENCHAMBER_DESKTOP_SERVER__:null,f=!!(u?.runtime?.isDesktop||typeof window<"u"&&window.opencodeDesktop),p=async k=>{try{return await k.json()}catch{return null}},h=async k=>{try{return await k.text()}catch{return null}},g=async k=>{try{const C=await fetch(k);return C.ok?await p(C):{status:C.status}}catch(C){return{error:C instanceof Error?C.message:String(C)}}};let x=null,b=null,y=null,w=null;const S=n?`/api/path?directory=${encodeURIComponent(n)}`:"/api/path";x=await g(S);const M=n?`/api/project/current?directory=${encodeURIComponent(n)}`:"/api/project/current";b=await g(M),y=await g("/api/config/settings");try{const k=await fetch("/api/health"),C=k.headers.get("content-type")||"",j=await h(k);w={status:k.status,ok:k.ok,contentType:C,type:C.includes("application/json")?"json":"html",preview:j?j.slice(0,120):null}}catch(k){w={error:k instanceof Error?k.message:String(k)}}let N={isGitRepo:null};if(n)try{N.isGitRepo=await zr(n)}catch(k){N={isGitRepo:null,error:k instanceof Error?k.message:String(k)}}const v=s.projects.map(k=>({id:k.id,path:k.path,label:k.label})),A={runtime:{platform:u?.runtime?.platform??null,isDesktop:f,isVSCode:!!u?.runtime?.isVSCode,hasRuntimeApis:!!u,desktopServerOrigin:m?.origin??null},location:typeof window<"u"?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:n,opencodeDirectory:x?.directory||x?.worktree||o,homeDirectory:t.homeDirectory||null,isHomeReady:t.isHomeReady,hasPersistedDirectory:t.hasPersistedDirectory,isSwitchingDirectory:t.isSwitchingDirectory},projects:{total:s.projects.length,activeProjectId:s.activeProjectId,samples:v},sessions:{total:a.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:l.size,directorySamples:Array.from(l).slice(0,5),directoryCounts:c},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:N,localStorage:d,opencode:{pathInfo:x,projectInfo:b,health:w},openchamber:{settingsInfo:y}};return console.log("[DEBUG] App status snapshot:",A),A},async buildDiagnosticsReport(){const t=await this.getAppStatus();return JSON.stringify(t,null,2)},async copyDiagnosticsReport(){const t=await this.buildDiagnosticsReport();return typeof navigator<"u"&&navigator.clipboard?(await navigator.clipboard.writeText(t),{ok:!0,report:t}):{ok:!1,report:t}},checkLastMessage(){const t=this.getLastAssistantMessage();if(!t)return!1;const r=t.isEmpty||t.isEmptyResponse;return r?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:t.messageId,isEmpty:t.isEmpty,isEmptyResponse:t.isEmptyResponse,partsCount:t.partsCount}),t.parts.length>0&&console.log("Parts:",t.parts)):console.log("[OK] Last message looks good!"),r},getStreamingState(){const t=be.getState(),r=t.currentSessionId?t.streamingMessageIds.get(t.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:r,streamingMessageIds:Array.from(t.streamingMessageIds.entries()),messageStreamStates:Array.from(t.messageStreamStates.entries())}),{streamingMessageId:r,streamingMessageIds:t.streamingMessageIds,streamStates:t.messageStreamStates}},findEmptyMessages(){const t=be.getState(),r=t.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=(t.messages.get(r)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],l=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),c=a.some(d=>d.type==="tool");return a.length===0||!l&&!c});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
|
|
245
|
+
`),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
|
|
246
|
+
`),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
|
|
247
|
+
`),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)
|
|
248
|
+
`),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(t={}){const{includeNonAssistant:r=!1,verbose:s=!0,maxTableRows:n=25}=t,o=be.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const l=o.messages.get(a)||[],c=r?l:l.filter(p=>p.info.role==="assistant"),d={totalMessages:l.length,analyzedMessages:c.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const h=p.filter(g=>typeof g=="number");return h.length>0?Math.max(...h):null},f=c.map((p,h)=>{const g=p.info??{},x=Array.isArray(p.parts)?p.parts:[],b=g.time??{},y=u(b.completed),w=y!==null,S=x.filter(I=>I.type==="tool"),M=x.filter(I=>I.type==="reasoning"),N=m(S.map(I=>u(I.state?.time?.end??I.state?.time?.start))),v=m(M.map(I=>u(I.time?.end??I.time?.start))),A=m([N,v].filter(I=>I!==null)),k=S.some(I=>["pending","running","started"].includes(I.state?.status)),C=M.some(I=>typeof I.time?.end!="number");S.length>0&&(d.withTools+=1),M.length>0&&(d.withReasoning+=1),w||(d.completedMissing+=1);const j=!!(w&&typeof N=="number"&&y<N);j&&(d.completedBeforeTool+=1);const T=!!(w&&typeof v=="number"&&y<v);return T&&(d.completedBeforeReasoning+=1),w&&k&&(d.runningToolsWhenCompleted+=1),w&&C&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:y,latestToolTimestamp:N,latestReasoningTimestamp:v,latestPartTimestamp:A,completed_missing:!w,completed_before_tool:j,completed_before_reasoning:T,running_tools_when_completed:!!(w&&k),reasoning_open_when_completed:!!(w&&C),has_tools:S.length>0,has_reasoning:M.length>0}});return s&&(console.table(f.slice(0,n)),f.length>n&&console.log(`Displayed first ${n} rows out of ${f.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:f}},checkCompletionStatus(){const t=be.getState(),r=t.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const n=(t.messages.get(r)||[]).filter(b=>b.info.role==="assistant");if(n.length===0)return console.log("[ERROR] No assistant messages"),null;const o=n[n.length-1],a=o.parts.filter(b=>b.type==="step-finish"),l=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&l),p=t.messageStreamStates,h=o.info.sessionID?t.streamingMessageIds.get(o.info.sessionID)??null:null,g=p.get(o.info.id),x=o.info.id===h;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",m),console.log("hasStopReason:",l),console.log("messageIsComplete:",f),console.log("lifecycle phase:",g?.phase),console.log("isStreamingCandidate:",x),console.log("streamingMessageId:",h),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:m,hasStopReason:l,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Nh,xs()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",t=>{try{const r=t.message||"",s=t.filename||"";typeof r=="string"&&r.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(s))&&t.preventDefault()}catch{}}));const kM=({open:t,onOpenChange:r})=>{const[s,n]=i.useState(null),[o,a]=i.useState(!1),[l,c]=i.useState(!1),d=i.useCallback(async()=>{if(!o){a(!0),c(!1);try{(await Nh.copyDiagnosticsReport()).ok?(c(!0),U.success("Diagnostics copied")):U.error("Copy failed")}catch(m){U.error("Copy failed"),console.error("Failed to copy diagnostics:",m)}finally{a(!1)}}},[o]);i.useEffect(()=>{if(!t)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:p}=await js(async()=>{const{getVersion:g}=await import("./vendor-.bun-Bui932eM.js").then(x=>x.dm);return{getVersion:g}},__vite__mapDeps([0,1])),h=await p();n(h)}catch{n("1.5.9")}})():n("1.5.9")},[t]);const u=s;return e.jsx(fs,{open:t,onOpenChange:r,children:e.jsx(ps,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(Oc,{width:64,height:64}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),u&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",u]})]}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["A fan-made interface for"," ",e.jsx("a",{href:"https://opencode.ai/",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground transition-colors",children:"OpenCode"})," ","agent"]}),e.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[e.jsx("button",{onClick:d,disabled:o,className:L("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:l?"Diagnostics copied":"Copy diagnostics"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Includes OpenChamber state, OpenCode health, directories, and projects."})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[e.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Kr,{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(ff,{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(El,{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 vl({apis:t,children:r}){return e.jsx(Nc.Provider,{value:t,children:r})}const CM="curl -fsSL https://opencode.ai/install | bash",MM=3e3;function DM({onCopy:t}){return e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsxs("code",{children:[e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),e.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),e.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),e.jsx("span",{className:"text-muted-foreground",children:" | "}),e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e.jsx("button",{onClick:t,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(rr,{className:"h-4 w-4"})})]})}const AM=3e4;function EM({onCliAvailable:t}){const[r,s]=i.useState(!1),[n,o]=i.useState(!1),[a,l]=i.useState(!1);i.useEffect(()=>{const m=setTimeout(()=>o(!0),AM);return()=>clearTimeout(m)},[]),i.useEffect(()=>{l(typeof window.opencodeDesktop<"u")},[]);const c=i.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await js(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-Bui932eM.js").then(g=>g.dl);return{getCurrentWindow:h}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=i.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=i.useCallback(async()=>{try{await navigator.clipboard.writeText(CM),s(!0),setTimeout(()=>s(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return i.useEffect(()=>{const m=async()=>{await d()&&t?.()},f=setInterval(m,MM);return m(),()=>clearInterval(f)},[d,t]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:c,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(Xs,{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(Pt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(DM,{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(Xs,{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 IM=()=>{const{isAboutDialogOpen:t,setAboutDialogOpen:r}=Me();return e.jsx(kM,{open:t,onOpenChange:r})};function PM({apis:t}){const{initializeApp:r,isInitialized:s,isConnected:n}=Ze(),{error:o,clearError:a,loadSessions:l}=be(),c=xt(v=>v.currentDirectory),d=xt(v=>v.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=lh(),h=Bs(v=>v.refreshStatus),[g,x]=i.useState(()=>t.runtime.isDesktop),[b,y]=i.useState(()=>t.runtime.isVSCode),[w,S]=i.useState(()=>t.runtime.isDesktop?wy():!0);i.useEffect(()=>{x(t.runtime.isDesktop),y(t.runtime.isVSCode)},[t.runtime.isDesktop,t.runtime.isVSCode]),i.useEffect(()=>(dd(t),()=>dd(null)),[t]),i.useEffect(()=>{h(t.github,{force:!0})},[t.github,h]),i.useEffect(()=>{if(typeof document>"u")return;const v=document.documentElement,A=Zu[f]?.stack??Zu[KN].stack,k=un[p]?.stack??un[_a].stack;v.style.setProperty("--font-sans",A),v.style.setProperty("--font-heading",A),v.style.setProperty("--font-family-sans",A),v.style.setProperty("--font-mono",k),v.style.setProperty("--font-family-mono",k),v.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=A)},[f,p]),i.useEffect(()=>{if(s){const A=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},150);return()=>clearTimeout(A)}},[s]),i.useEffect(()=>{const v=setTimeout(()=>{const A=document.getElementById("initial-loading");A&&!s&&(A.classList.add("fade-out"),setTimeout(()=>{A.remove()},300))},5e3);return()=>clearTimeout(v)},[s]),i.useEffect(()=>{(async()=>b||await r())()},[r,b]),i.useEffect(()=>{if(d)return;(async()=>b||n&&(Oe.setDirectory(c),await l()))()},[c,d,l,n,b]),ZC(),vM(),bM(),eM();const M=i.useCallback(()=>{m(v=>!v)},[]);tM(M),nM(),oM(),hh(),i.useEffect(()=>{const v=A=>{$s(A)&&A.shiftKey&&A.key==="D"&&(A.preventDefault(),m(k=>!k))};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=i.useCallback(()=>{S(!0),window.location.reload()},[]);return g&&!w?e.jsx(ls,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(EM,{onCliAvailable:N})})}):b?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(ls,{children:e.jsx(vl,{apis:t,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(zC,{}),e.jsx(Ki,{})]})})}):e.jsx(ls,{children:e.jsx(vl,{apis:t,children:e.jsx(Uu,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(AC,{}),e.jsx(Ki,{})]})})})}):e.jsx(ls,{children:e.jsx(vl,{apis:t,children:e.jsx(SM,{children:e.jsx(Uu,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(kC,{}),e.jsx(Ki,{}),e.jsx(NM,{}),e.jsx(IM,{}),u&&e.jsx(WC,{onClose:()=>m(!1)})]})})})})})}const kh=async()=>{if(typeof window>"u")return;let t=null,r=null;try{t=window.localStorage.getItem("homeDirectory"),r=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const s=xt.getState();t&&s.homeDirectory!==t&&s.synchronizeHomeDirectory(t),r&&!zt()&&s.setDirectory(r,{showOverlay:!1})},Ch="/auth/session",TM=async()=>fetch(Ch,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Fm=async t=>fetch(Ch,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:t})}),Uc=({children:t})=>e.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:{fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-55",style:{background:"radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)"}}),e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),e.jsx("div",{className:"relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:t})]}),FM=({message:t="Preparing workspace…"})=>e.jsx(Uc,{children:e.jsx("div",{className:"w-full max-w-sm rounded-3xl border border-border/40 bg-card/90 px-6 py-5 text-center shadow-none backdrop-blur",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:t})})}),RM=({onRetry:t})=>e.jsx(Uc,{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(je,{type:"button",onClick:t,className:"w-full max-w-xs",children:"Retry"})]})}),LM=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},OM=()=>{try{const t=new URL(window.location.href);t.searchParams.delete("token"),window.history.replaceState({},"",t.toString())}catch{}},_M=({children:t})=>{const r=i.useMemo(()=>ms(),[]),s=i.useMemo(()=>zt(),[]),n=r||s,[o,a]=i.useState(()=>n?"authenticated":"pending"),[l,c]=i.useState(""),[d,u]=i.useState(!1),[m,f]=i.useState(""),p=i.useRef(null),h=i.useRef(n),g=i.useRef(!1),x=i.useCallback(async()=>{if(n){a("authenticated");return}a(y=>y==="authenticated"?y:"pending");try{const y=await TM();if(y.ok){a("authenticated"),f("");return}if(y.status===401){a("locked");return}a("error")}catch(y){console.warn("Failed to check session status:",y),a("error")}},[n]);i.useEffect(()=>{n||x()},[x,n]),i.useEffect(()=>{!n&&o==="locked"&&(h.current=!1)},[n,o]),i.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),i.useEffect(()=>{if(n||o!=="locked"||g.current||d)return;const y=LM();y&&(g.current=!0,OM(),u(!0),f(""),Fm(y).then(w=>{if(w.ok){c(""),a("authenticated");return}if(w.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(w=>{console.warn("Failed to submit URL token:",w),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),i.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await Sf(),await Nf(),await kh()))())},[n,o]);const b=async y=>{if(y.preventDefault(),!(!l||d)){u(!0),f("");try{const w=await Fm(l);if(w.ok){c(""),a("authenticated");return}if(w.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(w){console.warn("Failed to submit UI password:",w),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(FM,{}):o==="error"?e.jsx(RM,{onRetry:()=>{x()}}):o==="locked"?e.jsx(Uc,{children:e.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold text-foreground",children:"Unlock OpenChamber"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"This session is password-protected."})]}),e.jsxs("form",{onSubmit:b,className:"w-full space-y-2","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ey,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(wt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:l,onChange:y=>{c(y.target.value),m&&f("")},className:"pl-10","aria-invalid":!!m||void 0,"aria-describedby":m?"oc-ui-auth-error":void 0,disabled:d})]}),e.jsx(je,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ty,{className:"h-4 w-4"})})]}),m&&e.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:m})]})]})}):e.jsx(e.Fragment,{children:t})},jl=t=>{if(!t||typeof t!="string")return null;const r=t.trim();if(!r.startsWith("#"))return null;let s=r.slice(1);if((s.length===3||s.length===4)&&(s=s.split("").map(c=>c+c).join("")),s.length===8&&(s=s.slice(0,6)),s.length!==6)return null;const n=Number.parseInt(s,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,l=n&255;return`${o} ${a} ${l}`};class $M{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(r){const s=[];return s.push(...this.generateTailwindVariables(r)),s.push(...this.generatePrimaryColors(r.colors.primary)),s.push(...this.generateSurfaceColors(r.colors.surface)),s.push(...this.generateInteractiveColors(r.colors.interactive)),s.push(...this.generateStatusColors(r.colors.status)),s.push(...this.generateSyntaxColors(r.colors.syntax)),s.push(...this.generateComponentColors(r.colors,r)),s.push(...this.generateTypographyVariables()),r.config&&s.push(...this.generateConfigVariables(r.config)),s.join(`
|
|
249
|
+
`)}generateTailwindVariables(r){const s=[];s.push(` --background: ${r.colors.surface.background} !important;`),s.push(` --foreground: ${r.colors.surface.foreground} !important;`),s.push(` --muted: ${r.colors.surface.muted} !important;`),s.push(` --muted-foreground: ${r.colors.surface.mutedForeground} !important;`),s.push(` --card: ${r.colors.surface.elevated} !important;`),s.push(` --card-foreground: ${r.colors.surface.elevatedForeground} !important;`),s.push(` --popover: ${r.colors.surface.elevated} !important;`),s.push(` --popover-foreground: ${r.colors.surface.elevatedForeground} !important;`),s.push(` --border: ${r.colors.interactive.border} !important;`),s.push(` --input: ${r.colors.interactive.border} !important;`),s.push(` --primary: ${r.colors.primary.base} !important;`),s.push(` --primary-foreground: ${r.colors.primary.foreground} !important;`),s.push(` --secondary: ${r.colors.surface.muted} !important;`),s.push(` --secondary-foreground: ${r.colors.surface.mutedForeground} !important;`),s.push(` --accent: ${r.colors.surface.subtle} !important;`),s.push(` --accent-foreground: ${r.colors.surface.foreground} !important;`),s.push(` --destructive: ${r.colors.status.error} !important;`),s.push(` --destructive-foreground: ${r.colors.status.errorForeground} !important;`),s.push(` --ring: ${r.colors.interactive.focusRing} !important;`),r.config?.radius?.md&&s.push(` --radius: ${r.config.radius.md} !important;`);const n=jl(r.colors.surface.muted),o=jl(r.colors.surface.subtle),a=jl(r.colors.interactive.border);s.push(` --sidebar-base: ${r.colors.surface.muted} !important;`),n&&s.push(` --sidebar-base-rgb: ${n} !important;`),s.push(" --sidebar: var(--sidebar-base) !important;"),s.push(` --sidebar-foreground: ${r.colors.surface.mutedForeground} !important;`),s.push(` --sidebar-primary: ${r.colors.primary.base} !important;`),s.push(` --sidebar-primary-foreground: ${r.colors.primary.foreground} !important;`),s.push(` --sidebar-accent-base: ${r.colors.surface.subtle} !important;`),o&&s.push(` --sidebar-accent-base-rgb: ${o} !important;`),s.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),s.push(` --sidebar-accent-foreground: ${r.colors.surface.foreground} !important;`),s.push(` --sidebar-border: ${r.colors.interactive.border} !important;`),a&&s.push(` --sidebar-border-rgb: ${a} !important;`),s.push(` --sidebar-ring: ${r.colors.interactive.focusRing} !important;`);const l=r.metadata.variant==="dark",c=l?.8:.95,d=l?.7:.9;if(n)s.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !important;`),s.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=r.colors.surface.muted;s.push(` --sidebar-overlay-strong: ${this.opacity(u,c)} !important;`),s.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return r.colors.charts?.series&&Array.isArray(r.colors.charts.series)&&r.colors.charts.series.forEach((u,m)=>{s.push(` --chart-${m+1}: ${u};`)}),r.colors.loading?(s.push(` --loading-spinner: ${r.colors.loading.spinner||r.colors.primary.base};`),s.push(` --loading-spinner-track: ${r.colors.loading.spinnerTrack||r.colors.surface.muted};`)):(s.push(` --loading-spinner: ${r.colors.primary.base};`),s.push(` --loading-spinner-track: ${r.colors.surface.muted};`)),s}apply(r){const s=this.generate(r),n=document.createElement("style");n.id="opencode-theme-variables";let o="";r.metadata.variant==="dark"?(o=`:root {
|
|
250
|
+
${s}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
.dark {
|
|
254
|
+
${s}
|
|
255
|
+
}`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
|
|
256
|
+
${s}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
:root:not(.dark) {
|
|
260
|
+
${s}
|
|
261
|
+
}`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),n.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(n),document.documentElement.setAttribute("data-theme",r.metadata.variant)}generatePrimaryColors(r){const s=[];return s.push(` --primary-base: ${r.base};`),s.push(` --primary-hover: ${r.hover||this.darken(r.base,10)};`),s.push(` --primary-active: ${r.active||this.darken(r.base,20)};`),s.push(` --primary-foreground: ${r.foreground||"#ffffff"};`),s.push(` --primary-muted: ${r.muted||this.opacity(r.base,.5)};`),s.push(` --primary-emphasis: ${r.emphasis||this.lighten(r.base,10)};`),s}generateSurfaceColors(r){const s=[];return s.push(` --surface-background: ${r.background};`),s.push(` --surface-foreground: ${r.foreground};`),s.push(` --surface-muted: ${r.muted};`),s.push(` --surface-muted-foreground: ${r.mutedForeground};`),s.push(` --surface-elevated: ${r.elevated};`),s.push(` --surface-elevated-foreground: ${r.elevatedForeground};`),s.push(` --surface-overlay: ${r.overlay};`),s.push(` --surface-subtle: ${r.subtle};`),s}generateInteractiveColors(r){const s=[];return s.push(` --interactive-border: ${r.border};`),s.push(` --interactive-border-hover: ${r.borderHover};`),s.push(` --interactive-border-focus: ${r.borderFocus};`),s.push(` --interactive-selection: ${r.selection};`),s.push(` --interactive-selection-foreground: ${r.selectionForeground};`),s.push(` --interactive-focus: ${r.focus};`),s.push(` --interactive-focus-ring: ${r.focusRing};`),s.push(` --interactive-cursor: ${r.cursor};`),s.push(` --interactive-hover: ${r.hover};`),s.push(` --interactive-active: ${r.active};`),s}generateStatusColors(r){const s=[];return s.push(` --status-error: ${r.error};`),s.push(` --status-error-foreground: ${r.errorForeground};`),s.push(` --status-error-background: ${r.errorBackground};`),s.push(` --status-error-border: ${r.errorBorder};`),s.push(` --status-warning: ${r.warning};`),s.push(` --status-warning-foreground: ${r.warningForeground};`),s.push(` --status-warning-background: ${r.warningBackground};`),s.push(` --status-warning-border: ${r.warningBorder};`),s.push(` --status-success: ${r.success};`),s.push(` --status-success-foreground: ${r.successForeground};`),s.push(` --status-success-background: ${r.successBackground};`),s.push(` --status-success-border: ${r.successBorder};`),s.push(` --status-info: ${r.info};`),s.push(` --status-info-foreground: ${r.infoForeground};`),s.push(` --status-info-background: ${r.infoBackground};`),s.push(` --status-info-border: ${r.infoBorder};`),s}generateSyntaxColors(r){const s=[];s.push(` --syntax-background: ${r.base.background};`),s.push(` --syntax-foreground: ${r.base.foreground};`),s.push(` --syntax-comment: ${r.base.comment};`),s.push(` --syntax-keyword: ${r.base.keyword};`),s.push(` --syntax-string: ${r.base.string};`),s.push(` --syntax-number: ${r.base.number};`),s.push(` --syntax-function: ${r.base.function};`),s.push(` --syntax-variable: ${r.base.variable};`),s.push(` --syntax-type: ${r.base.type};`),s.push(` --syntax-operator: ${r.base.operator};`);const n=this.generateSyntaxTokens(r);for(const[o,a]of Object.entries(n))s.push(` --syntax-${this.kebabCase(o)}: ${a};`);return s}generateSyntaxTokens(r){const s=r.base,n=r.tokens||{};return{commentDoc:n.commentDoc||this.lighten(s.comment,10),stringEscape:n.stringEscape||this.darken(s.string,20),stringInterpolation:n.stringInterpolation||s.variable,stringRegex:n.stringRegex||this.adjustHue(s.string,15),keywordControl:n.keywordControl||s.keyword,keywordOperator:n.keywordOperator||s.operator,keywordImport:n.keywordImport||this.lighten(s.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(s.keyword),functionCall:n.functionCall||this.lighten(s.function,5),functionBuiltin:n.functionBuiltin||this.darken(s.function,10),method:n.method||s.function,methodCall:n.methodCall||this.lighten(s.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(s.variable),variableProperty:n.variableProperty||this.lighten(s.variable,10),variableReadonly:n.variableReadonly||s.number,parameter:n.parameter||s.variable,typePrimitive:n.typePrimitive||this.darken(s.type,10),typeInterface:n.typeInterface||s.type,className:n.className||this.emphasize(s.type),enum:n.enum||s.type,boolean:n.boolean||s.number,null:n.null||this.opacity(s.number,.7),constant:n.constant||s.number,punctuation:n.punctuation||this.opacity(s.foreground,.7),delimiter:n.delimiter||this.opacity(s.foreground,.8),bracket:n.bracket||s.foreground,tag:n.tag||s.keyword,tagAttribute:n.tagAttribute||s.variable,tagAttributeValue:n.tagAttributeValue||s.string,tagBracket:n.tagBracket||this.opacity(s.foreground,.8),decorator:n.decorator||s.function,annotation:n.annotation||s.function,namespace:n.namespace||this.opacity(s.type,.8),module:n.module||this.opacity(s.type,.8),...n}}generateComponentColors(r,s){const n=[];return r.markdown?n.push(...this.generateMarkdownColors(r.markdown,s)):n.push(...this.generateDefaultMarkdownColors(s)),r.chat?n.push(...this.generateChatColors(r.chat,s)):n.push(...this.generateDefaultChatColors(s)),r.tools?n.push(...this.generateToolColors(r.tools,s)):n.push(...this.generateDefaultToolColors(s)),n}generateMarkdownColors(r,s){const n=[],o=s.colors.primary.base,a=s.colors.chat?.background||s.colors.surface.background;return n.push(` --markdown-heading1: ${r.heading1||o};`),n.push(` --markdown-heading2: ${r.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${r.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${r.heading4||s.colors.surface.foreground};`),n.push(` --markdown-link: ${r.link||o};`),n.push(` --markdown-link-hover: ${r.linkHover||s.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${r.inlineCode||s.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${r.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${r.blockquote||s.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${r.blockquoteBorder||s.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${r.bold||s.colors.surface.foreground};`),n.push(` --markdown-italic: ${r.italic||this.opacity(s.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${r.strikethrough||s.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${r.hr||s.colors.interactive.border};`),n}generateDefaultMarkdownColors(r){const s=[],n=r.colors.primary.base,o=r.colors.chat?.background||r.colors.surface.background;return s.push(` --markdown-heading1: ${n};`),s.push(` --markdown-heading2: ${this.opacity(n,.9)};`),s.push(` --markdown-heading3: ${this.opacity(n,.8)};`),s.push(` --markdown-heading4: ${r.colors.surface.foreground};`),s.push(` --markdown-link: ${n};`),s.push(` --markdown-link-hover: ${r.colors.primary.hover||this.darken(n,10)};`),s.push(` --markdown-inline-code: ${r.colors.syntax.base.string};`),s.push(` --markdown-inline-code-bg: ${o};`),s.push(` --markdown-blockquote: ${r.colors.surface.mutedForeground};`),s.push(` --markdown-blockquote-border: ${r.colors.interactive.border};`),s.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),s.push(` --markdown-bold: ${r.colors.surface.foreground};`),s.push(` --markdown-italic: ${this.opacity(r.colors.surface.foreground,.9)};`),s.push(` --markdown-strikethrough: ${r.colors.surface.mutedForeground};`),s.push(` --markdown-hr: ${r.colors.interactive.border};`),s}generateChatColors(r,s){const n=[],o=r.background||s.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${r.userMessage||s.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${r.userMessageBackground||s.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${r.assistantMessage||s.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${r.assistantMessageBackground||s.colors.surface.muted};`),n.push(` --chat-timestamp: ${r.timestamp||s.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${r.divider||s.colors.interactive.border};`),n.push(` --chat-typing: ${r.typing||s.colors.surface.mutedForeground};`),n}generateDefaultChatColors(r){const s=[];return s.push(` --chat-background: ${r.colors.surface.background};`),s.push(` --chat-user-message: ${r.colors.surface.foreground};`),s.push(` --chat-user-message-bg: ${r.colors.surface.elevated};`),s.push(` --chat-assistant-message: ${r.colors.surface.foreground};`),s.push(` --chat-assistant-message-bg: ${r.colors.surface.muted};`),s.push(` --chat-timestamp: ${r.colors.surface.mutedForeground};`),s.push(` --chat-divider: ${r.colors.interactive.border};`),s.push(` --chat-typing: ${r.colors.surface.mutedForeground};`),s}generateToolColors(r,s){const n=[];return n.push(` --tools-background: ${r?.background||this.opacity(s.colors.surface.muted,.2)};`),n.push(` --tools-border: ${r?.border||this.opacity(s.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${r?.headerHover||this.opacity(s.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${r?.icon||s.colors.surface.mutedForeground};`),n.push(` --tools-title: ${r?.title||s.colors.surface.foreground};`),n.push(` --tools-description: ${r?.description||this.opacity(s.colors.surface.mutedForeground,.6)};`),r?.edit?(n.push(` --tools-edit-added: ${r.edit.added||s.colors.status.success};`),n.push(` --tools-edit-added-bg: ${r.edit.addedBackground||s.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${r.edit.removed||s.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${r.edit.removedBackground||s.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${r.edit.modified||s.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${r.edit.modifiedBackground||s.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${r.edit.lineNumber||this.opacity(s.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${s.colors.status.success};`),n.push(` --tools-edit-added-bg: ${s.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${s.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${s.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${s.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${s.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(s.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(r){const s=[];return s.push(` --tools-background: ${this.opacity(r.colors.surface.muted,.2)};`),s.push(` --tools-border: ${this.opacity(r.colors.interactive.border,.3)};`),s.push(` --tools-header-hover: ${this.opacity(r.colors.surface.muted,.3)};`),s.push(` --tools-icon: ${r.colors.surface.mutedForeground};`),s.push(` --tools-title: ${r.colors.surface.foreground};`),s.push(` --tools-description: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),s.push(` --tools-edit-added: ${r.colors.status.success};`),s.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.successBackground),.15)};`),s.push(` --tools-edit-removed: ${r.colors.status.error};`),s.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.errorBackground),.15)};`),s.push(` --tools-edit-modified: ${r.colors.status.info};`),s.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.infoBackground),.15)};`),s.push(` --tools-edit-line-number: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),s}generateConfigVariables(r){const s=[];return r&&(r.fonts&&(r.fonts.sans&&(s.push(` --font-sans: ${r.fonts.sans};`),s.push(` --font-family-sans: ${r.fonts.sans};`)),r.fonts.mono&&(s.push(` --font-mono: ${r.fonts.mono};`),s.push(` --font-family-mono: ${r.fonts.mono};`)),r.fonts.heading&&s.push(` --font-heading: ${r.fonts.heading};`)),r.radius&&(r.radius.none&&s.push(` --radius-none: ${r.radius.none};`),r.radius.sm&&s.push(` --radius-sm: ${r.radius.sm};`),r.radius.md&&s.push(` --radius-md: ${r.radius.md};`),r.radius.lg&&s.push(` --radius-lg: ${r.radius.lg};`),r.radius.xl&&s.push(` --radius-xl: ${r.radius.xl};`),r.radius.full&&s.push(` --radius-full: ${r.radius.full};`)),r.transitions&&(r.transitions.fast&&s.push(` --transition-fast: ${r.transitions.fast};`),r.transitions.normal&&s.push(` --transition-normal: ${r.transitions.normal};`),r.transitions.slow&&s.push(` --transition-slow: ${r.transitions.slow};`))),s}generateTypographyVariables(){const r=[],s=zt()?Ey:pc;return r.push(" /* Semantic Typography Variables */"),r.push(" --ui-regular-font-weight: 400;"),r.push(" /* Markdown content - all markdown elements use same size */"),r.push(` --text-markdown: ${s.markdown};`),r.push(" /* Code content - all code elements use same size */"),r.push(` --text-code: ${s.code};`),r.push(" /* UI headers - dialog titles, panel headers */"),r.push(` --text-ui-header: ${s.uiHeader};`),r.push(" /* UI labels - buttons, menus, navigation */"),r.push(` --text-ui-label: ${s.uiLabel};`),r.push(" /* Metadata - timestamps, status, helper text */"),r.push(` --text-meta: ${s.meta};`),r.push(" /* Micro text - badges, shortcuts, indicators */"),r.push(` --text-micro: ${s.micro};`),r.push(" /* Heading line height and letter spacing */"),r.push(" --h1-line-height: 1.25rem;"),r.push(" --h2-line-height: 1.25rem;"),r.push(" --h3-line-height: 1.5rem;"),r.push(" --h4-line-height: 1.5rem;"),r.push(" --h5-line-height: 1.5rem;"),r.push(" --h6-line-height: 1.5rem;"),r.push(" --h1-letter-spacing: -0.025em;"),r.push(" --h2-letter-spacing: -0.02em;"),r.push(" --h3-letter-spacing: -0.015em;"),r.push(" --h4-letter-spacing: -0.01em;"),r.push(" --h5-letter-spacing: 0;"),r.push(" --h6-letter-spacing: 0.01em;"),r.push(" /* UI element line height and letter spacing */"),r.push(" --ui-button-line-height: 1.375rem;"),r.push(" --ui-button-letter-spacing: 0.02em;"),r.push(" --ui-button-font-weight: 500;"),r.push(" --ui-label-line-height: 1rem;"),r.push(" --ui-label-letter-spacing: 0.03em;"),r.push(" --ui-label-font-weight: 500;"),r.push(" --ui-caption-line-height: 1rem;"),r.push(" --ui-caption-letter-spacing: 0.025em;"),r.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Markdown line height and letter spacing */"),r.push(" --markdown-body-line-height: 1.5rem;"),r.push(" --markdown-body-letter-spacing: 0;"),r.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-h1-line-height: 1.25rem;"),r.push(" --markdown-h1-letter-spacing: -0.025em;"),r.push(" --markdown-h2-line-height: 1.25rem;"),r.push(" --markdown-h2-letter-spacing: -0.02em;"),r.push(" --markdown-h3-line-height: 1.5rem;"),r.push(" --markdown-h3-letter-spacing: -0.015em;"),r.push(" --markdown-h4-line-height: 1.5rem;"),r.push(" --markdown-h4-letter-spacing: -0.01em;"),r.push(" --markdown-h5-line-height: 1.5rem;"),r.push(" --markdown-h5-letter-spacing: 0;"),r.push(" --markdown-h6-line-height: 1.5rem;"),r.push(" --markdown-h6-letter-spacing: 0.01em;"),r.push(" --markdown-list-line-height: 1.375rem;"),r.push(" --markdown-code-block-line-height: 1rem;"),r.push(" --ui-button-small-line-height: 1.25rem;"),r.push(" --ui-button-small-letter-spacing: 0.02em;"),r.push(" --ui-button-small-font-weight: 500;"),r.push(" --markdown-body-small-line-height: 1.375rem;"),r.push(" --markdown-body-small-letter-spacing: 0;"),r.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-button-large-line-height: 1.5rem;"),r.push(" --ui-button-large-letter-spacing: 0.02em;"),r.push(" --ui-button-large-font-weight: 500;"),r.push(" --markdown-body-large-line-height: 1.625rem;"),r.push(" --markdown-body-large-letter-spacing: 0;"),r.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Code line height and letter spacing */"),r.push(" --code-inline-line-height: 1rem;"),r.push(" --code-inline-letter-spacing: 0;"),r.push(" --code-inline-font-weight: 400;"),r.push(" --code-block-line-height: 1.4rem;"),r.push(" --code-block-letter-spacing: 0;"),r.push(" --code-block-font-weight: 400;"),r.push(" --code-line-numbers-line-height: 1.25rem;"),r.push(" --code-line-numbers-letter-spacing: 0;"),r.push(" --code-line-numbers-font-weight: 400;"),r.push(" /* Additional UI element line height and letter spacing */"),r.push(" --ui-badge-line-height: 1rem;"),r.push(" --ui-badge-letter-spacing: 0.025em;"),r.push(" --ui-badge-font-weight: 500;"),r.push(" --ui-tooltip-line-height: 1rem;"),r.push(" --ui-tooltip-letter-spacing: 0.025em;"),r.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-input-line-height: 1.375rem;"),r.push(" --ui-input-letter-spacing: 0.02em;"),r.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-helper-text-line-height: 1rem;"),r.push(" --ui-helper-text-letter-spacing: 0.025em;"),r.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Additional markdown line height and letter spacing */"),r.push(" --markdown-blockquote-line-height: 1.5rem;"),r.push(" --markdown-blockquote-letter-spacing: 0;"),r.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-list-letter-spacing: 0;"),r.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-link-line-height: 1.5rem;"),r.push(" --markdown-link-letter-spacing: 0;"),r.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-code-line-height: 1.35;"),r.push(" --markdown-code-letter-spacing: 0;"),r.push(" --markdown-code-font-weight: 400;"),r.push(" --markdown-code-block-letter-spacing: 0;"),r.push(" --markdown-code-block-font-weight: 400;"),r}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(r,s){return r.startsWith("#")?`${r}${Math.round(s*255).toString(16).padStart(2,"0")}`:r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${s})`):r}removeTransparency(r){return r.startsWith("#")?r.length===9?r.slice(0,7):r.length===5?r.slice(0,4):r:r.startsWith("rgba")?r.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):r}addTransparency(r,s){if(r.startsWith("#")){const n=r.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),l=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${l}, ${s})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),l=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${l}, ${s})`}}return r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${s})`):r}darken(r,s){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*s),a=(n>>16)-o,l=(n>>8&255)-o,c=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return r}lighten(r,s){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*s),a=(n>>16)+o,l=(n>>8&255)+o,c=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return r}adjustHue(r,s){return this.lighten(r,s/10)}emphasize(r){return this.lighten(r,15)}kebabCase(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const Vc={metadata:{id:"flexoki-light",name:"Flexoki Light",description:"An inky color scheme for prose and code - light variant",author:"Steph Ango",version:"1.0.0",variant:"light",tags:["light","warm","natural","paper"]},colors:{primary:{base:"#EC8B49",hover:"#F9AE77",active:"#DA702C",foreground:"#FFFCF0",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#FFFCF0",foreground:"#100F0F",muted:"#F2F0E5",mutedForeground:"#6F6E69",elevated:"#E6E4D9",elevatedForeground:"#100F0F",overlay:"#100F0F20",subtle:"#DAD8CE"},interactive:{border:"#DAD8CE",borderHover:"#CECDC3",borderFocus:"#EC8B49",selection:"#100F0F44",selectionForeground:"#100F0F",focus:"#EC8B49",focusRing:"#EC8B4940",cursor:"#100F0F",hover:"#DAD8CE",active:"#CECDC3"},status:{error:"#AF3029",errorForeground:"#FFFCF0",errorBackground:"#D14D4120",errorBorder:"#D14D4150",warning:"#BC5215",warningForeground:"#FFFCF0",warningBackground:"#DA702C20",warningBorder:"#DA702C50",success:"#66800B",successForeground:"#FFFCF0",successBackground:"#879A3920",successBorder:"#879A3950",info:"#205EA6",infoForeground:"#FFFCF0",infoBackground:"#4385BE20",infoBorder:"#4385BE50"},syntax:{base:{background:"#F2F0E5",foreground:"#100F0F",comment:"#6F6E69",keyword:"#205EA6",string:"#24837B",number:"#5E409D",function:"#BC5215",variable:"#100F0F",type:"#AD8301",operator:"#AF3029"},tokens:{commentDoc:"#B7B5AC",stringEscape:"#100F0F",keywordImport:"#AF3029",storageModifier:"#205EA6",functionCall:"#BC5215",method:"#66800B",variableProperty:"#205EA6",variableOther:"#66800B",variableGlobal:"#A02F6F",variableLocal:"#E6E4D9",parameter:"#100F0F",constant:"#100F0F",class:"#BC5215",className:"#BC5215",interface:"#AD8301",struct:"#BC5215",enum:"#BC5215",typeParameter:"#BC5215",namespace:"#AD8301",module:"#AF3029",tag:"#205EA6",jsxTag:"#A02F6F",tagAttribute:"#AD8301",tagAttributeValue:"#24837B",boolean:"#AD8301",decorator:"#AD8301",label:"#A02F6F",punctuation:"#6F6E69",macro:"#205EA6",preprocessor:"#A02F6F",regex:"#24837B",url:"#205EA6",key:"#BC5215",exception:"#A02F6F"},highlights:{diffAdded:"#66800B",diffAddedBackground:"#879A3920",diffRemoved:"#AF3029",diffRemovedBackground:"#D14D4120",diffModified:"#205EA6",diffModifiedBackground:"#4385BE20",lineNumber:"#CECDC3",lineNumberActive:"#100F0F"}},markdown:{heading1:"#AD8301",heading2:"#BC5215",heading3:"#205EA6",heading4:"#100F0F",link:"#205EA6",linkHover:"#4385BE",inlineCode:"#24837B",inlineCodeBackground:"#F2F0E5",blockquote:"#6F6E69",blockquoteBorder:"#DAD8CE",listMarker:"#AD830199"},chat:{userMessage:"#100F0F",userMessageBackground:"#F2F0E5",assistantMessage:"#100F0F",assistantMessageBackground:"#FFFCF0",timestamp:"#6F6E69",divider:"#DAD8CE"},tools:{background:"#F2F0E550",border:"#DAD8CE80",headerHover:"#DAD8CE",icon:"#6F6E69",title:"#100F0F",description:"#6F6E69",edit:{added:"#66800B",addedBackground:"#66800B25",removed:"#AF3029",removedBackground:"#AF302925",lineNumber:"#CECDC3"}}},config:{fonts:{sans:'"IBM Plex Mono", monospace',mono:'"IBM Plex Mono", monospace',heading:'"IBM Plex Mono", monospace'},radius:{none:"0",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},transitions:{fast:"150ms ease",normal:"250ms ease",slow:"350ms ease"}}},Gc={metadata:{id:"flexoki-dark",name:"Flexoki Dark",description:"An inky color scheme for prose and code - dark variant",author:"Steph Ango",version:"1.0.0",variant:"dark",tags:["dark","warm","natural","ink"]},colors:{primary:{base:"#EC8B49",hover:"#DA702C",active:"#F9AE77",foreground:"#100F0F",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#100F0F",foreground:"#CECDC3",muted:"#1C1B1A",mutedForeground:"#878580",elevated:"#282726",elevatedForeground:"#CECDC3",overlay:"#00000080",subtle:"#343331"},interactive:{border:"#343331",borderHover:"#403E3C",borderFocus:"#EC8B49",selection:"#CECDC330",selectionForeground:"#CECDC3",focus:"#EC8B49",focusRing:"#EC8B4950",cursor:"#CECDC3",hover:"#343331",active:"#403E3C"},status:{error:"#D14D41",errorForeground:"#100F0F",errorBackground:"#AF302920",errorBorder:"#AF302950",warning:"#DA702C",warningForeground:"#100F0F",warningBackground:"#BC521520",warningBorder:"#BC521550",success:"#A0AF54",successForeground:"#100F0F",successBackground:"#66800B20",successBorder:"#66800B50",info:"#4385BE",infoForeground:"#100F0F",infoBackground:"#205EA620",infoBorder:"#205EA650"},syntax:{base:{background:"#1C1B1A",foreground:"#CECDC3",comment:"#878580",keyword:"#4385BE",string:"#3AA99F",number:"#8B7EC8",function:"#DA702C",variable:"#CECDC3",type:"#D0A215",operator:"#D14D41"},tokens:{commentDoc:"#575653",stringEscape:"#CECDC3",keywordImport:"#D14D41",storageModifier:"#4385BE",functionCall:"#DA702C",method:"#879A39",variableProperty:"#4385BE",variableOther:"#879A39",variableGlobal:"#CE5D97",variableLocal:"#282726",parameter:"#CECDC3",constant:"#CECDC3",class:"#DA702C",className:"#DA702C",interface:"#D0A215",struct:"#DA702C",enum:"#DA702C",typeParameter:"#DA702C",namespace:"#D0A215",module:"#D14D41",tag:"#4385BE",jsxTag:"#CE5D97",tagAttribute:"#D0A215",tagAttributeValue:"#3AA99F",boolean:"#D0A215",decorator:"#D0A215",label:"#CE5D97",punctuation:"#878580",macro:"#4385BE",preprocessor:"#CE5D97",regex:"#3AA99F",url:"#4385BE",key:"#DA702C",exception:"#CE5D97"},highlights:{diffAdded:"#879A39",diffAddedBackground:"#66800B20",diffRemoved:"#D14D41",diffRemovedBackground:"#AF302920",diffModified:"#4385BE",diffModifiedBackground:"#205EA620",lineNumber:"#403E3C",lineNumberActive:"#CECDC3"}},markdown:{heading1:"#D0A215",heading2:"#DA702C",heading3:"#4385BE",heading4:"#CECDC3",link:"#4385BE",linkHover:"#205EA6",inlineCode:"#A0AF54",inlineCodeBackground:"#1C1B1A",blockquote:"#878580",blockquoteBorder:"#343331",listMarker:"#D0A21599"},chat:{userMessage:"#CECDC3",userMessageBackground:"#282726",assistantMessage:"#CECDC3",assistantMessageBackground:"#100F0F",timestamp:"#878580",divider:"#343331"},tools:{background:"#1C1B1A50",border:"#34333180",headerHover:"#34333150",icon:"#878580",title:"#CECDC3",description:"#878580",edit:{added:"#879A39",addedBackground:"#66800B25",removed:"#D14D41",removedBackground:"#AF302925",lineNumber:"#403E3C"}}},config:{fonts:{sans:'"IBM Plex Mono", monospace',mono:'"IBM Plex Mono", monospace',heading:'"IBM Plex Mono", monospace'},radius:{none:"0",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},transitions:{fast:"150ms ease",normal:"250ms ease",slow:"350ms ease"}}},Wo=[Vc,Gc];function li(t){return Wo.find(r=>r.metadata.id===t)}const Mh=Vc.metadata.id,Dh=Gc.metadata.id,BM=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Ah=t=>t==="dark"?Gc:Vc,zM=t=>(Wo.find(s=>s.metadata.variant===t)??Ah(t)).metadata.id,Sa=(t,r)=>{const s=li(t);return s&&s.metadata.variant===r?s:Wo.find(o=>o.metadata.variant===r)??Ah(r)},HM=typeof window<"u"?i.useLayoutEffect:i.useEffect,ci=(t,r)=>{if(!t)return r==="light"?Mh:Dh;const s=li(t);return s&&s.metadata.variant===r?s.metadata.id:zM(r)},WM=t=>{let r=Mh,s=Dh,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),l=localStorage.getItem("darkThemeId"),c=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(c!==null){if(c==="true")n="system";else if(d){const f=li(d);f&&(n=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?s=f.metadata.id:r=f.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);r=ci(a,"light"),s=ci(l,"dark")}if(t){const o=li(t);o&&(o.metadata.variant==="light"?r=o.metadata.id:s=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:s}};function UM({children:t,defaultThemeId:r}){const s=Ae.useMemo(()=>new $M,[]),[n,o]=Ae.useState(()=>WM(r)),[a,l]=Ae.useState(()=>BM()),[c,d]=Ae.useState(()=>typeof window>"u"||!zt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Ae.useMemo(()=>zt(),[]),m=Ae.useMemo(()=>u&&c?c:n.themeMode==="light"?Sa(n.lightThemeId,"light"):n.themeMode==="dark"||a?Sa(n.darkThemeId,"dark"):Sa(n.lightThemeId,"light"),[u,n,a,c]),f=Ae.useMemo(()=>u&&c?[c,...Wo]:Wo,[u,c]);Ae.useEffect(()=>{if(!u)return;const M=A=>{d(A);const k=A.metadata.variant==="dark"?"dark":"light",C=Me.getState();C.theme!==k&&C.setTheme(k)},N=A=>{const k=A.detail;k?.theme&&M(k.theme)},v=window.__OPENCHAMBER_VSCODE_THEME__;return v&&M(v),window.addEventListener("openchamber:vscode-theme",N),()=>window.removeEventListener("openchamber:vscode-theme",N)},[u]);const p=Ae.useCallback(M=>{if(typeof document>"u")return;const N=M.colors.surface.background;document.body.style.backgroundColor=N;let v=document.querySelector('meta[name="theme-color"]');v||(v=document.createElement("meta"),v.setAttribute("name","theme-color"),document.head.appendChild(v)),v.setAttribute("content",N);const A=M.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let k=document.querySelector(`meta[name="theme-color"][media="${A}"]`);k||(k=document.createElement("meta"),k.setAttribute("name","theme-color"),k.setAttribute("media",A),document.head.appendChild(k)),k.setAttribute("content",N)},[]),h=Ae.useCallback(M=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",M)},[]);HM(()=>{if(typeof window>"u")return;s.apply(m),h(u),p(m);const M=document.documentElement;M.classList.remove("light","dark"),M.classList.add(m.metadata.variant)},[h,s,m,u,p]),Ae.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const M=window.matchMedia("(prefers-color-scheme: dark)"),N=v=>{l(v.matches)};return l(M.matches),M.addEventListener("change",N),()=>M.removeEventListener("change",N)},[n.themeMode]),Ae.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]),Ae.useEffect(()=>{cs({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]),Ae.useEffect(()=>{if(typeof window>"u")return;const M=N=>{const v=N.detail;v&&o(A=>{let k=A.themeMode;v.useSystemTheme===!0?k="system":v.useSystemTheme===!1&&(v.themeVariant==="dark"||v.themeVariant==="light")&&(k=v.themeVariant);let C=A.lightThemeId;typeof v.lightThemeId=="string"&&v.lightThemeId.length>0&&(C=ci(v.lightThemeId,"light"));let j=A.darkThemeId;return typeof v.darkThemeId=="string"&&v.darkThemeId.length>0&&(j=ci(v.darkThemeId,"dark")),k===A.themeMode&&C===A.lightThemeId&&j===A.darkThemeId?A:{themeMode:k,lightThemeId:C,darkThemeId:j}})};return window.addEventListener("openchamber:settings-synced",M),()=>window.removeEventListener("openchamber:settings-synced",M)},[]);const g=Ae.useCallback(M=>{const N=f.find(v=>v.metadata.id===M);N&&o(v=>N.metadata.variant==="dark"?v.darkThemeId===N.metadata.id&&v.themeMode==="dark"?v:{...v,darkThemeId:N.metadata.id,themeMode:"dark"}:v.lightThemeId===N.metadata.id&&v.themeMode==="light"?v:{...v,lightThemeId:N.metadata.id,themeMode:"light"})},[f]),x=Ae.useCallback(M=>{o(N=>N.themeMode===M?N:{...N,themeMode:M})},[]),b=Ae.useCallback(M=>{if(M){o(v=>v.themeMode==="system"?v:{...v,themeMode:"system"});return}const N=m.metadata.variant==="dark"?"dark":"light";o(v=>v.themeMode===N?v:{...v,themeMode:N})},[m.metadata.variant]),y=Ae.useCallback(M=>{const N=f.find(v=>v.metadata.id===M&&v.metadata.variant==="light");N&&o(v=>v.lightThemeId===N.metadata.id?v:{...v,lightThemeId:N.metadata.id})},[f]),w=Ae.useCallback(M=>{const N=f.find(v=>v.metadata.id===M&&v.metadata.variant==="dark");N&&o(v=>v.darkThemeId===N.metadata.id?v:{...v,darkThemeId:N.metadata.id})},[f]),S={currentTheme:m,availableThemes:f,setTheme:g,isSystemPreference:n.themeMode==="system",setSystemPreference:b,themeMode:n.themeMode,setThemeMode:x,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:y,setDarkThemePreference:w};return e.jsx(Mc.Provider,{value:S,children:t})}const VM=({children:t})=>{const{theme:r,applyTheme:s,fontSize:n,applyTypography:o,padding:a,applyPadding:l}=Me();return i.useLayoutEffect(()=>{s(),o(),l()},[r,s,n,o,a,l]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&s()};return c.addEventListener("change",d),()=>{c.removeEventListener("change",d)}},[r,s]),e.jsx(e.Fragment,{children:t})};let Rm=!1;const GM=()=>{if(Rm||typeof window>"u")return;Rm=!0;let t={showReasoningTraces:Me.getState().showReasoningTraces,showTextJustificationActivity:Me.getState().showTextJustificationActivity,nativeNotificationsEnabled:Me.getState().nativeNotificationsEnabled,notificationMode:Me.getState().notificationMode,autoDeleteEnabled:Me.getState().autoDeleteEnabled,autoDeleteAfterDays:Me.getState().autoDeleteAfterDays,toolCallExpansion:Me.getState().toolCallExpansion,fontSize:Me.getState().fontSize,padding:Me.getState().padding,cornerRadius:Me.getState().cornerRadius,inputBarOffset:Me.getState().inputBarOffset,diffLayoutPreference:Me.getState().diffLayoutPreference,diffViewMode:Me.getState().diffViewMode},r=null,s=null;const n=()=>{const a=r;r=null,s=null,a&&Object.keys(a).length>0&&cs(a)},o=a=>{r={...r??{},...a},!s&&(s=setTimeout(n,150))};Me.subscribe(a=>{const l={showReasoningTraces:a.showReasoningTraces,showTextJustificationActivity:a.showTextJustificationActivity,nativeNotificationsEnabled:a.nativeNotificationsEnabled,notificationMode:a.notificationMode,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays,toolCallExpansion:a.toolCallExpansion,fontSize:a.fontSize,padding:a.padding,cornerRadius:a.cornerRadius,inputBarOffset:a.inputBarOffset,diffLayoutPreference:a.diffLayoutPreference,diffViewMode:a.diffViewMode},c={};l.showReasoningTraces!==t.showReasoningTraces&&(c.showReasoningTraces=l.showReasoningTraces),l.showTextJustificationActivity!==t.showTextJustificationActivity&&(c.showTextJustificationActivity=l.showTextJustificationActivity),l.nativeNotificationsEnabled!==t.nativeNotificationsEnabled&&(c.nativeNotificationsEnabled=l.nativeNotificationsEnabled),l.notificationMode!==t.notificationMode&&(c.notificationMode=l.notificationMode),l.autoDeleteEnabled!==t.autoDeleteEnabled&&(c.autoDeleteEnabled=l.autoDeleteEnabled),l.autoDeleteAfterDays!==t.autoDeleteAfterDays&&(c.autoDeleteAfterDays=l.autoDeleteAfterDays),l.toolCallExpansion!==t.toolCallExpansion&&(c.toolCallExpansion=l.toolCallExpansion),l.fontSize!==t.fontSize&&(c.fontSize=l.fontSize),l.padding!==t.padding&&(c.padding=l.padding),l.cornerRadius!==t.cornerRadius&&(c.cornerRadius=l.cornerRadius),l.inputBarOffset!==t.inputBarOffset&&(c.inputBarOffset=l.inputBarOffset),l.diffLayoutPreference!==t.diffLayoutPreference&&(c.diffLayoutPreference=l.diffLayoutPreference),l.diffViewMode!==t.diffViewMode&&(c.diffViewMode=l.diffViewMode),t=l,Object.keys(c).length>0&&o(c)})};let Lm=!1;const Om="openchamber-typography-base",qM=()=>{if(typeof document>"u")return;const r=`:root {
|
|
262
|
+
${Object.entries(pc).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
|
|
263
|
+
`)}
|
|
264
|
+
}
|
|
265
|
+
`,s=document.getElementById(Om);if(s){s.textContent=r;return}const n=document.createElement("style");n.id=Om,n.textContent=r,document.head.appendChild(n)},KM=()=>{Lm||typeof window>"u"||(Lm=!0,qM())},YM=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await Sf();await Nf();GM();KM();await kh();typeof window<"u"&&(window.debugContextTokens=()=>{const t=window.__zustand_session_store__;if(!t)return;const r=t.getState(),s=r.currentSessionId;if(!s)return;const o=(r.messages.get(s)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const l=o[o.length-1].info.tokens;l&&typeof l=="object"&&console.debug("Token breakdown:",{base:(l.input||0)+(l.output||0)+(l.reasoning||0),cache:l.cache?(l.cache.read||0)+(l.cache.write||0):0}),r.sessionContextUsage.get(s);const c=window.__zustand_config_store__;if(c){const d=c.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const Eh=document.getElementById("root");if(!Eh)throw new Error("Root element not found");sy.createRoot(Eh).render(e.jsx(Ae.StrictMode,{children:e.jsx(UM,{children:e.jsx(VM,{children:e.jsx(_M,{children:e.jsx(PM,{apis:YM})})})})}));if(typeof window<"u"){const t=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(r){console.warn("Failed to notify desktop runtime that renderer is ready:",r)}};t(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()})}const XM=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{fs as D,Nr as S,ps as a,rp as b,L as c,F0 as d,R0 as e,Eu as f,Ar as g,L0 as h,_0 as i,XM as m,_p as p,O0 as r,Ca as t};
|