ikanban-web 0.1.2 → 0.1.5
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-Cq56vLok.js → ToolOutputDialog-omrlEaN1.js} +1 -1
- package/dist/assets/{index-DTPWfiSs.js → index-DnLcILNN.js} +2 -2
- package/dist/assets/main-B1F13c3o.js +311 -0
- package/dist/assets/{vendor-.bun-KwPUu5oc.js → vendor-.bun-CTUAJ4e1.js} +17 -17
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/main-DfG1dUG4.js +0 -311
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-CTUAJ4e1.js","assets/vendor--DEobTDja.css","assets/ToolOutputDialog-omrlEaN1.js","assets/index-DnLcILNN.js","assets/index-BQJPAP5f.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as Ib,c as Tb,F as Eb,j as e,R as Pb,T as Rb,P as Fb,C as Lb,A as Ob,a as _b,b as $b,d as Bb,e as zb,f as Ub,L as Hb,g as Vb,i as Wb,I as Gb,s as ss,S as Kb,k as qb,l as i,m as Ls,n as Us,p as Ar,o as Dr,q as hm,_ as Ks,r as co,u as hs,v as Qb,w as Jh,x as Yb,y as Jb,z as Xb,B as Zb,D as ev,E as tv,G as ne,V as vi,H as is,J as sv,K as go,M as Nr,W as rv,N as nv,O as ov,Q as Xh,U as av,X as iv,Y as Ra,Z as lv,$ as cv,a0 as dv,a1 as dr,a2 as Ot,a3 as ec,a4 as Rd,a5 as Zh,a6 as uv,a7 as Mr,a8 as bu,a9 as eg,aa as tg,ab as mv,ac as sg,ad as fv,ae as rg,af as vu,ag as Qn,ah as wu,ai as Mn,aj as Do,ak as ng,al as Fs,am as pv,an as hv,ao as gv,ap as Hr,aq as og,ar as Eo,as as Nn,at as fo,au as Ms,av as Fd,aw as xo,ax as ju,ay as xv,az as Po,aA as Su,aB as Ro,aC as ag,aD as uo,aE as Ld,aF as ig,aG as kl,aH as jr,aI as yv,aJ as po,aK as bv,aL as ol,aM as vv,aN as Cl,aO as gn,aP as cr,aQ as Fo,aR as Rr,aS as Ho,aT as ii,aU as xn,aV as Pn,aW as wv,aX as jv,aY as Sv,aZ as lg,a_ as Nu,a$ as Lo,b0 as Ja,b1 as Rn,b2 as cg,b3 as li,b4 as Nv,b5 as ku,b6 as Kn,b7 as qn,b8 as no,b9 as kv,ba as dg,bb as Cv,bc as Nc,bd as Mv,be as fn,bf as Av,bg as Dv,bh as gm,bi as Cu,bj as xm,bk as Iv,bl as Tv,bm as Ev,bn as Pv,bo as Rv,bp as Fv,bq as Lv,br as Ov,bs as _v,bt as kc,bu as $v,bv as Fn,bw as Bv,bx as zv,by as Uv,bz as Hv,bA as Vv,bB as Wv,bC as Gv,bD as Kv,bE as qv,bF as Qv,bG as Yv,bH as Jv,bI as Xv,bJ as Ml,bK as Ln,bL as In,bM as tc,bN as ma,bO as Od,bP as ug,bQ as Zv,bR as ew,bS as tw,bT as sc,bU as sw,bV as oo,bW as rw,bX as nw,bY as ow,bZ as Oo,b_ as aw,b$ as iw,c0 as lw,c1 as cw,c2 as dw,c3 as uw,c4 as ra,c5 as al,c6 as rc,c7 as mw,c8 as fw,c9 as _d,ca as mg,cb as pw,cc as en,cd as Vn,ce as fg,cf as hw,cg as gw,ch as $d,ci as pg,cj as hg,ck as xw,cl as yw,cm as bw,cn as Bd,co as il,cp as ym,cq as va,cr as vw,cs as ww,ct as kn,cu as jw,cv as Da,cw as bm,cx as Sw,cy as Nw,cz as Cc,cA as kw,cB as Cw,cC as Mw,cD as vm,cE as Aw,cF as gg,cG as xg,cH as Dw,cI as wm,cJ as Iw,cK as Tw,cL as Ew,cM as Pw,cN as Rw,cO as Fw,cP as yg,cQ as wt,cR as ll,cS as Lw,cT as Ow,cU as Vo,cV as _w,cW as $w,cX as Bw,cY as zw,cZ as Uw,c_ as Hw,c$ as Vw,d0 as Ww,d1 as Al,d2 as bg,d3 as vg,d4 as wg,d5 as jg,d6 as Sg,d7 as Gw,d8 as Ng,d9 as kg,da as oa,db as Kw,dc as qw,dd as zd,de as Cg,df as Ud,dg as Mu,dh as Mg,di as Qw,dj as Ag,dk as Au,dl as Du,dm as Iu,dn as Yw,dp as Jw,dq as Io,dr as Xw,ds as Zw,dt as ej,du as tj,dv as sj,dw as jm,dx as Sm,dy as Dg,dz as rj,dA as nj,dB as oj,dC as aj,dD as ci,dE as Ig,dF as Tg,dG as Fa,dH as nc,dI as Eg,dJ as ij,dK as Pg,dL as Rg,dM as Hd,dN as Nm,dO as Mc,dP as lj,dQ as cj,dR as dj,dS as uj,dT as mj,dU as fj,dV as pj,dW as hj,dX as gj,dY as xj}from"./vendor-.bun-CTUAJ4e1.js";import{c as yj,l as bj,d as vj,a as wj,v as jj,g as Sj,b as Nj,e as kj,f as Cj,u as Mj,h as Aj,i as Dj,j as Ij,k as Tj,m as Ej,n as Pj,o as Rj,r as Fj,p as Lj,q as Oj,s as _j}from"./index-DnLcILNN.js";const As=()=>typeof window>"u"?!1:typeof window.__TAURI__?.core?.invoke=="function",km=t=>{const s=t.trim();if(!s)return null;try{return new URL(s).origin}catch{try{return new URL(s.endsWith("/")?s:`${s}/`).origin}catch{return null}}},Or=()=>{if(typeof window>"u")return!1;const t=typeof window.__IKANBAN_LOCAL_ORIGIN__=="string"?window.__IKANBAN_LOCAL_ORIGIN__:"",s=km(t),r=km(window.location.origin)||window.location.origin;return!!(s&&r&&s===r)},Lr=()=>typeof window>"u"?!1:typeof window.__IKANBAN_LOCAL_ORIGIN__=="string"&&window.__IKANBAN_LOCAL_ORIGIN__.length>0?!0:As(),gs=()=>typeof window>"u"?!1:window.__IKANBAN_RUNTIME_APIS__?.runtime?.isVSCode===!0,_o=()=>{if(typeof window>"u")return!1;const s=window.__IKANBAN_RUNTIME_APIS__?.runtime?.platform;return s==="web"?!0:s==="desktop"||s==="vscode"?!1:!gs()},oc=async()=>{if(typeof window<"u"){const t=window.__IKANBAN_HOME__;if(t&&t.length>0)return t}return null},Fg=async t=>{if(As()&&Or())try{const r=await window.__TAURI__?.dialog?.open?.({directory:!0,multiple:!1,title:"Select Working Directory"});return!r||typeof r!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:r}}catch(s){return console.warn("Failed to request directory access (tauri)",s),{success:!1,error:s instanceof Error?s.message:String(s)}}return{success:!0,path:t}},Lg=async t=>({success:!0}),Og=async t=>({success:!0}),_g=async()=>{if(!As()||!Or())return null;try{return await window.__TAURI__?.core?.invoke?.("desktop_check_for_updates")}catch(t){return console.warn("Failed to check for updates (tauri)",t),null}},$g=async t=>{if(!As()||!Or())return!1;const s=window.__TAURI__;let r=null,n=0,o;try{return typeof t=="function"&&s?.event?.listen&&(r=await s.event.listen("ikanban:update-progress",a=>{const l=a?.payload;if(!l||typeof l!="object")return;const c=l,d=typeof c.event=="string"?c.event:null,u=c.data&&typeof c.data=="object"?c.data:null;if(d==="Started"){n=0,o=typeof u?.contentLength=="number"?u.contentLength:void 0,t({downloaded:n,total:o});return}if(d==="Progress"){const m=u?.downloaded,f=u?.total;typeof m=="number"&&(n=m),typeof f=="number"&&(o=f),t({downloaded:n,total:o});return}d==="Finished"&&t({downloaded:n,total:o})})),await s?.core?.invoke?.("desktop_download_and_install_update"),!0}catch(a){return console.warn("Failed to download update (tauri)",a),!1}finally{if(r)try{const a=r();a instanceof Promise&&await a}catch{}}},Bg=async()=>{if(!As()||!Or())return!1;try{return await window.__TAURI__?.core?.invoke?.("desktop_restart"),!0}catch(t){return console.warn("Failed to restart for update (tauri)",t),!1}},zg=async(t,s)=>{if(!As()||!Or())return!1;const r=t?.trim();if(!r)return!1;try{return await window.__TAURI__?.core?.invoke?.("desktop_open_path",{path:r,app:typeof s=="string"&&s.trim().length>0?s.trim():void 0}),!0}catch(n){return console.warn("Failed to open path (tauri)",n),!1}},Ug=async(t,s)=>{if(!As()||!Or())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const r=Array.isArray(t)?t.filter(n=>typeof n=="string"):[];if(r.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const o=await window.__TAURI__?.core?.invoke?.("desktop_get_installed_apps",{apps:r,force:s===!0?!0:void 0});if(!o||typeof o!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const a=o;return Array.isArray(a.apps)?{apps:a.apps.filter(c=>c&&typeof c=="object").map(c=>{const d=c;return{name:typeof d.name=="string"?d.name:"",iconDataUrl:typeof d.iconDataUrl=="string"?d.iconDataUrl:null}}).filter(c=>c.name.length>0),success:!0,hasCache:a.hasCache===!0,isCacheStale:a.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(n){return console.warn("Failed to fetch installed apps (tauri)",n),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},$j=Object.freeze(Object.defineProperty({__proto__:null,checkForDesktopUpdates:_g,downloadDesktopUpdate:$g,fetchDesktopInstalledApps:Ug,getDesktopHomeDirectory:oc,isDesktopLocalOriginActive:Or,isDesktopShell:Lr,isTauriShell:As,isVSCodeRuntime:gs,isWebRuntime:_o,openDesktopPath:zg,requestDirectoryAccess:Fg,restartToApplyUpdate:Bg,startAccessingDirectory:Lg,stopAccessingDirectory:Og},Symbol.toStringTag,{value:"Module"}));function L(...t){return Ib(Tb(t))}const Hg=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),kr=t=>Hg()&&As()?t.metaKey:t.ctrlKey,Ys=()=>Hg()&&As()?"⌘":"Ctrl",Vg=(t,s)=>{const r=t??"",n=Math.max(16,s?.maxLength??45);if(r.length<=n)return r;const o=r.split("/");if(o.length<=1)return r;const a=o.pop()??"";if(!a)return r;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}`},Dl=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function An(t,s){if(!t)return"";const r=Dl(t);if(r==="/")return"/";const n=s?Dl(s):void 0;if(n&&n!=="/"){if(r===n)return"~";if(r.startsWith(`${n}/`)){const o=r.slice(n.length+1);return o?`~/${o}`:"~"}}return r}function vo(t,s){if(!t)return"/";const r=Dl(t);if(!r||r==="/")return"/";const n=s?Dl(s):void 0;return n&&n!=="/"&&r===n?"~":r.split("/").pop()||r||"/"}function ao(t,s){return s?t?t.toLowerCase().includes(s.toLowerCase())?!0:new Eb([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(s).length>0:!1:!0}function Vd({delayDuration:t=0,...s}){return e.jsx(_b,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function gt({delayDuration:t=0,...s}){return e.jsx(Vd,{delayDuration:t,children:e.jsx(Pb,{"data-slot":"tooltip",...s})})}function xt({...t}){return e.jsx(Rb,{"data-slot":"tooltip-trigger",...t})}function ht({className:t,sideOffset:s=0,children:r,...n}){return e.jsx(Fb,{children:e.jsxs(Lb,{"data-slot":"tooltip-content",sideOffset:s,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:[r,e.jsx(Ob,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}function us({...t}){return e.jsx($b,{"data-slot":"dropdown-menu",...t})}function ms({...t}){return e.jsx(Bb,{"data-slot":"dropdown-menu-trigger",...t})}function fs({className:t,sideOffset:s=4,...r}){return e.jsx(zb,{children:e.jsx(Ub,{"data-slot":"dropdown-menu-content",sideOffset:s,style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:L("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-2 border-border/60 p-1 shadow-md",t),...r})})}function Et({className:t,inset:s,variant:r="default",...n}){return e.jsx(qb,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":r,className:L("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover 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 Il({...t}){return e.jsx(Vb,{"data-slot":"dropdown-menu-radio-group",...t})}function Tl({className:t,children:s,...r}){return e.jsxs(Wb,{"data-slot":"dropdown-menu-radio-item",className:L("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[state=checked]:bg-interactive-selection data-[state=checked]:text-interactive-selection-foreground 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 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",t),...r,children:[e.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:e.jsx(Gb,{children:e.jsx(ss,{className:"size-3"})})}),s]})}function Wr({className:t,inset:s,...r}){return e.jsx(Hb,{"data-slot":"dropdown-menu-label","data-inset":s,className:L("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",t),...r})}function lr({className:t,...s}){return e.jsx(Kb,{"data-slot":"dropdown-menu-separator",className:L("bg-border -mx-1 my-0.5 h-px",t),...s})}function di({tabs:t,value:s,onValueChange:r,className:n,isInteractive:o=!0,animate:a=!0,collapseLabelsOnSmall:l=!1,collapseLabelsOnNarrow:c=!1,size:d="default"}){const u=i.useRef(null),m=i.useRef(null),[f,p]=i.useState(!1),h=i.useCallback(()=>{const g=u.current,x=m.current;if(!g||!x)return;const y=g.offsetWidth;if(!y)return;const{offsetLeft:b,offsetWidth:v}=x,j=Math.max(0,Math.min(100,b/y*100)),k=Math.max(0,Math.min(100,(b+v)/y*100));g.style.clipPath=`inset(0 ${Number(100-k).toFixed(2)}% 0 ${Number(j).toFixed(2)}% round 8px)`},[]);return i.useLayoutEffect(()=>{h(),f||p(!0)},[f,h,s,t.length]),i.useEffect(()=>{const g=u.current;if(!g)return;const x=new ResizeObserver(()=>h());return x.observe(g),()=>x.disconnect()},[h]),e.jsxs("div",{className:L("relative isolate w-full",c&&"@container/animated-tabs",n),children:[e.jsx("div",{ref:u,"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&&f?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:L("flex items-center gap-1 bg-interactive-selection text-interactive-selection-foreground",d==="sm"?"h-7 rounded-md px-1":"h-9 rounded-lg px-1.5"),children:t.map(g=>{const x=g.icon;return e.jsxs("div",{className:L("flex flex-1 items-center justify-center font-semibold",d==="sm"?"h-5 rounded-md px-2 text-xs":"h-7 rounded-lg px-2.5 text-sm",l?"gap-0 sm:gap-1.25":"gap-1.25"),children:[x?e.jsx(x,{className:L(d==="sm"?"h-3.5 w-3.5":"h-4 w-4")}):null,e.jsx("span",{className:L("animated-tabs__label truncate",l?"hidden sm:inline":null),children:g.label})]},g.value)})})}),e.jsx("div",{className:L("relative z-20 flex items-center gap-1 bg-muted/20",d==="sm"?"h-7 rounded-md px-1":"h-9 rounded-lg px-1.5"),children:t.map(g=>{const x=s===g.value,y=g.icon;return e.jsxs("button",{ref:x?m:null,type:"button",onClick:()=>{o&&r(g.value)},className:L("animated-tabs__button flex flex-1 items-center justify-center font-semibold transition-colors duration-150",d==="sm"?"h-5 rounded-md px-2 text-xs":"h-7 rounded-lg px-2.5 text-sm",l?"gap-0 sm:gap-1.25":"gap-1.25",x?"text-accent-foreground":"text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background"),"aria-pressed":x,"aria-label":g.label,"aria-disabled":!o,tabIndex:o?0:-1,children:[y?e.jsx(y,{className:L(d==="sm"?"h-3.5 w-3.5":"h-4 w-4",x?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:L("animated-tabs__label truncate",l?"hidden sm:inline":null),children:g.label})]},g.value)})})]})}function Cm({size:t,className:s,style:r,...n}){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:s,style:{width:typeof t=="number"?`${t}px`:t,height:typeof t=="number"?`${t}px`:t,...r},...n,children:e.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}let Ac=null,Dc=null;const El=()=>{const t=new Map;return{getItem:s=>t.get(s)??null,setItem:(s,r)=>{t.set(s,r)},removeItem:s=>{t.delete(s)},clear:()=>{t.clear()},key:s=>Array.from(t.keys())[s]??null,get length(){return t.size}}},Bj=()=>{if(typeof window>"u"||!window.localStorage)return El();const t=window.localStorage,s=El();let r=!0;const n=()=>{r=!1};return{getItem:u=>{if(r)try{const m=t.getItem(u);if(m!==null)return m}catch{n()}return s.getItem(u)},setItem:(u,m)=>{if(r)try{t.setItem(u,m),s.removeItem(u);return}catch{n();try{t.removeItem(u)}catch{}}s.setItem(u,m)},removeItem:u=>{try{t.removeItem(u)}catch{n()}s.removeItem(u)},clear:()=>{try{t.clear()}catch{n()}s.clear()},key:u=>{if(r)try{return t.key(u)}catch{n()}return s.key(u)},get length(){if(r)try{return t.length+s.length}catch{n()}return s.length}}},Ws=()=>(Ac||(Ac=Bj()),Ac),zj=()=>{if(typeof window>"u"||!window.sessionStorage)return El();const t=window.sessionStorage,s=El();let r=!0;const n=()=>{r=!1};return{getItem:u=>{if(r)try{const m=t.getItem(u);if(m!==null)return m}catch{n()}return s.getItem(u)},setItem:(u,m)=>{if(r)try{t.setItem(u,m),s.removeItem(u);return}catch{n();try{t.removeItem(u)}catch{}}s.setItem(u,m)},removeItem:u=>{try{t.removeItem(u)}catch{n()}s.removeItem(u)},clear:()=>{try{t.clear()}catch{n()}s.clear()},key:u=>{if(r)try{return t.key(u)}catch{n()}return s.key(u)},get length(){if(r)try{return t.length+s.length}catch{n()}return s.length}}},Uj=()=>(Dc||(Dc=zj()),Dc),Tu={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Hj={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Mm(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Un={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)"}}},cl={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Un.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:cl.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Un.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:cl.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Un.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:cl.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Un.tool.inline})},Ei={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},Xn={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Pi=(t,s)=>t?t.title===s.title&&t.message===s.message:!1,Vj=t=>{if(!t||typeof t!="object")return!1;const s=t;return Pi(s.completion,Ei.completion)&&Pi(s.error,Ei.error)&&Pi(s.question,Ei.question)&&Pi(s.subtask,Ei.subtask)},Te=Ls()(Us(Ar((t,s)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:420,hasManuallyResizedRightSidebar:!1,isBottomTerminalOpen:!1,bottomTerminalHeight:300,hasManuallyResizedBottomTerminal:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",mainTabGuard:null,sidebarOpenBeforeFullscreenTab:null,pendingDiffFile:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,showTextJustificationActivity:!1,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,messageLimit:200,toolCallExpansion:"collapsed",fontSize:100,terminalFontSize:13,padding:100,cornerRadius:12,inputBarOffset:0,favoriteModels:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"stacked",isTimelineDialogOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...Xn.completion},error:{...Xn.error},question:{...Xn.question},subtask:{...Xn.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,isMobileSessionStatusBarCollapsed:!1,setTheme:r=>{t({theme:r}),s().applyTheme()},toggleSidebar:()=>{t(r=>{const n=!r.isSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:n,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:n}})},setSidebarOpen:r=>{t(()=>{if(r&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:r,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:r}})},setSidebarWidth:r=>{t({sidebarWidth:r,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(r=>{const n=!r.isRightSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.28);return{isRightSidebarOpen:n,rightSidebarWidth:o,hasManuallyResizedRightSidebar:!1}}return{isRightSidebarOpen:n}})},setRightSidebarOpen:r=>{t(()=>{if(r&&typeof window<"u"){const n=Math.floor(window.innerWidth*.28);return{isRightSidebarOpen:r,rightSidebarWidth:n,hasManuallyResizedRightSidebar:!1}}return{isRightSidebarOpen:r}})},setRightSidebarWidth:r=>{t({rightSidebarWidth:r,hasManuallyResizedRightSidebar:!0})},toggleBottomTerminal:()=>{t(r=>{const n=!r.isBottomTerminalOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:n,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:n}})},setBottomTerminalOpen:r=>{t(()=>{if(r&&typeof window<"u"){const n=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:r,bottomTerminalHeight:n,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:r}})},setBottomTerminalHeight:r=>{t({bottomTerminalHeight:r,hasManuallyResizedBottomTerminal:!0})},setSessionSwitcherOpen:r=>{t({isSessionSwitcherOpen:r})},setMainTabGuard:r=>{s().mainTabGuard!==r&&t({mainTabGuard:r})},setActiveMainTab:r=>{const n=s().mainTabGuard;if(n&&!n(r))return;const o=s(),a=o.activeMainTab,l=["files","diff"],c=l.includes(r)&&!l.includes(a),d=!l.includes(r)&&l.includes(a);if(c)t({activeMainTab:r,sidebarOpenBeforeFullscreenTab:o.isSidebarOpen,isSidebarOpen:!1});else if(d){const u=o.sidebarOpenBeforeFullscreenTab===!0;t({activeMainTab:r,sidebarOpenBeforeFullscreenTab:null,...u&&typeof window<"u"?{isSidebarOpen:!0,sidebarWidth:Math.floor(window.innerWidth*.2),hasManuallyResizedLeftSidebar:!1}:{}})}else t({activeMainTab:r})},setPendingDiffFile:r=>{t({pendingDiffFile:r})},navigateToDiff:r=>{const n=s().mainTabGuard;if(n&&!n("diff"))return;const o=s(),a=o.activeMainTab,c=!["files","diff"].includes(a);t(c?{pendingDiffFile:r,activeMainTab:"diff",sidebarOpenBeforeFullscreenTab:o.isSidebarOpen,isSidebarOpen:!1}:{pendingDiffFile:r,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:r}=s();return r&&t({pendingDiffFile:null}),r},setIsMobile:r=>{t({isMobile:r})},toggleCommandPalette:()=>{t(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen}))},setCommandPaletteOpen:r=>{t({isCommandPaletteOpen:r})},toggleHelpDialog:()=>{t(r=>({isHelpDialogOpen:!r.isHelpDialogOpen}))},setHelpDialogOpen:r=>{t({isHelpDialogOpen:r})},setAboutDialogOpen:r=>{t({isAboutDialogOpen:r})},setOpenCodeStatusDialogOpen:r=>{t({isOpenCodeStatusDialogOpen:r})},setOpenCodeStatusText:r=>{t({openCodeStatusText:r})},setSessionCreateDialogOpen:r=>{t({isSessionCreateDialogOpen:r})},setSettingsDialogOpen:r=>{t({isSettingsDialogOpen:r})},setModelSelectorOpen:r=>{t({isModelSelectorOpen:r})},setSidebarSection:r=>{t({sidebarSection:r})},setEventStreamStatus:(r,n)=>{t({eventStreamStatus:r,eventStreamHint:n??null})},setShowReasoningTraces:r=>{t({showReasoningTraces:r})},setShowTextJustificationActivity:r=>{t({showTextJustificationActivity:r})},setAutoDeleteEnabled:r=>{t({autoDeleteEnabled:r})},setAutoDeleteAfterDays:r=>{const n=Math.max(1,Math.min(365,r));t({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:r=>{t({autoDeleteLastRunAt:r})},setMessageLimit:r=>{const n=Math.max(10,Math.min(500,Math.round(r)));t({messageLimit:n})},setToolCallExpansion:r=>{t({toolCallExpansion:r})},setFontSize:r=>{const n=Math.max(50,Math.min(200,r));t({fontSize:n}),s().applyTypography()},setTerminalFontSize:r=>{const n=Math.round(r),o=Math.max(9,Math.min(52,n));t({terminalFontSize:o})},setPadding:r=>{const n=Math.max(50,Math.min(200,r));t({padding:n}),s().applyPadding()},setCornerRadius:r=>{t({cornerRadius:r})},applyTypography:()=>{const{fontSize:r}=s(),n=document.documentElement,o=r/100,a=Object.entries(Tu);if(o===1){for(const[l]of a)n.style.removeProperty(Mm(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Mm(l),`${d*o}rem`)}},applyPadding:()=>{const{padding:r}=s(),n=document.documentElement,o=r/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:r=>{t({diffLayoutPreference:r})},setDiffFileLayout:(r,n)=>{t(o=>({diffFileLayout:{...o.diffFileLayout,[r]:n}}))},setDiffWrapLines:r=>{t({diffWrapLines:r})},setDiffViewMode:r=>{t({diffViewMode:r})},setInputBarOffset:r=>{t({inputBarOffset:r})},setKeyboardOpen:r=>{t({isKeyboardOpen:r})},toggleFavoriteModel:(r,n)=>{t(o=>o.favoriteModels.some(l=>l.providerID===r&&l.modelID===n)?{favoriteModels:o.favoriteModels.filter(l=>!(l.providerID===r&&l.modelID===n))}:{favoriteModels:[{providerID:r,modelID:n},...o.favoriteModels]})},isFavoriteModel:(r,n)=>{const{favoriteModels:o}=s();return o.some(a=>a.providerID===r&&a.modelID===n)},addRecentModel:(r,n)=>{t(o=>{const a=o.recentModels.filter(l=>!(l.providerID===r&&l.modelID===n));return{recentModels:[{providerID:r,modelID:n},...a].slice(0,5)}})},addRecentAgent:r=>{const n=typeof r=="string"?r.trim():"";n&&t(o=>{if(o.recentAgents.includes(n))return o;const a=o.recentAgents;return{recentAgents:[n,...a].slice(0,5)}})},addRecentEffort:(r,n,o)=>{const a=typeof r=="string"?r.trim():"",l=typeof n=="string"?n.trim():"";if(!a||!l)return;const c=`${a}/${l}`,d=typeof o=="string"&&o.trim().length>0?o.trim():"default";t(u=>{const m=u.recentEfforts[c]??[];if(m.includes(d))return u;const f=m;return{recentEfforts:{...u.recentEfforts,[c]:[d,...f].slice(0,5)}}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||t(r=>{const n={};return r.isSidebarOpen&&!r.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),r.isRightSidebarOpen&&!r.hasManuallyResizedRightSidebar&&(n.rightSidebarWidth=Math.floor(window.innerWidth*.28)),r.isBottomTerminalOpen&&!r.hasManuallyResizedBottomTerminal&&(n.bottomTerminalHeight=Math.floor(window.innerHeight*.32)),n})},applyTheme:()=>{const{theme:r}=s(),n=document.documentElement;if(n.classList.remove("light","dark"),r==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(r)},setMultiRunLauncherOpen:r=>{t(n=>({isMultiRunLauncherOpen:r,multiRunLauncherPrefillPrompt:r?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:r=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:r,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:r=>{t({isTimelineDialogOpen:r})},setImagePreviewOpen:r=>{t({isImagePreviewOpen:r})},setNativeNotificationsEnabled:r=>{t({nativeNotificationsEnabled:r})},setNotificationMode:r=>{t({notificationMode:r})},setShowTerminalQuickKeysOnDesktop:r=>{t({showTerminalQuickKeysOnDesktop:r})},setNotifyOnSubtasks:r=>{t({notifyOnSubtasks:r})},setNotifyOnCompletion:r=>{t({notifyOnCompletion:r})},setNotifyOnError:r=>{t({notifyOnError:r})},setNotifyOnQuestion:r=>{t({notifyOnQuestion:r})},setNotificationTemplates:r=>{t({notificationTemplates:r})},setSummarizeLastMessage:r=>{t({summarizeLastMessage:r})},setSummaryThreshold:r=>{t({summaryThreshold:r})},setSummaryLength:r=>{t({summaryLength:r})},setMaxLastMessageLength:r=>{t({maxLastMessageLength:r})},setPersistChatDraft:r=>{t({persistChatDraft:r})},setIsMobileSessionStatusBarCollapsed:r=>{t({isMobileSessionStatusBarCollapsed:r})}}),{name:"ui-store",storage:Dr(()=>Ws()),version:3,migrate:(t,s)=>{if(!t||typeof t!="object")return t;const r=t;if(s<1&&Vj(r.notificationTemplates)&&(r.notificationTemplates={completion:{...Xn.completion},error:{...Xn.error},question:{...Xn.question},subtask:{...Xn.subtask}}),s<3){const n=new Set([90,120,180,220]),o=r.memoryLimitHistorical,a=r.memoryLimitActiveSession;typeof o=="number"&&!n.has(o)?r.messageLimit=o:typeof a=="number"&&!n.has(a)&&(r.messageLimit=a),delete r.memoryLimitHistorical,delete r.memoryLimitViewport,delete r.memoryLimitActiveSession}return r},partialize:t=>({theme:t.theme,isSidebarOpen:t.isSidebarOpen,sidebarWidth:t.sidebarWidth,isRightSidebarOpen:t.isRightSidebarOpen,rightSidebarWidth:t.rightSidebarWidth,isBottomTerminalOpen:t.isBottomTerminalOpen,bottomTerminalHeight:t.bottomTerminalHeight,isSessionSwitcherOpen:t.isSessionSwitcherOpen,activeMainTab:t.activeMainTab,sidebarSection:t.sidebarSection,isSessionCreateDialogOpen:t.isSessionCreateDialogOpen,showReasoningTraces:t.showReasoningTraces,showTextJustificationActivity:t.showTextJustificationActivity,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,autoDeleteLastRunAt:t.autoDeleteLastRunAt,messageLimit:t.messageLimit,toolCallExpansion:t.toolCallExpansion,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,diffViewMode:t.diffViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,showTerminalQuickKeysOnDesktop:t.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:t.notifyOnSubtasks,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,persistChatDraft:t.persistChatDraft,isMobileSessionStatusBarCollapsed:t.isMobileSessionStatusBarCollapsed})}),{name:"ui-store"}));async function Wj(){try{const t=await fetch("/api/ikanban/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Server responded with ${t.status}`);const s=await t.json();return{available:s.available??!1,version:s.version,currentVersion:s.currentVersion??"unknown",body:s.body,packageManager:s.packageManager,updateCommand:s.updateCommand}}catch(t){return console.warn("Failed to check for web updates:",t),null}}function Gj(){return As()?Or()?"desktop":"web":_o()?"web":null}const Am={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},ac=Ls()((t,s)=>({...Am,checkForUpdates:async()=>{const r=Gj();if(r){t({checking:!0,error:null,runtimeType:r});try{let n=null;r==="desktop"?n=await _g():r==="web"&&(n=await Wj()),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:r,runtimeType:n}=s();if(!(n!=="desktop"||!r)){t({downloading:!0,error:null,progress:null});try{if(!await $g(a=>{t({progress:a})}))throw new Error("Desktop update only works on Local instance");t({downloading:!1,downloaded:!0})}catch(o){t({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:r,runtimeType:n}=s();if(!(n!=="desktop"||!r))try{if(!await Bg())throw new Error("Desktop restart only works on Local instance")}catch(o){t({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{t({available:!1,downloaded:!1,info:null})},reset:()=>{t(Am)}})),Kj="/api",qj=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Qj=t=>{const s=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(qj.test(s)||typeof window>"u")return s;const r=window.location?.href||window.location?.origin;if(!r)return s;try{return new URL(s,r).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),s}},Yj=()=>{if(typeof window>"u")return null;const t=window.__IKANBAN_DESKTOP_SERVER__,s=!!window.__IKANBAN_RUNTIME_APIS__?.runtime?.isDesktop;if(!t||!s)return null;const r=typeof t.origin=="string"&&t.origin.length>0?t.origin:null;return r?`${r}/api`:null},Ri=t=>t.replace(/\\/g,"/"),Ic=()=>{if(typeof window>"u")return null;const t=window.__IKANBAN_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class Jj{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;globalSseQueue=[];globalSseBuffer=[];globalSseCoalesced=new Map;globalSseFlushTimer=null;globalSseLastFlushAt=0;constructor(s=Kj){const n=Yj()||s;this.baseUrl=Qj(n),this.client=hm({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}getScopedApiClient(s){const r=this.normalizeCandidatePath(s)??s,n=r||"",o=this.scopedClients.get(n);if(o)return o;const a=hm({baseUrl:this.baseUrl,directory:r});return this.scopedClients.set(n,a),a}normalizeCandidatePath(s){if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const n=r.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(s){const r=s.match(/^([A-Za-z]:)(?:\/|$)/);if(r){const a=r[1],c=s.slice(a.length+(s.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=s.startsWith("/"),o=s.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(s){this.currentDirectory=s}getDirectory(){return this.currentDirectory}async withDirectory(s,r){if(s==null)return r();const n=this.currentDirectory;this.currentDirectory=s;try{return await r()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const s=new Set,r=o=>{const a=this.normalizeCandidatePath(o);a&&s.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(r(a.directory),r(a.worktree),r(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!s.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);r(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!s.size)try{(await this.listSessions()).forEach(a=>r(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(r(this.currentDirectory),typeof window<"u")try{r(window.localStorage.getItem("lastDirectory")),r(window.localStorage.getItem("homeDirectory"))}catch{}if(!s.size&&typeof process<"u"&&typeof process.cwd=="function"&&r(process.cwd()),!s.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(s);return this.deriveHomeDirectory(n)}async probeDirectory(s){const r=this.normalizeCandidatePath(s);if(!r)return!1;try{const o=(await this.client.path.get({directory:r})).data,a=typeof o?.directory=="string"?o.directory:null;return!!(a&&a.trim().length>0)}catch{return!1}}async listSessions(){const s=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(s.data)?s.data:[]}async createSession(s){const r=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:s?.parentID,title:s?.title});if(!r.data)throw new Error("Failed to create session");return r.data}async getSession(s){const r=await this.client.session.get({sessionID:s,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!r.data)throw new Error("Session not found");return r.data}async deleteSession(s){return(await this.client.session.delete({sessionID:s,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(s,r){const n=await this.client.session.update({sessionID:s,...this.currentDirectory?{directory:this.currentDirectory}:{},title:r});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(s,r){return(await this.client.session.messages({sessionID:s,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof r=="number"?{limit:r}:{}})).data||[]}async getSessionTodos(s){try{const r=this.baseUrl.replace(/\/$/,""),n=new URL(`${r}/session/${encodeURIComponent(s)}/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(s){if(!s)return!1;const r=s.toLowerCase();return r.startsWith("text/")&&r!=="text/plain"||r==="application/octet-stream"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript"].includes(r)}isHeicMime(s){if(!s)return!1;const r=s.toLowerCase();return r==="image/heic"||r==="image/heif"}async convertHeicToJpeg(s){try{const r=(await Ks(async()=>{const{default:f}=await import("./vendor-.bun-CTUAJ4e1.js").then(p=>p.h);return{default:f}},__vite__mapDeps([0,1]))).default,n=s.url.indexOf(",");if(n===-1)return s;const o=s.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:s.mime}),d=await r({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=s.filename;return m&&(m=m.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:m,url:u}}catch(r){return console.warn("Failed to convert HEIC to JPEG:",r),s}}async normalizeFilePart(s){if(this.isHeicMime(s.mime))return this.convertHeicToJpeg(s);if(!this.shouldNormalizeToTextPlain(s.mime))return s;let r=s.url;if(s.url.startsWith("data:")){const n=s.url.indexOf(",");if(n!==-1){const o=s.url.substring(5,n),a=s.url.substring(n);r=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:s.filename,url:r}}async sendMessage(s){const r=Date.now(),n=s.messageId??`temp_${r}_${Math.random().toString(36).substring(2,9)}`,o=[];if(s.prefaceText&&s.prefaceText.trim()&&o.push({type:"text",text:s.prefaceText,synthetic:s.prefaceTextSynthetic!==!1}),s.text&&s.text.trim()){const a={type:"text",text:s.text};o.push(a)}if(s.files&&s.files.length>0)for(const a of s.files){const l=await this.normalizeFilePart(a),c={...a.id?{id:a.id}:{},type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(c)}if(s.additionalParts&&s.additionalParts.length>0){for(const a of s.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={...l.id?{id:l.id}:{},type:"file",mime:c.mime,filename:c.filename,url:c.url};o.push(d)}}if(s.agentMentions&&s.agentMentions.length>0){const[a]=s.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:s.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:s.providerID,modelID:s.modelID},agent:s.agent,variant:s.variant,parts:o}),n}async abortSession(s){return!!(await this.client.session.abort({sessionID:s,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(s,r,n){const o=await this.client.session.revert({sessionID:s,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:r,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(s){const r=await this.client.session.unrevert({sessionID:s,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!r.data)throw new Error("Failed to unrevert session");return r.data}async forkSession(s,r){const n=await this.client.session.fork({sessionID:s,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:r});if(!n.data)throw new Error("Failed to fork session");return n.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(s){try{const r=this.baseUrl.replace(/\/$/,""),n=new URL(`${r}/session/status`),o=typeof s=="string"?s.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 s=await fetch("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)return null;const r=await s.json().catch(()=>null);return!r||typeof r!="object"?null:r}catch{return null}}async listToolIds(s){try{const r=typeof s?.directory=="string"?s.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(r?{directory:r}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(s,r,n){return(await this.client.permission.reply({requestID:s,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:r,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async replyToQuestion(s,r){const n=!Array.isArray(r)||r.length===0?[]:Array.isArray(r[0])?r:[r];return(await this.client.question.reply({requestID:s,...this.currentDirectory?{directory:this.currentDirectory}:{},answers:n})).data||!1}async rejectQuestion(s){return(await this.client.question.reject({requestID:s,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async listPendingQuestions(s){const r=[],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[]}};r.push(n(null));const o=new Set;for(const d of s?.directories??[]){const u=this.normalizeCandidatePath(d??null);u&&o.add(u)}for(const d of o)r.push(n(d));const a=await Promise.all(r),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 s=await this.client.config.get();if(!s.data)throw new Error("Failed to get config");return s.data}async updateConfig(s){const r=`${this.baseUrl}/config`,n=await fetch(r,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});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(s){const r=await this.getConfig(),n=s(r);return await this.updateConfig(n)}async getProviders(){const s=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!s.data)throw new Error("Failed to get providers");return s.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(s){if(!s)return null;const r=s.split(`
|
|
3
|
+
`),n=[];let o;for(const l of r)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(s){if(!s||typeof s!="object")return null;const r=s,n=typeof r.directory=="string"?r.directory:typeof r.properties=="object"&&r.properties!==null?r.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof r.type=="string")return{directory:o&&o.length>0?o:"global",payload:r};const a=r.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(s){this.enqueueGlobalSseEvent(s)}notifyGlobalSseOpen(){for(const s of this.globalSseOpenListeners)try{s()}catch(r){console.warn("[OpencodeClient] Global SSE open handler error:",r)}}notifyGlobalSseError(s){for(const r of this.globalSseErrorListeners)try{r(s)}catch(n){console.warn("[OpencodeClient] Global SSE error handler failed:",n)}}ensureGlobalSseStarted(){if(this.globalSseTask)return;const s=new AbortController;this.globalSseAbortController=s,this.globalSseTask=this.runGlobalSseLoop(s).catch(r=>{r?.name==="AbortError"||s.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",r)}).finally(()=>{this.globalSseAbortController===s&&(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,this.clearGlobalSseQueue())}clearGlobalSseQueue(){this.globalSseFlushTimer&&(clearTimeout(this.globalSseFlushTimer),this.globalSseFlushTimer=null),this.globalSseQueue.length=0,this.globalSseBuffer.length=0,this.globalSseCoalesced.clear()}getGlobalSseCoalesceKey(s){const r=s.payload,n=typeof r.type=="string"?r.type:null;if(!n)return null;const o=typeof r.properties=="object"&&r.properties!==null?r.properties:null;if(n==="session.status"){const a=typeof o?.sessionID=="string"?o.sessionID:typeof o?.sessionId=="string"?o.sessionId:null;return a?`session.status:${s.directory}:${a}`:null}if(n==="ikanban:session-status"){const a=typeof o?.sessionId=="string"?o.sessionId:typeof o?.sessionID=="string"?o.sessionID:null;return a?`ikanban:session-status:${a}`:null}return null}flushGlobalSseQueue=()=>{if(this.globalSseFlushTimer&&(clearTimeout(this.globalSseFlushTimer),this.globalSseFlushTimer=null),this.globalSseQueue.length===0)return;const s=this.globalSseQueue;this.globalSseQueue=this.globalSseBuffer,this.globalSseBuffer=s,this.globalSseQueue.length=0,this.globalSseCoalesced.clear(),this.globalSseLastFlushAt=Date.now();for(const r of s)if(r)for(const n of this.globalSseListeners)try{n(r)}catch(o){console.warn("[OpencodeClient] Global SSE listener error:",o)}this.globalSseBuffer.length=0};scheduleGlobalSseFlush(){if(this.globalSseFlushTimer)return;const s=Date.now()-this.globalSseLastFlushAt,r=Math.max(0,16-s);this.globalSseFlushTimer=setTimeout(this.flushGlobalSseQueue,r)}enqueueGlobalSseEvent(s){const r=this.getGlobalSseCoalesceKey(s);if(r){const n=this.globalSseCoalesced.get(r);n!==void 0&&(this.globalSseQueue[n]=void 0),this.globalSseCoalesced.set(r,this.globalSseQueue.length)}this.globalSseQueue.push(s),this.scheduleGlobalSseFlush()}async runGlobalSseLoop(s){const r=`${this.baseUrl.replace(/\/+$/,"")}/global/event`;let n=0;for(;!s.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(r,{method:"GET",headers:a,signal:s.signal});if(!l.ok||!l.body)throw new Error(`Global SSE connect failed with status ${l.status}`);n=0,this.globalSseIsConnected=!0,s.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||s.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 y=this.normalizeRoutedSsePayload(x.data);y&&this.emitGlobalSseEvent(y)}}const m=u.trim();if(m&&!s.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"||s.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",a),this.notifyGlobalSseError(a)}if(s.signal.aborted)break;n+=1;const o=Math.min(3e3*Math.pow(2,n),3e4);await new Promise(a=>setTimeout(a,o))}this.flushGlobalSseQueue()}subscribeToGlobalEvents(s,r,n,o){const a=this.normalizeCandidatePath(o?.directory??null),l=c=>{a&&c.directory!==a||s(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)),r&&this.globalSseErrorListeners.add(r),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(l),n&&this.globalSseOpenListeners.delete(n),r&&this.globalSseErrorListeners.delete(r),this.maybeStopGlobalSse()}}subscribeToEvents(s,r,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 y=x.payload,b=typeof y.properties=="object"&&y.properties!==null?y.properties:{};return b.directory===x.directory?x.payload:{...y,properties:{...b,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||s(h(x))},r?x=>{u.signal.aborted||r(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 b={...(typeof x.properties=="object"&&x.properties!==null?x.properties:null)??{},directory:h.directory};return{...x,properties:b}}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,y={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:v=>{v instanceof Error&&v.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",v),r&&!u.signal.aborted&&r(v))},onSseEvent:v=>{if(u.signal.aborted)return;v.id&&typeof v.id=="string"&&(m=v.id);const j=v.data,k=f(j);k&&s(k)}};m&&(y.headers={...y.headers||{},"Last-Event-ID":m});const b=await this.client.event.subscribe(x,y);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const v of b.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),r&&r(x);const y=Math.min(3e3*Math.pow(2,g),3e4);await new Promise(b=>setTimeout(b,y)),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(y=>setTimeout(y,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(s){try{const r=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s,directory:this.currentDirectory})});if(!r.ok)throw new Error(`Failed to read file: ${r.statusText}`);return await r.text()}catch{return`// Content of ${s}
|
|
8
|
+
// This would be loaded from the server`}}async listFiles(s){try{const r=s||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:r})});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(r=>({name:r.name,description:r.description,agent:r.agent,model:r.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(r=>({name:r.name,description:r.description,agent:r.agent,model:r.model,template:r.template,subtask:r.subtask}))}catch{return[]}}async getCommandDetails(s){try{const r=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(r.data){const n=r.data.find(o=>o.name===s);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 s;const r=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;r==="/api"?s="/health":r.endsWith("/api")?s=`${r.slice(0,-4)}/health`:s=`${r}/health`;const n=await fetch(s);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(s,r){const n=Ic();if(n?.createDirectory)try{return await n.createDirectory(s)}catch(c){const d=c instanceof Error?c.message:String(c);throw new Error(d||"Failed to create directory")}const o={path:s,...r?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},a=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok){const c=await a.json().catch(()=>({error:"Failed to create directory"}));throw new Error(c.error||"Failed to create directory")}return await a.json()}async listLocalDirectory(s,r){const n=Ic();if(n)try{const o=await n.listDirectory(s||"",r);return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:Ri(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;s&&s.trim().length>0&&o.set("path",s),r?.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(s,r){const n=Ic(),o=typeof r?.directory=="string"&&r.directory.trim().length>0?r.directory.trim():this.currentDirectory,a=o?Ri(o):null;if(n)try{const m=await n.search({directory:o||"",query:s,maxResults:r?.limit,includeHidden:r?.includeHidden,respectGitignore:r?.respectGitignore});return Array.isArray(m)?m.map(f=>{const p=Ri(f.path),h=p.split("/").filter(Boolean).pop()||p,g=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?Ri(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 s=="string"&&l.set("q",s),typeof r?.limit=="number"&&Number.isFinite(r.limit)&&l.set("limit",String(r.limit)),r?.includeHidden&&l.set("includeHidden","true"),r?.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 s=await oc();if(s)return s;try{const r=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!r.ok){const o=await r.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 r.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(r){return console.warn("Failed to resolve filesystem home directory:",r),null}}async setOpenCodeWorkingDirectory(s){if(!s||typeof s!="string"||!s.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",s),null;const r=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",r,"with path:",s);try{const n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s})}),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:s}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const nt=new Jj,Xj=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:nt},Symbol.toStringTag,{value:"Module"})),Wd=new Set;function ic(t){return Wd.add(t),()=>{Wd.delete(t)}}function Tn(t,s){const r=Array.isArray(t)?t:[t],n=Array.from(new Set(r));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:s?.source,timestamp:Date.now()};for(const a of Wd)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 ui(t,s){return t.scopes.includes("all")||t.scopes.includes(s)}const Eu="Updating OpenCode configuration...";let En=0,ho=Eu;const Gd=new Set;function Pl(){const t={isUpdating:En>0,message:ho};Gd.forEach(s=>s(t))}function Gr(t){En+=1,En===1?(ho=t||Eu,Pl()):t&&(ho=t,Pl())}function Fr(){En!==0&&(En-=1,En===0&&(ho=Eu,Pl()))}function Wn(t){ho===t&&En>0||(ho=t,En>0&&Pl())}function Zj(t){return Gd.add(t),t({isUpdating:En>0,message:ho}),()=>{Gd.delete(t)}}function eS(){return{isUpdating:En>0,message:ho}}const Dn=Ls()(Us(Ar((t,s)=>({queuedMessages:{},queueModeEnabled:!0,addToQueue:(r,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[r]??[];return{queuedMessages:{...l.queuedMessages,[r]:[...c,a]}}})},removeFromQueue:(r,n)=>{t(o=>{const l=(o.queuedMessages[r]??[]).filter(c=>c.id!==n);if(l.length===0){const{[r]:c,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[r]:l}}})},popToInput:(r,n)=>{const l=(s().queuedMessages[r]??[]).find(c=>c.id===n);return l?(t(c=>{const u=(c.queuedMessages[r]??[]).filter(m=>m.id!==n);if(u.length===0){const{[r]:m,...f}=c.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...c.queuedMessages,[r]:u}}}),l):null},clearQueue:r=>{t(n=>{const{[r]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:r=>{t({queueModeEnabled:r}),xs({queueModeEnabled:r})},getQueueForSession:r=>s().queuedMessages[r]??[]}),{name:"message-queue-store",storage:Dr(()=>Ws()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),Wg="directoryTreeShowHidden",Kd="directory-show-hidden-change",Dm=()=>{if(typeof window>"u")return!0;try{const t=Ws().getItem(Wg);return t===null?!0:t==="true"}catch{return!0}},tS=()=>{typeof window>"u"||window.dispatchEvent(new Event(Kd))},Pu=(t,s={})=>{if(!(typeof window>"u")){try{Ws().setItem(Wg,t?"true":"false"),tS()}catch{}s.persist!==!1&&xs({directoryShowHidden:t})}},wi=()=>{const[t,s]=i.useState(Dm);return i.useEffect(()=>{if(typeof window>"u")return;const r=()=>{s(Dm())};return window.addEventListener("storage",r),window.addEventListener(Kd,r),()=>{window.removeEventListener("storage",r),window.removeEventListener(Kd,r)}},[]),t},Gg="filesViewShowGitignored",qd="files-view-show-gitignored-change",Im=()=>{if(typeof window>"u")return!1;try{return Ws().getItem(Gg)==="true"}catch{return!1}},sS=()=>{typeof window>"u"||window.dispatchEvent(new Event(qd))},Kg=(t,s={})=>{if(!(typeof window>"u")){try{Ws().setItem(Gg,t?"true":"false"),sS()}catch{}s.persist!==!1&&xs({filesViewShowGitignored:t})}},lc=()=>{const[t,s]=i.useState(Im);return i.useEffect(()=>{if(typeof window>"u")return;const r=()=>{s(Im())};return window.addEventListener("storage",r),window.addEventListener(qd,r),()=>{window.removeEventListener("storage",r),window.removeEventListener(qd,r)}},[]),t},rS=t=>{if(!t||typeof t!="object")return null;const s={};return typeof t.showReasoningTraces=="boolean"&&(s.showReasoningTraces=t.showReasoningTraces),Object.keys(s).length>0?s:null},nS=t=>!t||typeof t!="object"?null:{showReasoningTraces:t.showReasoningTraces},oS=t=>{const s=Te.getState();typeof t.showReasoningTraces=="boolean"&&s.setShowReasoningTraces(t.showReasoningTraces)},aS=async()=>{if(typeof window>"u")return null;const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const s=JSON.parse(t),r=nS(s);return rS(r)}catch(s){return console.warn("Failed to parse stored appearance preferences:",s),null}};let qg=null;const Tm=t=>{qg=t},Ur=()=>qg,Qd=t=>{if(!(typeof window>"u")){if(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.__IKANBAN_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"),Array.isArray(t.projects)&&t.projects.length>0){const s=t.projects.filter(r=>r.sidebarCollapsed===!0).map(r=>r.id).filter(r=>typeof r=="string"&&r.length>0);s.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(s)):localStorage.removeItem("oc.sessions.projectCollapse")}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"),typeof t.openInAppId=="string"&&t.openInAppId.length>0&&localStorage.setItem("openInAppId",t.openInAppId)}},iS=t=>{if(!Array.isArray(t))return;const s=[],r=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||r.has(a)||(r.add(a),s.push({id:a,label:l,source:c,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return s},lS=t=>{if(!Array.isArray(t))return;const s=[],r=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||r.has(l)||n.has(d))continue;r.add(l),n.add(d);const u={id:l,path:d};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),typeof a.sidebarCollapsed=="boolean"&&(u.sidebarCollapsed=a.sidebarCollapsed),s.push(u)}return s.length>0?s:void 0},Em=(t,s)=>{if(!Array.isArray(t))return;const r=[],n=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,l=typeof a.providerID=="string"?a.providerID.trim():"",c=typeof a.modelID=="string"?a.modelID.trim():"";if(!l||!c)continue;const d=`${l}/${c}`;if(!n.has(d)&&(n.add(d),r.push({providerID:l,modelID:c}),r.length>=s))break}return r},Qg=()=>{const t=Te.persist;if(t&&typeof t=="object")return t},Yg=()=>Ur()?.settings??null,Yd=t=>{const s=Te.getState(),r=Dn.getState();if(typeof t.showReasoningTraces=="boolean"&&t.showReasoningTraces!==s.showReasoningTraces&&s.setShowReasoningTraces(t.showReasoningTraces),typeof t.autoDeleteEnabled=="boolean"&&t.autoDeleteEnabled!==s.autoDeleteEnabled&&s.setAutoDeleteEnabled(t.autoDeleteEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)){const o=Math.max(1,Math.min(365,t.autoDeleteAfterDays));o!==s.autoDeleteAfterDays&&s.setAutoDeleteAfterDays(o)}const n=new Set([90,120,180,220]);if(typeof t.messageLimit=="number"&&Number.isFinite(t.messageLimit)&&(n.has(t.messageLimit)||s.setMessageLimit(t.messageLimit)),typeof t.queueModeEnabled=="boolean"&&t.queueModeEnabled!==r.queueModeEnabled&&r.setQueueMode(t.queueModeEnabled),typeof t.showTextJustificationActivity=="boolean"&&t.showTextJustificationActivity!==s.showTextJustificationActivity&&s.setShowTextJustificationActivity(t.showTextJustificationActivity),typeof t.nativeNotificationsEnabled=="boolean"&&t.nativeNotificationsEnabled!==s.nativeNotificationsEnabled&&s.setNativeNotificationsEnabled(t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&t.notificationMode!==s.notificationMode&&s.setNotificationMode(t.notificationMode),typeof t.notifyOnSubtasks=="boolean"&&t.notifyOnSubtasks!==s.notifyOnSubtasks&&s.setNotifyOnSubtasks(t.notifyOnSubtasks),typeof t.notifyOnCompletion=="boolean"&&t.notifyOnCompletion!==s.notifyOnCompletion&&s.setNotifyOnCompletion(t.notifyOnCompletion),typeof t.notifyOnError=="boolean"&&t.notifyOnError!==s.notifyOnError&&s.setNotifyOnError(t.notifyOnError),typeof t.notifyOnQuestion=="boolean"&&t.notifyOnQuestion!==s.notifyOnQuestion&&s.setNotifyOnQuestion(t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates=="object"&&s.setNotificationTemplates(t.notificationTemplates),typeof t.summarizeLastMessage=="boolean"&&t.summarizeLastMessage!==s.summarizeLastMessage&&s.setSummarizeLastMessage(t.summarizeLastMessage),typeof t.summaryThreshold=="number"&&Number.isFinite(t.summaryThreshold)&&s.setSummaryThreshold(t.summaryThreshold),typeof t.summaryLength=="number"&&Number.isFinite(t.summaryLength)&&s.setSummaryLength(t.summaryLength),typeof t.maxLastMessageLength=="number"&&Number.isFinite(t.maxLastMessageLength)&&s.setMaxLastMessageLength(t.maxLastMessageLength),typeof t.toolCallExpansion=="string"&&(t.toolCallExpansion==="collapsed"||t.toolCallExpansion==="activity"||t.toolCallExpansion==="detailed")&&t.toolCallExpansion!==s.toolCallExpansion&&s.setToolCallExpansion(t.toolCallExpansion),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&t.fontSize!==s.fontSize&&s.setFontSize(t.fontSize),typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&t.terminalFontSize!==s.terminalFontSize&&s.setTerminalFontSize(t.terminalFontSize),typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding!==s.padding&&s.setPadding(t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&t.cornerRadius!==s.cornerRadius&&s.setCornerRadius(t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&t.inputBarOffset!==s.inputBarOffset&&s.setInputBarOffset(t.inputBarOffset),Array.isArray(t.favoriteModels)){const o=s.favoriteModels,a=t.favoriteModels;o.length===a.length&&o.every((c,d)=>c.providerID===a[d]?.providerID&&c.modelID===a[d]?.modelID)||Te.setState({favoriteModels:a})}if(Array.isArray(t.recentModels)){const o=s.recentModels,a=t.recentModels;o.length===a.length&&o.every((c,d)=>c.providerID===a[d]?.providerID&&c.modelID===a[d]?.modelID)||Te.setState({recentModels:a})}typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&t.diffLayoutPreference!==s.diffLayoutPreference&&s.setDiffLayoutPreference(t.diffLayoutPreference),typeof t.diffViewMode=="string"&&(t.diffViewMode==="single"||t.diffViewMode==="stacked")&&t.diffViewMode!==s.diffViewMode&&s.setDiffViewMode(t.diffViewMode),typeof t.directoryShowHidden=="boolean"&&Pu(t.directoryShowHidden,{persist:!1}),typeof t.filesViewShowGitignored=="boolean"&&Kg(t.filesViewShowGitignored,{persist:!1})},Pm=t=>{if(!t||typeof t!="object")return null;const s=t,r={};if(typeof s.themeId=="string"&&s.themeId.length>0&&(r.themeId=s.themeId),(s.useSystemTheme===!0||s.useSystemTheme===!1)&&(r.useSystemTheme=s.useSystemTheme),typeof s.themeVariant=="string"&&(s.themeVariant==="light"||s.themeVariant==="dark")&&(r.themeVariant=s.themeVariant),typeof s.lightThemeId=="string"&&s.lightThemeId.length>0&&(r.lightThemeId=s.lightThemeId),typeof s.darkThemeId=="string"&&s.darkThemeId.length>0&&(r.darkThemeId=s.darkThemeId),typeof s.lastDirectory=="string"&&s.lastDirectory.length>0&&(r.lastDirectory=s.lastDirectory),typeof s.homeDirectory=="string"&&s.homeDirectory.length>0&&(r.homeDirectory=s.homeDirectory),typeof s.opencodeBinary=="string"){const c=s.opencodeBinary.trim();r.opencodeBinary=c.length>0?c:void 0}const n=lS(s.projects);if(n&&(r.projects=n),typeof s.activeProjectId=="string"&&s.activeProjectId.length>0&&(r.activeProjectId=s.activeProjectId),Array.isArray(s.approvedDirectories)&&(r.approvedDirectories=s.approvedDirectories.filter(c=>typeof c=="string"&&c.length>0)),Array.isArray(s.securityScopedBookmarks)&&(r.securityScopedBookmarks=s.securityScopedBookmarks.filter(c=>typeof c=="string"&&c.length>0)),Array.isArray(s.pinnedDirectories)&&(r.pinnedDirectories=Array.from(new Set(s.pinnedDirectories.filter(c=>typeof c=="string"&&c.length>0)))),typeof s.showReasoningTraces=="boolean"&&(r.showReasoningTraces=s.showReasoningTraces),typeof s.autoDeleteEnabled=="boolean"&&(r.autoDeleteEnabled=s.autoDeleteEnabled),typeof s.autoDeleteAfterDays=="number"&&Number.isFinite(s.autoDeleteAfterDays)&&(r.autoDeleteAfterDays=s.autoDeleteAfterDays),typeof s.defaultModel=="string"&&s.defaultModel.length>0&&(r.defaultModel=s.defaultModel),typeof s.defaultVariant=="string"&&s.defaultVariant.length>0&&(r.defaultVariant=s.defaultVariant),typeof s.defaultAgent=="string"&&s.defaultAgent.length>0&&(r.defaultAgent=s.defaultAgent),typeof s.autoCreateWorktree=="boolean"&&(r.autoCreateWorktree=s.autoCreateWorktree),typeof s.gitmojiEnabled=="boolean"&&(r.gitmojiEnabled=s.gitmojiEnabled),typeof s.queueModeEnabled=="boolean"&&(r.queueModeEnabled=s.queueModeEnabled),typeof s.showTextJustificationActivity=="boolean"&&(r.showTextJustificationActivity=s.showTextJustificationActivity),typeof s.nativeNotificationsEnabled=="boolean"&&(r.nativeNotificationsEnabled=s.nativeNotificationsEnabled),typeof s.notificationMode=="string"&&(s.notificationMode==="always"||s.notificationMode==="hidden-only")&&(r.notificationMode=s.notificationMode),typeof s.notifyOnSubtasks=="boolean"&&(r.notifyOnSubtasks=s.notifyOnSubtasks),typeof s.notifyOnCompletion=="boolean"&&(r.notifyOnCompletion=s.notifyOnCompletion),typeof s.notifyOnError=="boolean"&&(r.notifyOnError=s.notifyOnError),typeof s.notifyOnQuestion=="boolean"&&(r.notifyOnQuestion=s.notifyOnQuestion),s.notificationTemplates&&typeof s.notificationTemplates=="object"){const c=s.notificationTemplates,d=h=>{const g=c[h];if(!g||typeof g!="object")return;const x=g,y=typeof x.title=="string"?x.title:"",b=typeof x.message=="string"?x.message:"";return{title:y,message:b}},u=d("completion"),m=d("error"),f=d("question"),p=d("subtask");(u||m||f||p)&&(r.notificationTemplates={completion:u??{title:"Task Complete",message:"Your task has finished."},error:m??{title:"Error Occurred",message:"An error occurred while processing your task."},question:f??{title:"Input Needed",message:"Please provide input to continue."},subtask:p??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof s.summarizeLastMessage=="boolean"&&(r.summarizeLastMessage=s.summarizeLastMessage),typeof s.summaryThreshold=="number"&&Number.isFinite(s.summaryThreshold)&&(r.summaryThreshold=Math.max(0,Math.round(s.summaryThreshold))),typeof s.summaryLength=="number"&&Number.isFinite(s.summaryLength)&&(r.summaryLength=Math.max(10,Math.round(s.summaryLength))),typeof s.maxLastMessageLength=="number"&&Number.isFinite(s.maxLastMessageLength)&&(r.maxLastMessageLength=Math.max(10,Math.round(s.maxLastMessageLength))),typeof s.usageAutoRefresh=="boolean"&&(r.usageAutoRefresh=s.usageAutoRefresh),typeof s.usageRefreshIntervalMs=="number"&&Number.isFinite(s.usageRefreshIntervalMs)&&(r.usageRefreshIntervalMs=s.usageRefreshIntervalMs),(s.usageDisplayMode==="usage"||s.usageDisplayMode==="remaining")&&(r.usageDisplayMode=s.usageDisplayMode),Array.isArray(s.usageDropdownProviders)&&(r.usageDropdownProviders=s.usageDropdownProviders.filter(c=>typeof c=="string"&&c.length>0)),s.usageSelectedModels&&typeof s.usageSelectedModels=="object"){const c={};for(const[d,u]of Object.entries(s.usageSelectedModels))Array.isArray(u)&&(c[d]=u.filter(m=>typeof m=="string"));Object.keys(c).length>0&&(r.usageSelectedModels=c)}if(s.usageCollapsedFamilies&&typeof s.usageCollapsedFamilies=="object"){const c={};for(const[d,u]of Object.entries(s.usageCollapsedFamilies))Array.isArray(u)&&(c[d]=u.filter(m=>typeof m=="string"));Object.keys(c).length>0&&(r.usageCollapsedFamilies=c)}if(s.usageExpandedFamilies&&typeof s.usageExpandedFamilies=="object"){const c={};for(const[d,u]of Object.entries(s.usageExpandedFamilies))Array.isArray(u)&&(c[d]=u.filter(m=>typeof m=="string"));Object.keys(c).length>0&&(r.usageExpandedFamilies=c)}if(s.usageModelGroups&&typeof s.usageModelGroups=="object"){const c={};for(const[d,u]of Object.entries(s.usageModelGroups))if(u&&typeof u=="object"){const m=u,f={};Array.isArray(m.customGroups)&&(f.customGroups=m.customGroups.filter(p=>p&&typeof p=="object").map(p=>({id:String(p.id??""),label:String(p.label??""),models:Array.isArray(p.models)?p.models.filter(h=>typeof h=="string"):[],order:typeof p.order=="number"?p.order:0}))),m.modelAssignments&&typeof m.modelAssignments=="object"&&(f.modelAssignments=Object.fromEntries(Object.entries(m.modelAssignments).filter(([,p])=>typeof p=="string").map(([p,h])=>[p,String(h)]))),m.renamedGroups&&typeof m.renamedGroups=="object"&&(f.renamedGroups=Object.fromEntries(Object.entries(m.renamedGroups).filter(([,p])=>typeof p=="string").map(([p,h])=>[p,String(h)]))),Object.keys(f).length>0&&(c[d]=f)}Object.keys(c).length>0&&(r.usageModelGroups=c)}typeof s.toolCallExpansion=="string"&&(s.toolCallExpansion==="collapsed"||s.toolCallExpansion==="activity"||s.toolCallExpansion==="detailed")&&(r.toolCallExpansion=s.toolCallExpansion),typeof s.fontSize=="number"&&Number.isFinite(s.fontSize)&&(r.fontSize=s.fontSize),typeof s.terminalFontSize=="number"&&Number.isFinite(s.terminalFontSize)&&(r.terminalFontSize=s.terminalFontSize),typeof s.padding=="number"&&Number.isFinite(s.padding)&&(r.padding=s.padding),typeof s.cornerRadius=="number"&&Number.isFinite(s.cornerRadius)&&(r.cornerRadius=s.cornerRadius),typeof s.inputBarOffset=="number"&&Number.isFinite(s.inputBarOffset)&&(r.inputBarOffset=s.inputBarOffset);const o=Em(s.favoriteModels,64);o&&(r.favoriteModels=o);const a=Em(s.recentModels,16);a&&(r.recentModels=a),typeof s.diffLayoutPreference=="string"&&(s.diffLayoutPreference==="dynamic"||s.diffLayoutPreference==="inline"||s.diffLayoutPreference==="side-by-side")&&(r.diffLayoutPreference=s.diffLayoutPreference),typeof s.diffViewMode=="string"&&(s.diffViewMode==="single"||s.diffViewMode==="stacked")&&(r.diffViewMode=s.diffViewMode),typeof s.directoryShowHidden=="boolean"&&(r.directoryShowHidden=s.directoryShowHidden),typeof s.filesViewShowGitignored=="boolean"&&(r.filesViewShowGitignored=s.filesViewShowGitignored),typeof s.openInAppId=="string"&&s.openInAppId.length>0&&(r.openInAppId=s.openInAppId),typeof s.messageLimit=="number"&&Number.isFinite(s.messageLimit)&&(r.messageLimit=s.messageLimit);const l=iS(s.skillCatalogs);return l&&(r.skillCatalogs=l),r},cS=async()=>{const t=Yg();if(t)try{const s=await t.load();return Pm(s.settings)}catch(s){console.warn("Failed to load shared settings from runtime settings API:",s)}try{const s=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)return null;const r=await s.json().catch(()=>null);return Pm(r)}catch(s){return console.warn("Failed to load shared settings from server:",s),null}},Jg=async()=>{if(typeof window>"u")return;const t=Qg(),s=r=>{Qd(r);const n=()=>Yd(r);if(t?.hasHydrated?.())n();else if(n(),t?.onFinishHydration){const o=t.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("ikanban:settings-synced",{detail:r}))};try{const r=await cS();r&&s(r)}catch(r){console.warn("Failed to synchronise settings:",r)}},xs=async t=>{if(typeof window>"u")return;const s=Yg();if(s)try{const r=await s.save(t);r&&(Qd(r),Yd(r));return}catch(r){console.warn("Failed to update settings via runtime settings API:",r)}try{const r=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!r.ok){console.warn("Failed to update shared settings via API:",r.status,r.statusText);return}const n=await r.json().catch(()=>null);n&&(Qd(n),Yd(n))}catch(r){console.warn("Failed to update shared settings via API:",r)}},Xg=async()=>{if(typeof window>"u")return;const t=Qg();try{const s=await aS();if(!s)return;const r=()=>oS(s);if(t?.hasHydrated?.()){r();return}if(r(),t?.onFinishHydration){const n=t.onFinishHydration(()=>{n?.(),r()})}}catch(s){console.warn("Failed to load appearance preferences:",s)}},dS=3e4,uS=40,mS=60,fS=(t,s,r,n,o)=>{const a=t.trim(),l=s.trim().toLowerCase();return`${a}::${l}::${r}::${n?"1":"0"}::${o?"1":"0"}`},cc=Ls()(Us((t,s)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(r,n,o=mS,a){if(!r||r.trim().length===0)return[];const l=r.trim(),c=typeof n=="string"?n.trim():"",d=!!a?.includeHidden,u=a?.respectGitignore??!0,m=fS(l,c,o,d,u),f=Date.now(),p=s().cache[m];if(p&&f-p.timestamp<dS)return p.files;const h=s().inFlight[m];if(h)return h;const g=nt.searchFiles(c,{directory:l,limit:o,includeHidden:d,respectGitignore:u}).then(x=>(t(y=>{const b={...y.cache,[m]:{files:x,timestamp:Date.now()}},v=y.cacheKeys.filter(j=>j!==m);for(v.push(m);v.length>uS;){const j=v.shift();j&&delete b[j]}return{cache:b,cacheKeys:v}}),x)).finally(()=>{t(x=>{const y={...x.inFlight};return delete y[m],{inFlight:y}})});return t(x=>({inFlight:{...x.inFlight,[m]:g}})),g},invalidateDirectory(r){if(!r||r.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${r.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"})),tr=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("ikanban_stream_debug")==="1"}catch{return!1}};var pS={};let Cn=null;const un=Ws(),Rm=un.getItem("lastDirectory"),hS=typeof Rm=="string"&&Rm.length>0,Fi=t=>{try{cc.getState().invalidateDirectory(t)}catch(s){console.warn("Failed to invalidate file search cache:",s)}},wa=t=>{const s=t.trim();if(!s)return s;const r=s.replace(/\\/g,"/");return r.length>1?r.replace(/\/+$/,""):r},gS=(t,s)=>{const r=t.trim();return r.startsWith("~")?r==="~"?s||r:(r.startsWith("~/")||r.startsWith("~\\"))&&s?`${s}${r.slice(1)}`:r:r},dl=(t,s)=>{const r=gS(t,s);return wa(r)},xS=()=>{const t=un.getItem("homeDirectory");if(typeof t!="string"||t.trim().length===0)return null;const s=wa(t);return s.length>0?s:null},yS=()=>{const t=un.getItem("lastDirectory");if(typeof t!="string"||t.trim().length===0)return null;const s=wa(t);return s.length>0?s:null},bS=()=>{if(typeof process>"u")return null;const t=pS,s=t?.HOME||t?.USERPROFILE||(t?.HOMEDRIVE&&t?.HOMEPATH?`${t.HOMEDRIVE}${t.HOMEPATH}`:void 0);if(typeof s=="string"&&s.trim().length>0){const n=wa(s);return n.length>0?n:null}const r=process?.cwd?.();if(typeof r=="string"&&r.trim().length>0){const n=wa(r);return n.length>0?n:null}return null},Rl=()=>{if(typeof window<"u"){if(Cn)return Cn;const s=typeof window.__IKANBAN_HOME__=="string"&&window.__IKANBAN_HOME__.length>0?window.__IKANBAN_HOME__:null;if(s&&s.length>0)return Cn=s,un.setItem("homeDirectory",s),s;const r=xS();if(r&&!gs())return Cn=r,r}const t=bS();return t||"/"},vS=t=>{if(typeof t!="string")return null;const s=t.trim();if(!s)return null;const r=s.replace(/\\/g,"/");if(r.length>1){const n=r.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return r==="/"||r.length===0?null:r},wS=t=>(Cn=t,typeof window<"u"&&un.setItem("homeDirectory",t),xs({homeDirectory:t}),t),Zg=async()=>{const t=n=>{const o=vS(n);return o?wS(o):null};try{const n=await nt.getFilesystemHome(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await nt.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 oc(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const s=Rl(),r=t(s);return r||s},jS=()=>{if(!gs())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const s=wa(t);return s.length>0?s:null},mi=jS()||Rl(),Fl=(()=>{const t=yS();return t&&!gs()?dl(t,mi):mi})();Fl&&nt.setDirectory(Fl);const SS=!!(mi&&mi!=="/"),Yt=Ls()(Us((t,s)=>({currentDirectory:Fl,directoryHistory:[Fl],historyIndex:0,homeDirectory:mi,hasPersistedDirectory:hS,isHomeReady:SS,isSwitchingDirectory:!1,setDirectory:(r,n)=>{const o=Cn||s().homeDirectory||un.getItem("homeDirectory"),a=dl(r,o);tr()&&console.log("[DirectoryStore] setDirectory called with path:",a),nt.setDirectory(a),Fi(),t(l=>{const c=[...l.directoryHistory.slice(0,l.historyIndex+1),a];return un.setItem("lastDirectory",a),xs({lastDirectory:a}),{currentDirectory:a,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const r=s();if(r.historyIndex>0){const n=r.historyIndex-1,o=r.directoryHistory[n];nt.setDirectory(o),Fi(),un.setItem("lastDirectory",o),xs({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const r=s();if(r.historyIndex<r.directoryHistory.length-1){const n=r.historyIndex+1,o=r.directoryHistory[n];nt.setDirectory(o),Fi(),un.setItem("lastDirectory",o),xs({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:r,setDirectory:n}=s(),o=Cn||s().homeDirectory||Rl();if(r===o||r==="/")return;const a=r.endsWith("/")?r.slice(0,-1):r,l=a.lastIndexOf("/");if(l===-1){const c=Cn||Rl();n(c)}else n(l===0?"/":a.substring(0,l))},goHome:async()=>{const r=Cn||s().homeDirectory||await Zg();s().setDirectory(r)},synchronizeHomeDirectory:r=>{const n=s(),o=r;Cn=o;const a=n.homeDirectory!==o,l=un.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?dl(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(x=>dl(x,o)),p=f.some((x,y)=>x!==n.directoryHistory[y]),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;nt.setDirectory(x),Fi(),un.setItem("lastDirectory",x),xs({lastDirectory:x})}xs({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Zg().then(t=>{Yt.getState().synchronizeHomeDirectory(t)});const fa=Ws(),ex="projects",Jd="activeProjectId",NS=(t,s)=>{const r=t.trim();return!r.startsWith("~")||!s?r:r==="~"?s:r.startsWith("~/")||r.startsWith("~\\")?`${s}${r.slice(1)}`:r},dc=t=>{const s=t.trim();if(!s)return"";const r=fa.getItem("homeDirectory")||Yt.getState().homeDirectory||"",o=NS(s,r).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},tx=t=>{const s=dc(t);if(!s||s==="/")return"Root";const r=s.split("/").filter(Boolean);return r[r.length-1]||s},kS=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,sx=t=>{if(!Array.isArray(t))return[];const s=[],r=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=dc(c);if(!d||r.has(l)||n.has(d))continue;r.add(l),n.add(d);const u={id:l,path:d};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),typeof a.sidebarCollapsed=="boolean"&&(u.sidebarCollapsed=a.sidebarCollapsed),s.push(u)}return s},CS=()=>{try{const t=fa.getItem(ex);return t?sx(JSON.parse(t)):[]}catch{return[]}},MS=()=>{try{const t=fa.getItem(Jd);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},Ru=(t,s)=>{try{fa.setItem(ex,JSON.stringify(t))}catch{}try{s?fa.setItem(Jd,s):fa.removeItem(Jd)}catch{}},La=(t,s)=>{Ru(t,s),xs({projects:t,activeProjectId:s??void 0})},AS=CS(),DS=()=>{if(typeof window>"u"||!window.__IKANBAN_RUNTIME_APIS__?.runtime?.isVSCode)return null;const s=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof s!="string"||s.trim().length===0)return null;const r=dc(s);if(!r)return null;const n=`vscode:${r}`,o={id:n,path:r,label:tx(r),addedAt:Date.now(),lastOpenedAt:Date.now()};return tr()&&console.log("[IKanban][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},jn=DS(),Fu=jn?.projects??AS,rx=jn?.activeProjectId??MS()??Fu[0]?.id??null;jn&&Ru(Fu,rx);const ps=Ls()(Us((t,s)=>({projects:Fu,activeProjectId:rx,validateProjectPath:r=>{if(typeof r!="string"||r.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=dc(r);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(r,n)=>{if(jn)return null;const{validateProjectPath:o}=s(),a=o(r);if(!a.ok||!a.normalizedPath)return null;const l=a.normalizedPath,c=s().projects.find(g=>g.path===l);if(c)return s().setActiveProject(c.id),c;const d=Date.now(),u=n?.label?.trim()||tx(l),m=n?.id?.trim(),p={id:m&&!s().projects.some(g=>g.id===m)?m:kS(),path:l,label:u,addedAt:d,lastOpenedAt:d},h=[...s().projects,p];return t({projects:h}),tr()&&console.info("[ProjectsStore] Added project",p),s().setActiveProject(p.id),p},removeProject:r=>{if(jn)return;const n=s(),o=n.projects.filter(l=>l.id!==r);let a=n.activeProjectId;if(n.activeProjectId===r&&(a=o[0]?.id??null),t({projects:o,activeProjectId:a}),La(o,a),a){const l=o.find(c=>c.id===a);l&&(nt.setDirectory(l.path),Yt.getState().setDirectory(l.path,{showOverlay:!1}))}else Yt.getState().goHome()},setActiveProject:r=>{if(jn)return;const{projects:n,activeProjectId:o}=s();if(o===r)return;const a=n.find(d=>d.id===r);if(!a)return;const l=Date.now(),c=n.map(d=>d.id===r?{...d,lastOpenedAt:l}:d);t({projects:c,activeProjectId:r}),La(c,r),nt.setDirectory(a.path),Yt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:r=>{if(jn)return;const{projects:n,activeProjectId:o}=s();if(o===r||!n.find(d=>d.id===r))return;const l=Date.now(),c=n.map(d=>d.id===r?{...d,lastOpenedAt:l}:d);t({projects:c,activeProjectId:r}),La(c,r)},renameProject:(r,n)=>{if(jn)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:l}=s(),c=a.map(d=>d.id===r?{...d,label:o}:d);t({projects:c}),La(c,l)},reorderProjects:(r,n)=>{if(jn)return;const{projects:o,activeProjectId:a}=s();if(r<0||r>=o.length||n<0||n>=o.length||r===n)return;const l=[...o],[c]=l.splice(r,1);l.splice(n,0,c),t({projects:l}),La(l,a)},synchronizeFromSettings:r=>{if(jn)return;const n=sx(r.projects??[]),o=typeof r.activeProjectId=="string"&&r.activeProjectId.trim()?r.activeProjectId.trim():null,a=s(),l=JSON.stringify(a.projects)!==JSON.stringify(n),c=a.activeProjectId!==o;if(!(!l&&!c)&&(t({projects:n,activeProjectId:o}),Ru(n,o),o)){const d=n.find(u=>u.id===o);d&&(nt.setDirectory(d.path),Yt.getState().setDirectory(d.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:r,activeProjectId:n}=s();return n?r.find(o=>o.id===n)??null:null}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("ikanban:settings-synced",t=>{const s=t.detail;s&&typeof s=="object"&&ps.getState().synchronizeFromSettings(s)});const IS=new Set(["init","review"]),aa=t=>IS.has(t.name),Xa="useCommandsStore",Xd=t=>new Promise(s=>setTimeout(s,t)),Li=()=>{try{const s=ps.getState().getActiveProject?.();if(s?.path?.trim())return s.path.trim();const r=nt.getDirectory();if(r?.trim())return r.trim()}catch(t){console.warn("[CommandsStore] Error resolving config directory:",t)}return null},TS=2e4,Fm=300,Lm=4,ES=800,PS=200,RS=2e3,yo=Ls()(Us(Ar((t,s)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:r=>{t({selectedCommandName:r})},setCommandDraft:r=>{t({commandDraft:r})},loadCommands:async()=>{t({isLoading:!0});const r=s().commands;let n=null;for(let o=0;o<3;o++)try{const a=Li(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await nt.withDirectory(a,()=>nt.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(r)!==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:r,isLoading:!1}),!1},createCommand:async r=>{Gr("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",r.name);const o={template:r.template||""};r.description&&(o.description=r.description),r.agent&&(o.agent=r.agent),r.model&&(o.model=r.model),r.subtask!==void 0&&(o.subtask=r.subtask),r.scope&&(o.scope=r.scope),console.log("[CommandsStore] Command config to save:",o);const a=Li(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(r.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 Tc({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await s().loadCommands();return m&&Tn("commands",{source:Xa}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Fr()}},updateCommand:async(r,n)=>{Gr("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",r),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=Li(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(r)}${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 Tc({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await s().loadCommands();return f&&Tn("commands",{source:Xa}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Fr()}},deleteCommand:async r=>{Gr("Deleting command configuration…");let n=!1;try{const o=Li(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(r)}${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 Tc({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadCommands();return u&&Tn("commands",{source:Xa}),s().selectedCommandName===r&&t({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||Fr()}},getCommandByName:r=>{const{commands:n}=s();return n.find(o=>o.name===r)}}),{name:"commands-store",storage:Dr(()=>Ws()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=yo);async function FS(t){const s=typeof t=="number"&&t>0?Math.min(t,Fm):0;s>0&&await Xd(s);const r=Date.now();let n=0,o=null;for(;Date.now()-r<TS;){n+=1,Wn(`Waiting for OpenCode… (attempt ${n})`);try{if(await nt.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-r,l=n<=Lm&&a<1200?Fm:Math.min(ES+Math.max(0,n-Lm)*PS,RS);await Xd(l)}throw o||new Error("OpenCode did not become ready in time")}async function Tc(t={}){const{message:s,delayMs:r}=t;try{Wn(s||"Refreshing commands…")}catch{}try{await FS(r),Wn("Refreshing commands…"),await yo.getState().loadCommands(),Tn("commands",{source:Xa})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Wn("OpenCode refresh failed. Please retry refreshing configuration manually."),await Xd(1500)}finally{Fr()}}let Om=null;Om||(Om=ic(t=>{if(t.source!==Xa&&ui(t,"commands")){const{loadCommands:s}=yo.getState();s()}}));const Zn=()=>{const t=nt.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},ul="useSkillsStore",pn=Ls()(Us(Ar((t,s)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:r=>{t({selectedSkillName:r})},setSkillDraft:r=>{t({skillDraft:r})},loadSkills:async()=>{t({isLoading:!0});const r=s().skills;let n=null;for(let o=0;o<3;o++)try{const a=Zn(),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:r,isLoading:!1}),!1},getSkillDetail:async r=>{try{const n=Zn(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(r)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async r=>{Gr("Creating skill...");try{const n={name:r.name,description:r.description};r.instructions&&(n.instructions=r.instructions),r.scope&&(n.scope=r.scope),r.supportingFiles&&(n.supportingFiles=r.supportingFiles);const o=Zn(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(r.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 s().loadSkills();return d&&Tn("skills",{source:ul}),d}catch{return!1}finally{Fr()}},updateSkill:async(r,n)=>{Gr("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=Zn(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(r)}${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 s().loadSkills();return u&&Tn("skills",{source:ul}),u}catch{return!1}finally{Fr()}},deleteSkill:async r=>{Gr("Deleting skill...");try{const n=Zn(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(r)}${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 s().loadSkills();return c&&Tn("skills",{source:ul}),s().selectedSkillName===r&&t({selectedSkillName:null}),c}catch{return!1}finally{Fr()}},getSkillByName:r=>{const{skills:n}=s();return n.find(o=>o.name===r)},readSupportingFile:async(r,n)=>{try{const o=Zn(),a=o?`&directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(r)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return l.ok?(await l.json()).content??null:null}catch{return null}},writeSupportingFile:async(r,n,o)=>{try{const a=Zn(),l=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(r)}/files/${encodeURIComponent(n)}${l}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(r,n)=>{try{const o=Zn(),a=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(r)}/files/${encodeURIComponent(n)}${a}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:Dr(()=>Ws()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=pn);let _m=null;_m||(_m=ic(t=>{if(t.source!==ul&&ui(t,"skills")){const{loadSkills:s}=pn.getState();s()}}));const $m=[{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"}],Oi=()=>{const t=nt.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},ji=Ls()(Us((t,s)=>({sources:$m,itemsBySource:{},selectedSourceId:$m[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:r=>t({selectedSourceId:r}),loadCatalog:async r=>{t({isLoadingCatalog:!0,lastCatalogError:null});const n={sources:s().sources,itemsBySource:s().itemsBySource,pageInfoBySource:s().pageInfoBySource,loadedSourceIds:s().loadedSourceIds,clawdhubHasMoreBySource:s().clawdhubHasMoreBySource};let o=null;try{const a=r?.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=r?.refresh?{}:s().itemsBySource||{},p=r?.refresh?{}:s().pageInfoBySource||{},h=r?.refresh?{}:s().loadedSourceIds||{},g=r?.refresh?{}:s().clawdhubHasMoreBySource||{},x=s().selectedSourceId,y=x&&m.some(b=>b.id===x)?x:m[0]?.id??null;return t({sources:m,itemsBySource:f,pageInfoBySource:p,loadedSourceIds:h,clawdhubHasMoreBySource:g,selectedSourceId:y}),!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(r,n)=>{if(!r)return!1;t({isLoadingSource:!0,lastCatalogError:null});try{const o=Oi(),a=n?.refresh?"&refresh=true":"",l=o?`?directory=${encodeURIComponent(o)}&sourceId=${encodeURIComponent(r)}${a}`:`?sourceId=${encodeURIComponent(r)}${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?.[r];return p.ok&&h?.ok&&Array.isArray(g)?(t(x=>({itemsBySource:{...x.itemsBySource,[r]:g},pageInfoBySource:{...x.pageInfoBySource,[r]:{nextCursor:null}},loadedSourceIds:{...x.loadedSourceIds,[r]:!0},clawdhubHasMoreBySource:{...x.clawdhubHasMoreBySource,[r]:!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,[r]:m},pageInfoBySource:{...p.pageInfoBySource,[r]:{nextCursor:f}},loadedSourceIds:{...p.loadedSourceIds,[r]:!0},clawdhubHasMoreBySource:{...p.clawdhubHasMoreBySource,[r]: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 r=s().selectedSourceId;if(!r)return!1;const o=s().pageInfoBySource[r]?.nextCursor||null;t({isLoadingMore:!0});try{const a=Oi(),l=[`sourceId=${encodeURIComponent(r)}`];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=s().itemsBySource[r]||[],p=u.items||[],h=new Map(f.map(y=>[`${y.sourceId}:${y.skillDir}`,y]));let g=0;for(const y of p){const b=`${y.sourceId}:${y.skillDir}`;h.has(b)||(g+=1),h.set(b,y)}const x=p.length===0||g===0;return t(y=>({itemsBySource:{...y.itemsBySource,[r]:Array.from(h.values())},pageInfoBySource:{...y.pageInfoBySource,[r]:{nextCursor:m}},clawdhubHasMoreBySource:{...y.clawdhubHasMoreBySource,[r]:!x}})),!0}catch{return!1}finally{t({isLoadingMore:!1})}},scanRepo:async r=>{t({isScanning:!0,lastScanError:null,scanResults:null});try{const n=Oi(),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(r)}),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 r=>{t({isInstalling:!0,lastInstallError:null});try{const n=Oi(),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(r)}),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 pn.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"})),LS=()=>{const t=nt.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},_i=()=>{try{const s=ps.getState().getActiveProject?.();if(s?.path?.trim())return s.path.trim();const r=nt.getDirectory();if(r?.trim())return r.trim()}catch(t){console.warn("[AgentsStore] Error resolving config directory:",t)}return null},Mo=t=>{const s=t;return s.native===!0||s.builtIn===!0},nx=t=>{const s=t;return s.hidden===!0||s.options?.hidden===!0},ox=t=>t.filter(s=>!nx(s)),ml="useAgentsStore",Ll=t=>new Promise(s=>setTimeout(s,t)),OS=2e4,Bm=300,zm=4,_S=800,$S=200,BS=2e3,bo=Ls()(Us(Ar((t,s)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:r=>{t({selectedAgentName:r})},setAgentDraft:r=>{t({agentDraft:r})},loadAgents:async()=>{t({isLoading:!0});const r=s().agents;for(let n=0;n<3;n++)try{const o=_i(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await nt.withDirectory(o,()=>nt.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(r)!==JSON.stringify(c)?t({agents:c,isLoading:!1}):t({isLoading:!1}),!0}catch{}return t({isLoading:!1}),!1},createAgent:async r=>{Gr("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",r.name);const o={mode:r.mode||"subagent"};r.description&&(o.description=r.description),r.model&&(o.model=r.model),r.temperature!==void 0&&(o.temperature=r.temperature),r.top_p!==void 0&&(o.top_p=r.top_p),r.prompt&&(o.prompt=r.prompt),r.permission&&(o.permission=r.permission),r.disable!==void 0&&(o.disable=r.disable),r.scope&&(o.scope=r.scope),console.log("[AgentsStore] Agent config to save:",o);const a=_i(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(r.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 Za({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await s().loadAgents();return m&&Tn("agents",{source:ml}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||Fr()}},updateAgent:async(r,n)=>{Gr("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=_i(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(r)}${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 Za({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await s().loadAgents();return f&&Tn("agents",{source:ml}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||Fr()}},deleteAgent:async r=>{Gr("Deleting agent configuration…");let n=!1;try{const o=_i(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(r)}${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 Za({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await s().loadAgents();return u&&Tn("agents",{source:ml}),s().selectedAgentName===r&&t({selectedAgentName:null}),u}catch{return!1}finally{n||Fr()}},getAgentByName:r=>{const{agents:n}=s();return n.find(o=>o.name===r)},getVisibleAgents:()=>{const{agents:r}=s();return ox(r)}}),{name:"agents-store",storage:Dr(()=>Ws()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=bo);async function zS(t){const s=typeof t=="number"&&t>0?Math.min(t,Bm):0;s>0&&await Ll(s);const r=Date.now();let n=0,o=null;for(;Date.now()-r<OS;){n+=1,Wn(`Waiting for OpenCode… (attempt ${n})`);try{if(await nt.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-r,l=n<=zm&&a<1200?Bm:Math.min(_S+Math.max(0,n-zm)*$S,BS);await Ll(l)}throw o||new Error("OpenCode did not become ready in time")}const US=t=>{if(!t||t.length===0)return["all"];const s=Array.from(new Set(t));return s.includes("all")?["all"]:s};async function HS(t={}){const{message:s,delayMs:r}=t,n=US(t.scopes),o=t.mode??(n.includes("all")?"projects":"active");try{Wn(s||"Refreshing configuration…")}catch{}try{await zS(r);const a=ut.getState(),l=bo.getState(),c=yo.getState(),d=pn.getState(),u=ji.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=LS(),y=o==="projects"?ps.getState().projects:[],b=Array.from(new Set([...x?[x]:[],...y.map(k=>k.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&ut.setState({directoryScoped:{}});const v=[];for(const k of b)m&&v.push(a.loadProviders({directory:k}).then(()=>{})),f&&v.push(a.loadAgents({directory:k}).then(()=>{}));const j=[];p&&j.push(l.loadAgents().then(()=>{})),h&&j.push(c.loadCommands().then(()=>{})),g&&(j.push(d.loadSkills().then(()=>{})),j.push(u.loadCatalog().then(()=>{}))),Wn("Refreshing configuration…"),await Promise.all([...v,...j])}catch{Wn("OpenCode refresh failed. Please retry."),await Ll(1500)}finally{Fr()}}async function Za(t){await HS(t)}async function ei(t){Gr(t?.message||"Reloading OpenCode configuration…");try{const s=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),r=await s.json().catch(()=>null);if(!s.ok){const o=r?.error||"Failed to reload configuration";throw new Error(o)}const n={...t,scopes:t?.scopes??["all"],mode:t?.mode??"projects"};r?.requiresReload?await Za({...n,message:r.message,delayMs:r.reloadDelayMs}):await Za(n)}catch(s){throw console.error("[reloadOpenCodeConfiguration] Failed:",s),Wn("Failed to reload configuration. Please try again."),await Ll(2e3),Fr(),s}}let Um=null;Um||(Um=ic(t=>{if(t.source!==ml&&ui(t,"agents")){const{loadAgents:s}=bo.getState();s()}}));const VS="https://models.dev/api.json",WS="/api/ikanban/models-metadata",Hm="opencode",Vm="big-pickle",GS=async()=>{try{const t=Ur()?.settings;if(t)try{const u=(await t.load())?.settings;if(u){const m=typeof u?.defaultModel=="string"?u.defaultModel.trim():"",f=typeof u?.defaultVariant=="string"?u.defaultVariant.trim():"",p=typeof u?.defaultAgent=="string"?u.defaultAgent.trim():"",h=typeof u?.gitmojiEnabled=="boolean"?u.gitmojiEnabled:void 0,g=typeof u?.zenModel=="string"?u.zenModel.trim():"";return{defaultModel:m.length>0?m:void 0,defaultVariant:f.length>0?f:void 0,defaultAgent:p.length>0?p:void 0,autoCreateWorktree:typeof u?.autoCreateWorktree=="boolean"?u.autoCreateWorktree:void 0,gitmojiEnabled:h,zenModel:g.length>0?g:void 0}}}catch{}const s=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)return{};const r=await s.json(),n=typeof r?.defaultModel=="string"?r.defaultModel.trim():"",o=typeof r?.defaultVariant=="string"?r.defaultVariant.trim():"",a=typeof r?.defaultAgent=="string"?r.defaultAgent.trim():"",l=typeof r?.gitmojiEnabled=="boolean"?r.gitmojiEnabled:void 0,c=typeof r?.zenModel=="string"?r.zenModel.trim():"";return{defaultModel:n.length>0?n:void 0,defaultVariant:o.length>0?o:void 0,defaultAgent:a.length>0?a:void 0,autoCreateWorktree:typeof r?.autoCreateWorktree=="boolean"?r.autoCreateWorktree:void 0,gitmojiEnabled:l,zenModel:c.length>0?c:void 0}}catch{return{}}},$i=t=>{if(!t||typeof t!="string")return null;const s=t.split("/");return s.length!==2||!s[0]||!s[1]?null:{providerId:s[0],modelId:s[1]}},KS=t=>t?.toLowerCase?.()??"",qS=t=>t==="primary"||t==="all"||t===void 0||t===null,fi=t=>typeof t=="object"&&t!==null,Ol=t=>Array.isArray(t)&&t.every(s=>typeof s=="string"),QS=t=>{if(!fi(t))return!1;const s=t;if(s.modalities){const{input:r,output:n}=s.modalities;if(r&&!Ol(r)||n&&!Ol(n))return!1}return!0},YS=t=>{if(!fi(t))return!1;const s=t;return s.models===void 0||fi(s.models)},ax=(t,s)=>{const r=KS(t);return!r||!s?"":`${r}/${s}`},JS=t=>{const s=new Map;if(!fi(t))return s;for(const[r,n]of Object.entries(t)){if(!YS(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:r,a=n.models;if(!(!a||!fi(a)))for(const[l,c]of Object.entries(a)){if(!QS(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:Ol(c.modalities.input)?c.modalities.input:void 0,output:Ol(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=ax(o,d);m&&s.set(m,u)}}return s},XS=async()=>{if(typeof fetch!="function")return new Map;const t=[WS,VS];for(const s of t){const r=typeof AbortController<"u"?new AbortController:void 0,n=r?setTimeout(()=>r.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(s),a={signal:r?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const l=await fetch(s,a);if(!l.ok)throw new Error(`Metadata request to ${s} returned status ${l.status}`);const c=await l.json();return JS(c)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${s})`):console.warn(`Failed to fetch model metadata from ${s}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let Ec=null;const ZS=(t,s)=>{t().size>0||Ec||(Ec=XS().then(n=>(n.size>0&&s(n),n)).catch(()=>new Map).finally(()=>{Ec=null}))},e0=t=>new Promise(s=>setTimeout(s,t)),Lu="__global__",pa=t=>{const s=typeof t=="string"?t.trim():"";return s.length>0?s:Lu},Qo=t=>t===Lu?null:t,t0=()=>{if(typeof window>"u")return Lu;const t=nt.getDirectory()??Yt.getState().currentDirectory;return pa(t)},ut=Ls()(Us(Ar((t,s)=>({activeDirectoryKey:t0(),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,settingsZenModel:void 0,voiceProvider:(()=>{if(typeof window<"u"){const r=localStorage.getItem("voiceProvider");if(r==="openai"||r==="browser"||r==="say")return r}return"browser"})(),speechRate:(()=>{if(typeof window<"u"){const r=localStorage.getItem("speechRate");if(r){const n=parseFloat(r);if(!isNaN(n)&&n>=.5&&n<=2)return n}}return 1})(),speechPitch:(()=>{if(typeof window<"u"){const r=localStorage.getItem("speechPitch");if(r){const n=parseFloat(r);if(!isNaN(n)&&n>=.5&&n<=2)return n}}return 1})(),speechVolume:(()=>{if(typeof window<"u"){const r=localStorage.getItem("speechVolume");if(r){const n=parseFloat(r);if(!isNaN(n)&&n>=0&&n<=1)return n}}return 1})(),sayVoice:(()=>{if(typeof window<"u"){const r=localStorage.getItem("sayVoice");if(r)return r}return"Samantha"})(),browserVoice:(()=>{if(typeof window<"u"){const r=localStorage.getItem("browserVoice");if(r)return r}return""})(),openaiVoice:(()=>{if(typeof window<"u"){const r=localStorage.getItem("openaiVoice");if(r)return r}return"nova"})(),openaiApiKey:(()=>{if(typeof window<"u"){const r=localStorage.getItem("openaiApiKey");if(r)return r}return""})(),showMessageTTSButtons:typeof window<"u"&&localStorage.getItem("showMessageTTSButtons")==="true",voiceModeEnabled:typeof window<"u"&&localStorage.getItem("voiceModeEnabled")==="true",summarizeMessageTTS:typeof window<"u"&&localStorage.getItem("summarizeMessageTTS")==="true",summarizeVoiceConversation:typeof window<"u"&&localStorage.getItem("summarizeVoiceConversation")==="true",summarizeCharacterThreshold:(()=>{if(typeof window<"u"){const r=localStorage.getItem("summarizeCharacterThreshold");if(r){const n=parseInt(r,10);if(!isNaN(n)&&n>=50&&n<=2e3)return n}}return 200})(),summarizeMaxLength:(()=>{if(typeof window<"u"){const r=localStorage.getItem("summarizeMaxLength");if(r){const n=parseInt(r,10);if(!isNaN(n)&&n>=50&&n<=2e3)return n}}return 500})(),activateDirectory:async r=>{const n=pa(r);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:{}}}),s().isConnected&&(await s().loadProviders({directory:Qo(n)}),await s().loadAgents({directory:Qo(n)}))},loadProviders:async r=>{const n=pa(r?.directory??Qo(s().activeDirectoryKey)),o=s().directoryScoped[n],a=o?.providers??(s().activeDirectoryKey===n?s().providers:[]),l=o?.defaultProviders??(s().activeDirectoryKey===n?s().defaultProviders:{});let c=null;for(let d=0;d<3;d++)try{ZS(()=>s().modelsMetadata,h=>t({modelsMetadata:h}));const u=await nt.withDirectory(Qo(n),()=>nt.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(h=>{const g=h.models??{},x=Object.keys(g).map(y=>g[y]);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},y={directoryScoped:{...h.directoryScoped,[n]:x}};if(h.activeDirectoryKey===n&&(y.providers=p,y.defaultProviders=f,!h.currentProviderId&&!h.currentModelId&&h.settingsDefaultModel)){const b=$i(h.settingsDefaultModel);if(b){const v=p.find(j=>j.id===b.providerId);if(v?.models.some(j=>j.id===b.modelId)){const j=v.models.find(N=>N.id===b.modelId),k=h.settingsDefaultVariant&&j?.variants?.[h.settingsDefaultVariant]?h.settingsDefaultVariant:void 0;y.currentProviderId=b.providerId,y.currentModelId=b.modelId,y.currentVariant=k,y.selectedProviderId=b.providerId,x.currentProviderId=b.providerId,x.currentModelId=b.modelId,x.currentVariant=k,x.selectedProviderId=b.providerId}}}return y});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=$i(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(y=>y.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:r=>{const{providers:n}=s(),o=n.find(c=>c.id===r);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:r,currentModelId:l,selectedProviderId:r};return{currentProviderId:r,currentModelId:l,selectedProviderId:r,directoryScoped:{...c.directoryScoped,[d]:m}}})},setModel:r=>{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:r};return{currentModelId:r,directoryScoped:{...n.directoryScoped,[o]:l}}})},setCurrentVariant:r=>{t(n=>{if(n.currentVariant===r)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:r};return{currentVariant:r,directoryScoped:{...n.directoryScoped,[o]:l}}})},getCurrentModelVariants:()=>{const n=s().getCurrentModel()?.variants;return n?Object.keys(n):[]},cycleCurrentVariant:()=>{const r=s().getCurrentModelVariants();if(r.length===0)return;const n=s().currentVariant;if(!n){s().setCurrentVariant(r[0]);return}const o=r.indexOf(n);if(o===-1||o===r.length-1){s().setCurrentVariant(void 0);return}s().setCurrentVariant(r[o+1])},setSelectedProvider:r=>{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:r};return{selectedProviderId:r,directoryScoped:{...n.directoryScoped,[o]:l}}})},saveAgentModelSelection:(r,n,o)=>{t(a=>{const l=a.activeDirectoryKey,c={...a.agentModelSelections,[r]:{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:r=>{const{agentModelSelections:n}=s();return n[r]||null},loadAgents:async r=>{const n=pa(r?.directory??Qo(s().activeDirectoryKey)),a=s().directoryScoped[n]?.agents??(s().activeDirectoryKey===n?s().agents:[]);let l=null;for(let c=0;c<3;c++)try{const[d,u]=await Promise.all([nt.withDirectory(Qo(n),()=>nt.listAgents()),GS()]),m=Array.isArray(d)?d:[],f=s().activeDirectoryKey===n?s().providers:s().directoryScoped[n]?.providers??[];if(t(N=>{const C={...N.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},S={settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsGitmojiEnabled:u.gitmojiEnabled??!1,settingsZenModel:u.zenModel,directoryScoped:{...N.directoryScoped,[n]:C}};return N.activeDirectoryKey===n&&(S.agents=m),S}),m.length===0)return t(N=>{const C={...N.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},S={directoryScoped:{...N.directoryScoped,[n]:C}};return N.activeDirectoryKey===n&&(S.currentAgentName=void 0),S}),!0;const p=(N,w)=>{const C=f.find(S=>S.id===N);return C?C.models.some(S=>S.id===w):!1},h=m.filter(N=>qS(N.mode));let y=h.find(N=>N.name==="build")||h[0]||m[0];const b={};if(u.defaultAgent){const N=m.find(w=>w.name===u.defaultAgent);N?y=N:b.defaultAgent=""}let v,j,k;if(u.defaultModel){const N=$i(u.defaultModel);if(N&&p(N.providerId,N.modelId)){if(v=N.providerId,j=N.modelId,u.defaultVariant){const S=f.find(M=>M.id===N.providerId)?.models.find(M=>M.id===N.modelId)?.variants;S&&Object.prototype.hasOwnProperty.call(S,u.defaultVariant)?k=u.defaultVariant:b.defaultVariant=""}}else b.defaultModel=""}if(!v&&y?.model?.providerID&&y?.model?.modelID){const{providerID:N,modelID:w}=y.model;p(N,w)&&(v=N,j=w)}if(!v)if(p(Hm,Vm))v=Hm,j=Vm;else{const N=f[0],w=N?.models[0];N&&w&&(v=N.id,j=w.id)}return t(N=>{const w=N.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},C={...w,providers:f,agents:m,currentAgentName:y.name,currentProviderId:v??w.currentProviderId,currentModelId:j??w.currentModelId,currentVariant:k},S={directoryScoped:{...N.directoryScoped,[n]:C}};return N.activeDirectoryKey===n&&(S.currentAgentName=y.name,v&&j&&(S.currentProviderId=v,S.currentModelId=j,S.currentVariant=k)),S}),Object.keys(b).length>0&&(t({settingsDefaultModel:b.defaultModel!==void 0?void 0:s().settingsDefaultModel,settingsDefaultVariant:b.defaultVariant!==void 0?void 0:s().settingsDefaultVariant,settingsDefaultAgent:b.defaultAgent!==void 0?void 0:s().settingsDefaultAgent}),xs(b).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:r=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:l}=s();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:r};return{currentAgentName:r,directoryScoped:{...c.directoryScoped,[d]:m}}}),r&&typeof window<"u"){const c=window.__zustand_session_store__;if(c){const d=c.getState(),{currentSessionId:u,isIKanbanCreatedSession:m,initializeNewIKanbanSession:f,getAgentModelForSession:p}=d;u&&c.setState(h=>{const g=new Map(h.currentAgentContext);return g.set(u,r),{currentAgentContext:g}}),u&&m(u)&&(p(u,r)||f(u,n))}}if(r&&typeof window<"u"){const c=window.__zustand_session_store__;if(c?.getState){const{currentSessionId:m,getAgentModelForSession:f}=c.getState();if(m&&f(m,r))return}if(a){const m=$i(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 j=o.find(k=>k.id===m.providerId)?.models.find(k=>k.id===m.modelId)?.variants;j&&Object.prototype.hasOwnProperty.call(j,l)&&(x=l)}const y={...g,currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:x};return{currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:x,directoryScoped:{...p.directoryScoped,[h]:y}}});return}}const u=n.find(m=>m.name===r)?.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,b={...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]:b}}})}}},setSettingsDefaultModel:r=>{t({settingsDefaultModel:r})},setSettingsDefaultVariant:r=>{t({settingsDefaultVariant:r})},setSettingsDefaultAgent:r=>{t({settingsDefaultAgent:r})},setSettingsAutoCreateWorktree:r=>{t({settingsAutoCreateWorktree:r})},setSettingsGitmojiEnabled:r=>{t({settingsGitmojiEnabled:r})},setSettingsZenModel:r=>{t({settingsZenModel:r})},setVoiceProvider:r=>{t({voiceProvider:r}),typeof window<"u"&&localStorage.setItem("voiceProvider",r)},setSpeechRate:r=>{const n=Math.max(.5,Math.min(2,r));t({speechRate:n}),typeof window<"u"&&localStorage.setItem("speechRate",String(n))},setSpeechPitch:r=>{const n=Math.max(.5,Math.min(2,r));t({speechPitch:n}),typeof window<"u"&&localStorage.setItem("speechPitch",String(n))},setSpeechVolume:r=>{const n=Math.max(0,Math.min(1,r));t({speechVolume:n}),typeof window<"u"&&localStorage.setItem("speechVolume",String(n))},setSayVoice:r=>{t({sayVoice:r}),typeof window<"u"&&localStorage.setItem("sayVoice",r)},setBrowserVoice:r=>{t({browserVoice:r}),typeof window<"u"&&localStorage.setItem("browserVoice",r)},setOpenaiVoice:r=>{t({openaiVoice:r}),typeof window<"u"&&localStorage.setItem("openaiVoice",r)},setOpenaiApiKey:r=>{t({openaiApiKey:r}),typeof window<"u"&&localStorage.setItem("openaiApiKey",r)},setShowMessageTTSButtons:r=>{t({showMessageTTSButtons:r}),typeof window<"u"&&localStorage.setItem("showMessageTTSButtons",String(r))},setVoiceModeEnabled:r=>{t({voiceModeEnabled:r}),typeof window<"u"&&localStorage.setItem("voiceModeEnabled",String(r))},setSummarizeMessageTTS:r=>{t({summarizeMessageTTS:r}),typeof window<"u"&&localStorage.setItem("summarizeMessageTTS",String(r))},setSummarizeVoiceConversation:r=>{t({summarizeVoiceConversation:r}),typeof window<"u"&&localStorage.setItem("summarizeVoiceConversation",String(r))},setSummarizeCharacterThreshold:r=>{const n=Math.max(50,Math.min(2e3,r));t({summarizeCharacterThreshold:n}),typeof window<"u"&&localStorage.setItem("summarizeCharacterThreshold",String(n))},setSummarizeMaxLength:r=>{const n=Math.max(50,Math.min(2e3,r));t({summarizeMaxLength:n}),typeof window<"u"&&localStorage.setItem("summarizeMaxLength",String(n))},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await nt.checkHealth();return t({isConnected:a}),a}catch(a){o=a,n+=1;const l=400*n;await e0(l)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),t({isConnected:!1}),!1},initializeApp:async()=>{try{const r=tr();r&&console.log("Starting app initialization...");const n=await s().checkConnection();if(r&&console.log("Connection check result:",n),!n){r&&console.log("Server not connected"),t({isConnected:!1});return}r&&console.log("Initializing app..."),await nt.initApp(),r&&console.log("Loading providers..."),await s().loadProviders(),r&&console.log("Loading agents..."),await s().loadAgents(),t({isInitialized:!0,isConnected:!0}),r&&console.log("App initialized successfully")}catch(r){console.error("Failed to initialize app:",r),t({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:r,currentProviderId:n}=s();return r.find(o=>o.id===n)},getCurrentModel:()=>{const r=s().getCurrentProvider(),{currentModelId:n}=s();if(r)return r.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:r,currentAgentName:n}=s();if(n)return r.find(o=>o.name===n)},getModelMetadata:(r,n)=>{const o=ax(r,n);if(!o)return;const{modelsMetadata:a}=s();return a.get(o)},getVisibleAgents:()=>{const{agents:r}=s();return ox(r)}}),{name:"config-store",storage:Dr(()=>Ws()),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,settingsZenModel:t.settingsZenModel,speechRate:t.speechRate,speechPitch:t.speechPitch,speechVolume:t.speechVolume})})));typeof window<"u"&&(window.__zustand_config_store__=ut);let Wm=null;Wm||(Wm=ic(async t=>{const s=[];if(ui(t,"agents")){const{loadAgents:r}=ut.getState();s.push(r().then(()=>{}))}if(ui(t,"providers")){const{loadProviders:r}=ut.getState();s.push(r())}s.length>0&&await Promise.all(s)}));let Gm=null;typeof window<"u"&&!Gm&&(Gm=Yt.subscribe((t,s)=>{const r=pa(t.currentDirectory),n=pa(s.currentDirectory);r!==n&&ut.getState().activateDirectory(t.currentDirectory)}));const ha=200,Pc={MAX_SESSIONS:3,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},cn=()=>Te.getState?.()?.messageLimit??ha,uc=()=>Math.round(cn()*.6),ix={MAX_SESSIONS:Pc.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(ha*.6),HISTORICAL_MESSAGES:ha,FETCH_BUFFER:20,HISTORY_CHUNK:ha,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:Pc.BACKGROUND_STREAMING_BUFFER,ZOMBIE_TIMEOUT:Pc.ZOMBIE_TIMEOUT},Zd=()=>{const t=cn(),s=uc();return{...ix,HISTORICAL_MESSAGES:t,VIEWPORT_MESSAGES:s,HISTORY_CHUNK:t}},ga=ix,ur=()=>typeof window<"u"&&window.__IKANBAN_RUNTIME_APIS__?.git?window.__IKANBAN_RUNTIME_APIS__.git:null;async function Yn(t){const s=ur();return s?s.checkIsGitRepository(t):yj(t)}async function Ou(t){const s=ur();return s?s.getGitStatus(t):Sj(t)}async function _u(t){const s=ur();return s?s.getGitBranches(t):kj(t)}async function s0(t,s){const r=ur();return r?r.deleteGitBranch(t,s):Lj(t,s)}async function r0(t,s){const r=ur();return r?r.deleteRemoteBranch(t,s):Nj(t,s)}async function n0(t,s){const r=ur();return r?.generatePullRequestDescription?r.generatePullRequestDescription(t,s):Pj(t,s)}async function o0(t){const s=ur();return s?.worktree?.list?s.worktree.list(t):s?s.listGitWorktrees(t):bj(t)}async function a0(t,s){const r=ur();return r?.worktree?.validate?r.worktree.validate(t,s):r?.validateGitWorktree?r.validateGitWorktree(t,s):jj(t,s)}async function i0(t,s){const r=ur();return r?.worktree?.create?r.worktree.create(t,s):r?.createGitWorktree?r.createGitWorktree(t,s):wj(t,s)}async function l0(t,s){const r=ur();return r?.worktree?.remove?r.worktree.remove(t,s):r?.deleteGitWorktree?r.deleteGitWorktree(t,s):vj(t,s)}const Si={worktree:{list:o0,validate:a0,create:i0,remove:l0}};async function c0(t,s,r){const n=ur();return n?n.renameBranch(t,s,r):Fj(t,s,r)}async function d0(){const t=ur();return t?t.getGitIdentities():Tj()}async function u0(t){const s=ur();return s?s.createGitIdentity(t):Aj(t)}async function m0(t,s){const r=ur();return r?r.updateGitIdentity(t,s):Mj(t,s)}async function f0(t){const s=ur();return s?s.deleteGitIdentity(t):Cj(t)}async function p0(){const t=ur();return t?.discoverGitCredentials?t.discoverGitCredentials():Dj()}async function h0(){const t=ur();return t?.getGlobalGitIdentity?t.getGlobalGitIdentity():Ij()}async function g0(t){const s=ur();return s?s.getRemotes(t):Ej(t)}async function x0(t){const s=ur();return s?.getConflictDetails?s.getConflictDetails(t):Rj(t)}const Rc="/api",y0=()=>(Rc.startsWith("/"),Rc);function b0(){if(typeof window>"u")return null;const t=window.__IKANBAN_RUNTIME_APIS__;return t?.files?t.files:null}async function v0(t,s){const r=b0();if(r?.execCommands)return r.execCommands(t,s);const n=await fetch(`${y0()}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:t,cwd:s,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 Ds(t,s){const r=await v0([t],s),n=r.results[0];return n||{command:t,success:r.success}}const To=t=>{if(!t)return"";const s=t.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},w0=(t,s)=>{const r=To(t),n=To(s);if(!n)return r;if(n.startsWith("/"))return n;const o=r.split("/").filter(Boolean),a=n.split("/").filter(Boolean);for(const l of a)if(l!=="."){if(l===".."){o.pop();continue}o.push(l)}return`/${o.join("/")}`},Km=t=>{const s=To(t);if(!s)return null;if(s.endsWith("/.git"))return s.slice(0,-5)||null;const n=s.indexOf("/.git/worktrees/");return n>0&&s.slice(0,n)||null};async function Ni(t){const s=To(t),r=await Ou(s);return{isDirty:!r.isClean,ahead:r.ahead,behind:r.behind,upstream:r.tracking}}async function Wo(t){const s=To(t);if(!s)return"HEAD";const r=async n=>{const o=await Ds("git rev-parse --absolute-git-dir",n),a=To((o.stdout||"").trim());if(o.success&&a){const m=Km(a);if(m)return m}const l=await Ds("git rev-parse --git-common-dir",n),c=To((l.stdout||"").trim());if(!l.success||!c)return n;const d=w0(n,c),u=Km(d);return u||n};try{const n=await r(s).catch(()=>s),o=await Ou(n);return(typeof o.current=="string"?o.current.trim():"")||"HEAD"}catch{return"HEAD"}}const j0="ikanban.json",S0=".ikanban",N0=[".config","ikanban"],k0=[".config","ikanban","projects"],C0="settings.json",Fc=new Map,qm=t=>/^[A-Za-z0-9._-]+$/.test(t),M0=t=>{let s="";for(const r of t)s+=r.toString(16).padStart(2,"0");return s},A0=async t=>{try{if(typeof crypto>"u"||!crypto.subtle)return null;const r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-1",r);return M0(new Uint8Array(n))}catch{return null}};function mc(){if(typeof window>"u")return null;const t=window.__IKANBAN_RUNTIME_APIS__;return t?.files?t.files:null}const eu=1e3,fl=120,pi=t=>{if(!t)return"";const s=t.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},ja=(t,s)=>{const r=pi(t),n=s.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!r||r==="/"?`/${n}`:`${r}/${n}`},lx=t=>ja(ja(t,S0),j0),ki=()=>{const t="/api";return t.startsWith("/"),t},$u=async(t,s)=>{try{const r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return r.ok?{ok:!0,data:await r.json().catch(()=>null)}:{ok:!1,data:null}}catch{return{ok:!1,data:null}}},D0=async t=>{const s=mc();if(s?.createDirectory)try{if((await s.createDirectory(t))?.success)return!0}catch{}return!!(await $u(`${ki()}/fs/mkdir`,{path:t})).ok},cx=async t=>{const s=mc();if(s?.readFile)try{const r=await s.readFile(t);return typeof r?.content=="string"?r.content:""}catch{return null}try{const r=await fetch(`${ki()}/fs/read?path=${encodeURIComponent(t)}`);return r.ok?await r.text():null}catch{return null}},I0=async(t,s)=>{const r=mc();if(r?.writeFile)try{if((await r.writeFile(t,s))?.success)return!0}catch{}return!!(await $u(`${ki()}/fs/write`,{path:t,content:s})).ok},dx=async()=>{if(!gs()){const t=await oc().catch(()=>null);if(t&&t.trim().length>0)return pi(t)}try{const t=await fetch(`${ki()}/fs/home`);if(!t.ok)return null;const s=await t.json().catch(()=>null),r=typeof s?.home=="string"?s.home.trim():"";return r?pi(r):null}catch{return null}},T0=async()=>{const t=await dx();return t?N0.reduce((s,r)=>ja(s,r),t):null},ux=async()=>{const t=await dx();return t?k0.reduce((s,r)=>ja(s,r),t):null},E0=async()=>{const t=await T0();return t?ja(t,C0):null},P0=async t=>{const s=typeof t?.path=="string"?t.path.trim():"",r=s?pi(s):"",n=typeof t?.id=="string"?t.id.trim():"";if(n&&qm(n))return n;if(r){const a=Fc.get(r);if(a)return a}const o=await E0();if(o&&r){const a=await cx(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"?pi(u.path.trim()):"";if(m&&qm(m)&&f&&f===r)return Fc.set(r,m),m}}catch{}}if(r){const a=await A0(r),l=a?`path_${a}`:`path_${r.replace(/[^A-Za-z0-9._-]+/g,"_")}`;return Fc.set(r,l),l}return null},mx=async t=>{const s=await ux();if(!s)return null;const r=await P0(t);return r?ja(s,`${r}.json`):null},fx=(t,s)=>t.length<=s?t:t.slice(0,s),R0=t=>typeof t!="string"?"":fx(t,eu),F0=t=>{if(!Array.isArray(t))return[];const s=[];for(const r of t){if(!r||typeof r!="object")continue;const n=r,o=typeof n.id=="string"?n.id.trim():"",a=typeof n.text=="string"?n.text:"",l=fx(a.trim(),fl);if(!o||!l)continue;const c=!!n.completed,d=typeof n.createdAt=="number"&&Number.isFinite(n.createdAt)&&n.createdAt>=0?n.createdAt:Date.now();s.push({id:o,text:l,completed:c,createdAt:d})}return s},px=t=>({notes:R0(t?.notes),todos:F0(t?.todos)});async function Bu(t){const s=typeof t?.path=="string"?t.path.trim():"";if(!s)return null;const r=await mx(t),n=async c=>{const d=await cx(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(r){const c=o(await n(r));if(c)return c}const a=lx(s),l=o(await n(a));if(!l)return null;try{await hx(t,l)&&await $0(s)}catch{}return l}async function hx(t,s){if(!(typeof t?.path=="string"?t.path.trim():""))return!1;const n=await ux(),o=await mx(t);if(!n||!o)return!1;try{if(!await D0(n))return!1;const l=JSON.stringify(s,null,2);return await I0(o,l)}catch(a){return console.error("Failed to write ikanban config:",a),!1}}async function gx(t,s){const n={...await Bu(t)||{},...s};return hx(t,n)}async function Ia(t){return(await Bu(t))?.["setup-worktree"]??[]}async function xx(t,s){const r=s.filter(n=>n.trim().length>0);return gx(t,{"setup-worktree":r})}async function L0(t){const s=await Bu(t);return px({notes:s?.projectNotes,todos:s?.projectTodos})}async function O0(t,s){const r=px({notes:s.notes,todos:s.todos});return gx(t,{projectNotes:r.notes,projectTodos:r.todos})}function _0(t,s){return t.replace(/\$ROOT_PROJECT_PATH/g,s.rootWorktreePath).replace(/\$\{ROOT_PROJECT_PATH\}/g,s.rootWorktreePath).replace(/\$ROOT_WORKTREE_PATH/g,s.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,s.rootWorktreePath)}async function $0(t){const s=lx(t),r=mc();if(r?.delete)try{await r.delete(s);return}catch{}try{await $u(`${ki()}/fs/delete`,{path:s})}catch{}}const ti=t=>{const s=t.replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},B0=t=>t.trim().replace(/^refs\/heads\//,"").replace(/^heads\//,"").replace(/\s+/g,"-").replace(/^\/+|\/+$/g,"").split("/").join("-").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,80),Qm=t=>t.trim().replace(/^refs\/heads\//,"").replace(/^heads\//,"").replace(/\s+/g,"-").replace(/^\/+|\/+$/g,""),Ym=t=>{const s=ti(t),r=s.split("/").filter(Boolean);return r[r.length-1]??s},z0=t=>{const s=[];for(const n of t.setupCommands){const o=n.trim();o&&s.push(_0(o,{rootWorktreePath:t.projectDirectory}))}const r=s.filter(Boolean).join(" && ");return r.trim().length>0?r:void 0},yx=(t,s)=>{const r=t.mode==="existing"?"existing":"new",n=t.worktreeName??t.preferredName??"",o=B0(n),a=t.branchName??(r==="new"?t.preferredName:void 0)??"",l=Qm(a),c=Qm(t.existingBranch??t.branchName??""),d=(t.startRef||"").trim(),u=Array.isArray(t.setupCommands)?t.setupCommands:[],m=z0({projectDirectory:s,setupCommands:u});return{mode:r,...o?{worktreeName:o}:{},...l?{branchName:l}:{},...c?{existingBranch:c}:{},...d?{startRef:d}:{},...m?{startCommand:m}:{},...t.setUpstream?{setUpstream:!0}:{},...t.upstreamRemote?{upstreamRemote:t.upstreamRemote}:{},...t.upstreamBranch?{upstreamBranch:t.upstreamBranch}:{},...t.ensureRemoteName?{ensureRemoteName:t.ensureRemoteName}:{},...t.ensureRemoteUrl?{ensureRemoteUrl:t.ensureRemoteUrl}:{}}};async function $o(t){const s=t.path,r=ti(s);return(await Si.worktree.list(s).catch(()=>[])).filter(a=>typeof a.path=="string"&&a.path.trim().length>0).map(a=>{const l=ti(a.path),c=(a.branch||"").replace(/^refs\/heads\//,"").trim(),d=(a.name||"").trim();return{source:"sdk",name:d||Ym(l),path:l,projectDirectory:s,branch:c,label:c||d||Ym(l)}}).filter(a=>ti(a.path)!==r).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 U0(t,s){const r=t.path,n=yx(s,r),o=await Si.worktree.create(r,n),a=typeof o?.name=="string"?o.name:"",l=typeof o?.branch=="string"?o.branch:"",c=typeof o?.path=="string"?o.path:"";if(!a||!c)throw new Error("Worktree create missing name/path");return{source:"sdk",name:a,path:ti(c),projectDirectory:r,branch:l,label:l||a}}async function Jm(t,s){const r=t.path,n=yx(s,r);return Si.worktree.validate(r,n)}async function fc(t,s,r){const n=t.path,o=!!r?.deleteRemoteBranch,a=r?.deleteLocalBranch===!0,l=r?.remoteName;if(!(await Si.worktree.remove(n,{directory:s.path,deleteLocalBranch:a}))?.success)throw new Error("Worktree removal failed");const d=(s.branch||"").replace(/^refs\/heads\//,"").trim();o&&d&&await r0(n,{branch:d,remote:l}).catch(()=>{})}const H0=150,V0=1100;let _l=null;const zn=()=>{_l&&_l()};function W0(){const t=i.useRef(!1),s=i.useRef(!1),r=i.useRef(0),n=i.useRef(null),o=i.useRef(null),a=i.useCallback(async(c=!1)=>{const d=Date.now();if(!(!c&&d-r.current<1e3)){if(t.current){c&&(s.current=!0);return}t.current=!0,r.current=d;try{const u=await fetch("/api/sessions/snapshot",{method:"GET",cache:"no-store",headers:{Accept:"application/json"}});if(!u.ok){console.warn("[useServerSessionStatus] Failed to fetch session snapshot:",u.status);return}const m=await u.json(),f=m.statusSessions??{},p=m.attentionSessions??{},h=Ae.getState().sessionStatus||new Map;let g=null;const x=()=>(g||(g=new Map(h)),g);for(const[N,w]of Object.entries(f)){const C=h.get(N);(!C||C.type!==w.status||C.attempt!==w.metadata?.attempt||C.message!==w.metadata?.message||C.next!==w.metadata?.next||C.confirmedAt!==w.lastUpdateAt)&&x().set(N,{type:w.status,confirmedAt:w.lastUpdateAt,attempt:w.metadata?.attempt,message:w.metadata?.message,next:w.metadata?.next})}for(const[N,w]of g??h)(w.type==="busy"||w.type==="retry")&&!f[N]&&x().set(N,{type:"idle",confirmedAt:Date.now()});const y=Ae.getState().sessionAttentionStates||new Map;let b=null;const v=()=>(b||(b=new Map(y)),b);let j=!1;for(const[N,w]of Object.entries(p)){const C=y.get(N),S=w;(!C||C.needsAttention!==S.needsAttention||C.lastUserMessageAt!==S.lastUserMessageAt||C.lastStatusChangeAt!==S.lastStatusChangeAt||C.status!==S.status||C.isViewed!==S.isViewed)&&(v().set(N,S),j=!0)}for(const N of(b??y).keys()){const w=!!f[N],C=!!p[N];!w&&!C&&(v().delete(N),j=!0)}const k=g!==null;(k||j)&&Ae.setState({...k&&g?{sessionStatus:g}:{},...j&&b?{sessionAttentionStates:b}:{}})}catch(u){console.warn("[useServerSessionStatus] Error fetching session status:",u)}finally{t.current=!1,s.current&&(s.current=!1,setTimeout(()=>{a(!0)},120))}}},[]),l=i.useCallback(()=>{n.current&&clearTimeout(n.current),o.current&&clearTimeout(o.current),n.current=setTimeout(()=>{a(!0)},H0),o.current=setTimeout(()=>{a(!0)},V0)},[a]);return i.useEffect(()=>(a(!0),()=>{n.current&&clearTimeout(n.current),o.current&&clearTimeout(o.current)}),[a]),i.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&l()};return document.addEventListener("visibilitychange",c),()=>{document.removeEventListener("visibilitychange",c)}},[l]),i.useEffect(()=>(_l=l,()=>{_l=null}),[l]),{fetchSessionStatus:a,triggerImmediatePoll:l}}const bx=Ws(),vx="oc.sessionSelectionByDirectory",G0=()=>{try{const t=bx.getItem(vx);if(!t)return{};const s=JSON.parse(t);return!s||typeof s!="object"?{}:Object.entries(s).reduce((r,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(r[n]=o),r),{})}catch{return{}}};let pl=null;const zu=()=>(pl||(pl=G0()),pl),wx=t=>{pl=t;try{bx.setItem(vx,JSON.stringify(t))}catch{}},jx=t=>{if(!t)return null;const r=zu()[t];return typeof r=="string"?r:null},_n=(t,s)=>{if(!t)return;const r={...zu()};s?r[t]=s:delete r[t],wx(r)},K0=(t,s)=>{if(!t)return;const r=jx(t);if(!r)return;if(!new Set(s).has(r)){const o={...zu()};delete o[t],wx(o)}},Xm=async(t,s)=>{const r=t.status??await Ni(t.path).catch(()=>{}),n=ps.getState().projects,o=Vt(t.projectDirectory)??t.projectDirectory,l={id:n.find(c=>Vt(c.path)===o)?.id??`path:${o}`,path:o};await fc(l,r?{...t}:t,{deleteRemoteBranch:s?.deleteRemoteBranch,deleteLocalBranch:s?.deleteLocalBranch,remoteName:s?.remoteName})},Zm=async(t,s)=>{const r=nt.getApiClient(),n=Vt(s??null);return!!(await r.session.delete({sessionID:t,...n?{directory:n}:{}})).data},Vt=t=>{if(typeof t!="string")return null;const s=t.trim();if(!s)return null;const r=s.replace(/\\/g,"/");return r==="/"?"/":r.length>1?r.replace(/\/+$/,""):r},ef=()=>{if(typeof window>"u")return null;const t=window.__VSCODE_CONFIG__,s=typeof t?.workspaceFolder=="string"?t.workspaceFolder:null;return Vt(s)},q0=()=>typeof window>"u"?!1:!!window.__IKANBAN_RUNTIME_APIS__?.runtime?.isVSCode,Bi=(...t)=>{tr()&&q0()&&console.log("[IKanban][VSCode][sessions]",...t)},eo=t=>{const s=new Map;return t.forEach(r=>{if(!r||typeof r.id!="string"||r.id.length===0)return;const n=s.get(r.id);if(!n){s.set(r.id,r);return}const o=n.time?.updated??0;(r.time?.updated??0)>o&&s.set(r.id,r)}),Array.from(s.values())},nn=t=>{const s=new Map;t.forEach(r=>{const n=Vt(r.directory??null);if(!n)return;const o=s.get(n);o?o.push(r):s.set(n,[r])});for(const[r,n]of s.entries())s.set(r,eo(n));return s},Yo=(t,s)=>{const r=t.find(n=>n.id===s);return r?Vt(r.directory??null):null},Q0=async(t,s,r)=>{const n=Vt(s);if(!n||t.length===0)return null;const o=t.map(m=>({id:m.id,directory:Vt(m.directory)})).filter(m=>!!m.directory);if(o.length===0)return null;let a;try{a=await $o({id:`path:${n}`,path:n})}catch(m){return console.debug("Failed to hydrate worktree metadata from worktree list:",m),null}if(!Array.isArray(a)||a.length===0){let m=!1;const f=new Map(r);return o.forEach(({id:p})=>{f.delete(p)&&(m=!0)}),m?f:null}const l=new Map;a.forEach(m=>{const f=Vt(m.path)??m.path;f!==n&&l.set(f,m)});let c=!1;const d=new Map(r),u=(m,f)=>f?{...f,...m,branch:m.branch||f.branch,label:m.label||f.label,name:m.name||f.name,projectDirectory:m.projectDirectory||f.projectDirectory,createdFromBranch:m.createdFromBranch||f.createdFromBranch,kind:m.kind||f.kind,status:m.status||f.status}:m;return o.forEach(({id:m,directory:f})=>{const p=l.get(f);if(!p){d.delete(m)&&(c=!0);return}const h=d.get(m),g=u(p,h);(!h||h.path!==g.path||h.branch!==g.branch||h.label!==g.label||h.name!==g.name||h.projectDirectory!==g.projectDirectory||h.createdFromBranch!==g.createdFromBranch||h.kind!==g.kind||h.source!==g.source)&&(d.set(m,g),c=!0)}),c?d:null},Wt=Ls()(Us(Ar((t,s)=>({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 r=Yt.getState(),n=ps.getState(),o=nt.getApiClient(),a=ef(),l=!!a;Bi("loadSessions:start",{workspace:a,currentDirectory:r.currentDirectory,clientDirectory:nt.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const c=new Map,d=async T=>{const _=Vt(T)??T,F=_,I=c.get(F);if(I)return I;try{const E=await o.path.get({directory:T}),V=Vt(E.data?.directory??null)??_;return c.set(F,V),V}catch{return c.set(F,_),_}},u=(T,_,F)=>{const I=Vt(_);if(!I)return T;const W=F?.includeDescendants===!0?`${I}/`:null,V=F?.includeMissingDirectory===!0;return T.filter(ve=>{const oe=Vt(ve.directory??null);return oe?!!(oe===I||W&&oe.startsWith(W)):V})},m=(T,_,F)=>{const I=Vt(_);if(!I)return T;const E=Vt(F??null);if(!E||E===I)return T.map(ve=>Vt(ve.directory??null)?ve:{...ve,directory:I});const W=E==="/"?"/":`${E}/`,V=I==="/"?"/":`${I}/`;return T.map(ve=>{const oe=Vt(ve.directory??null);if(!oe)return{...ve,directory:I};if(oe===E)return{...ve,directory:I};if(W!=="/"&&oe.startsWith(W)){const Z=oe.slice(W.length);return{...ve,directory:`${V}${Z}`}}return ve})},f=async T=>{const _=Vt(T);if(!_)try{const oe=await o.session.list(void 0);return Array.isArray(oe.data)?oe.data:[]}catch(oe){throw console.debug("Failed to list sessions (global):",oe),oe}const F=await d(_),I=async()=>{const oe=await o.session.list({directory:_});return Array.isArray(oe.data)?oe.data:[]};let E=[],W=null,V=!1;try{E=await I()}catch(oe){console.debug("Failed to list sessions for directory:",_,oe),W=oe,E=[]}if(E.length===0){V=!0;try{const oe=await o.session.list(void 0),Z=Array.isArray(oe.data)?oe.data:[];E=u(Z,F,{includeDescendants:l,includeMissingDirectory:!1})}catch(oe){throw console.debug("Failed to list sessions (global fallback):",oe),W||oe}}const ve=u(E,F,{includeDescendants:l,includeMissingDirectory:!V});return Bi("fetchSessionsForDirectory",{requestedDirectory:_,canonicalDirectory:F,fetched:E.length,filtered:ve.length}),m(ve,_,F)},p=Vt(r.currentDirectory??nt.getDirectory()??null),h=n.projects.find(T=>T.id===n.activeProjectId)??null,g=Vt(h?.path??null),x=g??p??null,y=n.projects.length>0?n.projects:x?[{id:"legacy",path:x}]:[];if(y.length===0){t({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}const b=await Promise.all(y.map(async T=>{const _=Vt(T.path);if(!_)return{projectId:T.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const F=await Yn(_).catch(()=>!1),I=await f(_||null);Bi("projectSessions",{projectId:T.id,projectPath:_,isGitRepo:F,parentSessions:I.length});const E=[];let W=[];const V=new Set;if(V.add(_),F)try{const oe=new Set,Z=await $o({id:T.id,path:_}).catch(()=>[]);W=Z,Z.forEach(ce=>{ce?.path&&oe.add(Vt(ce.path)??ce.path)}),oe.forEach(ce=>{const Q=Vt(ce)??ce;V.add(Q)}),oe.size>0&&(await Promise.allSettled(Array.from(oe).map(Q=>f(Q)))).forEach(Q=>{Q.status==="fulfilled"&&Array.isArray(Q.value)&&E.push(...Q.value)})}catch{W=[]}const ve=eo([...I,...E]);return{projectId:T.id,projectPath:_,sessions:ve,discoveredWorktrees:W,validPaths:V}})),v=new Map;b.forEach(T=>{T.projectPath&&T.validPaths.forEach(_=>{const F=Vt(_)??_,I=T.sessions.filter(E=>(Vt(E.directory??null)??F)===F);v.set(F,eo(I))})});const j=eo(Array.from(v.values()).flat()),k=s();let N=k.worktreeMetadata;for(const T of b)if(T.projectPath)try{const _=await Q0(T.sessions,T.projectPath,N);_&&(N=_)}catch(_){console.debug("Failed to refresh worktree metadata during session load:",_)}const w=new Map;b.forEach(T=>{T.projectPath&&w.set(T.projectPath,T.discoveredWorktrees)});const C=new Set;b.forEach(T=>{T.validPaths.forEach(_=>{const F=Vt(_)??_;F&&C.add(F)})});const S=p??g??null,M=S&&C.has(S)?S:g??S,D=M?v.get(M)??[]:j,A=new Set(j.map(T=>T.id));for(const[T,_]of v.entries())K0(T,_.map(F=>F.id));const P=(M??null)!==(k.lastLoadedDirectory??null);let $=k.currentSessionId;if((!$||!A.has($)||P)&&($=D[0]?.id??j[0]?.id??null),M){const T=jx(M);T&&A.has(T)&&($=T)}const R=(()=>{if(!$)return M??null;const T=N.get($)?.path;if(T)return Vt(T)??T;const _=Yo(j,$);return _||(M??null)})();try{nt.setDirectory(R??void 0)}catch(T){console.warn("Failed to sync OpenCode directory after session load:",T)}const O=g?b.find(T=>T.projectPath===g)?.discoveredWorktrees??[]:[];t({sessions:j,sessionsByDirectory:v,currentSessionId:$,lastLoadedDirectory:M??null,isLoading:!1,worktreeMetadata:N,availableWorktrees:O,availableWorktreesByProject:w}),M&&_n(M,$),R&&R!==M&&_n(R,$)}catch(r){t({error:r instanceof Error?r.message:"Failed to load sessions",isLoading:!1})}},createSession:async(r,n,o)=>{t({error:null});const a=Yt.getState(),l=Vt(a.currentDirectory),c=ef(),d=c??Vt(n??nt.getDirectory()??l);Bi("createSession:start",{title:r,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:c});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=s(),f=new Set(m.sessions.map(x=>x.id)),p={id:u,title:r||"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 y=[p,...x.sessions],b=new Map(x.sessionsByDirectory);if(d){const v=b.get(d)??[];b.set(d,eo([p,...v]))}return{sessions:y,sessionsByDirectory:b,currentSessionId:u,webUICreatedSessions:new Set([...x.webUICreatedSessions,u]),isLoading:!1}}),d)try{nt.setDirectory(d)}catch(x){console.warn("Failed to sync OpenCode directory after session creation:",x)}const h=x=>{const y=d??null,b=y?{...x,directory:y}:x;t(v=>{const j=v.sessions.map(N=>N.id===u?b:N),k=new Map(v.sessionsByDirectory);if(d){const w=(k.get(d)??[]).map(C=>C.id===u?b:C);k.set(d,eo(w))}return{sessions:j,sessionsByDirectory:nn(j),currentSessionId:b.id,webUICreatedSessions:new Set([...Array.from(v.webUICreatedSessions).filter(N=>N!==u),b.id])}}),_n(d??null,b.id)},g=async()=>{const x=nt.getApiClient(),y=20;for(let b=0;b<y;b+=1){try{const v=await x.session.list(d?{directory:d}:void 0),k=(Array.isArray(v.data)?v.data:[]).find(N=>!(f.has(N.id)||r&&N.title&&N.title!==r));if(k)return k}catch(v){console.debug("Session poll attempt failed:",v)}await new Promise(v=>setTimeout(v,2e3))}return null};try{const x=()=>nt.createSession({title:r,parentID:o??void 0});let y=null;try{y=d?await nt.withDirectory(d,x):await x()}catch(b){console.warn("Direct session create failed or timed out, falling back to polling:",b)}return y||(y=await g()),y?(h(y),y):(t(b=>({sessions:b.sessions.filter(v=>v.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(b.webUICreatedSessions).filter(v=>v!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(x){return t(y=>({sessions:y.sessions.filter(b=>b.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(b=>b!==u)),isLoading:!1,error:x instanceof Error?x.message:"Failed to create session"})),null}},deleteSession:async(r,n)=>{t({isLoading:!0,error:null});const o=s().worktreeMetadata.get(r),a=typeof o?.path=="string"?o.path:null,l=typeof o?.projectDirectory=="string"?o.projectDirectory:null,c=Yo(s().sessions,r),d=Vt(l)??Vt(c)??Vt(nt.getDirectory()??null)??null;let u=!1;try{if(!await Zm(r,d))return t({isLoading:!1,error:"Failed to delete session"}),!1;if(o&&n?.archiveWorktree)try{await Xm(o,{deleteRemoteBranch:n?.deleteRemoteBranch,deleteLocalBranch:n?.deleteLocalBranch,remoteName:n?.remoteName}),u=!0}catch(h){const g=h instanceof Error?h.message:"Failed to delete worktree";t({error:g})}let f=null;t(h=>{const g=h.sessions.filter(j=>j.id!==r);f=h.currentSessionId===r?null:h.currentSessionId;const x=new Map(h.worktreeMetadata);x.delete(r);const y=!!(a&&n?.archiveWorktree&&u),b=y?h.availableWorktrees.filter(j=>Vt(j.path)!==Vt(a)):h.availableWorktrees,v=new Map(h.availableWorktreesByProject);if(y&&l){const j=Vt(l)??l,k=v.get(j)??[];v.set(j,k.filter(N=>Vt(N.path)!==Vt(a)))}return{sessions:g,sessionsByDirectory:nn(g),currentSessionId:f,isLoading:!1,worktreeMetadata:x,availableWorktrees:b,availableWorktreesByProject:v}});const p=Vt(c)??Vt(nt.getDirectory()??null)??null;return _n(p,f),!0}catch(m){const f=m instanceof Error?m.message:"Failed to delete session";return t({error:f,isLoading:!1}),!1}},deleteSessions:async(r,n)=>{const o=Array.from(new Set(r.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 Map,u=new Set;for(const b of o)try{const v=s().worktreeMetadata.get(b),j=Yo(s().sessions,b),k=Vt(v?.projectDirectory??null)??Vt(j)??Vt(nt.getDirectory()??null)??null;if(v&&n?.archiveWorktree){const w=Vt(v.path)??v.path;u.has(w)||(u.add(w),d.set(w,v))}await Zm(b,k)?l.push(b):c.push(b)}catch{c.push(b)}const m=[],f=[];if(n?.archiveWorktree&&d.size>0)for(const b of d.values())try{await Xm(b,{deleteRemoteBranch:n?.deleteRemoteBranch,deleteLocalBranch:n?.deleteLocalBranch,remoteName:n?.remoteName}),m.push({path:b.path,projectDirectory:b.projectDirectory})}catch(v){const j=v instanceof Error?v.message:"Failed to delete worktree";f.push(j)}f.length>0&&t({error:f[0]});const p=Yt.getState();m.forEach(({path:b,projectDirectory:v})=>{p.currentDirectory===b&&p.setDirectory(v,{showOverlay:!1})});const h=new Set(l),g=c.length>0?c.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let x=null;t(b=>{const v=b.sessions.filter(C=>!h.has(C.id));b.currentSessionId&&h.has(b.currentSessionId)?x=null:x=b.currentSessionId;const j=new Map(b.worktreeMetadata);for(const C of h)j.delete(C);const k=new Set(m.map(C=>Vt(C.path)).filter(C=>!!C)),N=k.size>0?b.availableWorktrees.filter(C=>!k.has(Vt(C.path)??C.path)):b.availableWorktrees,w=new Map(b.availableWorktreesByProject);return m.length>0&&m.reduce((S,M)=>{const D=Vt(M.projectDirectory)??M.projectDirectory,A=Vt(M.path)??M.path;return S.has(D)||S.set(D,new Set),S.get(D)?.add(A),S},new Map).forEach((S,M)=>{const A=(w.get(M)??[]).filter(P=>!S.has(Vt(P.path)??P.path));w.set(M,A)}),{sessions:v,sessionsByDirectory:nn(v),currentSessionId:x,...a?{}:{isLoading:!1,error:g},worktreeMetadata:j,availableWorktrees:N,availableWorktreesByProject:w}});const y=nt.getDirectory()??null;return _n(y,x),{deletedIds:l,failedIds:c}},updateSessionTitle:async(r,n)=>{try{const o=Yo(s().sessions,r),a=s().worktreeMetadata.get(r),l=()=>nt.updateSession(r,n),c=a?.path??o,d=c?await nt.withDirectory(c,l):await l();t(u=>{const m=u.sessions.map(f=>f.id===r?d:f);return{sessions:m,sessionsByDirectory:nn(m)}})}catch(o){t({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async r=>{try{const n=Yo(s().sessions,r),o=nt.getApiClient(),l=s().worktreeMetadata.get(r)?.path??n,c=async()=>{const u=n??nt.getDirectory();return o.session.share({sessionID:r,...u?{directory:u}:{}})},d=l?await nt.withDirectory(l,c):await c();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===r?d.data:f);return{sessions:m,sessionsByDirectory:nn(m)}}),d.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async r=>{try{const n=Yo(s().sessions,r),o=nt.getApiClient(),l=s().worktreeMetadata.get(r)?.path??n,c=async()=>{const u=n??nt.getDirectory();return o.session.unshare({sessionID:r,...u?{directory:u}:{}})},d=l?await nt.withDirectory(l,c):await c();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===r?d.data:f);return{sessions:m,sessionsByDirectory:nn(m)}}),d.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:r=>{const n=s().currentSessionId;t({currentSessionId:r,error:null}),n&&n!==r&&fetch(`/api/sessions/${n}/unview`,{method:"POST"}).catch(()=>{}),r&&fetch(`/api/sessions/${r}/view`,{method:"POST"}).catch(()=>{}),zn();const o=nt.getDirectory()??null;_n(o,r)},clearError:()=>{t({error:null})},getSessionsByDirectory:r=>{const n=Vt(r)??r,{sessionsByDirectory:o,sessions:a}=s(),l=o.get(n);return l||a.filter(c=>(Vt(c.directory??null)??n)===n)},getDirectoryForSession:r=>{if(!r)return null;const n=s().worktreeMetadata.get(r);if(n?.path)return Vt(n.path)??n.path;const o=s().sessions.find(l=>l.id===r);return Vt(o?.directory??null)},applySessionMetadata:(r,n)=>{!r||!n||t(o=>{const a=o.sessions.findIndex(h=>h.id===r);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:nn(p)}})},isIKanbanCreatedSession:r=>{const{webUICreatedSessions:n}=s();return n.has(r)},markSessionAsIKanbanCreated:r=>{t(n=>{const o=new Set(n.webUICreatedSessions);return o.add(r),{webUICreatedSessions:o}})},initializeNewIKanbanSession:r=>{const{markSessionAsIKanbanCreated:n}=s();n(r)},setWorktreeMetadata:(r,n)=>{r&&t(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(r,n):a.delete(r),{worktreeMetadata:a}})},getWorktreeMetadata:r=>{if(r)return s().worktreeMetadata.get(r)},setSessionDirectory:(r,n)=>{if(!r)return;const o=s().sessions,a=o.findIndex(u=>u.id===r);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:nn(m)}}),c&&_n(c,null),n&&_n(n,r))},updateSession:r=>{t(n=>{const a=n.sessions.findIndex(c=>c.id===r.id)===-1?[r,...n.sessions]:n.sessions.map(c=>c.id===r.id?r:c),l=eo(a);return{sessions:l,sessionsByDirectory:nn(l)}})},removeSessionFromStore:r=>{r&&t(n=>{const o=n.sessions.find(u=>u.id===r),a=Vt(o?.directory??null),l=n.sessions.filter(u=>u.id!==r);if(l.length===n.sessions.length)return n;const c=new Map(n.worktreeMetadata);c.delete(r);const d=n.currentSessionId===r?null:n.currentSessionId;return a&&_n(a,null),{sessions:l,sessionsByDirectory:nn(l),currentSessionId:d,worktreeMetadata:c}})}}),{name:"session-store",storage:Dr(()=>Ws()),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,s)=>{if(!(h=>typeof h=="object"&&h!==null)(t))return s;const n=Array.isArray(t.sessions)?t.sessions:s.sessions,o=typeof t.currentSessionId=="string"||t.currentSessionId===null?t.currentSessionId:s.currentSessionId,a=Array.isArray(t.webUICreatedSessions)?t.webUICreatedSessions:[],l=Array.isArray(t.worktreeMetadata)?t.worktreeMetadata:[],c=Array.isArray(t.availableWorktrees)?t.availableWorktrees:s.availableWorktrees,d=Array.isArray(t.availableWorktreesByProject)?t.availableWorktreesByProject:[],u=new Map(d),m=typeof t.lastLoadedDirectory=="string"?t.lastLoadedDirectory:s.lastLoadedDirectory??null,f=eo(n);return{...s,...t,sessions:f,sessionsByDirectory:nn(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(l),availableWorktrees:c,availableWorktreesByProject:u.size>0?u:s.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),Sx="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.",Y0="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: ",Lc=t=>typeof t=="string"&&t.trim()===Sx.trim(),Oc=(t,s)=>{const r=Date.now(),n=t.get(s),o=new Map(t);return o.set(s,{phase:"streaming",startedAt:n?.startedAt??r,lastUpdateAt:r}),o},Oa=(t,s)=>{const r=Array.from(s);if(!r.some(a=>t.has(a)))return t;const o=new Map(t);return r.forEach(a=>{o.delete(a)}),o},tf=new Map,Nx=t=>{const s=tf.get(t);s&&(clearTimeout(s),tf.delete(t))},wo=t=>{for(const s of t)Nx(s)},hi=t=>{if(!t)return"";if(typeof t=="string")return t;if(Array.isArray(t))return t.map(s=>hi(s)).join("");if(typeof t=="object"){if(typeof t.text=="string")return t.text;if(Array.isArray(t.content))return t.content.map(s=>hi(s)).join("")}return""},na=t=>{if(!t)return"";const s=t;if(typeof s.text=="string")return s.text;if(Array.isArray(s.text))return s.text.map(n=>typeof n=="string"?n:na(n)).join("");const r=hi(s.delta);return r||(typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||hi(o.delta)||""}return""}).join(""):"")},_a=(t,s)=>{const r={...t};if(r.type=r.type||"text",r.type==="text"){const n=s&&typeof s.text=="string"?s.text:"",o=typeof r.text=="string"?r.text:"",a=hi(t.delta);o?r.text=o:a?r.text=n?`${n}${a}`:a:n?r.text=n:r.text="",delete r.delta}return r},J0=50*1024*1024,kx=t=>{const s=(t||"").toLowerCase(),r=s.includes(".")&&s.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying","makefile","dockerfile","gemfile","rakefile","procfile","vagrantfile","justfile","taskfile"]).has(s))return"text/plain";switch(r){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";case"md":case"markdown":return"text/markdown";case"json":return"application/json";case"yaml":case"yml":return"application/x-yaml";case"xml":return"application/xml";case"toml":return"application/toml";case"txt":case"csv":case"log":case"env":case"ini":case"cfg":case"conf":case"properties":case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"pyi":case"rb":case"rs":case"go":case"java":case"kt":case"kts":case"scala":case"c":case"h":case"cpp":case"cc":case"cxx":case"hpp":case"hxx":case"cs":case"swift":case"m":case"mm":case"r":case"lua":case"pl":case"pm":case"php":case"ex":case"exs":case"erl":case"hrl":case"hs":case"lhs":case"ml":case"mli":case"fs":case"fsx":case"clj":case"cljs":case"cljc":case"dart":case"zig":case"nim":case"v":case"vhdl":case"verilog":case"sql":case"graphql":case"gql":case"proto":case"thrift":case"sh":case"bash":case"zsh":case"fish":case"ps1":case"bat":case"cmd":case"html":case"htm":case"css":case"scss":case"sass":case"less":case"vue":case"svelte":case"astro":case"tf":case"hcl":case"nix":case"cmake":case"mk":case"gradle":case"sbt":case"lock":case"gitignore":case"dockerignore":case"editorconfig":case"eslintrc":case"prettierrc":return"text/plain";default:return"application/octet-stream"}},X0=t=>{const s=t.type?.trim().toLowerCase()??"";return s.length>0&&s!=="application/octet-stream"&&!s.startsWith("application/octet-stream;")?t.type:kx(t.name)},tu=t=>t.replace(/\\/g,"/").trim(),Z0=t=>{const s=tu(t);if(s.startsWith("file://"))return s;const r=s.startsWith("/")?s:`/${s}`;return`file://${encodeURI(r)}`},eN=async t=>{const s=await fetch(`/api/fs/raw?path=${encodeURIComponent(t)}`);if(!s.ok)throw new Error(`Failed to read raw file: ${s.status}`);const r=await s.blob();return await new Promise((n,o)=>{const a=new FileReader;a.onload=()=>n(a.result),a.onerror=o,a.readAsDataURL(r)})},Jr=Ls()(Us(Ar((t,s)=>({attachedFiles:[],addAttachedFile:async r=>{const{attachedFiles:n}=s();if(n.some(g=>g.filename===r.name&&g.size===r.size)){console.log(`File "${r.name}" is already attached`);return}const a=J0;if(r.size>a)throw new Error(`File "${r.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=X0(r);!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(r)}),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:r,dataUrl:f,mimeType:c,filename:p(r.name),size:r.size,source:"local"};t(g=>({attachedFiles:[...g.attachedFiles,h]}))},addServerFile:async(r,n,o)=>{const a=tu(r),{attachedFiles:l}=s();if(l.some(x=>tu(x.serverPath||"")===a&&x.source==="server")){console.log(`Server file "${n}" is already attached`);return}const d=kx(n),u=d&&d.trim().length>0?d:"text/plain",m=u==="application/x-directory";let f=Z0(a);if(!m)try{const x=await eN(a),y=x.indexOf(",");if(y!==-1){const b=x.substring(5,y),v=x.substring(y);f=`data:${b.replace(/^[^;,]+/,u)}${v}`}else f=x}catch(x){console.warn("Failed to read server file, falling back to file://",x)}const p=typeof o=="string"?new TextEncoder().encode(o).length:0,h=new File([],n,{type:u}),g={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:h,dataUrl:f,mimeType:u,filename:n,size:p,source:"server",serverPath:a};t(x=>({attachedFiles:[...x.attachedFiles,g]}))},removeAttachedFile:r=>{t(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==r)}))},clearAttachedFiles:()=>{t({attachedFiles:[]})}}),{name:"file-store",storage:Dr(()=>Ws()),version:3,migrate:t=>{const s=t;return{attachedFiles:Array.isArray(s?.attachedFiles)?s.attachedFiles:[]}},partialize:t=>({attachedFiles:t.attachedFiles})}),{name:"file-store"})),tN=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),sN=t=>t?tN.has(t.toLowerCase()):!1,rN=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},nN=t=>{if(t)try{const s=rN();if(s?.getState)return s.getState().agents?.find?.(n=>n.name===t)}catch{}},oN=(t,s)=>{if(!t||t.length===0)return"ask";for(let r=t.length-1;r>=0;r-=1){const n=t[r];if(n.permission===s&&n.pattern==="*")return n.action}for(let r=t.length-1;r>=0;r-=1){const n=t[r];if(n.permission==="*"&&n.pattern==="*")return n.action}return"ask"},hl=t=>{const s=nN(t);return s?oN(s.permission,"edit"):"ask"},sf=t=>{if(!t||typeof t!="object")return 0;const s=t.input??0,r=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 s+r+n+o+a},_c=t=>{const s=t.info.tokens;if(typeof s=="number")return s;if(s&&typeof s=="object")return sf(s);const r=t.parts.find(n=>typeof n.tokens<"u");return!r||typeof r.tokens>"u"?0:typeof r.tokens=="number"?r.tokens:sf(r.tokens)},$c=(t,s,r)=>{const n=Number.isFinite(s)?Math.max(s,0):0,o=Number.isFinite(r)&&r>0,a=o?Math.max(r,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}},$a=["ask","allow","full"],rf="__global__",Lt=Ls()(Us(Ar((t,s)=>({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:(r,n,o)=>{t(a=>{const l=new Map(a.sessionModelSelections);return l.set(r,{providerId:n,modelId:o}),{sessionModelSelections:l}})},getSessionModelSelection:r=>{const{sessionModelSelections:n}=s();return n.get(r)||null},saveSessionAgentSelection:(r,n)=>{t(o=>{const a=new Map(o.sessionAgentSelections);a.set(r,n);const l=new Map(o.currentAgentContext);return l.set(r,n),{sessionAgentSelections:a,currentAgentContext:l}})},getSessionAgentSelection:r=>{const{sessionAgentSelections:n}=s();return n.get(r)||null},saveAgentModelForSession:(r,n,o,a)=>{t(l=>{const c=new Map(l.sessionAgentModelSelections);let d=c.get(r);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(r,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(r,n)=>{const{sessionAgentModelSelections:o}=s(),a=o.get(r);return a&&a.get(n)||null},saveAgentModelVariantForSession:(r,n,o,a,l)=>{t(c=>{const d=new Map(c.sessionAgentModelVariantSelections);let u=d.get(r);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(r):d.set(r,u)):(u.set(n,m),d.set(r,u))):(m.set(f,l),u.set(n,m),d.set(r,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(r,n,o,a)=>{const{sessionAgentModelVariantSelections:l}=s(),c=l.get(r);if(!c)return;const d=c.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(r,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:l}=s(),c=new Map,d=(g,x)=>{if("mode"in g&&g.mode&&typeof g.mode=="string"&&n.find(j=>j.name===g.mode))return g.mode;if("agent"in g&&g.agent&&typeof g.agent=="string"&&n.find(j=>j.name===g.agent))return g.agent;if(g.providerID&&g.modelID){const v=n.find(j=>j.model?.providerID===g.providerID&&j.model?.modelID===g.modelID);if(v)return v.name}const{currentAgentContext:y}=s(),b=y.get(r);if(b&&n.find(v=>v.name===b))return b;if(x>0&&g.providerID&&g.modelID){const j=(o.get(r)||[]).filter(k=>k.info.role==="assistant").sort((k,N)=>k.info.time.created-N.info.time.created);for(let k=x-1;k>=0;k--){const w=j[k].info;if(w.providerID===g.providerID&&w.modelID===g.modelID){if(w.mode&&typeof w.mode=="string"&&n.find(M=>M.name===w.mode))return w.mode;const C=n.find(S=>S.model?.providerID===w.providerID&&S.model?.modelID===w.modelID);if(C)return C.name}}}return g.providerID&&g.modelID&&n.find(j=>j.name==="build")?"build":null},u=o.get(r)||[],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:y}=x,b=y;if(b.role==="user"){const v=typeof b.mode=="string"&&b.mode.trim().length>0?b.mode:typeof b.agent=="string"&&b.agent.trim().length>0?b.agent:void 0,j=typeof b.model?.providerID=="string"&&b.model.providerID.trim().length>0?b.model.providerID:typeof b.providerID=="string"&&b.providerID.trim().length>0?b.providerID:void 0,k=typeof b.model?.modelID=="string"&&b.model.modelID.trim().length>0?b.model.modelID:typeof b.modelID=="string"&&b.modelID.trim().length>0?b.modelID:void 0;if(v&&j&&k&&n.find(N=>N.name===v)){const N={providerId:j,modelId:k,timestamp:y.time.created},w=c.get(v);(!w||N.timestamp>w.timestamp)&&c.set(v,N),typeof b.variant=="string"&&b.variant.trim().length>0&&l(r,v,j,k,b.variant)}p=typeof b.variant=="string"&&b.variant.trim().length>0?b.variant:void 0,h=b.model?.providerID&&b.model?.modelID?{providerID:b.model.providerID,modelID:b.model.modelID}:void 0;continue}if(b.providerID&&b.modelID){const v=d(b,f.indexOf(x));if(v&&n.find(j=>j.name===v)){p&&h&&h.providerID===b.providerID&&h.modelID===b.modelID&&l(r,v,b.providerID,b.modelID,p);const j={providerId:b.providerID,modelId:b.modelID,timestamp:y.time.created},k=c.get(v);(!k||j.timestamp>k.timestamp)&&c.set(v,j)}}p=void 0,h=void 0}for(const[g,x]of c)a(r,g,x.providerId,x.modelId);return c},getContextUsage:(r,n,o,a)=>{if(!r)return null;const l=$c(0,n,o),c=l.contextLimit,d=l.normalizedOutput??0,u=l.thresholdLimit;if(c===0||u===0)return null;const f=(a.get(r)||[]).filter(j=>j.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],h=p.info.id,g=j=>{const k=()=>{t(N=>{const w=N.sessionContextUsage.get(r);if(w&&w.totalTokens===j.totalTokens&&w.percentage===j.percentage&&w.contextLimit===j.contextLimit&&(w.outputLimit??0)===(j.outputLimit??0)&&(w.normalizedOutput??0)===(j.normalizedOutput??0)&&w.thresholdLimit===j.thresholdLimit&&w.lastMessageId===j.lastMessageId)return N;const C=new Map(N.sessionContextUsage);return C.set(r,j),{sessionContextUsage:C}})};typeof queueMicrotask=="function"?queueMicrotask(k):typeof window<"u"?window.setTimeout(k,0):setTimeout(k,0)},x=s().sessionContextUsage.get(r);if(x&&x.lastMessageId===h){const j=x.normalizedOutput??x.outputLimit??0,k=x.contextLimit!==c||j!==d||x.thresholdLimit!==u;if(k&&x.totalTokens>0){const N=x.totalTokens/u*100,w={totalTokens:x.totalTokens,percentage:Math.min(N,100),contextLimit:c,outputLimit:l.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return g(w),w}if(!k&&x.totalTokens>0)return x}const y=_c(p);if(y===0)return x||null;const b=$c(y,n,o),v={totalTokens:y,percentage:b.percentage,contextLimit:b.contextLimit,outputLimit:b.outputLimit,normalizedOutput:b.normalizedOutput,thresholdLimit:b.thresholdLimit,lastMessageId:h};return g(v),v},updateSessionContextUsage:(r,n,o,a)=>{const c=(a.get(r)||[]).filter(f=>f.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=_c(d);if(u===0)return;const m=$c(u,n,o);t(f=>{const p=new Map(f.sessionContextUsage);return p.set(r,{totalTokens:u,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit,normalizedOutput:m.normalizedOutput,thresholdLimit:m.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(r,n,o,a)=>{const c=s().sessionContextUsage.get(r);(!c||c.totalTokens===0)&&s().updateSessionContextUsage(r,n,o,a)},pollForTokenUpdates:(r,n,o,a=10)=>{let l=0;const c=()=>{l++;const u=(o.get(r)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&_c(u)>0){s().updateSessionContextUsage(r,0,0,o);return}l<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:r=>{const{currentAgentContext:n}=s();return n.get(r)},getSessionAgentEditMode:(r,n,o=hl(n))=>{if(!r||!n)return o;const l=s().sessionAgentEditModes.get(r)?.get(n);if(l!==void 0)return l;if(r!==rf){const d=s().sessionAgentEditModes.get(rf)?.get(n);if(d!==void 0)return d}return o},setSessionAgentEditMode:(r,n,o,a=hl(n))=>{if(!r||!n)return;const l=a??"ask";l==="deny"||o==="deny"||$a.includes(o)&&t(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(r)??new Map);return o===l?(u.delete(n),u.size===0?d.delete(r):d.set(r,u)):(u.set(n,o),d.set(r,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(r,n,o=hl(n))=>{if(!r||!n)return;const a=o??"ask";if(a==="deny")return;const l=s().getSessionAgentEditMode(r,n,a),c=$a.indexOf(l),d=$a.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%$a.length,f=$a[m];s().setSessionAgentEditMode(r,n,f,a)}}),{name:"context-store",storage:Dr(()=>Ws()),partialize:t=>({sessionModelSelections:Array.from(t.sessionModelSelections.entries()),sessionAgentSelections:Array.from(t.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(t.sessionAgentModelSelections.entries()).map(([s,r])=>[s,Array.from(r.entries())]),sessionAgentModelVariantSelections:Array.from(t.sessionAgentModelVariantSelections.entries()).map(([s,r])=>[s,Array.from(r.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(([s,r])=>[s,Array.from(r.entries())])}),merge:(t,s)=>{const r=new Map;t?.sessionAgentModelSelections&&t.sessionAgentModelSelections.forEach(([a,l])=>{r.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))}),{...s,...t,sessionModelSelections:new Map(t?.sessionModelSelections||[]),sessionAgentSelections:new Map(t?.sessionAgentSelections||[]),sessionAgentModelSelections:r,sessionAgentModelVariantSelections:n,currentAgentContext:new Map(t?.currentAgentContext||[]),sessionContextUsage:new Map(t?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),nf=(t,s)=>{const r=new Map(t);return r.delete(s),r};let Bc=[],zc=null;const aN=50,iN=3e4,jo=new Map,zi=new Map,Jo=new Map,lN=10,$l=t=>{if(typeof t!="string")return null;const s=t.trim();if(!s)return null;const r=s.indexOf("_"),n=r>=0?s.slice(r+1):s;return!n||n.length<lN?null:n},Ui=(t,s)=>{const r=$l(t),n=$l(s);return!r||!n||r.length!==n.length?!0:r>n},cN=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("ikanban_stream_debug")==="1"}catch{return!1}},ia=t=>!Array.isArray(t)||t.length===0?0:t.reduce((s,r)=>{if(!r||r.type!=="text")return s;const n=r.text??r.content;return typeof n=="string"?s+n.length:s},0),of=t=>{const s=t.replace(/\\/g,"/").trim();if(s.startsWith("file://"))return s;const r=s.startsWith("/")?s:`/${s}`;return`file://${encodeURI(r)}`},Bl=t=>t?.finish==="stop",af=t=>{if(t){if(typeof t.id=="string"&&t.id.length>0)return t.id;if(t.type){const s=t.reason,r=t.callID;return`${t.type}-${s??""}-${r??""}`}}},lf=new Set,zl=(t=[],s=[])=>{if(!s.length)return[...t];const r=[...t],n=new Set(t.map(af).filter(o=>!!o));return s.forEach(o=>{if(!o)return;const a=af(o);a&&n.has(a)||(r.push(o),a&&n.add(a))}),r},dN=(t,s)=>{const r=Array.isArray(t.parts)?t.parts:[],n=Array.isArray(s.parts)?s.parts:[],o=ia(r),a=ia(n),l=Bl(t.info),c=Bl(s.info);let d=n;return l&&o>=a?d=zl(r,n):c&&a>=o?d=zl(n,r):o>=a&&(d=r),{...s,info:{...t.info,...s.info},parts:d}},Ba=t=>{const s=[],r=new Map;for(const n of t){const o=typeof n?.info?.id=="string"?n.info.id:null;if(!o){s.push(n);continue}const a=r.get(o);if(a===void 0){r.set(o,s.length),s.push(n);continue}s[a]=dN(s[a],n)}return s},uN=(t,s)=>{let r=s,n=s?$l(s):null;for(const o of t){const a=o?.info?.id,l=$l(a);!a||!l||(!n||l>n)&&(n=l,r=a)}return r},vn=(t,s,r)=>{if(t.get(s)===r)return t;const o=new Map(t);return r?o.set(s,r):o.delete(s),o},Xo=(t,s,r)=>{if(t.get(s)===r)return t;const o=new Map(t);return o.set(s,r),o},Hi=(t,s)=>{const r=new Map(t);let n=!1;for(const o of s)r.delete(o)&&(n=!0);return n?r:t},mN=(t,s)=>{const r=new Set,n=t.streamingMessageIds.get(s);return n&&r.add(n),t.messageStreamStates.forEach((o,a)=>{t.messageSessionIndex.get(a)===s&&r.add(a)}),r},cf=(t,s,r)=>t.streamingMessageIds.get(s)===r?!0:t.messageSessionIndex.get(r)===s&&t.messageStreamStates.has(r),fN=async t=>{if(t)try{return Wt.getState().getDirectoryForSession(t)??void 0}catch(s){console.warn("Failed to resolve session directory override:",s);return}},df=t=>{if(!t)return null;try{return Wt.getState().sessions.find(n=>n.id===t)?.revert?.messageID??null}catch{return null}},uf=(t,s)=>{if(!s)return t;const r=t.findIndex(n=>n.info.id===s);return r===-1?t:t.slice(0,r)},Uc=async(t,s)=>{const r=await fN(t);return r?nt.withDirectory(r,s):s()},rs=Ls()(Us(Ar((t,s)=>({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(r,n)=>{const o=Zd(),a=n===1/0,l=s().sessionMemoryState.get(r),c=o.HISTORICAL_MESSAGES,d=l?.historyLimit,u=typeof n=="number"&&Number.isFinite(n)?n:Math.max(c,d??0),m=a?void 0:u+1,f=await Uc(r,()=>nt.getSessionMessages(r,m)),p=df(r),h=uf(f,p),g=typeof m=="number"?h.length>u:!1,x=s().sessionMemoryState.get(r)?.trimmedHeadMaxId,b=(x?h.filter(v=>{const j=v?.info?.id;return j?Ui(j,x):!0}):h).slice(-u);t(v=>{const j=new Map(v.messages),k=v.messages.get(r)||[],N=new Map(k.filter(T=>typeof T.info?.id=="string").map(T=>[T.info.id,T])),w=b.map(T=>{const _={...T.info,clientRole:T.info?.clientRole??T.info.role,userMessageMarker:T.info.role==="user"?!0:T.info?.userMessageMarker},F=(Array.isArray(T.parts)?T.parts:[]).map(E=>{if(E?.type==="text"){const W=E.text??E.content??"";if(Lc(W))return{...E,synthetic:!0}}return E}),I=_?.id?N.get(_.id):void 0;if(I&&I.info.role==="assistant"){const E=Array.isArray(I.parts)?I.parts:[],W=ia(E),V=ia(F);if(Bl(I.info)&&W>V){const oe=zl(E,F);return{...T,info:_,parts:oe}}}return{...T,info:_,parts:F}}),C=Ba(w),S=new Set(k.map(T=>T.info.id)),M=new Set(C.map(T=>T.info.id)),D=[];S.forEach(T=>{M.has(T)||D.push(T)}),j.set(r,C);const A=new Map(v.sessionMemoryState);A.set(r,{...l,viewportAnchor:C.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:l?.totalAvailableMessages,hasMoreAbove:g,historyLoading:!1,historyComplete:!g,historyLimit:u,trimmedHeadMaxId:l?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const P={messages:j,sessionMemoryState:A};wo(D);const $=Oa(v.messageStreamStates,D);if($!==v.messageStreamStates&&(P.messageStreamStates=$),D.length>0){const T=v.streamingMessageIds.get(r);T&&D.includes(T)&&(P.streamingMessageIds=vn(P.streamingMessageIds??v.streamingMessageIds,r,null))}if(D.length>0){const T=Hi(P.messageSessionIndex??v.messageSessionIndex,D);T!==(P.messageSessionIndex??v.messageSessionIndex)&&(P.messageSessionIndex=T)}if(D.length>0){const T=new Map(v.pendingAssistantParts);let _=!1;D.forEach(F=>{T.delete(F)&&(_=!0)}),_&&(P.pendingAssistantParts=T)}const R=P.messageSessionIndex??v.messageSessionIndex;let O=R;return C.forEach(T=>{const _=T?.info?.id;typeof _=="string"&&_.length>0&&(O=Xo(O,_,r))}),O!==R&&(P.messageSessionIndex=O),P})},sendMessage:async(r,n,o,a,l,c,d,u,m)=>{if(!l)throw new Error("No session selected");const f=l;s().sessionAbortFlags.has(f)&&t(p=>{const h=new Map(p.sessionAbortFlags);return h.delete(f),{sessionAbortFlags:h}}),await Uc(f,async()=>{try{let p=r;if(r.startsWith("/")){const g=r.indexOf(" "),x=g===-1?r.substring(1):r.substring(1,g),y=g===-1?"":r.substring(g+1).trim(),b=nt.getApiClient(),v=nt.getDirectory();if(x==="init"){const j=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await b.session.init({sessionID:f,...v?{directory:v}:{},messageID:j,providerID:n,modelID:o});return}if(x==="summarize"){await b.session.summarize({sessionID:f,...v?{directory:v}:{},providerID:n,modelID:o});return}try{const j=await nt.getCommandDetails(x);j?.template?p=j.template.replace(/\$ARGUMENTS/g,y):p=r}catch(j){console.error("Command template resolution failed:",j),p=r}}t({lastUsedProvider:{providerID:n,modelID:o}}),t(g=>{const x=g.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},y=Jo.get(f);y&&(clearTimeout(y),Jo.delete(f));const b=new Map(g.sessionMemoryState);return b.set(f,{...x,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:b}});try{const g=new AbortController;t(b=>{const v=new Map(b.abortControllers);return v.set(f,g),{abortControllers:v}});const x=(c??[]).map(b=>({type:"file",mime:b.mimeType,filename:b.filename,url:b.source==="server"&&b.serverPath&&b.mimeType==="application/x-directory"?of(b.serverPath):b.dataUrl}));t(b=>{const v=new Set(b.pendingAssistantHeaderSessions);v.add(f);const j=new Map(b.pendingUserMessageMetaBySession);return j.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:v,pendingUserMessageMetaBySession:j}});const y=u?.map(b=>({text:b.text,synthetic:b.synthetic,files:b.attachments?.map(v=>({type:"file",mime:v.mimeType,filename:v.filename,url:v.source==="server"&&v.serverPath&&v.mimeType==="application/x-directory"?of(v.serverPath):v.dataUrl}))}));if(await nt.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:x.length>0?x:void 0,additionalParts:y&&y.length>0?y:void 0,agentMentions:d?[{name:d}]:void 0}),x.length>0)try{Jr.getState().clearAttachedFiles()}catch(b){console.error("Failed to clear attached files after send",b)}t(b=>{const v=new Map(b.abortControllers);return v.delete(f),{abortControllers:v}})}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(y=>{const b=new Map(y.abortControllers);return b.delete(f),{abortControllers:b}});return}else g.message&&(x=g.message);throw t(y=>{const b=new Map(y.abortControllers);b.delete(f);const v=new Set(y.pendingAssistantHeaderSessions);v.delete(f);const j=new Map(y.pendingUserMessageMetaBySession);return j.delete(f),{abortControllers:b,pendingAssistantHeaderSessions:v,pendingUserMessageMetaBySession:j}}),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 y=new Set(g.pendingAssistantHeaderSessions);y.delete(f);const b=new Map(g.pendingUserMessageMetaBySession);return b.delete(f),{abortControllers:x,pendingAssistantHeaderSessions:y,pendingUserMessageMetaBySession:b}}),new Error(h)}})},abortCurrentOperation:async r=>{if(!r)return;const n=s(),{abortControllers:o,messages:a}=n;o.get(r)?.abort();const c=mN(n,r);if(c.size===0){const u=r?a.get(r)??[]:[];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=jo.get(u);m&&(clearTimeout(m),jo.delete(u),zi.delete(u))}c.size>0&&wo(c);const d=Date.now();t(u=>{const m=Oa(u.messageStreamStates,c),f=u.messages.get(r)??[];let p=!1,h=u.messages;if(f.length>0&&c.size>0){const b=f.map(v=>{if(!c.has(v.info.id)&&c.size>0)return v;const j=(v.parts??[]).map(k=>{if(k.type==="reasoning"){const N=k,w={...N.time??{}};return typeof w.end!="number"&&(w.end=d),{...N,time:w}}if(k.type==="tool"){const N=k,w={...N.state??{}};return(w.status==="running"||w.status==="pending")&&(w.status="aborted"),{...N,state:w}}return k.type==="step-start"?{...k,type:"step-finish",aborted:!0}:k});return p=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:j}});p&&(h=new Map(u.messages),h.set(r,b))}const g=u.sessionMemoryState.get(r);let x=u.sessionMemoryState;if(g){const b=new Map(u.sessionMemoryState);b.set(r,{...g,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),x=b}const y=new Map(u.sessionAbortFlags);return y.set(r,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:x,sessionAbortFlags:y,abortControllers:(()=>{const b=new Map(u.abortControllers);return b.delete(r),b})(),streamingMessageIds:vn(u.streamingMessageIds,r,null),...p?{messages:h}:{}}}),nt.abortSession(r).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(r,n,o,a,l)=>{const c=s();if(lf.has(n))return;const d=c.sessionMemoryState.get(r)?.trimmedHeadMaxId;if(d&&!Ui(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=c.messages.get(r)||[],m=u.find(h=>h.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",p=s().sessionMemoryState.get(r);if(p?.streamStartTime&&Date.now()-p.streamStartTime>ga.ZOMBIE_TIMEOUT){p.isZombie||t(g=>{const x=new Map(g.sessionMemoryState);return x.set(r,{...p,isZombie:!0}),{sessionMemoryState:x}}),setTimeout(()=>{s().completeStreamingMessage(r,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}t(h=>{const x=[...h.messages.get(r)||[]],y={},b=Xo(h.messageSessionIndex,n,r);b!==h.messageSessionIndex&&(y.messageSessionIndex=b);const v=M=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(r)))return M;const A=new Map(h.sessionAbortFlags);return A.delete(r),{...M,sessionAbortFlags:A}},j=M=>{const D=M||"",A=zi.get(n);if(D&&A===D){const R=s();if(cf(R,r,n)){const O=jo.get(n);O&&(clearTimeout(O),jo.delete(n)),setTimeout(()=>{const T=s();typeof T.forceCompleteMessage=="function"&&T.forceCompleteMessage(r,n,"timeout"),T.completeStreamingMessage(r,n)},100)}}zi.set(n,D);const P=jo.get(n);P&&clearTimeout(P);const $=setTimeout(()=>{const R=s();typeof R.forceCompleteMessage=="function"&&R.forceCompleteMessage(r,n,"timeout"),cf(R,r,n)&&R.completeStreamingMessage(r,n),jo.delete(n),zi.delete(n)},8e3);jo.set(n,$)},k=r!==l,N=h.sessionMemoryState.get(r);if(k&&N?.isStreaming){x.length>=ga.BACKGROUND_STREAMING_BUFFER&&x.shift();const M=new Map(h.sessionMemoryState);M.set(r,{...N,backgroundMessageCount:(N.backgroundMessageCount||0)+1}),h.sessionMemoryState=M}if(f==="assistant"){const M=h.sessionMemoryState.get(r);if(M){const D=Date.now(),A=new Map(h.sessionMemoryState);A.set(r,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??D,lastAccessedAt:D,isZombie:!1}),h.sessionMemoryState=A}}const w=na(o);if(Lc(w)&&(o.synthetic=!0),cN()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:w.length,snapshotParts:u.length})}catch{}const C=y.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const M=vn(C,r,n);M!==C&&(y.streamingMessageIds=M,window.__messageTracker?.(n,"streamingId_set_latest"))}const S=x.findIndex(M=>M.info.id===n);if(S!==-1&&f==="user"){const M=x[S],D=M.parts.findIndex(O=>O.id===o.id);if(o.synthetic===!0){const O=na(o).trim();if(!(O.startsWith("User has requested to enter plan mode")||O.startsWith("The plan at ")))return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h}const A=_a(o,D!==-1?M.parts[D]:void 0);window.__messageTracker?.(n,`user_part_type:${A.type||"unknown"}`);const P={...M};D!==-1?P.parts=P.parts.map((O,T)=>T===D?A:O):P.parts=[...P.parts,A];const $=[...x];$[S]=P;const R=new Map(h.messages);return R.set(r,$),v({messages:R})}if(f==="assistant"&&S!==-1){const M=x[S],D=M.parts.findIndex(T=>T.id===o.id),A=_a(o,D!==-1?M.parts[D]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const P={...M};D!==-1?P.parts=P.parts.map((T,_)=>_===D?A:T):P.parts=[...P.parts,A];const $=[...x];$[S]=P;const R=new Map(h.messages);R.set(r,$),y.messageStreamStates=Oc(h.messageStreamStates,n);const O=vn(y.streamingMessageIds??h.streamingMessageIds,r,n);return O!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=O,window.__messageTracker?.(n,"streamingId_set")),A.type==="text"?j(A.text||""):j(""),v({messages:R,...y})}if(S===-1){if(f==="user"){if(o.synthetic===!0){const J=na(o).trim();if(!(J.startsWith("User has requested to enter plan mode")||J.startsWith("The plan at ")))return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h}const ce=_a(o);window.__messageTracker?.(n,`new_user_part_type:${ce.type||"unknown"}`);const Q=h.pendingUserMessageMetaBySession.get(r),Y=Lt.getState(),ie=Q?.mode??Y.getSessionAgentSelection(r)??Y.getCurrentAgent(r),B=typeof ie=="string"&&ie.trim().length>0?ie.trim():void 0,se=Q?.providerID??(h.lastUsedProvider?.providerID||void 0),H=Q?.modelID??(h.lastUsedProvider?.modelID||void 0);Q&&(y.pendingUserMessageMetaBySession=nf(h.pendingUserMessageMetaBySession,r));const le={info:{id:n,sessionID:r,role:"user",clientRole:"user",userMessageMarker:!0,...B?{mode:B}:{},...se?{providerID:se}:{},...H?{modelID:H}:{},time:{created:Date.now()}},parts:[ce]},ge=[...x,le];ge.sort((J,je)=>{const X=J.info?.time?.created||0,G=je.info?.time?.created||0;return X-G});const z=new Map(h.messages);return z.set(r,ge),v({messages:z})}if(o?.type==="text"){const ce=na(o).trim();if(ce.length>0){const Q=[...x].reverse().find(Y=>Y.info.role==="user");if(Q){const Y=Q.parts.map(ie=>na(ie)).join("").trim();if(Y.length>0&&Y===ce)return lf.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const M=_a(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?j(M.text||""):j("");const D=h.pendingAssistantParts.get(n),A=D?[...D.parts]:[],P=A.findIndex(ce=>ce.id===M.id);P!==-1?A[P]=M:A.push(M);const $=new Map(h.pendingAssistantParts);$.set(n,{sessionId:r,parts:A});const R=h.lastUsedProvider?.providerID||"",O=h.lastUsedProvider?.modelID||"",T=Date.now(),_=nt.getDirectory()??"/",F=Lt.getState(),I=F.getSessionAgentSelection(r)??F.getCurrentAgent(r),E=typeof I=="string"&&I.trim().length>0?I.trim():void 0,W=h.pendingAssistantHeaderSessions.has(r);if(W){const ce=new Set(h.pendingAssistantHeaderSessions);ce.delete(r),y.pendingAssistantHeaderSessions=ce}const ve={info:f==="user"?{id:n,sessionID:r,role:"user",time:{created:T},agent:E||"default",model:{providerID:R,modelID:O},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:r,role:"assistant",time:{created:T},parentID:n,modelID:O,providerID:R,mode:E||"default",...W?{ikanbanHeaderAnchor:!0}:{},path:{cwd:_,root:_},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:A},oe=[...x,ve],Z=new Map(h.messages);if(Z.set(r,oe),f==="assistant"){y.messageStreamStates=Oc(h.messageStreamStates,n);const ce=vn(y.streamingMessageIds??h.streamingMessageIds,r,n);ce!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=ce,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:Z,pendingAssistantParts:$,...y})}else{const M=x[S],D=M.parts.findIndex(O=>O.id===o.id),A=_a(o,D!==-1?M.parts[D]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const P={...M};D!==-1?P.parts=P.parts.map((O,T)=>T===D?A:O):P.parts=[...P.parts,A];const $=[...x];$[S]=P;const R=new Map(h.messages);if(R.set(r,$),P.info.role==="assistant"){y.messageStreamStates=Oc(h.messageStreamStates,n);const O=vn(y.streamingMessageIds??h.streamingMessageIds,r,n);O!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=O,window.__messageTracker?.(n,"streamingId_set"))}return A.type==="text"?j(A.text||""):j(""),v({messages:R,...y})}})},addStreamingPart:(r,n,o,a,l)=>{if(a!=="user"){s()._addStreamingPartImmediate(r,n,o,a,l);return}Bc.push({sessionId:r,messageId:n,part:o,role:a,currentSessionId:l}),zc||(zc=setTimeout(()=>{const c=[...Bc];Bc=[],zc=null;const d=s();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},aN))},forceCompleteMessage:(r,n,o="timeout")=>{const a=l=>{if(r)return r;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 y=!1;const b=m.parts.map(N=>{if(!N)return N;if(N.type==="tool"){const w=N.state;if(!w)return N;const C=w.status,S=C==="running"||C==="pending"||C==="started",M=!w.time||typeof w.time?.end!="number";if(S||M){const D={...w};return S&&(D.status="completed"),M&&(D.time={...w.time??{},end:f}),y=!0,{...N,state:D}}return N}if(N.type==="reasoning"){const w=N.time;return!w||typeof w.end!="number"?(y=!0,{...N,time:{...w??{},end:f}}):N}if(N.type==="text"){const w=N.time;return w&&typeof w.end!="number"?(y=!0,{...N,time:{...w,end:f}}):N}return N});if(!g&&!y)return l;window.__messageTracker?.(n,`force_complete:${o}`);const v={...m,info:x,parts:y?b:m.parts},j=[...d];j[u]=v;const k=new Map(l.messages);return k.set(c,j),{messages:k}})},markMessageStreamSettled:r=>{t(n=>{Nx(r);const o=new Map(n.messageStreamStates);o.delete(r);let a=n.messages,l=!1;return n.messages.forEach((d,u)=>{if(l)return;const m=d.findIndex(x=>x.info.id===r);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}:{}}}),wo([r])},updateMessageInfo:(r,n,o)=>{t(c=>{const d=c.sessionMemoryState.get(r)?.trimmedHeadMaxId;if(d&&!Ui(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(r)??[]],f=m.findIndex(S=>S.info.id===n),p=c.pendingAssistantParts.get(n),h=(S=[],M=[])=>{if(!M.length)return S;const D=[...S];return M.forEach(A=>{const P=D.findIndex($=>$.id===A.id);P===-1?D.push(A):D[P]=A}),D},g=S=>{if(!S)return S;const M=S.clientRole??S.role,D=M==="user"?!0:S.userMessageMarker;return{...S,clientRole:M,...D?{userMessageMarker:!0}:{}}};if(f===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:r,messageId:n,messageInfo:o,existingCount:m.length}),m.length>0){const _=m[0]?.info,F=typeof _?.time?.created=="number"?_.time.created:null,I=typeof _?.id=="string"?_.id:null,E=o,W=typeof E?.time?.created=="number"?E.time.created:null,V=typeof E?.id=="string"?E.id:n;let ve=!1;if(W!==null&&F!==null&&(ve=W<F),!ve&&V&&I&&(ve=V.localeCompare(I)<0),ve)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const S=g(o);if(S&&S.role==="user"){const T=p?.parts??[],_=c.pendingUserMessageMetaBySession.get(r),F={info:{...S,userMessageMarker:!0,clientRole:"user",..._?.mode?{mode:_.mode}:{},..._?.providerID?{providerID:_.providerID}:{},..._?.modelID?{modelID:_.modelID}:{}},parts:T.length>0?[...T]:[]},I=new Map(c.messages),E=[...m,F];E.sort((ve,oe)=>{const Z=ve.info?.time?.created||0,ce=oe.info?.time?.created||0;return Z-ce}),I.set(r,E);const W={messages:I,..._?{pendingUserMessageMetaBySession:nf(c.pendingUserMessageMetaBySession,r)}:{}},V=Xo(W.messageSessionIndex??c.messageSessionIndex,n,r);if(V!==(W.messageSessionIndex??c.messageSessionIndex)&&(W.messageSessionIndex=V),p){const ve=new Map(c.pendingAssistantParts);ve.delete(n),W.pendingAssistantParts=ve}return W}if(!S||S.role!=="assistant")return c;const M=p?.parts??[],D=c.pendingAssistantHeaderSessions.has(r),A={info:{...S,animationSettled:S?.animationSettled??!1,...D?{ikanbanHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},P=new Map(c.messages),$=[...m,A];P.set(r,$);const R={messages:P,...D?{pendingAssistantHeaderSessions:(()=>{const T=new Set(c.pendingAssistantHeaderSessions);return T.delete(r),T})()}:{}},O=Xo(R.messageSessionIndex??c.messageSessionIndex,n,r);if(O!==(R.messageSessionIndex??c.messageSessionIndex)&&(R.messageSessionIndex=O),p){const T=new Map(c.pendingAssistantParts);T.delete(n),R.pendingAssistantParts=T}return R}const x=m[f],y=x.info;if(y.userMessageMarker===!0||y.clientRole==="user"||y.role==="user"){const S={...x.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:y.providerID||void 0,modelID:y.modelID||void 0},M=c.pendingUserMessageMetaBySession.get(r);M&&!S.mode&&M.mode&&(S.mode=M.mode);const D={...x,info:S},A=new Map(c.messages),P=[...m];if(P[f]=D,A.set(r,P),M){const $=new Map(c.pendingUserMessageMetaBySession);return $.delete(r),{messages:A,pendingUserMessageMetaBySession:$}}return{messages:A}}const v={...x.info,...o};o.role&&o.role!==x.info.role&&(v.role=x.info.role),v.clientRole=v.clientRole??x.info.clientRole??x.info.role,v.clientRole==="user"&&(v.userMessageMarker=!0);const j=p?.parts?h(x.parts,p.parts):x.parts,k={...x,info:v,parts:j},N=new Map(c.messages),w=[...m];w[f]=k,N.set(r,w);const C={messages:N};if(p){const S=new Map(c.pendingAssistantParts);S.delete(n),C.pendingAssistantParts=S}return C});const a=o?.finish,l=o?.role;typeof a=="string"&&l!=="user"&&setTimeout(()=>{s().completeStreamingMessage(r,n)},0)},completeStreamingMessage:(r,n)=>{const o=s();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(r)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(r,n,"cooldown");const a=o.streamingMessageIds.get(r)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const l={};if(a&&(l.streamingMessageIds=vn(o.streamingMessageIds,r,null),l.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(r),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}}),wo([n]);let c=!1;if(t(d=>{const u=d.sessionMemoryState.get(r);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(r,p),c=!0,{sessionMemoryState:m}}),c){const d=Jo.get(r);d&&(clearTimeout(d),Jo.delete(r));const u=setTimeout(()=>{t(m=>{const f=m.sessionMemoryState.get(r);if(!f||f.isStreaming)return m;const p=new Map(m.sessionMemoryState),{streamingCooldownUntil:h,...g}=f;return p.set(r,g),{sessionMemoryState:p}}),Jo.delete(r)},2e3);Jo.set(r,u)}},syncMessages:(r,n)=>{const o=df(r),a=uf(n,o),l=s().sessionMemoryState.get(r)?.trimmedHeadMaxId,c=l?a.filter(d=>{const u=d?.info?.id;return u?Ui(u,l):!0}):a;t(d=>{const u=new Map(d.messages),m=d.messages.get(r)||[],f=new Map(m.filter(N=>typeof N.info?.id=="string").map(N=>[N.info.id,N])),p=c.map(N=>{const w={...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},C=(Array.isArray(N.parts)?N.parts:[]).map(D=>{if(D?.type==="text"){const A=D.text??D.content??"";if(Lc(A))return{...D,synthetic:!0}}return D}),S=typeof w?.id=="string"?w.id:void 0,M=S?f.get(S):void 0;if(M&&M.info.role==="assistant"){const D=Array.isArray(M.parts)?M.parts:[],A=ia(D),P=ia(C);if(Bl(M.info)&&A>P){const R=zl(D,C);return{...N,info:w,parts:R}}}return{...N,info:w,parts:C}}),h=Ba(p),g=new Set(m.map(N=>N.info.id)),x=new Set(h.map(N=>N.info.id)),y=[];g.forEach(N=>{x.has(N)||y.push(N)}),u.set(r,h);const b={messages:u,isSyncing:!0};wo(y);const v=Oa(d.messageStreamStates,y);if(v!==d.messageStreamStates&&(b.messageStreamStates=v),y.length>0){const N=d.streamingMessageIds.get(r);N&&y.includes(N)&&(b.streamingMessageIds=vn(b.streamingMessageIds??d.streamingMessageIds,r,null))}if(y.length>0){const N=Hi(b.messageSessionIndex??d.messageSessionIndex,y);N!==(b.messageSessionIndex??d.messageSessionIndex)&&(b.messageSessionIndex=N)}if(y.length>0){const N=new Map(d.pendingAssistantParts);let w=!1;y.forEach(C=>{N.delete(C)&&(w=!0)}),w&&(b.pendingAssistantParts=N)}const j=b.messageSessionIndex??d.messageSessionIndex;let k=j;return h.forEach(N=>{const w=N?.info?.id;typeof w=="string"&&w.length>0&&(k=Xo(k,w,r))}),k!==j&&(b.messageSessionIndex=k),b}),setTimeout(()=>{t({isSyncing:!1})},100)},updateSessionCompaction:(r,n)=>{t(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(r)?(a.delete(r),{sessionCompactionUntil:a}):o;const l=n+iN;return a.get(r)===l?o:(a.set(r,l),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:r=>{r&&t(n=>{const o=n.sessionAbortFlags.get(r);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(r,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(r,n)=>{t(o=>{const a=o.sessionMemoryState.get(r)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},l=new Map(o.sessionMemoryState);return l.set(r,{...a,viewportAnchor:n}),{sessionMemoryState:l}})},trimToViewportWindow:(r,n,o)=>{const a=n??uc(),l=s(),c=l.messages.get(r);if(!c||c.length<=a)return;const d=l.sessionMemoryState.get(r)||{viewportAnchor:c.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(d.isStreaming&&r===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(y=>y.info.id)),x=c.filter(y=>!g.has(y.info.id)).map(y=>y.info.id);t(y=>{const b=new Map(y.messages);b.set(r,p);const v=new Map(y.sessionMemoryState),j={...d,viewportAnchor:u-m,hasMoreAbove:!!d.hasMoreAbove||m>0,trimmedHeadMaxId:uN(h,d.trimmedHeadMaxId)};v.set(r,j);const k={messages:b,sessionMemoryState:v};wo(x);const N=Oa(y.messageStreamStates,x);if(N!==y.messageStreamStates&&(k.messageStreamStates=N),x.length>0){const S=y.streamingMessageIds.get(r);S&&x.includes(S)&&(k.streamingMessageIds=vn(k.streamingMessageIds??y.streamingMessageIds,r,null))}if(x.length>0){const S=Hi(k.messageSessionIndex??y.messageSessionIndex,x);S!==(k.messageSessionIndex??y.messageSessionIndex)&&(k.messageSessionIndex=S)}const w=k.messageSessionIndex??y.messageSessionIndex;let C=w;return p.forEach(S=>{const M=S?.info?.id;typeof M=="string"&&M.length>0&&(C=Xo(C,M,r))}),C!==w&&(k.messageSessionIndex=C),k})},evictLeastRecentlyUsed:r=>{const n=s();if(n.messages.size<=ga.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!==r&&!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(k=>k.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((k,N)=>{k.sessionId===c&&(g.delete(N),x=!0)}),x&&(h.pendingAssistantParts=g);const y=new Map(d.sessionCompactionUntil);y.delete(c)&&(h.sessionCompactionUntil=y),wo(m);const b=Oa(d.messageStreamStates,m);b!==d.messageStreamStates&&(h.messageStreamStates=b);const v=Hi(h.messageSessionIndex??d.messageSessionIndex,m);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const j=vn(d.streamingMessageIds,c,null);if(j!==d.streamingMessageIds&&(h.streamingMessageIds=j),d.abortControllers.has(c)){const k=new Map(d.abortControllers);k.delete(c),h.abortControllers=k}return h})},loadMoreMessages:async(r,n="up")=>{const o=s(),a=o.messages.get(r),l=o.sessionMemoryState.get(r);if(!a||!l||l.historyLoading)return;const c=Zd(),d=l.historyLimit??Math.max(c.HISTORICAL_MESSAGES+c.FETCH_BUFFER,a.length+c.FETCH_BUFFER),u=n==="up"?d+c.HISTORY_CHUNK:d;t(m=>{const f=new Map(m.sessionMemoryState),p=f.get(r);return p?(f.set(r,{...p,historyLoading:!0,historyLimit:u}),{sessionMemoryState:f}):m});try{const m=u+1,f=await Uc(r,()=>nt.getSessionMessages(r,m));if(n==="up"&&a.length>0){const p=Ba(f),h=f.length>=m,g=a[0],x=p.findIndex(y=>y.info.id===g.info.id);if(x>0){const y=Math.min(c.HISTORY_CHUNK,x),b=p.slice(x-y,x);t(v=>{const j=v.messages.get(r)??a,k=v.sessionMemoryState.get(r)??l,N=[...b,...j],w=Ba(N),C=Math.max(0,w.length-j.length),S=new Map(v.messages);S.set(r,w);const M=new Map(v.sessionMemoryState);return M.set(r,{...k,viewportAnchor:k.viewportAnchor+C,hasMoreAbove:x-y>0||h,historyLoading:!1,historyLimit:u,historyComplete:!(x-y>0||h),totalAvailableMessages:Math.max(k.totalAvailableMessages??0,p.length)}),{messages:S,sessionMemoryState:M}});return}if(x===0){t(y=>{const b=y.sessionMemoryState.get(r)??l,v=new Map(y.sessionMemoryState);return v.set(r,{...b,hasMoreAbove:h,historyLoading:!1,historyLimit:u,historyComplete:!h,totalAvailableMessages:Math.max(b.totalAvailableMessages??0,p.length)}),{sessionMemoryState:v}});return}if(x<0){t(y=>{const b=y.messages.get(r)??a,v=y.sessionMemoryState.get(r)??l,j=new Set(b.map(D=>D.info.id)),k=p.filter(D=>!j.has(D.info.id)),N=Ba([...k,...b]),w=Math.max(0,N.length-b.length),C=k.length>0||h,S=new Map(y.messages);w>0&&S.set(r,N);const M=new Map(y.sessionMemoryState);return M.set(r,{...v,viewportAnchor:v.viewportAnchor+w,hasMoreAbove:C,historyLoading:!1,historyLimit:u,historyComplete:!C,totalAvailableMessages:Math.max(v.totalAvailableMessages??0,p.length)}),{messages:S,sessionMemoryState:M}});return}}}finally{t(m=>{const f=m.sessionMemoryState.get(r);if(!f||!f.historyLoading)return m;const p=new Map(m.sessionMemoryState);return p.set(r,{...f,historyLoading:!1}),{sessionMemoryState:p}})}},getLastMessageModel:r=>{const{messages:n}=s(),o=n.get(r);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:Dr(()=>Ws()),partialize:t=>({lastUsedProvider:t.lastUsedProvider,sessionMemoryState:Array.from(t.sessionMemoryState.entries()).map(([s,r])=>[s,{viewportAnchor:r.viewportAnchor,isStreaming:r.isStreaming,lastAccessedAt:r.lastAccessedAt,backgroundMessageCount:r.backgroundMessageCount,totalAvailableMessages:r.totalAvailableMessages,hasMoreAbove:r.hasMoreAbove,historyLoading:r.historyLoading,historyComplete:r.historyComplete,historyLimit:r.historyLimit,trimmedHeadMaxId:r.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(t.sessionAbortFlags.entries()).map(([s,r])=>[s,{timestamp:r.timestamp,acknowledged:r.acknowledged}])}),merge:(t,s)=>{if(!t)return s;let r=s.sessionMemoryState;Array.isArray(t.sessionMemoryState)&&(r=new Map(t.sessionMemoryState.map(o=>{const[a,l]=o;return[a,{...l,hasMoreAbove:void 0,historyComplete:void 0,historyLimit:void 0,historyLoading:!1}]})));let n=s.sessionAbortFlags;return Array.isArray(t.sessionAbortFlags)&&(n=new Map(t.sessionAbortFlags)),{...s,lastUsedProvider:t.lastUsedProvider??s.lastUsedProvider,sessionMemoryState:r,sessionAbortFlags:n}}}),{name:"message-store"})),pN=t=>typeof t=="object"&&t!==null,hN=t=>{if(!Array.isArray(t))return[];const s=[];return t.forEach(r=>{if(!Array.isArray(r)||r.length!==2)return;const[n,o]=r;typeof n!="string"||!Array.isArray(o)||s.push([n,o])}),s},gN=async(t,s)=>{try{const n=Wt.getState().getDirectoryForSession(t);if(n)return nt.withDirectory(n,s)}catch(r){console.warn("Failed to resolve session directory for permission handling:",r)}return s()},gi=Ls()(Us(Ar((t,s)=>({permissions:new Map,addPermission:(r,n)=>{const o=r.sessionID;if(!o||s().permissions.get(o)?.some(f=>f.id===r.id))return;const l=r.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=hl(c),u=n?.getSessionAgentEditMode?.(o,c)??d;if((u==="allow"||u==="full")&&sN(l)){s().respondToPermission(o,r.id,"once").catch(()=>{});return}t(f=>{const p=f.permissions.get(o)||[],h=new Map(f.permissions);return h.set(o,[...p,r]),{permissions:h}})},respondToPermission:async(r,n,o)=>{await gN(r,()=>nt.replyToPermission(n,o)),o==="reject"&&await rs.getState().abortCurrentOperation(r),t(a=>{const c=(a.permissions.get(r)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(r,c),{permissions:d}})}}),{name:"permission-store",storage:Dr(()=>Ws()),partialize:t=>({permissions:Array.from(t.permissions.entries())}),merge:(t,s)=>{if(!pN(t))return s;const r=hN(t.permissions);return{...s,permissions:new Map(r)}}}),{name:"permission-store"})),xN=t=>typeof t=="object"&&t!==null,yN=t=>{if(!Array.isArray(t))return[];const s=[];return t.forEach(r=>{if(!Array.isArray(r)||r.length!==2)return;const[n,o]=r;typeof n!="string"||!Array.isArray(o)||s.push([n,o])}),s},mf=async(t,s)=>{try{const n=Wt.getState().getDirectoryForSession(t);if(n)return nt.withDirectory(n,s)}catch(r){console.warn("Failed to resolve session directory for question handling:",r)}return s()},la=Ls()(Us(Ar((t,s)=>({questions:new Map,addQuestion:r=>{const n=r.sessionID;!n||s().questions.get(n)?.some(a=>a.id===r.id)||t(a=>{const l=a.questions.get(n)||[],c=new Map(a.questions);return c.set(n,[...l,r]),{questions:c}})},dismissQuestion:(r,n)=>{!r||!n||t(o=>{const l=(o.questions.get(r)||[]).filter(d=>d.id!==n),c=new Map(o.questions);return c.set(r,l),{questions:c}})},respondToQuestion:async(r,n,o)=>{await mf(r,()=>nt.replyToQuestion(n,o)),s().dismissQuestion(r,n)},rejectQuestion:async(r,n)=>{await mf(r,()=>nt.rejectQuestion(n)),s().dismissQuestion(r,n)}}),{name:"question-store",storage:Dr(()=>Ws()),partialize:t=>({questions:Array.from(t.questions.entries())}),merge:(t,s)=>{if(!xN(t))return s;const r=yN(t.questions);return{...s,questions:new Map(r)}}}),{name:"question-store"})),Ul=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
|
+
`),si=t=>{if(typeof t!="string")return null;const s=t.trim();if(!s)return null;const r=s.replace(/\\/g,"/");return r==="/"?"/":r.length>1?r.replace(/\/+$/,""):r},ff=(t,s,r)=>{if(!s)return null;const n=r(s)?.path;if(typeof n=="string"&&n.trim().length>0)return si(n);const o=t.find(a=>a.id===s);return o?si(o.directory??null):null},Ae=Ls()(Us((t,s)=>({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,sessionStatus:new Map,sessionAttentionStates:new Map,userSummaryTitles:new Map,pendingInputText:null,pendingInputMode:"replace",pendingSyntheticParts:null,newSessionDraft:{open:!0,directoryOverride:null,parentID:null},voiceStatus:"disconnected",voiceMode:"idle",setVoiceStatus:r=>{t({voiceStatus:r})},setVoiceMode:r=>{t({voiceMode:r})},getSessionAgentEditMode:(r,n,o)=>Lt.getState().getSessionAgentEditMode(r,n,o),toggleSessionAgentEditMode:(r,n,o)=>Lt.getState().toggleSessionAgentEditMode(r,n,o),setSessionAgentEditMode:(r,n,o,a)=>Lt.getState().setSessionAgentEditMode(r,n,o,a),loadSessions:()=>Wt.getState().loadSessions(),openNewSessionDraft:r=>{let n=null;r?.directoryOverride!==void 0?n=r.directoryOverride:n=ps.getState().getActiveProject()?.path??null,t({newSessionDraft:{open:!0,directoryOverride:n,parentID:r?.parentID??null,title:r?.title,initialPrompt:r?.initialPrompt,syntheticParts:r?.syntheticParts},currentSessionId:null,error:null,...r?.initialPrompt?{pendingInputText:r.initialPrompt,pendingInputMode:"replace"}:{}});try{const o=ut.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 r=Wt.getState().currentSessionId;t({newSessionDraft:{open:!1,directoryOverride:null,parentID:null,title:void 0,initialPrompt:void 0,syntheticParts:void 0},currentSessionId:r})},createSession:async(r,n,o)=>{s().closeNewSessionDraft();const a=await Wt.getState().createSession(r,n,o);return a?.id&&await s().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async r=>{if(!r)return;const n=rs.getState(),{messages:o,lastUsedProvider:a}=n;let l,c;if(o.forEach((b,v)=>{const j=b.find(k=>k.info?.id===r);j&&!l&&(l=j,c=v)}),!l||l.info.role!=="assistant")return;const d=Ul(l.parts);if(!d.trim())return;const u=Wt.getState(),m=ff(u.sessions,c??null,u.getWorktreeMetadata),f=await s().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:g}=ut.getState(),x=p||a?.providerID,y=h||a?.modelID;!x||!y||await nt.sendMessage({id:f.id,providerID:x,modelID:y,text:d,prefaceText:Sx,agent:g??void 0})},deleteSession:(r,n)=>Wt.getState().deleteSession(r,n),deleteSessions:(r,n)=>Wt.getState().deleteSessions(r,n),updateSessionTitle:(r,n)=>Wt.getState().updateSessionTitle(r,n),shareSession:r=>Wt.getState().shareSession(r),unshareSession:r=>Wt.getState().unshareSession(r),setCurrentSession:async r=>{r&&s().closeNewSessionDraft();const n=Wt.getState().currentSessionId,o=ff(Wt.getState().sessions,r,Wt.getState().getWorktreeMetadata),a=nt.getDirectory()??Yt.getState().currentDirectory??null,l=o??a;try{nt.setDirectory(l??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}if(n&&n!==r&&!s().sessionMemoryState.get(n)?.isStreaming){const d=s().messages.get(n)||[];d.length>0&&s().updateViewportAnchor(n,d.length-1),s().trimToViewportWindow(n,uc())}if(Wt.getState().setCurrentSession(r),r){const c=s().messages.get(r),d=s().sessionMemoryState.get(r),u=!d||d.historyComplete===void 0;(!c||u)&&await s().loadMessages(r),s().trimToViewportWindow(r,cn());const m=s().messages.get(r);if(m&&m.length>0){const f=ut.getState().agents;if(f.length>0)try{await Lt.getState().analyzeAndSaveExternalSessionChoices(r,f,s().messages)}catch(p){console.warn("Failed to analyze session choices:",p)}}}s().evictLeastRecentlyUsed()},loadMessages:(r,n)=>rs.getState().loadMessages(r,n),sendMessage:async(r,n,o,a,l,c,d,u)=>{const m=s().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=(b,v)=>{t(j=>{const k=new Map(j.sessionStatus??new Map);return k.set(b,{type:v}),{sessionStatus:k}})};if(m?.open){const b=await Wt.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!b?.id)throw new Error("Failed to create session");const v=ut.getState(),j=v.currentAgentName,k=f??j,N=v.currentProviderId,w=v.currentModelId;if(N&&w)try{Lt.getState().saveSessionModelSelection(b.id,N,w)}catch{}if(k){try{Lt.getState().saveSessionAgentSelection(b.id,k)}catch{}if(N&&w){try{Lt.getState().saveAgentModelForSession(b.id,k,N,w)}catch{}if(u!==void 0)try{Lt.getState().saveAgentModelVariantForSession(b.id,k,N,w,u)}catch{}}}try{Wt.getState().initializeNewIKanbanSession(b.id,v.agents)}catch{}const C=m.syntheticParts;s().closeNewSessionDraft(),p(b.id,"busy");const S=C?.length?[...d||[],...C]:d;try{return await rs.getState().sendMessage(r,n,o,k,b.id,l,c,S,u)}catch(M){throw p(b.id,"idle"),M}}const h=Wt.getState().currentSessionId,g=h?Lt.getState().getSessionAgentSelection(h):null,x=ut.getState().currentAgentName,y=f||g||x||void 0;if(h&&y){try{Lt.getState().saveSessionAgentSelection(h,y)}catch{}if(u!==void 0)try{Lt.getState().saveAgentModelVariantForSession(h,y,n,o,u)}catch{}}if(h){p(h,"busy");const b=s().sessionMemoryState.get(h);if(!b||!b.lastUserMessageAt){const v=s().sessionMemoryState,j=new Map(v);j.set(h,{viewportAnchor:b?.viewportAnchor??0,isStreaming:b?.isStreaming??!1,lastAccessedAt:Date.now(),backgroundMessageCount:b?.backgroundMessageCount??0,lastUserMessageAt:Date.now()}),t({sessionMemoryState:j})}}h&&fetch(`/api/sessions/${h}/message-sent`,{method:"POST"}).catch(()=>{});try{return await rs.getState().sendMessage(r,n,o,y,h||void 0,l,c,d,u)}catch(b){throw h&&p(h,"idle"),b}},abortCurrentOperation:()=>{const r=Wt.getState().currentSessionId;return rs.getState().abortCurrentOperation(r||void 0)},armAbortPrompt:(r=3e3)=>{const n=Wt.getState().currentSessionId;if(!n)return null;const o=Date.now()+r;return t({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{t({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:r=>{r&&rs.getState().acknowledgeSessionAbort(r)},addStreamingPart:(r,n,o,a)=>{const c=Wt.getState().currentSessionId||r;return rs.getState().addStreamingPart(r,n,o,a,c)},completeStreamingMessage:(r,n)=>rs.getState().completeStreamingMessage(r,n),markMessageStreamSettled:r=>rs.getState().markMessageStreamSettled(r),updateMessageInfo:(r,n,o)=>rs.getState().updateMessageInfo(r,n,o),updateSessionCompaction:(r,n)=>rs.getState().updateSessionCompaction(r,n??null),addPermission:r=>{const n={currentAgentContext:Lt.getState().currentAgentContext,sessionAgentSelections:Lt.getState().sessionAgentSelections,getSessionAgentEditMode:Lt.getState().getSessionAgentEditMode};return gi.getState().addPermission(r,n)},respondToPermission:(r,n,o)=>gi.getState().respondToPermission(r,n,o),addQuestion:r=>la.getState().addQuestion(r),dismissQuestion:(r,n)=>la.getState().dismissQuestion(r,n),respondToQuestion:(r,n,o)=>la.getState().respondToQuestion(r,n,o),rejectQuestion:(r,n)=>la.getState().rejectQuestion(r,n),clearError:()=>Wt.getState().clearError(),getSessionsByDirectory:r=>Wt.getState().getSessionsByDirectory(r),getDirectoryForSession:r=>Wt.getState().getDirectoryForSession(r),getLastMessageModel:r=>rs.getState().getLastMessageModel(r),getCurrentAgent:r=>Lt.getState().getCurrentAgent(r),syncMessages:(r,n)=>rs.getState().syncMessages(r,n),applySessionMetadata:(r,n)=>Wt.getState().applySessionMetadata(r,n),addAttachedFile:r=>Jr.getState().addAttachedFile(r),addServerFile:(r,n,o)=>Jr.getState().addServerFile(r,n,o),removeAttachedFile:r=>Jr.getState().removeAttachedFile(r),clearAttachedFiles:()=>Jr.getState().clearAttachedFiles(),updateViewportAnchor:(r,n)=>rs.getState().updateViewportAnchor(r,n),trimToViewportWindow:(r,n)=>{const o=Wt.getState().currentSessionId,a=s().sessionStatus?.get(r);if(!(a?.type==="busy"||a?.type==="retry"))return rs.getState().trimToViewportWindow(r,n,o||void 0)},evictLeastRecentlyUsed:()=>{const r=Wt.getState().currentSessionId;return rs.getState().evictLeastRecentlyUsed(r||void 0)},loadMoreMessages:(r,n)=>rs.getState().loadMoreMessages(r,n),saveSessionModelSelection:(r,n,o)=>Lt.getState().saveSessionModelSelection(r,n,o),getSessionModelSelection:r=>Lt.getState().getSessionModelSelection(r),saveSessionAgentSelection:(r,n)=>Lt.getState().saveSessionAgentSelection(r,n),getSessionAgentSelection:r=>Lt.getState().getSessionAgentSelection(r),saveAgentModelForSession:(r,n,o,a)=>Lt.getState().saveAgentModelForSession(r,n,o,a),getAgentModelForSession:(r,n)=>Lt.getState().getAgentModelForSession(r,n),saveAgentModelVariantForSession:(r,n,o,a,l)=>Lt.getState().saveAgentModelVariantForSession(r,n,o,a,l),getAgentModelVariantForSession:(r,n,o,a)=>Lt.getState().getAgentModelVariantForSession(r,n,o,a),analyzeAndSaveExternalSessionChoices:(r,n)=>{const o=rs.getState().messages;return Lt.getState().analyzeAndSaveExternalSessionChoices(r,n,o)},isIKanbanCreatedSession:r=>Wt.getState().isIKanbanCreatedSession(r),markSessionAsIKanbanCreated:r=>Wt.getState().markSessionAsIKanbanCreated(r),initializeNewIKanbanSession:(r,n)=>Wt.getState().initializeNewIKanbanSession(r,n),setWorktreeMetadata:(r,n)=>Wt.getState().setWorktreeMetadata(r,n),setSessionDirectory:(r,n)=>Wt.getState().setSessionDirectory(r,n),getWorktreeMetadata:r=>Wt.getState().getWorktreeMetadata(r),getContextUsage:(r,n)=>{if(s().newSessionDraft?.open)return null;const o=Wt.getState().currentSessionId;if(!o)return null;const a=rs.getState().messages;return Lt.getState().getContextUsage(o,r,n,a)},updateSessionContextUsage:(r,n,o)=>{const a=rs.getState().messages;return Lt.getState().updateSessionContextUsage(r,n,o,a)},initializeSessionContextUsage:(r,n,o)=>{const a=rs.getState().messages;return Lt.getState().initializeSessionContextUsage(r,n,o,a)},debugSessionMessages:async r=>{const n=rs.getState().messages.get(r)||[],o=Wt.getState().sessions.find(a=>a.id===r);console.log(`Debug session ${r}:`,{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:(r,n,o)=>{const a=rs.getState().messages;return Lt.getState().pollForTokenUpdates(r,n,a,o)},updateSession:r=>Wt.getState().updateSession(r),removeSessionFromStore:r=>Wt.getState().removeSessionFromStore(r),revertToMessage:async(r,n)=>{const a=(rs.getState().messages.get(r)||[]).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 nt.revertSession(r,n);Wt.getState().updateSession(c);const d=rs.getState().messages.get(r)||[],u=c.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);rs.getState().syncMessages(r,f)}}l&&t({pendingInputText:l,pendingInputMode:"replace"})},handleSlashUndo:async r=>{const o=(s().messages.get(r)||[]).filter(p=>p.info.role==="user"),l=s().sessions.find(p=>p.id===r);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 s().revertToMessage(r,d.info.id);const{toast:f}=await Ks(async()=>{const{toast:p}=await import("./vendor-.bun-CTUAJ4e1.js").then(h=>h.d_);return{toast:p}},__vite__mapDeps([0,1]));f.success(`Undid to: ${m}`)},handleSlashRedo:async r=>{const a=s().sessions.find(m=>m.id===r)?.revert?.messageID;if(!a)return;const c=(s().messages.get(r)||[]).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 s().revertToMessage(r,u.info.id);const{toast:p}=await Ks(async()=>{const{toast:h}=await import("./vendor-.bun-CTUAJ4e1.js").then(g=>g.d_);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await nt.unrevertSession(r);await Wt.getState().updateSession(m),await s().loadMessages(r);const{toast:f}=await Ks(async()=>{const{toast:p}=await import("./vendor-.bun-CTUAJ4e1.js").then(h=>h.d_);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(r,n)=>{const a=s().sessions.find(l=>l.id===r);if(a)try{const l=await nt.forkSession(r,n);if(!l||!l.id){const{toast:f}=await Ks(async()=>{const{toast:p}=await import("./vendor-.bun-CTUAJ4e1.js").then(h=>h.d_);return{toast:p}},__vite__mapDeps([0,1]));f.error("Failed to fork session");return}const d=(s().messages.get(r)||[]).find(f=>f.info.id===n);if(!d){const{toast:f}=await Ks(async()=>{const{toast:p}=await import("./vendor-.bun-CTUAJ4e1.js").then(h=>h.d_);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||"");s().setCurrentSession(l.id),u&&t({pendingInputText:u,pendingInputMode:"replace"}),await s().loadMessages(l.id);const{toast:m}=await Ks(async()=>{const{toast:f}=await import("./vendor-.bun-CTUAJ4e1.js").then(p=>p.d_);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 Ks(async()=>{const{toast:d}=await import("./vendor-.bun-CTUAJ4e1.js").then(u=>u.d_);return{toast:d}},__vite__mapDeps([0,1]));c.error("Failed to fork session")}},setPendingInputText:(r,n="replace")=>{t({pendingInputText:r,pendingInputMode:n})},consumePendingInputText:()=>{const r=s().pendingInputText,n=s().pendingInputMode;return r!==null&&t({pendingInputText:null,pendingInputMode:"replace"}),r===null?null:{text:r,mode:n}},setPendingSyntheticParts:r=>{t({pendingSyntheticParts:r})},consumePendingSyntheticParts:()=>{const r=s().pendingSyntheticParts;return r!==null&&t({pendingSyntheticParts:null}),r}}),{name:"composed-session-store"}));Wt.subscribe((t,s)=>{if(t.sessions===s.sessions&&t.sessionsByDirectory===s.sessionsByDirectory&&t.currentSessionId===s.currentSessionId&&t.lastLoadedDirectory===s.lastLoadedDirectory&&t.isLoading===s.isLoading&&t.error===s.error&&t.webUICreatedSessions===s.webUICreatedSessions&&t.worktreeMetadata===s.worktreeMetadata&&t.availableWorktrees===s.availableWorktrees&&t.availableWorktreesByProject===s.availableWorktreesByProject)return;const r=Ae.getState().newSessionDraft?.open;Ae.setState({sessions:t.sessions,sessionsByDirectory:t.sessionsByDirectory,currentSessionId:r?null:t.currentSessionId,lastLoadedDirectory:t.lastLoadedDirectory,isLoading:t.isLoading,error:t.error,webUICreatedSessions:t.webUICreatedSessions,worktreeMetadata:t.worktreeMetadata,availableWorktrees:t.availableWorktrees,availableWorktreesByProject:t.availableWorktreesByProject})});rs.subscribe((t,s)=>{if(t.messages===s.messages&&t.sessionMemoryState===s.sessionMemoryState&&t.messageStreamStates===s.messageStreamStates&&t.sessionCompactionUntil===s.sessionCompactionUntil&&t.sessionAbortFlags===s.sessionAbortFlags&&t.streamingMessageIds===s.streamingMessageIds&&t.abortControllers===s.abortControllers&&t.lastUsedProvider===s.lastUsedProvider&&t.isSyncing===s.isSyncing)return;const r=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;r.set(o,{title:u,createdAt:m});break}}}}}),Ae.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:r})});Jr.subscribe((t,s)=>{t.attachedFiles!==s.attachedFiles&&Ae.setState({attachedFiles:t.attachedFiles})});Lt.subscribe((t,s)=>{t.sessionModelSelections===s.sessionModelSelections&&t.sessionAgentSelections===s.sessionAgentSelections&&t.sessionAgentModelSelections===s.sessionAgentModelSelections&&t.currentAgentContext===s.currentAgentContext&&t.sessionContextUsage===s.sessionContextUsage&&t.sessionAgentEditModes===s.sessionAgentEditModes||Ae.setState({sessionModelSelections:t.sessionModelSelections,sessionAgentSelections:t.sessionAgentSelections,sessionAgentModelSelections:t.sessionAgentModelSelections,currentAgentContext:t.currentAgentContext,sessionContextUsage:t.sessionContextUsage,sessionAgentEditModes:t.sessionAgentEditModes})});gi.subscribe((t,s)=>{t.permissions!==s.permissions&&Ae.setState({permissions:t.permissions})});la.subscribe((t,s)=>{t.questions!==s.questions&&Ae.setState({questions:t.questions})});Yt.subscribe((t,s)=>{const r=si(t.currentDirectory??null),n=si(s.currentDirectory??null);if(r===n)return;const o=Ae.getState().newSessionDraft;if(!o?.open)return;const a=si(o.directoryOverride);a&&a!==n||Ae.setState(l=>({newSessionDraft:{...l.newSessionDraft,directoryOverride:r,parentID:null}}))});const bN=Ae.getState().newSessionDraft?.open;Ae.setState({sessions:Wt.getState().sessions,currentSessionId:bN?null:Wt.getState().currentSessionId,lastLoadedDirectory:Wt.getState().lastLoadedDirectory,isLoading:Wt.getState().isLoading,error:Wt.getState().error,webUICreatedSessions:Wt.getState().webUICreatedSessions,worktreeMetadata:Wt.getState().worktreeMetadata,availableWorktrees:Wt.getState().availableWorktrees,availableWorktreesByProject:Wt.getState().availableWorktreesByProject,messages:rs.getState().messages,sessionMemoryState:rs.getState().sessionMemoryState,messageStreamStates:rs.getState().messageStreamStates,sessionCompactionUntil:rs.getState().sessionCompactionUntil,sessionAbortFlags:rs.getState().sessionAbortFlags,streamingMessageIds:rs.getState().streamingMessageIds,abortControllers:rs.getState().abortControllers,lastUsedProvider:rs.getState().lastUsedProvider,isSyncing:rs.getState().isSyncing,permissions:gi.getState().permissions,questions:la.getState().questions,attachedFiles:Jr.getState().attachedFiles,sessionModelSelections:Lt.getState().sessionModelSelections,sessionAgentSelections:Lt.getState().sessionAgentSelections,sessionAgentModelSelections:Lt.getState().sessionAgentModelSelections,currentAgentContext:Lt.getState().currentAgentContext,sessionContextUsage:Lt.getState().sessionContextUsage,sessionAgentEditModes:Lt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=Ae);const yn=[{id:"claude",name:"Claude"},{id:"codex",name:"Codex"},{id:"github-copilot",name:"GitHub Copilot"},{id:"google",name:"Google"},{id:"kimi-for-coding",name:"Kimi for Coding"},{id:"nano-gpt",name:"NanoGPT"},{id:"openrouter",name:"OpenRouter"},{id:"zai-coding-plan",name:"z.ai"}];yn.reduce((t,s)=>(t[s.id]=s,t),{});const Cx=t=>typeof t!="number"||Number.isNaN(t)?null:Math.max(0,Math.min(100,Math.round(t))),Sn=t=>{const s=Cx(t);return s===null?"-":`${s}%`},Mx=t=>t===null?"safe":t>=80?"critical":t>=50?"warn":"safe",Hl=t=>t==="5h"?"5-Hour":t==="7d"?"7-Day Limit":t==="7d-sonnet"?"7-Day Sonnet Limit":t==="7d-opus"?"7-Day Opus Limit":t==="weekly"?"Weekly Limit":t==="daily"?"Daily":t==="monthly"?"Monthly Limit":t==="credits"?"Credits":t==="premium"?"Premium Interactions":t==="chat"?"Chat Requests":t==="completions"?"Completions":t==="premium_interactions"?"Premium interactions":t,vN=t=>{const s=t.toLowerCase().trim();if(s==="5h")return 5*3600;if(s==="7d"||s==="weekly"||s==="7d-sonnet"||s==="7d-opus")return 7*86400;if(s==="monthly")return 30*86400;if(s==="24h"||s==="daily")return 86400;if(s==="1h")return 3600;const r=s.match(/^(\d+)h$/);if(r)return parseInt(r[1],10)*3600;const n=s.match(/^(\d+)d$/);return n?parseInt(n[1],10)*86400:null},ca=(t,s,r,n)=>{let o=r;if(o===null&&n&&(o=vN(n)),t===null||s===null||o===null||o<=0)return null;const a=Date.now(),l=Math.max(0,(s-a)/1e3),c=Math.max(0,Math.min(o,o-l)),d=Math.max(0,Math.min(1,c/o)),u=t/100,m=t>=100&&l>0;let f;d>.01?f=Math.min(999,u/d*100):f=t;let p;m?p="exhausted":u<=d?p="on-track":f<=130?p="slightly-fast":p="too-fast";const h=o>=120*3600,g=h?86400:3600,x=h?"d":"h",y=o/g,b=Math.max(c/g,y*.01),v=t/b,j=Number.isFinite(v)?`${Math.min(999.9,Math.max(0,v)).toFixed(1)}%/${x}`:"-",k=f>100?`+${Math.round(f)}%`:`${Math.round(f)}%`;let N=null;const w=o/86400;return w>=7&&(N=100/w),{elapsedRatio:d,usageRatio:u,predictedFinalPercent:f,remainingSeconds:l,isExhausted:m,elapsedSeconds:c,totalSeconds:o,status:p,paceRateText:j,predictText:k,dailyAllocationPercent:N}},wN=t=>{switch(t){case"exhausted":case"too-fast":return"var(--status-error)";case"slightly-fast":return"var(--status-warning)";case"on-track":return"var(--status-success)"}},pf=t=>{const s=Math.max(0,Math.floor(t)),r=Math.floor(s/60),n=Math.floor(r/60),o=Math.floor(n/24),a=n%24,l=r%60;return o>0?`${o}d ${a}h`:n>0?`${n}h`:r===0?"<1m":`${l}m`},ln=t=>Math.min(100,Math.max(0,t*100));function Vl(t){const s=t.indexOf("/");if(s!==-1){const r=t.substring(0,s);if(r==="gemini"||r==="antigravity")return t.substring(s+1)}return t}const jN=[{id:"gemini-auth",label:"Gemini",matcher:t=>t.startsWith("gemini/"),order:1},{id:"antigravity-auth",label:"Antigravity",matcher:t=>t.startsWith("antigravity/"),order:2}],Ax={google:jN};function Dx(t,s){const r=Ax[s]??[];for(const n of r)if(n.matcher(t))return n;return null}function Ix(t){return Ax[t]??[]}function Tx(t){return[...t].sort((s,r)=>s.order-r.order)}function SN(t,s){const r=new Map;for(const n of Object.keys(t)){const a=Dx(n,s)?.id??null;r.has(a)||r.set(a,[]),r.get(a).push(n)}return r}function NN(t,s,r){const n=new Map;for(const o of t){const a=s(o),c=Dx(a,r)?.id??null;n.has(c)||n.set(c,[]),n.get(c).push(o)}return n}function kN(t,s){return s.filter(r=>{const n=r.toLowerCase(),o=n.includes("/")?n.split("/")[1]:n;return!!(o.startsWith("gemini-3-")||o.startsWith("claude-"))})}const Uu=6e4,hf=t=>{const s=yn.map(f=>f.id),r=typeof t?.usageAutoRefresh=="boolean"?t.usageAutoRefresh:!1,n=typeof t?.usageRefreshIntervalMs=="number"&&Number.isFinite(t.usageRefreshIntervalMs)?Math.max(3e4,Math.min(3e5,Math.round(t.usageRefreshIntervalMs))):Uu,o=t?.usageDisplayMode==="remaining"?"remaining":"usage",a=Array.isArray(t?.usageDropdownProviders)?t?.usageDropdownProviders:null,l=a?a.filter(f=>typeof f=="string"&&s.includes(f)):s,c={},d=t?.usageSelectedModels;if(d&&typeof d=="object")for(const[f,p]of Object.entries(d))Array.isArray(p)&&(c[f]=p.filter(h=>typeof h=="string"));const u={},m=t?.usageExpandedFamilies;if(m&&typeof m=="object")for(const[f,p]of Object.entries(m))Array.isArray(p)&&(u[f]=p.filter(h=>typeof h=="string"));return{autoRefresh:r,refreshIntervalMs:n,displayMode:o,dropdownProviderIds:l,selectedModels:c,expandedFamilies:u}},CN=async()=>{const t=Ur()?.settings;if(t)try{const r=(await t.load())?.settings;return hf(r??null)}catch{}if(!gs()){const s=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(s.ok){const r=await s.json().catch(()=>null);return hf(r)}}return{autoRefresh:!1,refreshIntervalMs:Uu,displayMode:"usage",dropdownProviderIds:yn.map(s=>s.id),selectedModels:{},expandedFamilies:{}}},ts=Ls()(Us((t,s)=>({results:[],selectedProviderId:null,isLoading:!1,isFetchingProvider:{},lastUpdated:null,error:null,autoRefresh:!1,refreshIntervalMs:Uu,displayMode:"usage",dropdownProviderIds:yn.map(r=>r.id),selectedModels:{},expandedFamilies:{},loadSettings:async()=>{try{const r=await CN();t(r)}catch(r){console.warn("Failed to load usage settings:",r)}},fetchAllQuotas:async()=>{t({isLoading:!0,error:null});const r=yn.map(n=>n.id);try{await Promise.all(r.map(n=>s().fetchProviderQuota(n))),t({isLoading:!1,lastUpdated:Date.now()})}catch(n){const o=n instanceof Error?n.message:"Failed to fetch quotas";t({isLoading:!1,error:o})}},fetchProviderQuota:async r=>{t(n=>({isFetchingProvider:{...n.isFetchingProvider,[r]:!0}}));try{const n=await fetch(`/api/quota/${encodeURIComponent(r)}`),o=await n.json().catch(()=>null);if(!n.ok)throw new Error(o?.error||"Failed to fetch quota");const a=o;t(l=>{const c=l.results.filter(d=>d.providerId!==r);return c.push(a),{results:c,error:null}})}catch(n){const o=n instanceof Error?n.message:"Failed to fetch quota",a={providerId:r,providerName:r,ok:!1,configured:!1,error:o,usage:null,fetchedAt:Date.now()};t(l=>{const c=l.results.filter(d=>d.providerId!==r);return c.push(a),{results:c,error:o}})}finally{t(n=>({isFetchingProvider:{...n.isFetchingProvider,[r]:!1}}))}},setSelectedProvider:r=>t({selectedProviderId:r}),setAutoRefresh:r=>t({autoRefresh:r}),setRefreshInterval:r=>{const n=Math.max(3e4,Math.min(3e5,Math.round(r)));t({refreshIntervalMs:n})},setDisplayMode:r=>t({displayMode:r}),setDropdownProviderIds:r=>t({dropdownProviderIds:r}),setSelectedModels:(r,n)=>{t(o=>({selectedModels:{...o.selectedModels,[r]:n}}))},toggleModelSelected:(r,n)=>{t(o=>{const a=o.selectedModels[r]??[],c=a.includes(n)?a.filter(d=>d!==n):[...a,n];return{selectedModels:{...o.selectedModels,[r]:c}}})},setExpandedFamilies:(r,n)=>{t(o=>({expandedFamilies:{...o.expandedFamilies,[r]:n}})),xs({usageExpandedFamilies:s().expandedFamilies})},toggleFamilyExpanded:(r,n)=>{t(o=>{const a=o.expandedFamilies[r]??[],c=a.includes(n)?a.filter(d=>d!==n):[...a,n];return{expandedFamilies:{...o.expandedFamilies,[r]:c}}}),xs({usageExpandedFamilies:s().expandedFamilies})},applyDefaultSelections:(r,n)=>{if((s().selectedModels[r]?.length??0)>0)return;const a=kN(r,n);a.length!==0&&(t(l=>({selectedModels:{...l.selectedModels,[r]:a}})),xs({usageSelectedModels:s().selectedModels}))}}),{name:"quota-store"})),Hu=()=>{const t=ts(n=>n.autoRefresh),s=ts(n=>n.refreshIntervalMs),r=ts(n=>n.fetchAllQuotas);i.useEffect(()=>{if(!t)return;const n=window.setInterval(()=>{r()},s);return()=>window.clearInterval(n)},[t,s,r])},MN=async t=>{if(t)return await t.authStatus();const s=await fetch("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),r=await s.json().catch(()=>null);if(!s.ok||!r)throw new Error(r?.error||s.statusText||"Failed to load GitHub status");return r},$r=Ls((t,s)=>({status:null,isLoading:!1,hasChecked:!1,setStatus:r=>t({status:r,hasChecked:!0}),refreshStatus:async(r,n)=>{const{hasChecked:o,status:a}=s();if(o&&!n?.force)return a;t({isLoading:!0});try{const l=await MN(r);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}}})),Vu=i.createContext(null),Vr=()=>{const t=i.useContext(Vu);if(!t)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return t},AN=t=>{const s=Vr();return t(s)},Ex=()=>AN(t=>t.runtime.isVSCode),pc=({containerRef:t,minThumbSize:s=32,hideDelayMs:r=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),y=i.useCallback(()=>{const M=t.current;if(!M)return;const{scrollHeight:D,clientHeight:A,scrollTop:P,scrollWidth:$,clientWidth:R,scrollLeft:O}=M,T=8;if(D>A){const _=Math.max(A-T*2,0),F=A/D*_,I=Math.max(s,Math.min(_,F)),E=Math.max(_-I,0),W=Math.max(D-A,1),V=P/W*E;d({length:I,offset:V})}else d({length:0,offset:0});if(!o&&$>R){const _=Math.max(R-T*2,0),F=R/$*_,I=Math.max(s,Math.min(_,F)),E=Math.max(_-I,0),W=Math.max($-R,1),V=O/W*E;m({length:I,offset:V})}else m({length:0,offset:0})},[t,s,o]),b=i.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),r)},[r]),v=i.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{y(),l(!0),b()})},[b,y]);i.useEffect(()=>{const M=t.current;if(!M)return;y(),l(!0),b(),M.addEventListener("scroll",v,{passive:!0});const D=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null;D?.observe(M);const A=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return A?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",v),D?.disconnect(),A?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[t,v,b,y]);const j=(M,D)=>{const A=t.current;A&&(h.current=!0,g.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:A.scrollTop,scrollLeft:A.scrollLeft},x.current=D,l(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},k=M=>{if(!h.current)return;const D=t.current;if(!D)return;const A=x.current;if(A==="vertical"){const{pointerY:P,scrollTop:$}=g.current,R=M.clientY-P,O=D.clientHeight,T=Math.max(O-c.length,1),_=Math.max(D.scrollHeight-D.clientHeight,1),F=R/T*_;D.scrollTop=$+F}else if(A==="horizontal"){const{pointerX:P,scrollLeft:$}=g.current,R=M.clientX-P,O=D.clientWidth,T=Math.max(O-u.length,1),_=Math.max(D.scrollWidth-D.clientWidth,1),F=R/T*_;D.scrollLeft=$+F}},N=M=>{h.current&&(h.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),b())},w=c.length>0,C=u.length>0;if(!w&&!C)return null;const S=8;return e.jsxs("div",{className:L("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[w&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${S+c.offset}px`,right:`${S/2}px`},onPointerDown:M=>j(M,"vertical"),onPointerMove:k,onPointerUp:N,onPointerCancel:N}),C&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${S+u.offset}px`,bottom:`${S/2}px`},onPointerDown:M=>j(M,"horizontal"),onPointerMove:k,onPointerUp:N,onPointerCancel:N})]})},Ut=i.forwardRef(({className:t,outerClassName:s,children:r,style:n,minThumbSize:o,hideDelayMs:a,as:l="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,preventOverscroll:f=!1,...p},h)=>{const g=i.useRef(null);return i.useImperativeHandle(h,()=>g.current,[]),e.jsxs("div",{className:L("relative flex flex-col min-h-0 w-full overflow-hidden",f&&"overscroll-none",s),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(l,{ref:g,className:L("overlay-scrollbar-target overlay-scrollbar-container",f&&"overscroll-none",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,...p,children:r}),e.jsx(pc,{containerRef:g,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});Ut.displayName="ScrollableOverlay";const gf="mobile-overlay-root",DN=()=>{if(typeof document>"u")return null;let t=document.getElementById(gf);return t||(t=document.createElement("div"),t.id=gf,document.body.appendChild(t)),t},Cr=({open:t,title:s,onClose:r,children:n,footer:o,className:a,contentMaxHeightClassName:l,renderHeader:c})=>{const d=i.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=DN()),i.useEffect(()=>{if(!t)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const p=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",p)}},[t,r]),!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:r,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:r,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-interactive-hover",children:e.jsx(hs,{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:s}),f]})})(),e.jsx(Ut,{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 co.createPortal(m,d.current)},Px=({totalTokens:t,percentage:s,contextLimit:r,outputLimit:n,size:o="default",isMobile:a=!1,hideIcon:l=!1})=>{const[c,d]=i.useState(!1),u=g=>g>=1e6?`${(g/1e6).toFixed(1)}M`:g>=1e3?`${(g/1e3).toFixed(1)}K`:g.toFixed(1).replace(/\.0$/,""),m=g=>g>=90?"text-status-error":g>=75?"text-status-warning":"text-status-success",f=typeof n=="number"?Math.max(n,0):0,p=[`Used tokens: ${u(t)}`,`Context limit: ${u(r)}`,`Output limit: ${u(f)}`],h=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",onClick:a?()=>d(!0):void 0,children:[!a&&!l&&e.jsx(Qb,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:L(m(s),"font-medium"),children:[Math.min(s,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[h,e.jsx(Cr,{open:c,onClose:()=>d(!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(r)})]}),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(s)),children:[Math.min(s,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:h}),e.jsx(ht,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(g=>e.jsx("p",{className:"typography-micro leading-tight",children:g},g))})})]})},za={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Rx=(t,s,r)=>{if(typeof window>"u")return;const n=document.documentElement,o=s==="mobile",a=s==="tablet";n.classList.remove("device-mobile","device-tablet","device-desktop"),n.classList.add(s==="mobile"?"device-mobile":s==="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",s),n.style.setProperty("--font-scale",o?"0.9":a?"0.95":"1"),n.style.setProperty("--has-coarse-pointer",r?"1":"0"),n.style.setProperty("--has-touch-input",r?"1":"0"),r?n.classList.add("mobile-pointer"):n.classList.remove("mobile-pointer"))};function Hc(){const t=window.innerWidth,s=typeof window.matchMedia=="function",r=s?window.matchMedia("(pointer: coarse)"):null,n=s?window.matchMedia("(hover: none)"):null,o=r?.matches??!1,a=n?.matches??!1,l=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=As(),d=o||a||l>0,u=t>za.md&&t<=za.lg,m=t<=za.md;let f=d&&m,p=d&&!f&&u,h=!d||t>za.lg,g="desktop";c?(f=!1,p=!1,h=!0,g="desktop"):f?g="mobile":p?g="tablet":(h=!0,g="desktop"),Rx(c,g,d);let x="xs";for(const[y,b]of Object.entries(za))t>=b&&(x=y);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:g,screenWidth:t,breakpoint:x,hasTouchInput:d}}function IN(){if(typeof window>"u"||typeof window<"u"&&As())return!1;const t=document.documentElement,s=t.style.getPropertyValue("--is-mobile")||getComputedStyle(t).getPropertyValue("--is-mobile");return s==="1"||s==="true"}function ks(){const[t,s]=i.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Hc());return i.useEffect(()=>{if(typeof window>"u")return;const r=()=>{s(Hc())};return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{s(Hc())},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(r),l(n),()=>{a.forEach(c=>c())}},[]),i.useEffect(()=>{if(typeof window>"u")return;const r=As(),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;Rx(r,t.deviceType,u)},[t.deviceType,t.hasTouchInput]),t}const Ci=()=>{const{currentSessionId:t,sessions:s,worktreeMetadata:r,newSessionDraft:n}=Ae(),{currentDirectory:o}=Yt();if(t){const a=r.get(t);if(a?.path)return a.path;const c=s.find(d=>d.id===t)?.directory;if(c)return c}return n?.open&&n.directoryOverride?n.directoryOverride:o??void 0},Vi=5e3,TN=1e4,EN=5e3,PN=1e4,RN=25,FN=4,xf=15e3,LN=30,ON=20*1024*1024,wn=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),yf=(t,s=LN,r=ON)=>{let n=0;for(const c of t.values())n+=(c.original?.length??0)+(c.modified?.length??0);if(t.size<=s&&n<=r)return t;const o=Array.from(t.entries()).sort((c,d)=>c[1].fetchedAt-d[1].fetchedAt),a=new Map;let l=0;for(let c=o.length-1;c>=0;c--){const[d,u]=o[c],m=(u.original?.length??0)+(u.modified?.length??0);if(a.size>=s)break;l+m>r&&a.size>0||(a.set(d,u),l+=m)}return a},_N=(t,s)=>{if(!t&&!s)return!1;if(!t||!s)return!0;const r=new Set([...Object.keys(t),...Object.keys(s)]);for(const n of r){const o=t[n],a=s[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},$N=(t,s)=>{if(!t&&!s)return!1;if(!t||!s)return!0;const r=t.files??[],n=s.files??[];if(r.length!==n.length||t.ahead!==s.ahead||t.behind!==s.behind||t.current!==s.current||t.tracking!==s.tracking||t.isClean!==s.isClean)return!0;const o=new Set(r.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!!_N(t.diffStats,s.diffStats)},BN=(t,s)=>{const r=new Set;if(!s)return r;const n=t?.files??[],o=s.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){r.add(f);continue}if(p.index!==h.index||p.working_dir!==h.working_dir){r.add(f);continue}}const d=t?.diffStats??{},u=s.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){r.add(f);continue}(p.insertions!==h.insertions||p.deletions!==h.deletions)&&r.add(f)}return r},or=Ls()(Us((t,s)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:Vi,setActiveDirectory:r=>{const{activeDirectory:n,directories:o}=s();if(n!==r)if(r&&!o.has(r)){const a=new Map(o);a.set(r,wn()),t({activeDirectory:r,directories:a})}else t({activeDirectory:r})},getDirectoryState:r=>s().directories.get(r)??null,fetchStatus:async(r,n,o={})=>{const{silent:a=!1}=o,{directories:l}=s();let c=l.get(r);c||(c=wn()),a||t({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(r)){const f=new Map(l);return f.set(r,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),t({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(r);if($N(c.status,m)){d=!0;const f=new Map(s().directories),p=f.get(r)??wn(),h=BN(p.status,m),g=new Set((p.status?.files??[]).map(v=>v.path)),x=new Set((m.files??[]).map(v=>v.path)),y=new Map(p.diffCache);for(const v of g)x.has(v)||y.delete(v);for(const v of h)y.delete(v);const b=h.size>0;f.set(r,{...p,isGitRepo:!0,status:m,diffCache:y,lastStatusFetch:Date.now(),lastStatusChange:b?Date.now():p.lastStatusChange}),t({directories:f})}else{const f=new Map(s().directories),p=f.get(r)??wn();f.set(r,{...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(r,n)=>{t({isLoadingBranches:!0});try{const o=await n.getGitBranches(r),a=new Map(s().directories),l=a.get(r)??wn();a.set(r,{...l,branches:o}),t({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{t({isLoadingBranches:!1})}},fetchLog:async(r,n,o)=>{const{directories:a}=s(),l=a.get(r),c=o??l?.logMaxCount??25;t({isLoadingLog:!0});try{const d=await n.getGitLog(r,{maxCount:c}),u=new Map(s().directories),m=u.get(r)??wn();u.set(r,{...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(r,n)=>{t({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(r),a=new Map(s().directories),l=a.get(r)??wn();a.set(r,{...l,identity:o}),t({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{t({isLoadingIdentity:!1})}},fetchAll:async(r,n,o={})=>{const{directories:a}=s();let l=a.get(r);if(!l){l=wn();const f=new Map(a);f.set(r,l),t({directories:f})}const{force:c=!1}=o,d=Date.now();await s().fetchStatus(r,n);const u=s().directories.get(r);if(!u?.isGitRepo)return;await s().fetchBranches(r,n);const m=d-(u.lastLogFetch||0);(c||m>PN||!u.log)&&await s().fetchLog(r,n),await s().fetchIdentity(r,n),s().fetchAllDiffs(r,n)},getDiff:(r,n)=>s().directories.get(r)?.diffCache.get(n)??null,setDiff:(r,n,o)=>{const a=new Map(s().directories),l=a.get(r)??wn(),c=new Map(l.diffCache);c.set(n,{...o,fetchedAt:Date.now()});const d=yf(c);a.set(r,{...l,diffCache:d}),t({directories:a})},clearDiffCache:r=>{const n=new Map(s().directories),o=n.get(r);o&&(n.set(r,{...o,diffCache:new Map}),t({directories:n}))},fetchAllDiffs:async(r,n)=>{const o=s().directories.get(r);if(!o?.status?.files||o.status.files.length===0)return;const c=o.status.files.filter(j=>!o.diffCache.has(j.path)).slice(0,RN);if(c.length===0)return;let d=0;const u=[],m=()=>{const j=d;return d+=1,j<c.length?c[j]:null},f=async j=>{const k=n.getGitFileDiff(r,{path:j}),N=new Promise((C,S)=>{setTimeout(()=>S(new Error(`Timed out after ${xf}ms`)),xf)}),w=await Promise.race([k,N]);return{path:j,diff:{original:w.original??"",modified:w.modified??""}}},p=async()=>{for(;;){const j=m();if(!j)return;try{u.push(await f(j.path))}catch{}}},h=Math.min(FN,c.length);await Promise.allSettled(Array.from({length:h},()=>p()));const g=new Map(s().directories),x=g.get(r);if(!x)return;const y=new Map(x.diffCache),b=Date.now();u.forEach(j=>{y.set(j.path,{...j.diff,fetchedAt:b})});const v=yf(y);g.set(r,{...x,diffCache:v}),t({directories:g})},setLogMaxCount:(r,n)=>{const o=new Map(s().directories),a=o.get(r)??wn();o.set(r,{...a,logMaxCount:n}),t({directories:o})},startPolling:r=>{const{pollIntervalId:n}=s();if(n)return;const o=()=>{const{currentPollInterval:a}=s();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){t({pollIntervalId:o()});return}const{activeDirectory:c}=s();if(!c){t({pollIntervalId:o()});return}if(await s().fetchStatus(c,r,{silent:!0}))await s().fetchLog(c,r),s().fetchAllDiffs(c,r),t({currentPollInterval:Vi});else{const m=Math.min(a+EN,TN);t({currentPollInterval:m})}const{pollIntervalId:u}=s();u!==null&&t({pollIntervalId:o()})},a)};t({pollIntervalId:o(),currentPollInterval:Vi})},stopPolling:()=>{const{pollIntervalId:r}=s();r&&(clearTimeout(r),t({pollIntervalId:null,currentPollInterval:Vi}))},refresh:async(r,n={})=>{const{activeDirectory:o}=s();o&&await s().fetchAll(o,r,n)}}),{name:"git-store"})),Wu=t=>or(s=>t?s.directories.get(t)?.status??null:null),zN=t=>or(s=>t?s.directories.get(t)?.branches??null:null),UN=t=>or(s=>t?s.directories.get(t)?.log??null:null),HN=t=>or(s=>t?s.directories.get(t)?.identity??null:null),Fx=t=>or(s=>t?s.directories.get(t)?.isGitRepo??null:null),VN=t=>or(s=>t?s.directories.get(t)?.status?.files?.length??0:0),WN=Yb("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-interactive-hover hover:text-foreground",secondary:"bg-interactive-hover text-foreground shadow-none hover:bg-interactive-active",ghost:"text-foreground hover:bg-interactive-hover hover:text-foreground",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 Me({className:t,variant:s,size:r,asChild:n=!1,...o}){const a=n?Jh:"button";return e.jsx(a,{"data-slot":"button",className:L(WN({variant:s,size:r,className:t})),...o})}const tn=Jb,On=({className:t,...s})=>e.jsx(Xb,{className:L("flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",t),...s}),sn=({className:t,...s})=>e.jsx(Zb,{className:L("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",t),...s}),GN={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 Gu(t){return GN[t]||{displayName:t.charAt(0).toUpperCase()+t.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function KN(t,s,r){const n=Gu(t);if(n.outputLanguage==="auto"){if(r?.filePath||r?.file_path||r?.sourcePath){const o=r.filePath||r.file_path||r.sourcePath,a=Jn(o);if(a)return a}if(t==="webfetch"){if(s.trim().startsWith("{")||s.trim().startsWith("["))try{return JSON.parse(s),"json"}catch{}if(s.trim().startsWith("<"))return"html";if(s.includes("```"))return"markdown"}return"text"}return n.outputLanguage||"text"}function Jn(t){const s=t.split(".").pop()?.toLowerCase(),r=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[r]?n[r]:{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:"html",heex:"html",leex:"html",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"}[s||""]||null}const qN=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function xi(t){const s=t.split(".").pop()?.toLowerCase();return qN.includes(s||"")}function su(t){const s=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"}[s||""]||"image/png"}function QN(t,s){if(!t)return"";const r=n=>{const o=t[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(s==="bash"){const n=r("command");if(n)return n}if(s==="task"){const n=r("prompt");if(n)return n;const o=r("description");if(o)return o}if(s==="apply_patch"&&typeof t=="object"){const n=r("patchText")||r("patch_text")||r("patch");if(n)return n}if((s==="edit"||s==="multiedit")&&typeof t=="object"){const n=r("filePath")||r("file_path")||r("path");if(n)return`File path: ${n}`}if(s==="write"&&typeof t=="object"){const n=r("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 Lx=({mode:t,onModeChange:s,className:r})=>{const n=i.useCallback(o=>{o.stopPropagation(),s(t==="side-by-side"?"unified":"side-by-side")},[t,s]);return e.jsx(Me,{size:"sm",variant:"ghost",className:L("h-5 w-5 p-0 opacity-60 hover:opacity-100",r),onClick:n,title:t==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:t==="side-by-side"?e.jsx(ev,{className:"h-3 w-3"}):e.jsx(tv,{className:"h-3 w-3"})})},Ku=ne.createContext(void 0);function rn(){const t=ne.useContext(Ku);if(!t)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return t}function Ta(){return ne.useContext(Ku)}function qu({draft:t,onEdit:s,onDelete:r,className:n}){const a=Ta()?.currentTheme,[l,c]=ne.useState(!1),d=t.text.length>150||t.text.split(`
|
|
13
|
+
`).length>3;return e.jsx("div",{className:L("rounded-lg border shadow-sm w-full overflow-hidden transition-all duration-200",n),style:{backgroundColor:a?.colors?.surface?.elevated,borderColor:a?.colors?.interactive?.border},"data-comment-card":"true",children:e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground mb-1.5",children:[e.jsx("span",{className:"truncate max-w-[200px]",title:t.fileLabel,children:t.fileLabel}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:["Lines ",t.startLine,"-",t.endLine]}),t.side&&e.jsxs("span",{children:["(",t.side,")"]})]}),e.jsxs(tn,{open:l||!d,onOpenChange:c,children:[e.jsx("div",{className:L("text-sm whitespace-pre-wrap break-words leading-relaxed",!l&&d&&"line-clamp-3"),children:t.text}),d&&e.jsx(On,{asChild:!0,children:e.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 px-0 mt-1 text-xs text-muted-foreground hover:text-foreground w-full justify-start",children:l?e.jsxs(e.Fragment,{children:[e.jsx(vi,{className:"size-3 mr-1"}),"Show less"]}):e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"size-3 mr-1"}),"Show more"]})})}),e.jsx(sn,{})]})]}),e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(Me,{variant:"ghost",size:"icon",className:"h-6 w-6 -mr-1 text-muted-foreground hover:text-foreground",children:e.jsx(sv,{className:"size-4"})})}),e.jsxs(fs,{align:"end",children:[e.jsxs(Et,{onClick:s,children:[e.jsx(go,{className:"size-4 mr-2"}),"Edit comment"]}),e.jsxs(Et,{onClick:r,className:"text-destructive",children:[e.jsx(Nr,{className:"size-4 mr-2"}),"Delete comment"]})]})]})]})})}const hr=ne.forwardRef(({className:t,outerClassName:s,...r},n)=>e.jsx(Ut,{as:"textarea",ref:n,disableHorizontal:!0,fillContainer:!1,outerClassName:L("w-full rounded-lg focus-within:ring-1 focus-within:ring-primary/50",s),className:L("text-foreground border border-border/80 placeholder:text-muted-foreground appearance-none dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg bg-transparent px-3 py-2 typography-markdown outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","hover:border-input aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive","focus:border-primary/70",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...r}));hr.displayName="Textarea";function Sa({initialText:t="",onSave:s,onCancel:r,fileLabel:n,lineRange:o,isEditing:a=!1,className:l}){const d=Ta()?.currentTheme,{isMobile:u}=ks(),[m,f]=i.useState(t),p=ne.useRef(null),h=ne.useRef(o);ne.useEffect(()=>{o&&(h.current=o)},[o]);const g=v=>{if(!v)return;const j=Math.min(v.start,v.end),k=Math.max(v.start,v.end);return{...v,start:j,end:k}},x=g(o);ne.useEffect(()=>{const v=p.current;if(!v)return;const j=v.closest(".overlay-scrollbar-container"),k=j?.scrollTop??window.scrollY,N=j?.scrollLeft??window.scrollX;if(u){v.scrollIntoView({behavior:"auto",block:"nearest"});try{v.focus({preventScroll:!0})}catch{v.focus()}return}try{v.focus({preventScroll:!0})}catch{v.focus()}const w=v.value.length;try{v.setSelectionRange(w,w)}catch{}requestAnimationFrame(()=>{j?(j.scrollTop=k,j.scrollLeft=N):window.scrollTo({top:k,left:N})})},[u]);const y=v=>{(v.metaKey||v.ctrlKey)&&v.key==="Enter"?(v.preventDefault(),m.trim()&&s(m,g(h.current))):v.key==="Escape"&&(v.preventDefault(),r())},b=v=>{v.stopPropagation(),m.trim()&&s(m,g(h.current))};return e.jsx("div",{className:L("rounded-lg border shadow-sm w-full overflow-hidden animate-in fade-in zoom-in-95 duration-200",l),style:{backgroundColor:d?.colors?.surface?.elevated,borderColor:d?.colors?.interactive?.border},"data-comment-input":"true",onPointerDown:v=>v.stopPropagation(),onTouchStart:v=>v.stopPropagation(),children:e.jsxs("div",{className:"p-3",children:[(n||o)&&e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground mb-2",children:[n&&e.jsx("span",{className:"truncate max-w-[200px]",children:n}),n&&o&&e.jsx("span",{children:"•"}),x&&e.jsxs("span",{children:["Lines ",x.start,"-",x.end]})]}),e.jsx(hr,{ref:p,value:m,onChange:v=>f(v.target.value),onKeyDown:y,placeholder:"Add a comment... (Cmd+Enter to save)",className:"min-h-[80px] text-sm resize-y",style:{backgroundColor:d?.colors?.surface?.subtle}}),e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-3",children:[e.jsx(Me,{variant:"ghost",size:"sm",onClick:r,onPointerDown:v=>v.stopPropagation(),onTouchStart:v=>v.stopPropagation(),className:"h-8 text-muted-foreground hover:text-foreground",children:"Cancel"}),e.jsx(Me,{size:"sm",onClick:b,onPointerDown:v=>v.stopPropagation(),onTouchStart:v=>v.stopPropagation(),disabled:!m.trim(),className:"h-8 min-w-[80px]",style:{backgroundColor:d?.colors?.status?.success,color:d?.colors?.status?.successForeground},children:a?"Save":"Comment"})]})]})})}function YN(){return new Worker(rv,{type:"module"})}const JN=t=>/^#[0-9a-fA-F]{6}$/.test(t),XN=t=>/^#[0-9a-fA-F]{8}$/.test(t),ZN=(t,s)=>/^[0-9a-fA-F]{2}$/.test(s)?JN(t)?`${t}${s}`:XN(t)?`${t.slice(0,7)}${s}`:t:t,Tr=(t,s)=>typeof t=="string"&&t.trim().length>0?t:s,ek=t=>{const s=t.colors.syntax.base,r=t.colors.syntax.tokens??{},n=(o,a)=>Tr(r[o],a);return[{name:"plain",scope:["source","support.type.property-name.css"],settings:{foreground:s.foreground}},{name:"classes",scope:["entity.name.type.class"],settings:{foreground:n("className",n("class",s.function))}},{name:"interfaces",scope:["entity.name.type.interface","entity.name.type"],settings:{foreground:n("interface",s.type)}},{name:"structs",scope:["entity.name.type.struct"],settings:{foreground:n("struct",s.function)}},{name:"enums",scope:["entity.name.type.enum"],settings:{foreground:n("enum",s.function)}},{name:"keys",scope:["meta.object-literal.key","support.type.property-name"],settings:{foreground:n("key",s.function)}},{name:"methods",scope:["entity.name.function.method","meta.function.method"],settings:{foreground:n("method",t.colors.status.success)}},{name:"functions",scope:["entity.name.function","support.function","meta.function-call.generic"],settings:{foreground:s.function,fontStyle:"bold"}},{name:"variables",scope:["variable","meta.variable","variable.other.object.property"],settings:{foreground:s.variable}},{name:"variablesOther",scope:["variable.other.object","variable.other.readwrite.alias"],settings:{foreground:n("variableOther",n("method",t.colors.status.success))}},{name:"globalVariables",scope:["variable.other.global","variable.language.this"],settings:{foreground:n("variableGlobal",s.number)}},{name:"localVariables",scope:["variable.other.local"],settings:{foreground:n("variableLocal",t.colors.surface.elevated)}},{name:"parameters",scope:["variable.parameter","meta.parameter"],settings:{foreground:n("parameter",s.foreground)}},{name:"properties",scope:["variable.other.property","meta.property"],settings:{foreground:n("variableProperty",t.colors.status.info)}},{name:"strings",scope:["string","string.other.link","markup.inline.raw.string.markdown"],settings:{foreground:s.string}},{name:"stringEscapeSequences",scope:["constant.character.escape","constant.other.placeholder"],settings:{foreground:n("stringEscape",s.foreground)}},{name:"keywords",scope:["keyword"],settings:{foreground:s.keyword}},{name:"keywordsControl",scope:["keyword.control.import","keyword.control.from","keyword.import"],settings:{foreground:n("keywordImport",s.operator)}},{name:"storageModifiers",scope:["storage.modifier","keyword.modifier","storage.type"],settings:{foreground:n("storageModifier",s.keyword)}},{name:"comments",scope:["comment","punctuation.definition.comment"],settings:{foreground:s.comment}},{name:"docComments",scope:["comment.documentation","comment.line.documentation"],settings:{foreground:n("commentDoc",t.colors.surface.mutedForeground)}},{name:"numbers",scope:["constant.numeric"],settings:{foreground:s.number}},{name:"booleans",scope:["constant.language.boolean","constant.language.json"],settings:{foreground:n("boolean",s.type)}},{name:"operators",scope:["keyword.operator"],settings:{foreground:s.operator}},{name:"macros",scope:["entity.name.function.preprocessor","meta.preprocessor"],settings:{foreground:n("macro",s.keyword)}},{name:"preprocessor",scope:["meta.preprocessor"],settings:{foreground:n("preprocessor",n("label",s.number))}},{name:"urls",scope:["markup.underline.link"],settings:{foreground:n("url",t.colors.status.info)}},{name:"tags",scope:["entity.name.tag"],settings:{foreground:n("tag",s.keyword)}},{name:"jsxTags",scope:["support.class.component"],settings:{foreground:n("jsxTag",n("label",s.number))}},{name:"attributes",scope:["entity.other.attribute-name","meta.attribute"],settings:{foreground:n("tagAttribute",s.type)}},{name:"types",scope:["support.type"],settings:{foreground:s.type}},{name:"constants",scope:["variable.other.constant","variable.readonly"],settings:{foreground:n("constant",s.foreground)}},{name:"labels",scope:["entity.name.label","punctuation.definition.label"],settings:{foreground:n("label",n("variableGlobal",s.number))}},{name:"namespaces",scope:["entity.name.namespace","storage.modifier.namespace","markup.bold.markdown"],settings:{foreground:n("namespace",s.type)}},{name:"modules",scope:["entity.name.module","storage.modifier.module"],settings:{foreground:n("module",s.operator)}},{name:"typeParameters",scope:["variable.type.parameter","variable.parameter.type"],settings:{foreground:n("typeParameter",s.function)}},{name:"exceptions",scope:["keyword.control.exception","keyword.control.trycatch"],settings:{foreground:n("exception",n("label",s.number))}},{name:"decorators",scope:["meta.decorator","punctuation.decorator","entity.name.function.decorator"],settings:{foreground:n("decorator",s.type)}},{name:"calls",scope:["variable.function"],settings:{foreground:s.foreground}},{name:"punctuation",scope:["punctuation","punctuation.terminator","punctuation.definition.tag","punctuation.separator","punctuation.definition.string","punctuation.section.block"],settings:{foreground:n("punctuation",s.comment)}},{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:s.type}},{name:"green",scope:[],settings:{foreground:n("method",t.colors.status.success)}},{name:"cyan",scope:["markup.italic.markdown","support.type.python","variable.legacy.builtin.python","support.constant.property-value.css","storage.modifier.attribute.swift"],settings:{foreground:s.string}},{name:"blue",scope:[],settings:{foreground:s.keyword}},{name:"purple",scope:["keyword.channel.go","keyword.other.platform.os.swift"],settings:{foreground:s.number}},{name:"magenta",scope:["punctuation.definition.heading.markdown"],settings:{foreground:n("label",n("variableGlobal",s.number))}},{name:"red",scope:[],settings:{foreground:s.operator}},{name:"orange",scope:[],settings:{foreground:s.function}}]},tk=t=>{const s=t.colors.surface,r=t.colors.interactive,n=t.colors.status,o=t.colors.syntax.base,a=t.colors.syntax.highlights??{},l=Tr(a.diffAddedBackground,n.successBackground),c=Tr(a.diffRemovedBackground,n.errorBackground);return{"editor.background":s.background,"editor.foreground":s.foreground,"editor.hoverHighlightBackground":Tr(r.hover,s.subtle),"editor.lineHighlightBackground":s.muted,"editor.selectionBackground":r.selection,"editor.selectionHighlightBackground":r.selection,"editor.findMatchBackground":o.type,"editor.findMatchHighlightBackground":ZN(o.type,"cc"),"editor.findRangeHighlightBackground":s.muted,"editor.inactiveSelectionBackground":s.elevated,"editor.lineHighlightBorder":s.elevated,"editor.rangeHighlightBackground":Tr(r.active,r.borderHover),"notifications.background":s.elevated,"editorInlayHint.typeBackground":s.subtle,"editorInlayHint.typeForeground":s.foreground,"editorWhitespace.foreground":r.borderHover,"editorIndentGuide.background1":s.subtle,"editorHoverWidget.background":s.elevated,"editorLineNumber.activeForeground":Tr(a.lineNumberActive,s.foreground),"editorLineNumber.foreground":Tr(a.lineNumber,s.mutedForeground),"editorGutter.background":s.background,"editorGutter.modifiedBackground":n.info,"editorGutter.addedBackground":n.success,"editorGutter.deletedBackground":n.error,"editorBracketMatch.background":s.elevated,"editorBracketMatch.border":s.subtle,"editorError.foreground":n.error,"editorWarning.foreground":n.warning,"editorInfo.foreground":n.info,"diffEditor.insertedTextBackground":l,"diffEditor.removedTextBackground":c,"editorGroupHeader.tabsBackground":s.background,"editorGroup.border":r.border,"tab.activeBackground":s.background,"tab.inactiveBackground":s.muted,"tab.inactiveForeground":s.mutedForeground,"tab.activeForeground":s.foreground,"tab.hoverBackground":s.subtle,"tab.unfocusedHoverBackground":s.subtle,"tab.border":r.border,"tab.activeModifiedBorder":o.type,"tab.inactiveModifiedBorder":n.info,"tab.unfocusedActiveModifiedBorder":o.type,"tab.unfocusedInactiveModifiedBorder":n.info,"editorWidget.background":s.muted,"editorWidget.border":r.border,"editorSuggestWidget.background":s.background,"editorSuggestWidget.border":r.border,"editorSuggestWidget.foreground":s.foreground,"editorSuggestWidget.highlightForeground":s.mutedForeground,"editorSuggestWidget.selectedBackground":s.subtle,"peekView.border":r.border,"peekViewEditor.background":s.background,"peekViewEditor.matchHighlightBackground":s.subtle,"peekViewResult.background":s.muted,"peekViewResult.fileForeground":s.foreground,"peekViewResult.lineForeground":s.mutedForeground,"peekViewResult.matchHighlightBackground":s.subtle,"peekViewResult.selectionBackground":s.elevated,"peekViewResult.selectionForeground":s.mutedForeground,"peekViewTitle.background":s.subtle,"peekViewTitleDescription.foreground":s.mutedForeground,"peekViewTitleLabel.foreground":s.foreground,"merge.currentHeaderBackground":n.success,"merge.currentContentBackground":Tr(a.diffAdded,n.success),"merge.incomingHeaderBackground":n.info,"merge.incomingContentBackground":Tr(a.diffModified,n.info),"merge.border":r.border,"merge.commonContentBackground":s.subtle,"merge.commonHeaderBackground":s.muted,"panel.background":s.background,"panel.border":r.border,"panelTitle.activeBorder":r.borderHover,"panelTitle.activeForeground":s.foreground,"panelTitle.inactiveForeground":s.mutedForeground,"statusBar.background":s.background,"statusBar.foreground":s.foreground,"statusBar.border":r.border,"statusBar.debuggingBackground":n.error,"statusBar.debuggingForeground":n.errorForeground,"statusBar.noFolderBackground":s.subtle,"statusBar.noFolderForeground":s.mutedForeground,"titleBar.activeBackground":s.background,"titleBar.activeForeground":s.foreground,"titleBar.inactiveBackground":s.muted,"titleBar.inactiveForeground":s.mutedForeground,"titleBar.border":r.border,"menu.foreground":s.foreground,"menu.background":s.background,"menu.selectionForeground":s.foreground,"menu.selectionBackground":s.subtle,"menu.border":r.border,"editorInlayHint.foreground":s.mutedForeground,"editorInlayHint.background":s.subtle,"terminal.foreground":s.foreground,"terminal.background":s.background,"terminalCursor.foreground":s.foreground,"terminalCursor.background":s.background,"terminal.ansiRed":Tr(a.diffRemoved,n.error),"terminal.ansiGreen":Tr(a.diffAdded,n.success),"terminal.ansiYellow":n.warning,"terminal.ansiBlue":Tr(a.diffModified,n.info),"terminal.ansiMagenta":o.keyword,"terminal.ansiCyan":o.type,"activityBar.background":s.background,"activityBar.foreground":s.foreground,"activityBar.inactiveForeground":s.mutedForeground,"activityBar.activeBorder":s.foreground,"activityBar.border":r.border,"sideBar.background":s.background,"sideBar.foreground":s.foreground,"sideBar.border":r.border,"sideBarTitle.foreground":s.foreground,"sideBarSectionHeader.background":s.muted,"sideBarSectionHeader.foreground":s.foreground,"sideBarSectionHeader.border":r.border,"sideBar.activeBackground":s.subtle,"sideBar.activeForeground":s.foreground,"sideBar.hoverBackground":s.muted,"sideBar.hoverForeground":s.foreground,"list.warningForeground":n.warning,"list.errorForeground":n.error,"list.inactiveSelectionBackground":s.subtle,"list.activeSelectionBackground":s.elevated,"list.inactiveSelectionForeground":s.foreground,"list.activeSelectionForeground":s.foreground,"list.hoverForeground":s.foreground,"list.hoverBackground":s.muted,"input.background":s.muted,"input.foreground":s.foreground,"input.border":r.border,"input.placeholderForeground":s.mutedForeground,"inputOption.activeBorder":r.border,"inputOption.activeBackground":s.elevated,"inputOption.activeForeground":s.foreground,"inputValidation.infoBackground":n.infoBackground,"inputValidation.infoBorder":n.infoBorder,"inputValidation.warningBackground":n.warningBackground,"inputValidation.warningBorder":n.warningBorder,"inputValidation.errorBackground":n.errorBackground,"inputValidation.errorBorder":n.errorBorder,"dropdown.background":s.muted,"dropdown.foreground":s.foreground,"dropdown.border":r.border,"dropdown.listBackground":s.background,"badge.background":t.colors.primary.base,"activityBarBadge.background":t.colors.primary.base,"button.background":t.colors.primary.base,"button.foreground":Tr(t.colors.primary.foreground,s.background),"badge.foreground":Tr(t.colors.primary.foreground,s.background),"activityBarBadge.foreground":Tr(t.colors.primary.foreground,s.background)}};function sk(t){return{name:t.metadata.name,type:t.metadata.variant,colors:tk(t),tokenColors:ek(t)}}const rk=t=>/^#[0-9a-fA-F]{8}$/.test(t),bf=t=>rk(t)?t.slice(0,7):t;function nk(t,s){return Object.defineProperty(t,"toString",{value:()=>s,enumerable:!1,configurable:!0}),Object.defineProperty(t,Symbol.toPrimitive,{value:()=>s,enumerable:!1,configurable:!0}),t}const vf=new Map,wf=new Set,ok=(t,s)=>{const r=t.colors?.["editor.background"],n=t.colors?.["editor.foreground"],o=r?bf(r):void 0,a=n?bf(n):void 0;if(!o||!a)throw new Error(`Theme "${s}" is missing editor.background/editor.foreground`);const l=t.tokenColors??[];return nk({...t,name:s,fg:a,bg:o,settings:l},s)},ak=t=>sk(t),yi=t=>{const s=vf.get(t.metadata.id);if(s)return s;const r=ak(t),n=ok(r,t.metadata.id);return vf.set(t.metadata.id,n),n},Wl=t=>{const s=t.metadata.id;if(wf.has(s))return;const r=yi(t);nv(s,async()=>r),wf.add(s)},ik=(t,s)=>[yi(t),yi(s)],lk="#8957e5",ck="#8250df",dk=t=>{const s=t.colors.syntax?.tokens??{},r=[s.className,s.enum,s.variableGlobal,t.colors.syntax?.base?.keyword].filter(n=>typeof n=="string"&&n.trim().length>0);return r.length>0?r[0]:t.metadata.variant==="dark"?lk:ck},Qu=t=>t.colors.pr?t:{...t,colors:{...t.colors,pr:{open:t.colors.status.success,draft:t.colors.surface.mutedForeground,blocked:t.colors.status.warning,merged:dk(t),closed:t.colors.status.error}}},uk={id:"dark-colorblind-high-contrast",name:"Dark Colorblind High Contrast",description:"Converted from @primer/primitives dark-colorblind-high-contrast.css",version:"1.0.0",variant:"dark",tags:["dark","primer","colorblind","high-contrast"]},mk={primary:{base:"#74b9ff",hover:"#2a7aef",active:"#3685f3",foreground:"#ffffff",muted:"#5cacff1a",emphasis:"#409eff"},surface:{background:"#010409",foreground:"#ffffff",muted:"#151b23",mutedForeground:"#b7bdc8",elevated:"#3d444d",elevatedForeground:"#ffffff",overlay:"#00000080",subtle:"#212830"},interactive:{border:"#b7bdc8",borderHover:"#5cacff",borderFocus:"#409eff",selection:"#5cacff66",selectionForeground:"#ffffff",focus:"#409eff",focusRing:"#409eff",cursor:"#ffffff",hover:"#2f3742",active:"#3d444d"},status:{error:"#ffb757",errorForeground:"#ffffff",errorBackground:"#ff80801a",errorBorder:"#e7811d",warning:"#f0b72f",warningForeground:"#ffffff",warningBackground:"#edaa2726",warningBorder:"#e09b13",success:"#addcff",successForeground:"#ffffff",successBackground:"#5cacff33",successBorder:"#409eff",info:"#74b9ff",infoForeground:"#ffffff",infoBackground:"#5cacff1a",infoBorder:"#409eff"},pr:{open:"#ffb757",draft:"#b7bdc8",blocked:"#f0b72f",merged:"#d3abff",closed:"#b7bdc8"},syntax:{base:{background:"#151b23",foreground:"#ffffff",comment:"#9198a1",keyword:"#fe9a2d",string:"#addcff",number:"#91cbff",function:"#dbb7ff",variable:"#ffb757",type:"#f0f6fc",operator:"#ffffff"},tokens:{commentDoc:"#9198a1",stringEscape:"#addcff",keywordImport:"#fe9a2d",storageModifier:"#f0f6fc",functionCall:"#dbb7ff",method:"#addcff",variableProperty:"#ffb757",variableOther:"#ffb757",variableGlobal:"#dbb7ff",variableLocal:"#ffffff",parameter:"#ffb757",constant:"#91cbff",class:"#dbb7ff",className:"#dbb7ff",interface:"#f0f6fc",struct:"#dbb7ff",enum:"#dbb7ff",typeParameter:"#dbb7ff",namespace:"#f0f6fc",module:"#fe9a2d",tag:"#addcff",jsxTag:"#409eff",tagAttribute:"#fbd669",tagAttributeValue:"#addcff",boolean:"#91cbff",decorator:"#dbb7ff",label:"#409eff",punctuation:"#9198a1",macro:"#dbb7ff",preprocessor:"#fe9a2d",regex:"#addcff",url:"#409eff",key:"#ffb757",exception:"#f48b25"},highlights:{diffAdded:"#56d4dd",diffAddedBackground:"#106c70",diffRemoved:"#fbd669",diffRemovedBackground:"#7b4900",diffModified:"#d3abff",diffModifiedBackground:"#6921d7",lineNumber:"#b7bdc8",lineNumberActive:"#ffffff"}},markdown:{heading1:"#ffffff",heading2:"#f0f6fc",heading3:"#d1d7e0",heading4:"#b7bdc8",link:"#74b9ff",linkHover:"#409eff",inlineCode:"#addcff",inlineCodeBackground:"#151b23",blockquote:"#b7bdc8",blockquoteBorder:"#b7bdc8",listMarker:"#fbd66999"},chat:{userMessage:"#ffffff",userMessageBackground:"#212830",assistantMessage:"#ffffff",assistantMessageBackground:"#010409",timestamp:"#b7bdc8",divider:"#b7bdc8"},tools:{background:"#151b2380",border:"#b7bdc89d",headerHover:"#2a313c",icon:"#d1d7e0",title:"#ffffff",description:"#b7bdc8",edit:{added:"#56d4dd",addedBackground:"#106c704d",removed:"#fbd669",removedBackground:"#7b49004d",lineNumber:"#b7bdc8"}},loading:{spinner:"#74b9ff",spinnerTrack:"#151b23",dot:"#b7bdc8"},charts:{series:["#71b7ff","#ffb757","#d3abff","#f0b72f","#addcff","#fe9a2d"]}},fk={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"}},pk={metadata:uk,colors:mk,config:fk},hk=[pk].map(t=>Qu(t)),gk={id:"flexoki-light",name:"Flexoki",description:"An inky color scheme for prose and code - light variant",version:"1.0.0",variant:"light",tags:["light","warm","natural","paper"]},xk={primary:{base:"#EC8B49",hover:"#F9AE77",active:"#DA702C",foreground:"#FFFCF0",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#FFFCF0",foreground:"#100F0F",muted:"#F2F0E5",mutedForeground:"#474643",elevated:"#fdf6ec",elevatedForeground:"#100F0F",overlay:"#100F0F20",subtle:"#f9f1e4"},interactive:{border:"#DAD8CE",borderHover:"#CECDC3",borderFocus:"#EC8B49",selection:"#76736f30",selectionForeground:"#100F0F",focus:"#EC8B49",focusRing:"#EC8B4940",cursor:"#100F0F",hover:"#76736f20",active:"#76736f20"},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"},pr:{open:"#66800B",draft:"#6F6E69",blocked:"#BC5215",merged:"#5E409D",closed:"#AF3029"},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:"#100F0F",heading2:"#100F0F",heading3:"#100F0F",heading4:"#100F0F",link:"#205EA6",linkHover:"#4385BE",inlineCode:"#24837B",inlineCodeBackground:"#F2F0E5",blockquote:"#6F6E69",blockquoteBorder:"#DAD8CE",listMarker:"#AD830199"},chat:{userMessage:"#100F0F",userMessageBackground:"#f9f1e4",assistantMessage:"#100F0F",assistantMessageBackground:"#FFFCF0",timestamp:"#6F6E69",divider:"#DAD8CE"},tools:{background:"#F2F0E550",border:"#b4b2a980",headerHover:"#DAD8CE",icon:"#6F6E69",title:"#100F0F",description:"#6F6E69",edit:{added:"#66800B",addedBackground:"#66800B25",removed:"#AF3029",removedBackground:"#AF302925",lineNumber:"#CECDC3"}}},yk={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"}},bk={metadata:gk,colors:xk,config:yk},vk={id:"flexoki-dark",name:"Flexoki",description:"An inky color scheme for prose and code - dark variant",version:"1.0.0",variant:"dark",tags:["dark","warm","natural","ink"]},wk={primary:{base:"#EC8B49",hover:"#DA702C",active:"#F9AE77",foreground:"#100F0F",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#100F0F",foreground:"#CECDC3",muted:"#1C1B1A",mutedForeground:"#878580",elevated:"#1C1A19",elevatedForeground:"#CECDC3",overlay:"#00000080",subtle:"#1e1d1c"},interactive:{border:"#343331",borderHover:"#403E3C",borderFocus:"#EC8B49",selection:"#f4f4f41f",selectionForeground:"#CECDC3",focus:"#EC8B49",focusRing:"#EC8B4950",cursor:"#CECDC3",hover:"#ffffff18",active:"#ffffff1f"},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"},pr:{open:"#A0AF54",draft:"#878580",blocked:"#DA702C",merged:"#8B7EC8",closed:"#D14D41"},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:"#fbf9e6",heading2:"#e6e4d2",heading3:"#CECDC3",heading4:"#CECDC3",link:"#4385BE",linkHover:"#205EA6",inlineCode:"#A0AF53",inlineCodeBackground:"#1C1B1A",blockquote:"#878580",blockquoteBorder:"#343331",listMarker:"#D0A21599"},chat:{userMessage:"#CECDC3",userMessageBackground:"#2d1d15",assistantMessage:"#CECDC3",assistantMessageBackground:"#100F0F",timestamp:"#878580",divider:"#343331"},tools:{background:"#1C1B1A50",border:"#42403e9d",headerHover:"#34333150",icon:"#aca7a1",title:"#CECDC3",description:"#878580",edit:{added:"#879A39",addedBackground:"#66800B25",removed:"#D14D41",removedBackground:"#AF302925",lineNumber:"#403E3C"}}},jk={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"}},Sk={metadata:vk,colors:wk,config:jk},Ox=Qu(bk),Nk=Qu(Sk),_x="flexoki-light",$x="flexoki-dark",Gl=[Ox,Nk,...hk];function ru(t){const s=t==="app-light"?"flexoki-light":t==="app-dark"?"flexoki-dark":t;return Gl.find(r=>r.metadata.id===s)}function Bo(t){const s=t?"dark":"light",n=ru(t?$x:_x);return n&&n.metadata.variant===s?n:Gl.find(o=>o.metadata.variant===s)??Gl[0]??Ox}const kk=["typescript","javascript","tsx","jsx","json","markdown"],Ck=({children:t,renderTheme:s})=>{const r=Xh();return ne.useEffect(()=>{r&&r.setRenderOptions({theme:s,lineDiffType:"none"})},[s,r]),e.jsx(e.Fragment,{children:t})},Mk=({children:t})=>{const s=Ta(),r=s?.currentTheme?.metadata?.variant==="dark",n=Bo(!1),o=Bo(!0),a=s?.lightThemeId??n.metadata.id,l=s?.darkThemeId??o.metadata.id,c=s?.availableThemes.find(f=>f.metadata.id===a)??n,d=s?.availableThemes.find(f=>f.metadata.id===l)??o;Wl(c),Wl(d);const u=ne.useMemo(()=>({theme:{dark:d.metadata.id,light:c.metadata.id},themeType:r?"dark":"light",langs:kk}),[d.metadata.id,r,c.metadata.id]),m=ne.useMemo(()=>({light:c.metadata.id,dark:d.metadata.id}),[d.metadata.id,c.metadata.id]);return e.jsx(ov,{poolOptions:{workerFactory:YN,poolSize:2,totalASTLRUCacheSize:50},highlighterOptions:u,children:e.jsx(Ck,{renderTheme:m,children:t})})},Vc=({...t})=>{const{theme:s="system"}=av();return e.jsx(iv,{theme:s,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})},jf=async t=>{try{await navigator.clipboard.writeText(t)}catch(s){console.error("Failed to copy to clipboard:",s)}},Kl=t=>t==null||typeof t=="boolean"?"":typeof t=="string"||typeof t=="number"?String(t):Array.isArray(t)?t.map(Kl).join(" ").trim():ne.isValidElement(t)?Kl(t.props?.children):"",Ak=t=>typeof t=="function"?t():t,Sf=(t,s)=>{const r=Kl(Ak(s?.description));return r.length>0?r:Kl(t)},K={...Ra,success:(t,s)=>Ra.success(t,{...s,action:s?.action||{label:"OK",onClick:()=>{}}}),info:(t,s)=>Ra.info(t,{...s,action:s?.action||{label:"OK",onClick:()=>{}}}),error:(t,s)=>Ra.error(t,{...s,action:s?.action||{label:"Copy",onClick:()=>jf(Sf(t,s))}}),warning:(t,s)=>Ra.warning(t,{...s,action:s?.action||{label:"Copy",onClick:()=>jf(Sf(t,s))}})},Br=Ls()(Us(Ar((t,s)=>({drafts:{},addDraft:r=>{const n=`icd-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,o={...r,id:n,createdAt:Date.now()};return t(a=>{const l=a.drafts[r.sessionKey]??[];return{drafts:{...a.drafts,[r.sessionKey]:[...l,o]}}}),n},updateDraft:(r,n,o)=>{t(a=>{const c=(a.drafts[r]??[]).map(d=>d.id!==n?d:{...d,...o});return{drafts:{...a.drafts,[r]:c}}})},removeDraft:(r,n)=>{t(o=>{const l=(o.drafts[r]??[]).filter(c=>c.id!==n);if(l.length===0){const{[r]:c,...d}=o.drafts;return{drafts:d}}return{drafts:{...o.drafts,[r]:l}}})},clearDrafts:r=>{t(n=>{const{[r]:o,...a}=n.drafts;return{drafts:a}})},getDrafts:r=>s().drafts[r]??[],consumeDrafts:r=>{const n=s().drafts[r]??[];if(n.length===0)return[];const o=[...n].sort((a,l)=>a.createdAt-l.createdAt);return t(a=>{const{[r]:l,...c}=a.drafts;return{drafts:c}}),o},getDraftCount:r=>(s().drafts[r]??[]).length,hasDrafts:r=>(s().drafts[r]??[]).length>0}),{name:"ikanban-inline-comment-drafts",storage:Dr(()=>Ws())}),{name:"inline-comment-draft-store"})),Dk=`
|
|
14
|
+
:host {
|
|
15
|
+
font-family: var(--font-mono);
|
|
16
|
+
font-size: var(--text-code);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
:host, pre, [data-diffs], [data-code] {
|
|
20
|
+
transform: translateZ(0);
|
|
21
|
+
-webkit-transform: translateZ(0);
|
|
22
|
+
-webkit-backface-visibility: hidden;
|
|
23
|
+
backface-visibility: hidden;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
pre, [data-code] {
|
|
27
|
+
font-family: var(--font-mono);
|
|
28
|
+
font-size: var(--text-code);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
[data-code] {
|
|
32
|
+
-webkit-overflow-scrolling: touch;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/* Mobile touch selection support */
|
|
36
|
+
[data-line-number] {
|
|
37
|
+
touch-action: manipulation;
|
|
38
|
+
-webkit-tap-highlight-color: transparent;
|
|
39
|
+
cursor: pointer;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/* Ensure interactive line numbers work on touch */
|
|
43
|
+
pre[data-interactive-line-numbers] [data-line-number] {
|
|
44
|
+
touch-action: manipulation;
|
|
45
|
+
}
|
|
46
|
+
/* Reduce hunk separator height */
|
|
47
|
+
// [data-separator-content] {
|
|
48
|
+
// height: 24px !important;
|
|
49
|
+
// }
|
|
50
|
+
// [data-expand-button] {
|
|
51
|
+
// height: 24px !important;
|
|
52
|
+
// width: 24px !important;
|
|
53
|
+
// }
|
|
54
|
+
// [data-separator-multi-button] {
|
|
55
|
+
// row-gap: 0 !important;
|
|
56
|
+
// }
|
|
57
|
+
// [data-expand-up] {
|
|
58
|
+
// height: 12px !important;
|
|
59
|
+
// min-height: 12px !important;
|
|
60
|
+
// max-height: 12px !important;
|
|
61
|
+
// margin: 0 !important;
|
|
62
|
+
// margin-top: 3px !important;
|
|
63
|
+
// padding: 0 !important;
|
|
64
|
+
// border-radius: 4px 4px 0 0 !important;
|
|
65
|
+
// }
|
|
66
|
+
// [data-expand-down] {
|
|
67
|
+
// height: 12px !important;
|
|
68
|
+
// min-height: 12px !important;
|
|
69
|
+
// max-height: 12px !important;
|
|
70
|
+
// margin: 0 !important;
|
|
71
|
+
// margin-top: -3px !important;
|
|
72
|
+
// padding: 0 !important;
|
|
73
|
+
// border-radius: 0 0 4px 4px !important;
|
|
74
|
+
// }
|
|
75
|
+
`;function Ik(t){let s=2166136261;for(let r=0;r<t.length;r+=1)s^=t.charCodeAt(r),s=s+((s<<1)+(s<<4)+(s<<7)+(s<<8)+(s<<24))>>>0;return s.toString(16)}function Nf(t){const s=t.length>400?`${t.slice(0,200)}${t.slice(-200)}`:t;return`${t.length}:${Ik(s)}`}const Tk=(t,s,r)=>{const a=(r.side==="deletions"?t:s).split(`
|
|
76
|
+
`),l=Math.min(r.start,r.end),c=Math.max(r.start,r.end),d=Math.max(1,l),u=Math.min(a.length,c);return d>u?"":a.slice(d-1,u).join(`
|
|
77
|
+
`)},Ek=(t,s)=>t===s?!0:!t||!s?!1:t.start===s.start&&t.end===s.end&&t.side===s.side,Wi=new WeakMap,Pk={lineHeight:24,hunkSeparatorHeight:24,fileGap:0};function Rk(t){const s=t.closest("[data-diff-virtual-root]");if(s instanceof HTMLElement){const r=s.querySelector("[data-diff-virtual-content]");return{key:s,root:s,content:r instanceof HTMLElement?r:void 0}}return{key:document,root:document,content:void 0}}function Fk(t){if(typeof document>"u")return null;const s=Rk(t);let r=Wi.get(s.key);if(!r){const o=new dv;o.setup(s.root,s.content),r={virtualizer:o,refs:0},Wi.set(s.key,r)}r.refs+=1;let n=!1;return{virtualizer:r.virtualizer,release:()=>{if(n)return;n=!0;const o=Wi.get(s.key);o&&(o.refs-=1,!(o.refs>0)&&(o.virtualizer.cleanUp(),Wi.delete(s.key)))}}}const Bx=({original:t,modified:s,language:r,fileName:n,renderSideBySide:o,wrapLines:a,layout:l="fill"})=>{const c=Ta(),d=c?.currentTheme.metadata.variant==="dark",u=c?.availableThemes.find(H=>H.metadata.id===c.lightThemeId)??Bo(!1),m=c?.availableThemes.find(H=>H.metadata.id===c.darkThemeId)??Bo(!0);Te();const{isMobile:f}=ks(),p=Br(H=>H.addDraft),h=Br(H=>H.updateDraft),g=Br(H=>H.removeDraft),x=Br(H=>H.drafts),y=Ae(H=>H.currentSessionId),b=ne.useCallback(()=>y??"draft",[y]),[v,j]=ne.useState(null),[k,N]=ne.useState(""),[w,C]=ne.useState(null),S=ne.useRef(null),M=ne.useRef(null),D=ne.useRef(!1),A=ne.useRef(null);ne.useEffect(()=>{S.current=v},[v]),ne.useEffect(()=>{M.current=w},[w]);const P=ne.useCallback(H=>{if(D.current)return;const le=S.current;if(f&&le&&H&&H.side===le.side){const ge=Math.min(le.start,H.start),z=Math.max(le.end,H.end);j({...H,start:ge,end:z})}else j(H);H&&(M.current||N(""))},[f]),$=ne.useCallback(()=>{N(""),j(null),C(null)},[]),R=ne.useCallback(H=>H.type==="saved"||H.type==="edit"?`draft-${H.draft.id}`:H.type==="new"?"new-comment-input":"",[]),O=ne.useCallback(H=>{if(!H||!W.current)return null;const le=W.current.querySelector("diffs-container");if(!le)return null;const ge=le.shadowRoot?.querySelector(`[data-annotation-id="${H}"]`);if(ge)return ge;const z=le.querySelector(`[data-annotation-id="${H}"]`);if(z)return z;const J=W.current.querySelector(`[data-annotation-id="${H}"]`);return J||null},[]),T=ne.useCallback(H=>{const le=document.createElement("div");le.className="w-full my-2";const ge=H.metadata,z=R(ge);return le.dataset.annotationId=z,le},[R]),_=ne.useCallback((H,le)=>{const ge=le??v;if(!ge||!H.trim())return;const z=Math.min(ge.start,ge.end),J=Math.max(ge.start,ge.end),je={...ge,start:z,end:J},X=b();if(!X){K.error("Select a session to save comment");return}const G=je.side==="deletions"?"original":"modified",ae=Tk(t,s,je);w?h(X,w,{fileLabel:n||"unknown",startLine:je.start,endLine:je.end,side:G,code:ae,language:r,text:H.trim()}):p({sessionKey:X,source:"diff",fileLabel:n||"unknown",startLine:je.start,endLine:je.end,side:G,code:ae,language:r,text:H.trim()}),N(""),j(null),C(null)},[v,n,r,t,s,p,h,b,w]),F=ne.useCallback(H=>{j(H);const le=V.current;if(le)try{D.current=!0,le.setSelectedLines(H),A.current=H}catch{}finally{D.current=!1}},[]);Wl(u),Wl(m);const I=`${u.metadata.id}:${m.metadata.id}:${d?"dark":"light"}`,E=ne.useRef(null),W=ne.useRef(null),V=ne.useRef(null),ve=ne.useRef(null),[,oe]=i.useReducer(H=>H+1,0),Z=Xh(),ce=ne.useMemo(()=>yi(u),[u]),Q=ne.useMemo(()=>yi(m),[m]);i.useLayoutEffect(()=>{const H=E.current;if(!H)return;const le=H.querySelector("diffs-container");if(!le)return;const ge=d?Q:ce,z=(ye,he)=>ye.colors?.[he],J=z(ce,"terminal.ansiGreen"),je=z(ce,"terminal.ansiRed"),X=z(ce,"terminal.ansiBlue"),G=z(Q,"terminal.ansiGreen"),ae=z(Q,"terminal.ansiRed"),me=z(Q,"terminal.ansiBlue");le.style.setProperty("--shiki-light",ce.fg),le.style.setProperty("--shiki-light-bg",ce.bg),J&&le.style.setProperty("--shiki-light-addition-color",J),je&&le.style.setProperty("--shiki-light-deletion-color",je),X&&le.style.setProperty("--shiki-light-modified-color",X),le.style.setProperty("--shiki-dark",Q.fg),le.style.setProperty("--shiki-dark-bg",Q.bg),G&&le.style.setProperty("--shiki-dark-addition-color",G),ae&&le.style.setProperty("--shiki-dark-deletion-color",ae),me&&le.style.setProperty("--shiki-dark-modified-color",me),le.style.setProperty("--diffs-bg",ge.bg),le.style.setProperty("--diffs-fg",ge.fg);const Oe=d?G:J,Be=d?ae:je,fe=d?me:X;Oe&&le.style.setProperty("--diffs-addition-color-override",Oe),Be&&le.style.setProperty("--diffs-deletion-color-override",Be),fe&&le.style.setProperty("--diffs-modified-color-override",fe);const q=le.shadowRoot?.querySelector("pre");q&&(q.style.setProperty("--shiki-light",ce.fg),q.style.setProperty("--shiki-light-bg",ce.bg),J&&q.style.setProperty("--shiki-light-addition-color",J),je&&q.style.setProperty("--shiki-light-deletion-color",je),X&&q.style.setProperty("--shiki-light-modified-color",X),q.style.setProperty("--shiki-dark",Q.fg),q.style.setProperty("--shiki-dark-bg",Q.bg),G&&q.style.setProperty("--shiki-dark-addition-color",G),ae&&q.style.setProperty("--shiki-dark-deletion-color",ae),me&&q.style.setProperty("--shiki-dark-modified-color",me),q.style.setProperty("--diffs-bg",ge.bg),q.style.setProperty("--diffs-fg",ge.fg),Oe&&q.style.setProperty("--diffs-addition-color-override",Oe),Be&&q.style.setProperty("--diffs-deletion-color-override",Be),fe&&q.style.setProperty("--diffs-modified-color-override",fe))},[Q,I,d,ce]);const Y=ne.useMemo(()=>({theme:{dark:m.metadata.id,light:u.metadata.id},themeType:d?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"none",maxLineDiffLength:1e3,maxLineLengthForHighlighting:1e3,expansionLineCount:20,overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!0,enableHoverUtility:!1,onLineSelected:P,unsafeCSS:Dk,renderAnnotation:T}),[m.metadata.id,d,u.metadata.id,o,a,P,T]),ie=ne.useMemo(()=>{const H=b();if(!H)return[];const le=x[H]??[],ge=n||"unknown",z=le.filter(je=>je.source==="diff"&&je.fileLabel===ge),J=[];return z.forEach(je=>{const X=je.side==="original"?"deletions":"additions";je.id===w?J.push({lineNumber:je.endLine,side:X,metadata:{type:"edit",draft:je}}):J.push({lineNumber:je.endLine,side:X,metadata:{type:"saved",draft:je}})}),v&&!w&&J.push({lineNumber:v.end,side:v.side??"additions",metadata:{type:"new",selection:v}}),J},[x,b,n,w,v]),B=ne.useRef(ie);if(ne.useEffect(()=>{B.current=ie},[ie]),ne.useEffect(()=>{if(typeof window>"u")return;const H=W.current;if(!H||!Z)return;V.current?.cleanUp(),V.current=null,ve.current?.release(),ve.current=null,H.innerHTML="";const le=Fk(H);ve.current=le;const ge=le?new lv(Y,le.virtualizer,Pk,Z):new cv(Y,Z);V.current=ge,A.current=null;const z={name:n||"",contents:t,lang:r,cacheKey:`old:${I}:${n}:${Nf(t)}`},J={name:n||"",contents:s,lang:r,cacheKey:`new:${I}:${n}:${Nf(s)}`};return ge.render({oldFile:z,newFile:J,lineAnnotations:B.current,containerWrapper:H}),requestAnimationFrame(()=>oe()),()=>{ge.cleanUp(),V.current===ge&&(V.current=null),le?.release(),le&&ve.current===le&&(ve.current=null),H.innerHTML=""}},[I,n,r,s,Y,t,Z]),ne.useEffect(()=>{const H=V.current;H&&(H.setLineAnnotations(ie),requestAnimationFrame(()=>{if(V.current===H){try{H.rerender()}catch{}oe()}}))},[ie]),ne.useEffect(()=>{const H=V.current;if(!H||v!==null)return;const le=A.current;if(!Ek(v,le))try{D.current=!0,H.setSelectedLines(v),A.current=v}catch{}finally{D.current=!1}},[v]),ne.useEffect(()=>{const H=W.current;if(!H)return;let le=null,ge=()=>{};const z=()=>{const je=H.querySelector("diffs-container")?.shadowRoot;if(!je){le=requestAnimationFrame(z);return}const X=G=>{if(!(G instanceof MouseEvent)||G.button!==0||!(G.target instanceof Element))return;const ae=G.target.closest("[data-column-number]");if(!(ae instanceof HTMLElement))return;const me=ae.getAttribute("data-column-number"),Oe=me?parseInt(me,10):NaN;if(Number.isNaN(Oe))return;const fe=(ae.closest("[data-line-type]")?.getAttribute("data-line-type")??ae.getAttribute("data-line-type"))==="change-deletion"?"deletions":"additions";P({start:Oe,end:Oe,side:fe}),G.preventDefault(),G.stopPropagation()};je.addEventListener("click",X,!0),ge=()=>{je.removeEventListener("click",X,!0)}};return z(),()=>{le!==null&&cancelAnimationFrame(le),ge()}},[I,n,P]),ne.useEffect(()=>{const H=W.current;if(!H)return;let le=null,ge=null;const J=setTimeout(()=>{const je=H.querySelector("diffs-container");je&&(le=new MutationObserver(X=>{X.some(ae=>Array.from(ae.addedNodes).some(me=>me instanceof HTMLElement&&me.hasAttribute("data-annotation-id"))||Array.from(ae.removedNodes).some(me=>me instanceof HTMLElement&&me.hasAttribute("data-annotation-id")))&&(ge&&cancelAnimationFrame(ge),ge=requestAnimationFrame(()=>{oe(),ge=null}))}),je.shadowRoot&&le.observe(je.shadowRoot,{childList:!0,subtree:!0}),le.observe(je,{childList:!0,subtree:!0}))},100);return()=>{clearTimeout(J),ge&&cancelAnimationFrame(ge),le?.disconnect()}},[I,n]),typeof window>"u")return null;const se=ie.map(H=>{const le=H.metadata,ge=R(le),z=O(ge);return z?le.type==="saved"?co.createPortal(e.jsx(qu,{draft:le.draft,onEdit:()=>{const J=le.draft.side==="original"?"deletions":"additions";F({start:le.draft.startLine,end:le.draft.endLine,side:J}),N(le.draft.text),C(le.draft.id)},onDelete:()=>g(le.draft.sessionKey,le.draft.id)},ge),z,ge):le.type==="edit"?co.createPortal(e.jsx(Sa,{initialText:k,fileLabel:n?.split("/").pop()??"",lineRange:{start:le.draft.startLine,end:le.draft.endLine,side:le.draft.side==="original"?"deletions":"additions"},isEditing:!0,onSave:_,onCancel:$},ge),z,ge):co.createPortal(e.jsx(Sa,{initialText:k,fileLabel:n?.split("/").pop()??"",lineRange:v||void 0,isEditing:!1,onSave:_,onCancel:$},ge),z,ge):null});return l==="fill"?e.jsx("div",{className:L("flex flex-col relative","size-full"),"data-diff-virtual-root":!0,children:e.jsx("div",{className:"flex-1 relative min-h-0",children:e.jsx(Ut,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,"data-diff-virtual-content":!0,children:e.jsxs("div",{ref:E,className:"size-full relative",children:[e.jsx("div",{ref:W,className:"size-full"}),se]})})})}):e.jsx("div",{className:L("relative","w-full"),children:e.jsxs("div",{ref:E,className:"pierre-diff-wrapper w-full overflow-x-auto overflow-y-visible relative",children:[e.jsx("div",{ref:W,className:"w-full"}),se]})})},Lk=1100,zx=15e3,Ok=t=>t<=6?t:t<=12?6:t<=25?4:2,Ux={"?":{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"}},_k=Ux.M,gl=[{value:"single",label:"Single file",description:"Show one file at a time"},{value:"stacked",label:"All files",description:"Stack all modified files together"}],$k=t=>{const s=t.index?.trim(),r=t.working_dir?.trim();return s&&s!=="?"?s.charAt(0):r?r.charAt(0):s?.charAt(0)||r?.charAt(0)||"M"},Hx=t=>{const s=$k(t);return Ux[s]??_k},Bk=t=>{const{index:s,working_dir:r}=t;return s==="A"||r==="A"||s==="?"||r==="?"},ql=(t,s)=>{const r=t??0,n=s??0;return!r&&!n?null:e.jsxs("span",{className:"typography-meta flex flex-shrink-0 items-center gap-1 text-xs whitespace-nowrap",children:[r?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",r]}):null,n?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",n]}):null]})},zk=i.memo(({changedFiles:t,selectedFile:s,selectedFileEntry:r,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(us,{children:[e.jsx(ms,{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-interactive-hover hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[r?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(r.path)}),ql(r.insertions,r.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(is,{className:"size-4 opacity-50"})]})}),e.jsxs(fs,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:[a&&l&&c?e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"typography-meta text-muted-foreground",children:"View mode"}),e.jsx(Il,{value:l,onValueChange:u=>c(u),children:gl.map(u=>e.jsx(Tl,{value:u.value,className:"items-center",children:e.jsx("span",{className:"typography-meta text-foreground",children:u.label})},u.value))}),e.jsx(lr,{})]}):null,e.jsx(Il,{value:s??"",onValueChange:n,children:t.map(u=>e.jsx(Tl,{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:ql(u.insertions,u.deletions)})]})},u.path))})]})]})}),Uk=i.memo(({mode:t,onModeChange:s})=>{const r=gl.find(n=>n.value===t)??gl[0];return e.jsxs(us,{children:[e.jsx(ms,{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-interactive-hover hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("span",{className:"min-w-0 truncate typography-meta",children:r.label}),e.jsx(is,{className:"size-4 opacity-50"})]})}),e.jsx(fs,{className:"min-w-[220px]",children:e.jsx(Il,{value:t,onValueChange:n=>s(n),children:gl.map(n=>e.jsx(Tl,{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))})})]})}),Hk=i.memo(({changedFiles:t,selectedFile:s,onSelectFile:r})=>t.length===0?null:e.jsx(Ut,{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=Hx(n),a=s===n.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>r(n.path),className:L("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",a?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover 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}),ql(n.insertions,n.deletions)]})},n.path)})})})),Vk=i.memo(({filePath:t,diff:s,isVisible:r,renderSideBySide:n})=>{const o=s.original.length>0,a=s.modified.length>0;if(!r)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:s.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:s.modified,alt:`Modified: ${t}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Wk=i.memo(({filePath:t,diff:s,renderSideBySide:r})=>{const n=s.original.length>0,o=s.modified.length>0,a=r?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",l=r?"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:s.original,alt:`Original: ${t}`,className:r?"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:s.modified,alt:`Modified: ${t}`,className:r?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Gk=i.memo(({filePath:t,diff:s,renderSideBySide:r,wrapLines:n})=>{const o=i.useMemo(()=>Jn(t)||"text",[t]);return xi(t)?e.jsx(Wk,{filePath:t,diff:s,renderSideBySide:r}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(Bx,{original:s.original,modified:s.modified,language:o,fileName:t,renderSideBySide:r,wrapLines:n,layout:"inline"})})}),Kk=i.memo(({filePath:t,diff:s,isVisible:r,renderSideBySide:n,wrapLines:o})=>{const a=i.useMemo(()=>Jn(t)||"text",[t]);return r?xi(t)?e.jsx(Vk,{filePath:t,diff:s,isVisible:r,renderSideBySide:n}):e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(Bx,{original:s.original,modified:s.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})}):null}),qk=i.memo(({directory:t,filePath:s,isVisible:r,renderSideBySide:n,wrapLines:o})=>{const a=or(i.useCallback(c=>c.directories.get(t)?.diffCache.get(s)??null,[t,s])),l=i.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return l?e.jsx(Kk,{filePath:s,diff:l,isVisible:r,renderSideBySide:n,wrapLines:o}):null}),Qk=i.memo(({directory:t,file:s,layout:r,wrapLines:n,scrollRootRef:o,isSelected:a,onSelect:l,registerSectionRef:c,defaultCollapsed:d=!1})=>{const{git:u}=Vr(),m=or(i.useCallback(O=>O.directories.get(t)?.diffCache.get(s.path)??null,[t,s.path])),f=or(O=>O.setDiff),p=Te(O=>O.setDiffFileLayout),[h,g]=i.useState(!d),[x,y]=i.useState(!1),[b,v]=i.useState(0),[j,k]=i.useState(null),[N,w]=i.useState(!1),C=i.useRef(null),S=i.useRef(null),M=i.useMemo(()=>Hx(s),[s]),D=r==="side-by-side",A=i.useMemo(()=>m?{original:m.original,modified:m.modified}:null,[m]),P=i.useCallback(O=>{S.current=O,c(s.path,O)},[s.path,c]),$=i.useCallback(O=>{g(O),O&&y(!0)},[]),R=i.useCallback(()=>{l(s.path)},[s.path,l]);return i.useEffect(()=>{if(!h||x)return;const O=S.current;if(!O)return;if(!o.current||typeof IntersectionObserver>"u"){y(!0);return}const T=new IntersectionObserver(_=>{_.some(F=>F.isIntersecting)&&(y(!0),T.disconnect())},{root:o.current,rootMargin:"200px 0px",threshold:.1});return T.observe(O),()=>T.disconnect()},[x,h,o]),i.useEffect(()=>{if(!h||!x)return;if(!t||A){C.current=null,w(!1);return}const O=`${t}::${s.path}::${b}`;if(C.current===O)return;C.current=O,k(null),w(!0);let T=!1;return(async()=>{try{const _=u.getGitFileDiff(t,{path:s.path}),F=zx,I=new Promise((W,V)=>{setTimeout(()=>V(new Error(`Timed out after ${F}ms`)),F)}),E=await Promise.race([_,I]);if(T)return;f(t,s.path,{original:E.original??"",modified:E.modified??""}),w(!1)}catch(_){if(T)return;const F=_ instanceof Error?_.message:String(_);k(F),w(!1)}})(),()=>{T=!0,C.current===O&&(C.current=null)}},[t,A,b,s.path,u,x,h,f]),e.jsx("div",{ref:P,className:"scroll-mt-4",children:e.jsxs(tn,{open:h,onOpenChange:$,className:"group/collapsible",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background",children:e.jsxs(On,{onClick:R,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",h?"rounded-b-none":"rounded-b-xl",a?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[e.jsx("div",{className:L("absolute inset-0 pointer-events-none transition-colors",a?"bg-interactive-selection":"group-hover:bg-interactive-hover")}),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:h?e.jsx(is,{className:"size-4"}):e.jsx(dr,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:M.color},title:M.description,"aria-label":M.description,children:M.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",style:{direction:"rtl",textAlign:"left"},title:s.path,children:s.path})]}),e.jsxs("div",{className:"relative flex items-center gap-2",children:[ql(s.insertions,s.deletions),e.jsx(Lx,{mode:D?"side-by-side":"unified",onModeChange:O=>{const T=O==="side-by-side"?"side-by-side":"inline";p(s.path,T)},className:"opacity-70"})]})]})}),e.jsx(sn,{children:e.jsxs("div",{className:"relative border border-t-0 border-border/60 bg-background rounded-b-xl overflow-hidden",children:[j?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:j}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>v(O=>O+1),children:"Retry"})]}):null,N&&!A&&!j?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(Ot,{size:16,className:"animate-spin"}),"Loading diff…"]}):null,h&&A?e.jsx(Gk,{filePath:s.path,diff:A,renderSideBySide:D,wrapLines:n}):null]})})]})})}),Yk=()=>{const{git:t}=Vr(),s=Ci(),{screenWidth:r,isMobile:n}=ks(),o=Fx(s??null),a=Wu(s??null),l=or(z=>z.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=or(),[m,f]=i.useState(null),[p,h]=i.useState(0),[g,x]=i.useState(null),y=i.useRef(null),b=Te(z=>z.pendingDiffFile),v=Te(z=>z.setPendingDiffFile),j=Te(z=>z.diffLayoutPreference),k=Te(z=>z.diffFileLayout),N=Te(z=>z.setDiffFileLayout),w=Te(z=>z.diffWrapLines),C=Te(z=>z.setDiffWrapLines),S=Te(z=>z.diffViewMode),M=Te(z=>z.setDiffViewMode),D=n||w,A=S==="stacked",P=n||r<=768,$=!P&&r>=1024,R=i.useRef(null),O=i.useRef(new Map),T=i.useRef(null),_=i.useMemo(()=>{if(!a?.files)return[];const z=a.diffStats??{};return a.files.map(J=>({...J,insertions:z[J.path]?.insertions??0,deletions:z[J.path]?.deletions??0,isNew:Bk(J)})).sort((J,je)=>J.path.localeCompare(je.path))},[a]),F=i.useMemo(()=>m?_.find(z=>z.path===m)??null:null,[_,m]),I=i.useCallback(z=>{const J=k[z.path];if(J)return J;if(j==="inline")return"inline";if(j==="side-by-side")return"side-by-side";const je=r<Lk;return z.isNew||je?"inline":"side-by-side"},[k,j,r]),E=i.useMemo(()=>F?I(F):null,[I,F]);i.useEffect(()=>{s&&(c(s),or.getState().directories.get(s)?.status||d(s,t))},[s,c,d,t]),i.useEffect(()=>{b&&(f(b),v(null),A&&(T.current=b))},[A,b,v]),i.useEffect(()=>{!m&&!b&&_.length>0&&f(_[0].path)},[_,m,b]),i.useEffect(()=>{if(!A){T.current=null;return}const z=T.current;if(!z)return;const J=O.current.get(z);J&&(J.scrollIntoView({behavior:"smooth",block:"start"}),T.current=null)},[_,A]),i.useEffect(()=>{m&&_.length>0&&(_.some(J=>J.path===m)||f(_[0]?.path??null))},[_,m]);const W=i.useCallback((z,J)=>{const je=O.current;J?je.set(z,J):je.delete(z)},[]),V=i.useCallback((z,J="smooth")=>{const je=O.current.get(z);return je?(je.scrollIntoView({behavior:J,block:"start"}),!0):!1},[]),ve=i.useCallback(z=>{f(z)},[]),oe=i.useCallback(z=>{f(z),A&&!V(z)&&(T.current=z)},[A,V]),Z=i.useCallback(z=>{M(z),z==="stacked"&&m&&!V(m,"auto")&&(T.current=m)},[V,m,M]),ce=i.useCallback(z=>{const J=z==="side-by-side"?"side-by-side":"inline";if(A){_.forEach(je=>{N(je.path,J)});return}F&&N(F.path,J)},[_,A,F,N]),Q=(E??"side-by-side")==="side-by-side",Y=!A||!$,ie=or(i.useCallback(z=>!s||!m?null:z.directories.get(s)?.diffCache.get(m)??null,[s,m])),B=!!ie,se=!A&&!!m&&!B;i.useEffect(()=>{if(A)return;if(x(null),!s||!m){y.current=null;return}if(ie){y.current=null;return}const z=`${s}::${m}::${p}`;if(y.current===z)return;y.current=z;let J=!1;return(async()=>{try{const je=t.getGitFileDiff(s,{path:m}),X=zx,G=new Promise((me,Oe)=>{setTimeout(()=>Oe(new Error(`Timed out after ${X}ms`)),X)}),ae=await Promise.race([je,G]);if(J)return;u(s,m,{original:ae.original??"",modified:ae.modified??""})}catch(je){if(J)return;const X=je instanceof Error?je.message:String(je);x(X)}})(),()=>{J=!0,y.current===z&&(y.current=null)}},[s,A,m,ie,t,u,p]);const H=()=>!s||!m?null:e.jsx(qk,{directory:s,filePath:m,isVisible:!0,renderSideBySide:Q,wrapLines:D},m),le=()=>{if(!s)return null;const z=Ok(_.length);return e.jsxs("div",{className:"flex flex-1 min-h-0 h-full gap-3 px-3 pb-3 pt-2",children:[$&&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:_.length})]}),e.jsx(Hk,{changedFiles:_,selectedFile:m,onSelectFile:oe})]}),e.jsx(Ut,{ref:R,outerClassName:"flex-1 min-h-0 h-full",className:"pr-2",disableHorizontal:!0,"data-diff-virtual-root":!0,"data-diff-virtual-content":!0,children:e.jsx("div",{className:"flex flex-col gap-3",children:_.map((J,je)=>e.jsx(Qk,{directory:s,file:J,layout:I(J),wrapLines:D,scrollRootRef:R,isSelected:J.path===m,onSelect:ve,registerSectionRef:W,defaultCollapsed:je>=z},J.path))})})]})},ge=()=>s?l&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ot,{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."}):_.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"}):A?le():e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative","data-diff-virtual-root":!0,"data-diff-virtual-content":!0,children:[H(),se&&!B&&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(z=>z+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ot,{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(ec,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:l&&!a?"Loading changes…":`${_.length} ${_.length===1?"file":"files"} changed`})]}),!P&&e.jsx(Uk,{mode:S,onModeChange:Z}),Y&&e.jsx(zk,{changedFiles:_,selectedFile:m,selectedFileEntry:F,onSelectFile:oe,isMobile:P,showModeSelector:P,mode:S,onModeChange:Z}),e.jsx("div",{className:"flex-1"}),F&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>C(!w),className:L("h-5 w-5 p-0 transition-opacity",D?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:D?"Disable line wrap":"Enable line wrap",children:e.jsx(Rd,{className:"size-4"})}),F&&E&&e.jsx(Lx,{mode:E==="side-by-side"?"side-by-side":"unified",onModeChange:ce})]}),ge()]})},Jk=()=>{const{git:t}=Vr(),s=Ci(),{setActiveDirectory:r,fetchStatus:n}=or(),o=VN(s??null);return i.useEffect(()=>{s&&(r(s),or.getState().directories.get(s)?.status||n(s,t))},[s,r,n,t]),o},nr=ne.forwardRef(({className:t,...s},r)=>e.jsx(Zh,{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-[var(--interactive-focus-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-[var(--interactive-border)]",t),style:{width:"36px",height:"20px",minWidth:"36px",minHeight:"20px"},...s,ref:r,children:e.jsx(uv,{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"}})}));nr.displayName=Zh.displayName;const Xk={},xl=t=>{if(typeof t!="string")return null;const s=t.trim();if(!s)return null;const r=s.replace(/\\/g,"/");return r.length>1?r.replace(/\/+$/,""):r},kf=t=>xl(t)??"__global__",Zk=t=>{const s=Object.entries(t??{}),r=s.filter(([,l])=>l?.status==="connected").length,n=s.length,o=s.some(([,l])=>l?.status==="failed"),a=s.some(([,l])=>l?.status==="needs_auth"||l?.status==="needs_client_registration");return{connected:r,total:n,hasFailed:o,hasAuthRequired:a}},Hn=Ls()(Us((t,s)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:r=>{const n=kf(r??Yt.getState().currentDirectory);return s().byDirectory[n]??Xk},refresh:async r=>{const n=xl(r?.directory??Yt.getState().currentDirectory),o=kf(n);r?.silent||t(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const c=(await nt.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(r,n)=>{const o=xl(n??Yt.getState().currentDirectory);await nt.getApiClient().mcp.connect({name:r,...o?{directory:o}:{}},{throwOnError:!0}),await s().refresh({directory:o,silent:!0})},disconnect:async(r,n)=>{const o=xl(n??Yt.getState().currentDirectory);await nt.getApiClient().mcp.disconnect({name:r,...o?{directory:o}:{}},{throwOnError:!0}),await s().refresh({directory:o,silent:!0})}})));function eC(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 Vx=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}},Wx=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},Gx=({active:t,className:s})=>{const n=Yt(g=>g.currentDirectory)??null,o=Hn(g=>g.getStatusForDirectory(n)),a=Hn(g=>g.refresh),l=Hn(g=>g.connect),c=Hn(g=>g.disconnect),[d,u]=i.useState(!1),[m,f]=i.useState(null);i.useEffect(()=>{a({directory:n,silent:!0})},[a,n]),i.useEffect(()=>{t&&a({directory:n,silent:!0})},[t,a,n]);const p=i.useMemo(()=>Object.keys(o).sort((g,x)=>g.localeCompare(x)),[o]),h=i.useCallback(g=>{if(g?.preventDefault(),d)return;u(!0);const x=new Promise(y=>setTimeout(y,500));Promise.all([a({directory:n}),x]).finally(()=>{u(!1)})},[d,a,n]);return e.jsxs("div",{className:L("w-full",s),children:[e.jsx("div",{className:"sticky top-0 z-20 bg-[var(--surface-elevated)] border-b border-[var(--interactive-border)]",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 px-2 py-2.5",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:"MCP Servers"}),n&&e.jsx("div",{className:"truncate typography-ui-label text-muted-foreground",children:n.split("/").pop()||n})]}),e.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",disabled:d,onClick:h,"aria-label":"Refresh",children:e.jsx(Mr,{className:L("h-4 w-4",d&&"animate-spin")})})]})}),e.jsxs("div",{className:"max-h-64 overflow-y-auto py-1",children:[p.map(g=>{const x=o[g],y=Wx(x),b=x?.status==="connected",v=m===g,j=Vx(x);return e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-interactive-hover/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:[e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx("span",{className:L("h-2 w-2 rounded-full flex-shrink-0",y==="success"&&"bg-status-success",y==="error"&&"bg-status-error",y==="warning"&&"bg-status-warning",y==="default"&&"bg-muted-foreground/40"),"aria-label":j})}),e.jsx(ht,{side:"left",children:e.jsx("p",{children:j})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:g})]})}),e.jsx(nr,{checked:b,disabled:v,className:"data-[state=checked]:bg-status-info",onCheckedChange:async k=>{f(g);try{k?await l(g,n):await c(g,n)}finally{f(null)}}})]},g)}),p.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."})]})]})},Kx=({headerIconButtonClass:t})=>{const[s,r]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(!1),{isMobile:l}=ks(),d=Yt(S=>S.currentDirectory)??null,u=Hn(S=>S.getStatusForDirectory(d)),m=Hn(S=>S.refresh),f=Hn(S=>S.connect),p=Hn(S=>S.disconnect),h=i.useCallback(S=>{S||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),r(S)},[]),g=i.useCallback(S=>{a.current||o(S)},[]),[x,y]=i.useState(!1),[b,v]=i.useState(null);i.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),i.useEffect(()=>{s&&m({directory:d,silent:!0})},[s,m,d]);const j=i.useMemo(()=>Zk(u),[u]),k=i.useMemo(()=>Object.keys(u).sort((S,M)=>S.localeCompare(M)),[u]),N=i.useCallback(S=>{if(S?.preventDefault(),x)return;y(!0);const M=new Promise(D=>setTimeout(D,500));Promise.all([m({directory:d}),M]).finally(()=>{y(!1)})},[x,m,d]),w=()=>e.jsxs(e.Fragment,{children:[k.map(S=>{const M=u[S],D=Wx(M),A=M?.status==="connected",P=b===S,$=Vx(M);return e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-interactive-hover/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",D==="success"&&"bg-status-success",D==="error"&&"bg-status-error",D==="warning"&&"bg-status-warning",D==="default"&&"bg-muted-foreground/40"),"aria-label":$}):e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx("span",{className:L("h-2 w-2 rounded-full flex-shrink-0",D==="success"&&"bg-status-success",D==="error"&&"bg-status-error",D==="warning"&&"bg-status-warning",D==="default"&&"bg-muted-foreground/40"),"aria-label":$})}),e.jsx(ht,{side:"left",children:e.jsx("p",{children:$})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:S})]})}),e.jsx(nr,{checked:A,disabled:P,className:"data-[state=checked]:bg-status-info",onCheckedChange:async R=>{v(S);try{R?await f(S,d):await p(S,d)}finally{v(null)}}})]},S)}),k.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."})]}),C=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:L(t,"relative"),onClick:l?()=>r(!0):void 0,children:[e.jsx(eC,{className:"h-[1.0625rem] w-[1.0625rem]"}),j.total>0&&e.jsx("span",{className:L("absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full",j.hasFailed?"bg-status-error":j.hasAuthRequired?"bg-status-warning":j.connected>0?"bg-status-success":"bg-muted-foreground/40"),"aria-label":"MCP status"})]});return l?e.jsxs(e.Fragment,{children:[C,e.jsxs(Cr,{open:s,title:"MCP Servers",onClose:()=>r(!1),renderHeader:S=>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-interactive-hover transition-colors",disabled:x,onClick:N,"aria-label":"Refresh",children:e.jsx(Mr,{className:L("h-4 w-4",x&&"animate-spin")})}),S]})]}),children:[e.jsx("div",{className:"py-1",children:w()}),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(us,{open:s,onOpenChange:h,children:[e.jsxs(gt,{delayDuration:1e3,open:s?!1:n,onOpenChange:g,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:C})}),e.jsx(ht,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsx(fs,{align:"end",className:"w-72",children:e.jsx(Gx,{active:s})})]})},tC="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",sC=Object.assign({"../assets/provider-logos/gocode.svg":tC}),nu=new Map,rC=new Map([["codex","openai"],["claude","anthropic"]]);for(const[t,s]of Object.entries(sC)){const r=t.match(/provider-logos\/([^/]+)\.svg$/i);r?.[1]&&s&&nu.set(r[1].toLowerCase(),s)}function qx(t){const s=t?.toLowerCase()??null,r=s?rC.get(s)??s:null,n=r?nu.has(r):!1,o=r?nu.get(r)??null:null,[a,l]=ne.useState(n?"local":"remote");ne.useEffect(()=>{l(n?"local":"remote")},[n,r]);const c=ne.useCallback(()=>{l(d=>d==="local"&&n?"remote":"none")},[n]);return r?a==="local"&&o?{src:o,onError:c,hasLogo:!0}:a==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:c,hasLogo:!0}:{src:null,onError:c,hasLogo:!1}:{src:null,onError:c,hasLogo:!1}}const Os=({providerId:t,alt:s,className:r,onError:n})=>{const{src:o,onError:a,hasLogo:l}=qx(t),c=i.useCallback(()=>{a(),n?.()},[a,n]);return!l||!o?null:e.jsx("img",{src:o,alt:s||`${t} logo`,className:L("dark:invert",r),onError:c})},da=({percent:t,tonePercent:s,className:r,expectedMarkerPercent:n})=>{const o=Cx(t)??0,a=Mx(s??t),l=n!=null?Math.max(0,Math.min(100,n)):null,c=a==="critical"?{backgroundColor:"var(--status-error)"}:a==="warn"?{backgroundColor:"var(--status-warning)"}:{backgroundColor:"var(--status-success)"};return e.jsxs("div",{className:L("relative h-2.5 rounded-full bg-[var(--interactive-border)] overflow-hidden",r),children:[e.jsx("div",{className:"h-full transition-all duration-300",style:{...c,width:`${o}%`},role:"progressbar","aria-valuenow":o,"aria-valuemin":0,"aria-valuemax":100}),l!=null&&l>0&&l<100&&e.jsx("div",{className:"absolute top-0 h-full w-0.5 bg-foreground",style:{left:`${l}%`},title:`Expected usage if spread evenly: ${Math.round(l)}% of quota`,"aria-hidden":"true"})]})},ua=({paceInfo:t,className:s,compact:r=!1})=>{const n=wN(t.status),o=i.useMemo(()=>{switch(t.status){case"on-track":return"On track";case"slightly-fast":return"Slightly fast";case"too-fast":return"Too fast";case"exhausted":return"Used up"}},[t.status]),a=`Predicted usage at window end based on current pace: ${t.predictText}`;return r?e.jsxs("div",{className:L("flex items-center gap-1.5",s),children:[e.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0",style:{backgroundColor:n},title:o}),e.jsx("span",{className:"typography-micro tabular-nums",style:{color:n},title:t.isExhausted?void 0:a,children:t.isExhausted?e.jsxs(e.Fragment,{children:["Wait ",pf(t.remainingSeconds)]}):e.jsxs(e.Fragment,{children:["Pred: ",t.predictText]})})]}):e.jsxs("div",{className:L("flex items-center justify-between gap-2",s),children:[e.jsx("div",{className:"flex items-center gap-1.5",children:!t.isExhausted&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Pace: ",t.paceRateText]})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-micro tabular-nums",style:{color:n},children:t.isExhausted?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:o}),e.jsx("span",{className:"text-muted-foreground",children:" · Wait "}),e.jsx("span",{className:"font-medium",children:pf(t.remainingSeconds)})]}):e.jsxs("span",{title:a,children:[e.jsx("span",{className:"text-muted-foreground",children:"Pred: "}),e.jsx("span",{className:"font-medium",children:t.predictText})]})}),e.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0",style:{backgroundColor:n},title:o})]})]})};let Gi=0;function bs({...t}){return e.jsx(eg,{"data-slot":"dialog",...t})}function nC({...t}){return e.jsx(sg,{"data-slot":"dialog-portal",...t})}const Qx=ne.forwardRef(({className:t,...s},r)=>(ne.useEffect(()=>(Gi+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Gi=Math.max(0,Gi-1),Gi===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(bu,{ref:r,"data-slot":"dialog-overlay",className:L("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",t),...s})));Qx.displayName=bu.displayName;function vs({className:t,children:s,showCloseButton:r=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(nC,{"data-slot":"dialog-portal",children:[e.jsx(Qx,{className:"rounded-none"}),e.jsxs(tg,{"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:[s,r&&e.jsxs(mv,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-interactive-active data-[state=open]:text-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(hs,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function js({className:t,...s}){return e.jsx("div",{"data-slot":"dialog-header",className:L("flex flex-col gap-2 text-center sm:text-left",t),...s})}function Js({className:t,...s}){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),...s})}function Ss({className:t,...s}){return e.jsx(fv,{"data-slot":"dialog-title",className:L("typography-markdown leading-none font-semibold text-foreground",t),...s})}function Is({className:t,...s}){return e.jsx(rg,{"data-slot":"dialog-description",className:L("text-muted-foreground typography-ui-label",t),...s})}function Bt({className:t,type:s,...r}){return e.jsx("input",{type:s,"data-slot":"input",className:L("text-foreground border border-border/80 file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none flex h-9 w-full min-w-0 rounded-lg bg-transparent px-3 py-1 typography-markdown 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","hover:border-input","focus:ring-1 focus:ring-primary/50 focus:border-primary/70","aria-invalid:border-destructive aria-invalid:ring-destructive",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...r})}const Yu=t=>typeof t=="object"&&t!==null,xa=(t,s)=>{const r=t[s];return typeof r=="string"?r:null},Cf=(t,s)=>{const r=t[s];return typeof r=="number"&&Number.isFinite(r)?r:null},oC=t=>{if(!Yu(t))return null;const s=xa(t,"id"),r=xa(t,"label"),n=xa(t,"url");return!s||!r||!n?null:{id:s,label:r,url:n}},hc=()=>{if(!As())return null;const t=window.__TAURI__;return typeof t?.core?.invoke=="function"?t.core.invoke:null},Yx=async()=>{const t=hc();if(!t)return{hosts:[],defaultHostId:"local"};const s=await t("desktop_hosts_get");if(!Yu(s))return{hosts:[],defaultHostId:null};const r=s.hosts,n=Array.isArray(r)?r.map(oC).filter(a=>!!a):[],o=xa(s,"defaultHostId")||xa(s,"default_host_id")||xa(s,"defaultHostID");return{hosts:n,defaultHostId:o}},aC=async t=>{const s=hc();s&&await s("desktop_hosts_set",{config:{hosts:t.hosts,defaultHostId:t.defaultHostId}})},Mf=async t=>{const s=hc();if(!s)return{status:"unreachable",latencyMs:0};const r=await s("desktop_host_probe",{url:t});if(!Yu(r))return{status:"unreachable",latencyMs:0};const n=r.status,o=n==="ok"||n==="auth"||n==="unreachable"?n:"unreachable",a=Cf(r,"latencyMs")??Cf(r,"latency_ms")??0;return{status:o,latencyMs:a}},iC=async t=>{const s=hc();s&&await s("desktop_new_window_at_url",{url:t})},Er="local",dn=t=>{const s=t.trim();if(!s)return null;try{const r=new URL(s);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.origin}catch{try{const r=new URL(s.endsWith("/")?s:`${s}/`);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.origin}catch{return null}}},Af=t=>{const s=t.trim();return s&&(s.endsWith("/")?s:`${s}/`)},ri=()=>typeof window>"u"?"":window.__IKANBAN_LOCAL_ORIGIN__||window.location.origin,lC=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,cC=t=>t==="ok"?"bg-status-success":t==="auth"?"bg-status-warning":t==="unreachable"?"bg-status-error":"bg-muted-foreground/40",dC=t=>t==="ok"?"Connected":t==="auth"?"Auth required":t==="unreachable"?"Unreachable":"Unknown",uC=t=>t==="ok"?e.jsx(ss,{className:"h-4 w-4"}):t==="auth"?e.jsx(pv,{className:"h-4 w-4"}):t==="unreachable"?e.jsx(hv,{className:"h-4 w-4"}):e.jsx(gv,{className:"h-4 w-4"}),mC=()=>({id:Er,label:"Local",url:ri()}),fC=t=>{const s=typeof window>"u"?"":window.location.origin,r=ri(),n=dn(s)||s,o=dn(r)||r;if(n&&o&&n===o)return{id:Er,label:"Local",url:o};const a=t.find(l=>{const c=dn(l.url);return c&&c===n});return a?{id:a.id,label:a.label,url:dn(a.url)||a.url}:{id:"custom",label:n||"Instance",url:n}};function Jx({open:t,onOpenChange:s,embedded:r=!1,onHostSwitched:n}){const[o,a]=ne.useState([]),[l,c]=ne.useState(null),[d,u]=ne.useState({}),[m,f]=ne.useState(!1),[p,h]=ne.useState(!1),[g,x]=ne.useState(!1),[y,b]=ne.useState(null),[v,j]=ne.useState(""),[k,N]=ne.useState(null),[w,C]=ne.useState(""),[S,M]=ne.useState(""),[D,A]=ne.useState(""),[P,$]=ne.useState(""),[R,O]=ne.useState(!r),T=ne.useMemo(()=>{const H=mC(),le=o.map(ge=>({...ge,url:dn(ge.url)||ge.url}));return[H,...le]},[o]),_=ne.useMemo(()=>fC(T),[T]),F=ne.useMemo(()=>{const H=l||Er;return T.find(le=>le.id===H)?.label||"Local"},[T,l]),I=ne.useCallback(async(H,le)=>{if(As()){x(!0),j("");try{const ge=H.filter(z=>z.id!==Er);await aC({hosts:ge,defaultHostId:le}),a(ge),c(le)}catch(ge){j(ge instanceof Error?ge.message:"Failed to save")}finally{x(!1)}}},[]),E=ne.useCallback(async()=>{if(As()){f(!0),j("");try{const H=await Yx();a(H.hosts||[]),c(H.defaultHostId??null)}catch(H){j(H instanceof Error?H.message:"Failed to load"),a([]),c(null)}finally{f(!1)}}},[]),W=ne.useCallback(async H=>{if(As()){h(!0);try{const le=await Promise.all(H.map(async z=>{const J=dn(z.url);if(!J)return[z.id,{status:"unreachable",latencyMs:0}];const je=await Mf(J).catch(()=>({status:"unreachable",latencyMs:0}));return[z.id,{status:je.status,latencyMs:je.latencyMs}]})),ge={};for(const[z,J]of le)ge[z]=J;u(ge)}finally{h(!1)}}},[]);ne.useEffect(()=>{if(!t){N(null),C(""),M(""),A(""),$(""),O(!r),j("");return}E()},[r,t,E]),ne.useEffect(()=>{t&&W(T)},[t,T,W]);const V=ne.useCallback(async H=>{const le=H.id===Er?ri():dn(H.url)||"";if(!le)return;if(H.id!==Er&&As()){b(H.id);const z=await Mf(le).catch(()=>({status:"unreachable",latencyMs:0}));if(u(J=>({...J,[H.id]:{status:z.status,latencyMs:z.latencyMs}})),z.status==="unreachable"){K.error(`Instance "${H.label}" is unreachable`),b(null);return}}const ge=Af(le);n?.();try{window.location.assign(ge)}catch{window.location.href=ge}},[n]),ve=ne.useCallback(H=>{N(H.id),C(H.label),M(H.url),j("")},[]),oe=ne.useCallback(()=>{N(null),C(""),M("")},[]),Z=ne.useCallback(async()=>{if(!k)return;if(k===Er){oe();return}const H=dn(S);if(!H){j("Invalid URL (must be http/https)");return}const le=(w||H).trim(),ge=o.map(z=>z.id===k?{...z,label:le,url:H}:z);await I(ge,l),oe()},[oe,o,l,w,S,k,I]),ce=ne.useCallback(async()=>{const H=dn(P);if(!H){j("Invalid URL (must be http/https)");return}const le=(D||H).trim(),z=[{id:lC(),label:le,url:H},...o];await I(z,l),A(""),$(""),r&&O(!1)},[o,l,r,D,P,I]),Q=ne.useCallback(async H=>{if(H===Er)return;const le=o.filter(z=>z.id!==H);await I(le,l===H?Er:l)},[o,l,I]),Y=ne.useCallback(async H=>{await I(o,H===Er?Er:H)},[o,I]),ie=ne.useCallback(H=>{const le=H.id===Er?ri():dn(H.url)||"";if(!le)return;const ge=Af(le);iC(ge).catch(z=>{K.error("Failed to open new window",{description:z instanceof Error?z.message:String(z)})})},[]);if(!Lr())return null;const B=As(),se=e.jsxs(e.Fragment,{children:[r?e.jsx("div",{className:"flex-shrink-0 border-b border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 py-2.5",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Current"}),e.jsx("span",{className:"max-w-[9rem] truncate typography-ui-label text-muted-foreground",children:_.label}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Default"}),e.jsx("span",{className:"max-w-[9rem] truncate typography-ui-label text-muted-foreground",children:F})]}),e.jsx("button",{type:"button",className:L("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:()=>{W(T)},disabled:!B||m||p,"aria-label":"Refresh instances",children:e.jsx(Mr,{className:L("h-4 w-4",p&&"animate-spin")})})]})}):e.jsxs(js,{className:"flex-shrink-0",children:[e.jsxs(Ss,{className:"flex items-center gap-2",children:[e.jsx(vu,{className:"h-5 w-5"}),"Instance"]}),e.jsx(Is,{children:"Switch between Local and remote IKanban servers"})]}),!r&&e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current:"}),e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:_.label}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current default:"}),e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:F})]}),e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(Me,{type:"button",size:"sm",variant:"ghost",onClick:()=>{W(T)},disabled:!B||m||p,children:[e.jsx(Mr,{className:L("h-4 w-4",p&&"animate-spin")}),"Refresh"]})})]}),!B&&e.jsx("div",{className:"flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3",children:e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Instance switcher is limited on this page. Use Local to recover."})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"space-y-1",children:m?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading…"}):T.map(H=>{const le=H.id===Er,ge=H.id===_.id,z=(l||Er)===H.id,J=d[H.id]||null,je=k===H.id,X=le?ri():dn(H.url)||H.url;return e.jsxs("div",{className:L("group flex items-center gap-2 px-2.5 py-2 rounded-md overflow-hidden",je?"bg-interactive-hover/20":"hover:bg-interactive-hover/30"),children:[e.jsxs("button",{type:"button",className:L("flex items-center gap-2 flex-1 min-w-0 text-left",je&&"pointer-events-none opacity-70"),onClick:()=>{V(H)},disabled:y===H.id,"aria-label":`Switch to ${H.label}`,children:[e.jsx("span",{className:L("h-2 w-2 rounded-full flex-shrink-0",cC(J?.status??null))}),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("span",{className:L("typography-ui-label truncate","text-foreground"),children:H.label}),ge&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Current"}),e.jsxs("span",{className:"inline-flex items-center gap-1 typography-micro text-muted-foreground",children:[uC(J?.status??null),e.jsxs("span",{children:[dC(J?.status??null),J?.status==="ok"&&typeof J.latencyMs=="number"?` · ${Math.max(0,Math.round(J.latencyMs))}ms ping`:""]})]})]}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate font-mono",children:X})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!le&&e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-8 w-8 rounded-md inline-flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-interactive-hover transition-colors","aria-label":"Instance actions",disabled:g,onClick:G=>G.stopPropagation(),children:e.jsx(Qn,{className:"h-4 w-4"})})}),e.jsxs(fs,{align:"end",className:"w-fit min-w-28",children:[e.jsxs(Et,{onClick:G=>{G.stopPropagation(),ve(H)},disabled:g,children:[e.jsx(wu,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsxs(Et,{onClick:G=>{G.stopPropagation(),Q(H.id)},className:"text-destructive focus:text-destructive",disabled:g,children:[e.jsx(Nr,{className:"h-4 w-4 mr-1"}),"Delete"]})]})]}),le&&e.jsx("div",{className:"h-8 w-8 opacity-0 pointer-events-none","aria-hidden":"true"}),e.jsxs(gt,{delayDuration:700,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",className:L("h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors",z?"text-primary hover:text-primary/80":"text-muted-foreground/60 hover:text-primary/80"),onClick:()=>{Y(H.id)},"aria-label":z?"Default instance":"Set as default",disabled:g,children:z?e.jsx(Mn,{className:"h-4 w-4"}):e.jsx(Do,{className:"h-4 w-4"})})}),e.jsx(ht,{sideOffset:6,children:z?"Default":"Set as default"})]}),e.jsxs(gt,{delayDuration:700,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",className:L("h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors",J?.status==="unreachable"?"text-muted-foreground/30 cursor-not-allowed":"text-muted-foreground/60 hover:text-foreground"),onClick:G=>{G.stopPropagation(),ie(H)},disabled:J?.status==="unreachable","aria-label":"Open in new window",children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsx(ht,{sideOffset:6,children:J?.status==="unreachable"?"Instance unreachable":"Open in new window"})]})]})]},H.id)})})}),B&&k&&k!==Er&&e.jsxs("div",{className:"flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Edit instance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{type:"button",variant:"outline",size:"sm",onClick:oe,disabled:g,children:"Cancel"}),e.jsxs(Me,{type:"button",size:"sm",onClick:()=>{Z()},disabled:g,children:[g?e.jsx(Ot,{className:"h-4 w-4 animate-spin"}):null,"Save"]})]})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsx(Bt,{value:w,onChange:H=>C(H.target.value),placeholder:"Label",disabled:g}),e.jsx(Bt,{value:S,onChange:H=>M(H.target.value),placeholder:"https://host:port",disabled:g})]})]}),r&&!R?e.jsx("div",{className:"flex-shrink-0 border-t border-[var(--interactive-border)]",children:e.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-2 text-left text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors",onClick:()=>O(!0),disabled:!B||g,children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label",children:"Add instance"})]})}):e.jsxs("div",{className:L("flex-shrink-0",r?"border-t border-[var(--interactive-border)] px-2 py-2":"rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2.5"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Add instance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx(Me,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(!1),disabled:g,children:"Cancel"}),e.jsxs(Me,{type:"button",size:"sm",onClick:()=>{ce()},disabled:!B||g||!P.trim(),children:[g?e.jsx(Ot,{className:"h-4 w-4 animate-spin"}):null,"Add"]})]})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsx(Bt,{value:D,onChange:H=>A(H.target.value),placeholder:"Label (optional)",disabled:!B||g}),e.jsx(Bt,{value:P,onChange:H=>$(H.target.value),placeholder:"https://host:port",disabled:!B||g})]})]}),v&&e.jsx("div",{className:"flex-shrink-0 typography-meta text-status-error",children:v})]});return r?e.jsx("div",{className:"w-full max-h-[70vh] flex flex-col overflow-hidden gap-2",children:se}):e.jsx(bs,{open:t,onOpenChange:s,children:e.jsx(vs,{className:"w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3",children:se})})}function pC(){const[t,s]=ne.useState(!1);return Lr()?e.jsxs(e.Fragment,{children:[e.jsxs(Me,{type:"button",variant:"ghost",size:"sm","data-oc-host-switcher":!0,className:"w-full justify-center",onClick:()=>s(!0),children:[e.jsx(vu,{className:"h-4 w-4"}),"Switch instance"]}),e.jsx(Jx,{open:t,onOpenChange:s})]}):null}const hC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",gC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",so=[{id:"finder",label:"Finder",appName:"Finder",fallbackIconDataUrl:hC},{id:"terminal",label:"Terminal",appName:"Terminal",fallbackIconDataUrl:gC},{id:"iterm2",label:"iTerm2",appName:"iTerm"},{id:"ghostty",label:"Ghostty",appName:"Ghostty"},{id:"vscode",label:"VS Code",appName:"Visual Studio Code"},{id:"intellij",label:"IntelliJ",appName:"IntelliJ IDEA"},{id:"visual-studio",label:"Visual Studio",appName:"Visual Studio"},{id:"cursor",label:"Cursor",appName:"Cursor"},{id:"android-studio",label:"Android Studio",appName:"Android Studio"},{id:"pycharm",label:"PyCharm",appName:"PyCharm"},{id:"xcode",label:"Xcode",appName:"Xcode"},{id:"sublime-text",label:"Sublime",appName:"Sublime Text"},{id:"webstorm",label:"WebStorm",appName:"WebStorm"},{id:"rider",label:"Rider",appName:"Rider"},{id:"zed",label:"Zed",appName:"Zed"},{id:"phpstorm",label:"PhpStorm",appName:"PhpStorm"},{id:"eclipse",label:"Eclipse",appName:"Eclipse"},{id:"windsurf",label:"Windsurf",appName:"Windsurf"},{id:"vscodium",label:"VSCodium",appName:"VSCodium"},{id:"rustrover",label:"RustRover",appName:"RustRover"},{id:"trae",label:"Trae",appName:"Trae"}],ou="finder",Xx=new Set(["finder","terminal"]),Df=()=>so.filter(t=>Xx.has(t.id)),xC=()=>{if(typeof window>"u")return ou;const t=window.localStorage.getItem("openInAppId");return t&&so.some(s=>s.id===t)?t:ou},If=({label:t,iconDataUrl:s,fallbackIconDataUrl:r})=>{const[n,o]=i.useState(!1),a=t.trim().slice(0,1).toUpperCase()||"?",l=s||r;return l&&!n?e.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):e.jsx("span",{className:L("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},yC=({directory:t,className:s})=>{const[r,n]=i.useState(xC),[o,a]=i.useState(Df),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,f]=i.useState(!1),p=i.useRef(!0),h=i.useRef(!1),g=i.useRef(!1),x=i.useRef(!1),y=i.useRef(null),b=i.useRef(0);i.useEffect(()=>{if(typeof window>"u")return;const D=A=>{const P=A.detail,$=P&&typeof P.openInAppId=="string"&&P.openInAppId.length>0&&so.some(R=>R.id===P.openInAppId)?P.openInAppId:null;$&&(window.localStorage.setItem("openInAppId",$),n($))};return window.addEventListener("ikanban:settings-synced",D),()=>window.removeEventListener("ikanban:settings-synced",D)},[]),i.useEffect(()=>()=>{p.current=!1,y.current&&clearTimeout(y.current)},[]);const v=i.useCallback(D=>{x.current=D,c(D)},[]),j=As()&&Or(),k=i.useCallback(D=>{if(D.length===0){a(Df()),v(!1);return}const A=new Set(D.map(O=>O.name)),P=new Map(D.map(O=>[O.name,O.iconDataUrl??void 0])),R=so.filter(O=>A.has(O.appName)||Xx.has(O.id)).map(O=>({...O,iconDataUrl:P.get(O.appName)}));a(R),v(!0)},[v]),N=i.useCallback(async D=>{if(h.current||l&&!D)return;const A=so.map(P=>P.appName);y.current&&(clearTimeout(y.current),y.current=null),D&&v(!1),h.current=!0,f(!0),g.current=!1;try{const{apps:P,success:$,hasCache:R,isCacheStale:O}=await Ug(A,D);if(!p.current)return;if(u(R?O:!1),k(P),$){if(!R&&P.length===0&&b.current<3){const _=[800,1600,3200][b.current]??3200;b.current+=1,g.current=!0,y.current=setTimeout(()=>{N()},_);return}b.current=0,g.current=!1;return}if(b.current<3){const _=[1e3,3e3,7e3][b.current]??7e3;b.current+=1,g.current=!0,y.current=setTimeout(()=>{N()},_)}}finally{h.current=!1,g.current||f(!1)}},[k,l,v]);i.useEffect(()=>{if(!j||typeof window>"u")return;N();const D=()=>{N()};window.addEventListener("ikanban:app-ready",D);const A=$=>{const R=$.detail;Array.isArray(R)&&(b.current=3,g.current=!1,f(!1),u(!1),k(R))};return window.addEventListener("ikanban:installed-apps-updated",A),window.__ikanbanAppReady&&N(),()=>{window.removeEventListener("ikanban:app-ready",D),window.removeEventListener("ikanban:installed-apps-updated",A)}},[k,j,N]),i.useEffect(()=>{if(!j||typeof window>"u")return;const D=window.setTimeout(()=>{x.current||N()},5e3);return()=>window.clearTimeout(D)},[j,N]);const w=i.useMemo(()=>{const D=so.find(A=>A.id===r)??so.find(A=>A.id===ou)??so[0];if(D){const A=o.find(P=>P.appName===D.appName)?.iconDataUrl;return A?{...D,iconDataUrl:A}:D}return o[0]},[o,r]);if(!j||!t||o.length===0)return null;const C=async D=>{await zg(t,D.appName)},S=async D=>{n(D.id),typeof window<"u"&&window.localStorage.setItem("openInAppId",D.id),await xs({openInAppId:D.id}),await C(D)},M=async()=>{if(typeof navigator>"u")return;const D=t;let A=!1;if(navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(D),A=!0}catch{}if(!A){const P=document.createElement("textarea");P.value=D,P.setAttribute("readonly",""),P.style.position="absolute",P.style.left="-9999px",document.body.appendChild(P),P.select(),A=document.execCommand("copy"),document.body.removeChild(P)}A&&K.success("Path copied to clipboard")};return e.jsxs("div",{className:L("app-region-no-drag inline-flex h-7 items-center self-center rounded-md border border-[var(--interactive-border)]","bg-[var(--surface-elevated)] shadow-sm overflow-hidden",s),children:[e.jsxs("button",{type:"button",onClick:()=>{C(w)},className:L("inline-flex h-full items-center gap-2 px-3 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors"),"aria-label":`Open in ${w.label}`,children:[e.jsx(If,{label:w.label,iconDataUrl:w.iconDataUrl,fallbackIconDataUrl:w.fallbackIconDataUrl}),e.jsx("span",{className:L("header-open-label",m?"animate-pulse text-muted-foreground":void 0),children:"Open"})]}),e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx("button",{type:"button",className:L("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:e.jsx(is,{className:"h-4 w-4"})})}),e.jsxs(fs,{align:"end",className:"w-64 max-h-[70vh] overflow-y-auto",children:[e.jsxs(Et,{className:"flex items-center gap-2",onClick:()=>{M()},children:[e.jsx(Hr,{className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),e.jsx(lr,{}),o.map(D=>e.jsxs(Et,{className:"flex items-center gap-2",onClick:()=>{S(D)},children:[e.jsx(If,{label:D.label,iconDataUrl:D.iconDataUrl,fallbackIconDataUrl:D.fallbackIconDataUrl}),e.jsx("span",{className:"typography-ui-label text-foreground",children:D.label}),w.id===D.id?e.jsx(ss,{className:"ml-auto h-4 w-4 text-primary"}):null]},D.id)),d?e.jsxs(Et,{className:"flex items-center gap-2",onClick:()=>{N(!0)},children:[e.jsx(Mr,{className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},Tf=t=>{if(!t)return"-";try{return new Date(t).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}catch{return"-"}},yl=t=>{if(!t)return"";const s=t.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Ef=(t,s)=>{const r=yl(t),n=s.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!r||r==="/"?`/${n}`:`${r}/${n}`},bC=t=>Ef(Ef(t,".opencode"),"plans"),vC=()=>"~/.opencode/plans",wC=(t,s)=>{const r=t.trim();return r.startsWith("~")?r==="~"?s||r:(r.startsWith("~/")||r.startsWith("~\\"))&&s?`${s}${r.slice(1)}`:r:r},Pf=()=>{const t=Te(de=>de.setSessionSwitcherOpen),s=Te(de=>de.toggleSidebar),r=Te(de=>de.toggleBottomTerminal),n=Te(de=>de.toggleRightSidebar),o=Te(de=>de.setSettingsDialogOpen),a=Te(de=>de.activeMainTab),l=Te(de=>de.setActiveMainTab),{getCurrentModel:c}=ut(),d=Vr(),u=Ae(de=>de.getContextUsage),m=Ae(de=>de.currentSessionId),f=Ae(de=>de.sessions),p=ts(de=>de.results),h=ts(de=>de.fetchAllQuotas),g=ts(de=>de.isLoading),x=ts(de=>de.lastUpdated),y=ts(de=>de.displayMode),b=ts(de=>de.dropdownProviderIds),v=ts(de=>de.loadSettings),j=ts(de=>de.setDisplayMode),k=Yt(de=>de.homeDirectory),{isMobile:N}=ks(),w=Jk(),C=ac(de=>de.available),S=$r(de=>de.status),M=$r(de=>de.setStatus),D=i.useRef(null),[A,P]=i.useState(()=>typeof window>"u"?!1:Lr()),$=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),R=i.useMemo(()=>{if(typeof window>"u")return null;const de=window.__IKANBAN_MACOS_MAJOR__;if(typeof de=="number"&&Number.isFinite(de)&&de>0)return de;if(typeof navigator>"u")return null;const ke=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ke)return null;const We=Number.parseInt(ke[1],10),qe=Number.parseInt(ke[2],10);return Number.isNaN(We)?null:We===10?qe:We},[]);ne.useEffect(()=>{typeof window>"u"||P(Lr())},[]);const O=c(),T=O&&typeof O.limit=="object"&&O.limit!==null?O.limit:null,_=T&&typeof T.context=="number"?T.context:0,F=T&&typeof T.output=="number"?T.output:0,I=u(_,F),E=Te(de=>de.isSessionSwitcherOpen),W=S?.connected?S.user?.avatarUrl:null,V=S?.connected?S.user?.login:null,ve=S?.accounts??[],[oe,Z]=i.useState(!1),[ce,Q]=i.useState(!1),[Y,ie]=i.useState(!1),[B,se]=i.useState(!1),[H,le]=i.useState("Local"),[ge,z]=i.useState(A?"instance":"usage");ne.useEffect(()=>{!A&&ge==="instance"&&z("usage")},[ge,A]);const J=i.useCallback(async()=>{if(typeof window>"u"||!A)return;const de=ke=>{const We=ke.trim();if(!We)return null;try{const qe=new URL(We);return qe.protocol!=="http:"&&qe.protocol!=="https:"?null:qe.origin}catch{try{const qe=new URL(We.endsWith("/")?We:`${We}/`);return qe.protocol!=="http:"&&qe.protocol!=="https:"?null:qe.origin}catch{return null}}};try{const ke=await Yx(),We=window.location.origin,qe=window.__IKANBAN_LOCAL_ORIGIN__||We,et=de(We)||We,ct=de(qe)||qe;if(et&&ct&&et===ct){le("Local");return}const bt=ke.hosts.find(at=>{const _t=de(at.url);return _t&&_t===et});if(bt?.label?.trim()){le(bt.label.trim());return}le("Instance")}catch{le("Local")}},[A]);ne.useEffect(()=>{J()},[J]),Hu();const je=ts(de=>de.selectedModels),X=ts(de=>de.expandedFamilies),G=ts(de=>de.toggleFamilyExpanded),ae=i.useMemo(()=>{const de=[];for(const ke of yn){if(!b.includes(ke.id))continue;const We=p.find(at=>at.providerId===ke.id),qe=We?.usage?.windows??{},et=We?.usage?.models,ct=Object.entries(qe),bt={providerId:ke.id,providerName:ke.name,entries:ct,error:We&&!We.ok&&We.configured?We.error:void 0};if(et&&Object.keys(et).length>0){const at=je[ke.id]??[],_t=at.length>0,Nt=SN(et,ke.id),Gt=Ix(ke.id),zt=Tx(Gt);bt.modelFamilies=[];for(const Mt of zt){const Zt=Nt.get(Mt.id)??[];if(Zt.length===0)continue;const jt=_t?Zt.filter(Ye=>at.includes(Ye)):Zt;if(jt.length===0)continue;const es=[];for(const Ye of jt){const ft=et[Ye];if(ft?.windows){const vt=Object.entries(ft.windows);vt.length>0&&es.push([Ye,vt[0][1]])}}es.length>0&&bt.modelFamilies.push({familyId:Mt.id,familyLabel:Mt.label,models:es})}const Ct=Nt.get(null)??[],Qt=_t?Ct.filter(Mt=>at.includes(Mt)):Ct;if(Qt.length>0){const Mt=[];for(const Zt of Qt){const jt=et[Zt];if(jt?.windows){const es=Object.entries(jt.windows);es.length>0&&Mt.push([Zt,es[0][1]])}}Mt.length>0&&bt.modelFamilies.push({familyId:null,familyLabel:"Other",models:Mt})}}(ct.length>0||bt.modelFamilies&&bt.modelFamilies.length>0||bt.error)&&de.push(bt)}return de},[b,p,je]),me=ae.length>0;i.useEffect(()=>{v()},[v]);const Oe=i.useCallback(async de=>{j(de);try{await xs({usageDisplayMode:de})}catch(ke){console.warn("Failed to update usage display mode:",ke)}},[j]),Be=i.useCallback(()=>{if(B)return;se(!0);const de=new Promise(ke=>setTimeout(ke,500));Promise.all([h(),de]).finally(()=>{se(!1)})},[h,B]),fe=i.useMemo(()=>m?f.find(de=>de.id===m)??null:null,[m,f]),q=Ae(de=>m?de.worktreeMetadata.get(m)?.path??"":""),ye=i.useMemo(()=>yl(q||""),[q]),he=i.useMemo(()=>{const de=typeof fe?.directory=="string"?fe.directory:"";return yl(de||"")},[fe?.directory]),He=Ae(de=>de.newSessionDraft?.open?yl(de.newSessionDraft.directoryOverride??""):""),ot=i.useMemo(()=>ye||he||He,[He,he,ye]),[ue,Ve]=i.useState(!1),De=ue,we=i.useRef(""),Fe=i.useCallback(async de=>{if(!(!de||oe)){Z(!0);try{const ke=d.github?await d.github.authActivate(de):await(async()=>{const We=await fetch("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:de})}),qe=await We.json().catch(()=>null);if(!We.ok||!qe)throw new Error(qe?.error||We.statusText);return qe})();M(ke)}catch(ke){console.error("Failed to switch GitHub account:",ke)}finally{Z(!1)}}},[oe,d.github,M]);i.useEffect(()=>{let de=!1;const ke=async(ct,bt)=>{if(!ct||!bt||!d.files?.listDirectory)return!1;try{const at=await d.files.listDirectory(ct);return(Array.isArray(at?.entries)?at.entries:[]).some(Nt=>Nt?.name===bt&&!Nt?.isDirectory)}catch{return!1}},We=async()=>{if(de)return;if(!fe?.slug||!fe?.time?.created||!he){Ve(!1),Te.getState().activeMainTab==="plan"&&Te.getState().setActiveMainTab("chat");return}const ct=`${fe.time.created}-${fe.slug}.md`,bt=bC(he),at=wC(vC(),k||null),[_t,Nt]=await Promise.all([ke(bt,ct),ke(at,ct)]);if(de)return;const Gt=_t||Nt;Ve(Gt),!Gt&&Te.getState().activeMainTab==="plan"&&Te.getState().setActiveMainTab("chat")},qe=`${m||"none"}:${he||"none"}:${fe?.time?.created||0}:${fe?.slug||"none"}`;we.current!==qe&&(we.current=qe,Ve(!1)),We();const et=window.setInterval(()=>{We()},3e3);return()=>{de=!0,window.clearInterval(et)}},[he,fe?.slug,fe?.time?.created,m,k,d.files]);const Pe=i.useCallback(()=>{if(typeof document>"u")return;const de=document.activeElement;if(!de)return;const ke=de.tagName;(ke==="INPUT"||ke==="TEXTAREA"||ke==="SELECT"||de.isContentEditable)&&de.blur()},[]),$e=i.useCallback(()=>{if(N){Pe(),t(!E);return}s()},[Pe,N,E,t,s]),Ze=i.useCallback(()=>{N&&Pe(),t(!1),o(!0)},[Pe,N,t,o]),Ue="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-interactive-hover transition-colors",Ee=i.useMemo(()=>A&&$?"pl-[5.5rem]":"pl-3",[A,$]),Re=i.useMemo(()=>!A||!$||R===null?"":R>=26?"h-12":R<=15?"h-14":"",[A,$,R]),Xe=i.useCallback(()=>{if(typeof document>"u")return;const de=D.current?.getBoundingClientRect().height;de&&document.documentElement.style.setProperty("--oc-header-height",`${de}px`)},[]);ne.useEffect(()=>{if(typeof window>"u")return;Xe();const de=D.current;if(!de||typeof ResizeObserver>"u")return()=>{};const ke=new ResizeObserver(()=>{Xe()});return ke.observe(de),window.addEventListener("resize",Xe),window.addEventListener("orientationchange",Xe),()=>{ke.disconnect(),window.removeEventListener("resize",Xe),window.removeEventListener("orientationchange",Xe)}},[Xe]),ne.useEffect(()=>{Xe()},[Xe,N,Re]);const st=i.useCallback(async de=>{if(!de.target.closest("button, a, input, select, textarea")&&de.button===0&&A)try{const{getCurrentWindow:ke}=await Ks(async()=>{const{getCurrentWindow:qe}=await import("@tauri-apps/api/window");return{getCurrentWindow:qe}},[]);await ke().startDragging()}catch(ke){console.error("Failed to start window dragging:",ke)}},[A]),St=i.useCallback(async de=>{if(de.button===0&&A)try{const{getCurrentWindow:ke}=await Ks(async()=>{const{getCurrentWindow:qe}=await import("@tauri-apps/api/window");return{getCurrentWindow:qe}},[]);await ke().startDragging()}catch(ke){console.error("Failed to start window dragging:",ke)}},[A]),mt=i.useMemo(()=>{const de=[{id:"chat",label:"Chat",icon:og}];return De&&de.push({id:"plan",label:"Plan",icon:Eo}),de.push({id:"diff",label:"Diff",icon:"diff",badge:!N&&w>0?w:void 0},{id:"files",label:"Files",icon:Nn}),N&&de.push({id:"terminal",label:"Terminal",icon:fo},{id:"git",label:"Git",icon:Ms,showDot:w>0}),de},[w,N,De]);ne.useEffect(()=>{!N&&(a==="git"||a==="terminal")&&l("chat")},[a,N,l]);const Tt=i.useMemo(()=>{const de=[];return A&&de.push({value:"instance",label:"Instance",icon:vu}),de.push({value:"usage",label:"Usage",icon:Fd},{value:"mcp",label:"MCP",icon:xo}),de},[A]),qt=i.useMemo(()=>[{value:"usage",label:"Used"},{value:"remaining",label:"Remaining"}],[]);ne.useEffect(()=>{const de=ke=>{if(kr(ke)&&!ke.shiftKey&&!ke.altKey){const We=parseInt(ke.key,10);We>=1&&We<=mt.length&&(ke.preventDefault(),l(mt[We-1].id))}};return window.addEventListener("keydown",de),()=>window.removeEventListener("keydown",de)},[mt,l]);const yt=de=>{const ke=a===de.id,We=de.icon==="diff",qe=We?null:de.icon,et=de.id==="chat",ct=et&&!N&&I&&I.totalTokens>0,bt=Nt=>We?e.jsx(Cm,{size:Nt}):qe?e.jsx(qe,{size:Nt}):null,at=Nt=>Nt>=1e6?`${(Nt/1e6).toFixed(1)}M`:Nt>=1e3?`${(Nt/1e3).toFixed(1)}K`:Nt.toFixed(1).replace(/\.0$/,""),_t=e.jsxs("button",{type:"button",onClick:()=>l(de.id),onMouseDown:ke?St:void 0,className:L("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",ke?"app-region-drag bg-interactive-selection text-interactive-selection-foreground shadow-sm":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",et&&!N&&"min-w-[100px] justify-center"),"aria-label":de.label,"aria-selected":ke,role:"tab",children:[N?bt(20):e.jsxs(e.Fragment,{children:[bt(16),e.jsx("span",{className:"header-tab-label",children:de.label})]}),ct&&e.jsx("span",{className:"header-tab-badge",children:e.jsx("div",{className:L("app-region-no-drag flex items-center gap-1.5 text-muted-foreground/60 select-none typography-micro"),children:e.jsxs("span",{className:L("font-medium",I.percentage>=90?"text-status-error":I.percentage>=75?"text-status-warning":"text-status-success"),children:[Math.min(I.percentage,999).toFixed(1),"%"]})})}),de.badge!==void 0&&de.badge>0&&e.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:de.badge})]});if(ct){const Nt=typeof I.outputLimit=="number"?Math.max(I.outputLimit,0):0;return e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:_t}),e.jsx(ht,{children:e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("p",{className:"typography-micro leading-tight",children:["Used tokens: ",at(I.totalTokens)]}),e.jsxs("p",{className:"typography-micro leading-tight",children:["Context limit: ",at(I.contextLimit)]}),e.jsxs("p",{className:"typography-micro leading-tight",children:["Output limit: ",at(Nt)]})]})})]},de.id)}return e.jsx(i.Fragment,{children:_t},de.id)},os=()=>e.jsxs("div",{onMouseDown:st,className:L("app-region-drag relative flex h-12 select-none items-center",Ee,Re),role:"tablist","aria-label":"Main navigation",children:[e.jsx("button",{type:"button",onClick:$e,"aria-label":"Open sessions",className:`${Ue} mr-2`,children:e.jsx(Su,{className:"h-5 w-5"})}),e.jsx("div",{className:"flex items-center gap-1 p-1 bg-background/50 rounded-lg",children:mt.map(de=>yt(de))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsx(yC,{directory:ot,className:"mr-1"}),e.jsxs(us,{open:Y,onOpenChange:de=>{ie(de),de&&(J(),ge==="usage"&&p.length===0&&h())},children:[e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":A?`Open instance, usage and MCP (current: ${H})`:"Open services, usage and MCP",className:L(Ue,A?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-9 w-9"),children:[e.jsx(Ro,{className:"h-5 w-5"}),A&&e.jsx("span",{className:"truncate text-base font-normal",children:H})]})})}),e.jsx(ht,{children:e.jsx("p",{children:A?`Current instance: ${H}`:"Services"})})]}),e.jsxs(fs,{align:"end",className:"w-[min(30rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto bg-[var(--surface-elevated)] p-0",children:[e.jsx("div",{className:"sticky top-0 z-20 border-b border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2",children:e.jsx(di,{value:ge,onValueChange:de=>{z(de),de==="usage"&&p.length===0&&h()},tabs:Tt,className:"rounded-md"})}),A&&ge==="instance"&&e.jsx(Jx,{embedded:!0,open:Y&&ge==="instance",onOpenChange:()=>{},onHostSwitched:()=>ie(!1)}),ge==="mcp"&&e.jsx(Gx,{active:Y&&ge==="mcp"}),ge==="usage"&&e.jsxs("div",{className:"overflow-x-hidden",children:[e.jsx("div",{className:"bg-[var(--surface-elevated)] border-b border-[var(--interactive-border)]",children:e.jsxs(Wr,{className:"flex items-center justify-between gap-3 py-2.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Rate limits"}),e.jsxs("span",{className:"truncate typography-ui-label text-muted-foreground",children:["Last updated ",Tf(x)]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(di,{value:y,onValueChange:Oe,tabs:qt,size:"sm",className:"w-[8.25rem]"}),e.jsx("button",{type:"button",className:L("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:Be,disabled:g||B,"aria-label":"Refresh rate limits",children:e.jsx(Mr,{className:L("h-4 w-4",B&&"animate-spin")})})]})]})}),!me&&e.jsx(Et,{className:"cursor-default hover:bg-transparent focus:bg-transparent data-[highlighted]:bg-transparent",onSelect:de=>de.preventDefault(),children:e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"No rate limits available."})}),ae.map((de,ke)=>{const We=X[de.providerId]??[];return e.jsxs(i.Fragment,{children:[e.jsxs(Wr,{className:"flex items-center gap-2 border-b border-[var(--interactive-border)] bg-[var(--surface-elevated)] typography-ui-label text-foreground",children:[e.jsx(Os,{providerId:de.providerId,className:"h-4 w-4"}),de.providerName]}),de.entries.length===0&&(!de.modelFamilies||de.modelFamilies.length===0)?e.jsx(Et,{className:"cursor-default hover:bg-transparent focus:bg-transparent data-[highlighted]:bg-transparent",onSelect:qe=>qe.preventDefault(),children:e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:de.error??"No rate limits reported."})},`${de.providerId}-empty`):e.jsxs(e.Fragment,{children:[de.entries.map(([qe,et])=>{const ct=y==="remaining"?et.remainingPercent:et.usedPercent,bt=ca(et.usedPercent,et.resetAt,et.windowSeconds,qe),at=bt?.dailyAllocationPercent!=null?y==="remaining"?100-ln(bt.elapsedRatio):ln(bt.elapsedRatio):null;return e.jsx(Et,{className:"cursor-default items-start hover:bg-transparent focus:bg-transparent data-[highlighted]:bg-transparent",onSelect:_t=>_t.preventDefault(),children:e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[e.jsxs("span",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsxs("span",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:Hl(qe)}),et.resetAfterFormatted??et.resetAtFormatted?e.jsx("span",{className:"truncate typography-ui-label text-muted-foreground",children:et.resetAfterFormatted??et.resetAtFormatted}):null]}),e.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Sn(ct)==="-"?"":Sn(ct)})]}),e.jsx(da,{percent:ct,tonePercent:et.usedPercent,className:"h-1.5",expectedMarkerPercent:at}),bt&&e.jsx("div",{className:"mb-1",children:e.jsx(ua,{paceInfo:bt,compact:!0})})]})},`${de.providerId}-${qe}`)}),de.modelFamilies&&de.modelFamilies.length>0&&e.jsx("div",{className:"px-2 py-1",children:de.modelFamilies.map(qe=>{const et=We.includes(qe.familyId??"other");return e.jsxs(tn,{open:et,onOpenChange:()=>G(de.providerId,qe.familyId??"other"),children:[e.jsxs(On,{className:"flex w-full items-center justify-between py-1.5 text-left",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:qe.familyLabel}),et?e.jsx(is,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(dr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(sn,{children:e.jsx("div",{className:"space-y-1 pl-2",children:qe.models.map(([ct,bt])=>{const at=y==="remaining"?bt.remainingPercent:bt.usedPercent,_t=ca(bt.usedPercent,bt.resetAt,bt.windowSeconds),Nt=_t?.dailyAllocationPercent!=null?y==="remaining"?100-ln(_t.elapsedRatio):ln(_t.elapsedRatio):null;return e.jsx("div",{className:"py-1.5",children:e.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[e.jsxs("span",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Vl(ct)}),e.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Sn(at)==="-"?"":Sn(at)})]}),e.jsx(da,{percent:at,tonePercent:bt.usedPercent,className:"h-1.5",expectedMarkerPercent:Nt}),_t&&e.jsx("div",{className:"mb-1",children:e.jsx(ua,{paceInfo:_t,compact:!0})})]})},`${de.providerId}-${ct}`)})})})]},qe.familyId??"other")})})]}),ke<ae.length-1&&e.jsx(lr,{})]},de.providerId)})]})]})]}),e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:r,"aria-label":"Toggle terminal panel",className:Ue,children:e.jsx(fo,{className:"h-5 w-5"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Terminal panel"})})]}),e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Toggle git sidebar",className:Ue,children:e.jsx(ag,{className:"h-5 w-5"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Git sidebar"})})]}),S?.connected&&!N?ve.length>1?e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx("button",{type:"button",className:L(Ue,"h-8 w-8 p-0 overflow-hidden rounded-full border border-border/60 bg-muted/80"),title:V?`GitHub: ${V}`:"GitHub connected",disabled:oe,children:W?e.jsx("img",{src:W,alt:V?`${V} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(uo,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs(fs,{align:"end",className:"w-64",children:[e.jsx(Wr,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),e.jsx(lr,{}),ve.map(de=>{const ke=de.user,We=!!de.current;return e.jsxs(Et,{className:"gap-2",disabled:We||oe,onSelect:()=>{We||Fe(de.id)},children:[ke?.avatarUrl?e.jsx("img",{src:ke.avatarUrl,alt:ke.login?`${ke.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(uo,{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:ke?.name?.trim()||ke?.login||"GitHub"}),ke?.login?e.jsx("span",{className:"typography-micro text-muted-foreground truncate font-mono",children:ke.login}):null]}),We?e.jsx(ss,{className:"h-4 w-4 text-primary"}):null]},de.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:V?`GitHub: ${V}`:"GitHub connected",children:W?e.jsx("img",{src:W,alt:V?`${V} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(uo,{className:"h-4 w-4 text-muted-foreground"})}):null]})]}),cs=()=>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 shrink-0",children:[E?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-interactive-active","aria-label":"Back",children:e.jsx(ju,{className:"h-5 w-5"})}):e.jsx("button",{onClick:$e,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-interactive-active","aria-label":"Open sessions",children:e.jsx(xv,{className:"h-5 w-5"})}),!E&&I&&I.totalTokens>0&&a==="chat"&&e.jsx(Px,{totalTokens:I.totalTokens,percentage:I.percentage,contextLimit:I.contextLimit,outputLimit:I.outputLimit??0,size:"compact",isMobile:!0}),E&&e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),!E&&e.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:e.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain",children:e.jsxs("div",{className:"flex w-max items-center gap-1 pr-1",children:[e.jsx("div",{className:"flex items-center gap-0.5",role:"tablist","aria-label":"Main navigation",children:mt.map(de=>{const ke=a===de.id,We=de.icon==="diff",qe=We?null:de.icon;return e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{N&&Pe(),l(de.id)},"aria-label":de.label,"aria-selected":ke,role:"tab",className:L(Ue,"relative",ke&&"bg-interactive-selection text-interactive-selection-foreground"),children:[We?e.jsx(Cm,{className:"h-5 w-5"}):qe?e.jsx(qe,{className:"h-5 w-5"}):null,de.badge!==void 0&&de.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:de.badge}),de.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(ht,{children:e.jsx("p",{children:de.label})})]},de.id)})}),e.jsx(Kx,{headerIconButtonClass:Ue}),e.jsxs(us,{open:ce,onOpenChange:de=>{Q(de),de&&p.length===0&&h()},children:[e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"View rate limits",className:Ue,disabled:g,children:e.jsx(Fd,{className:"h-5 w-5"})})})}),e.jsx(ht,{children:e.jsx("p",{children:"Rate limits"})})]}),e.jsx(fs,{align:"end",sideOffset:0,className:"h-dvh w-[100vw] max-h-none rounded-none border-0 p-0 overflow-hidden",children:e.jsxs("div",{className:"flex h-full flex-col bg-[var(--surface-elevated)]",children:[e.jsxs("div",{className:"sticky top-0 z-20 border-b border-[var(--interactive-border)] bg-[var(--surface-elevated)]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-3",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Rate limits"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center rounded-md border border-[var(--interactive-border)] p-0.5",children:[e.jsx("button",{type:"button",className:L("px-1.5 py-0.5 rounded-sm typography-micro text-[9px] transition-colors",y==="usage"?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:text-foreground"),onClick:()=>Oe("usage"),"aria-label":"Show used quota",children:"Used"}),e.jsx("button",{type:"button",className:L("px-1.5 py-0.5 rounded-sm typography-micro text-[9px] transition-colors",y==="remaining"?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:text-foreground"),onClick:()=>Oe("remaining"),"aria-label":"Show remaining quota",children:"Remaining"})]}),e.jsx("button",{type:"button",className:L("inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:()=>h(),disabled:g,"aria-label":"Refresh rate limits",children:e.jsx(Mr,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:()=>Q(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover","aria-label":"Close rate limits",children:e.jsx(hs,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"px-3 pb-3 text-right typography-micro text-muted-foreground text-[8px]",children:["Last updated ",Tf(x)]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden pb-[calc(4rem+env(safe-area-inset-bottom))]",children:[!me&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No rate limits available."}),ae.map(de=>e.jsxs(i.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-[var(--surface-elevated)] px-3 py-2",children:[e.jsx(Os,{providerId:de.providerId,className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:de.providerName})]}),de.entries.length===0&&(!de.modelFamilies||de.modelFamilies.length===0)&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:de.error??"No rate limits reported."}),de.entries.map(([ke,We])=>{const qe=y==="remaining"?We.remainingPercent:We.usedPercent,et=ca(We.usedPercent,We.resetAt,We.windowSeconds,ke),ct=et?.dailyAllocationPercent!=null?y==="remaining"?100-ln(et.elapsedRatio):ln(et.elapsedRatio):null;return e.jsxs("div",{className:"px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Hl(ke)}),e.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Sn(qe)})]}),e.jsx(da,{percent:qe,tonePercent:We.usedPercent,className:"mt-2 h-1",expectedMarkerPercent:ct}),et&&e.jsx("div",{className:"mt-1.5",children:e.jsx(ua,{paceInfo:et,compact:!0})}),e.jsx("div",{className:"mt-1 typography-micro text-muted-foreground text-[10px]",children:We.resetAfterFormatted??We.resetAtFormatted??""})]},`${de.providerId}-${ke}`)}),de.modelFamilies&&de.modelFamilies.length>0&&e.jsx("div",{className:"px-2 py-1",children:de.modelFamilies.map(ke=>{const qe=(X[de.providerId]??[]).includes(ke.familyId??"other");return e.jsxs(tn,{open:qe,onOpenChange:()=>G(de.providerId,ke.familyId??"other"),children:[e.jsxs(On,{className:"flex w-full items-center justify-between py-2 text-left",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:ke.familyLabel}),qe?e.jsx(is,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(dr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(sn,{children:e.jsx("div",{className:"space-y-2 pl-2",children:ke.models.map(([et,ct])=>{const bt=y==="remaining"?ct.remainingPercent:ct.usedPercent,at=ca(ct.usedPercent,ct.resetAt,ct.windowSeconds),_t=at?.dailyAllocationPercent!=null?y==="remaining"?100-ln(at.elapsedRatio):ln(at.elapsedRatio):null;return e.jsxs("div",{className:"py-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Vl(et)}),e.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Sn(bt)==="-"?"":Sn(bt)})]}),e.jsx(da,{percent:bt,tonePercent:ct.usedPercent,className:"mt-1.5 h-1",expectedMarkerPercent:_t}),at&&e.jsx("div",{className:"mt-1",children:e.jsx(ua,{paceInfo:at,compact:!0})})]},`${de.providerId}-${et}`)})})})]},ke.familyId??"other")})})]},de.providerId))]})]})})]}),e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:Ze,"aria-label":"Open settings",className:L(Ue,"relative"),children:[e.jsx(Po,{className:"h-5 w-5"}),C&&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(ht,{children:e.jsx("p",{children:C?"Settings (Update available)":"Settings"})})]})]})})})]}),ds=L("header-safe-area border-b border-border/50 relative z-10",A?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:D,className:ds,style:{"--padding-scale":"1"},children:N?cs():os()})},Wc=180,Gc=640,jC=110,SC=({isOpen:t,isMobile:s,children:r})=>{const n=Te(k=>k.bottomTerminalHeight),o=Te(k=>k.setBottomTerminalHeight),a=Te(k=>k.setBottomTerminalOpen),[l,c]=i.useState(!1),[d,u]=i.useState(null),[m,f]=i.useState(!1),p=i.useRef(null),h=i.useRef(0),g=i.useRef(n||300),x=i.useRef(n||300),y=i.useMemo(()=>Math.min(Gc,Math.max(Wc,n||300)),[n]);if(i.useEffect(()=>{t||(c(!1),u(null),f(!1))},[t]),i.useEffect(()=>{if(s||!t||!l)return;const k=()=>{const C=p.current?.parentElement?.getBoundingClientRect().height;if(!C||C<=0)return;const S=Math.round(C);u(M=>M===S?M:S)};k();const N=p.current?.parentElement;if(!N)return;const w=new ResizeObserver(k);return w.observe(N),()=>{w.disconnect()}},[l,s,t]),i.useEffect(()=>{if(s||!m||l)return;const k=w=>{const C=h.current-w.clientY,S=Math.min(Gc,Math.max(Wc,g.current+C));o(S)},N=()=>{f(!1),Te.getState().bottomTerminalHeight<=jC&&a(!1)};return window.addEventListener("pointermove",k),window.addEventListener("pointerup",N,{once:!0}),()=>{window.removeEventListener("pointermove",k),window.removeEventListener("pointerup",N)}},[l,s,m,o,a]),s)return null;const b=t?l?Math.max(y,d??y):y:0,v=k=>{!t||l||(f(!0),h.current=k.clientY,g.current=b,k.preventDefault())},j=()=>{if(t){if(l){c(!1);const k=Math.min(Gc,Math.max(Wc,x.current));o(k);return}x.current=y,c(!0)}};return e.jsxs("section",{ref:p,className:L("relative flex overflow-hidden border-t border-border bg-sidebar",m?"transition-none":"transition-[height] duration-300 ease-in-out",!t&&"border-t-0"),style:{height:`${b}px`,minHeight:`${b}px`,maxHeight:`${b}px`},"aria-hidden":!t||b===0,children:[t&&!l&&e.jsx("div",{className:L("absolute left-0 top-0 z-20 h-[4px] w-full cursor-row-resize hover:bg-primary/50 transition-colors",m&&"bg-primary"),onPointerDown:v,role:"separator","aria-orientation":"horizontal","aria-label":"Resize terminal panel"}),t&&e.jsxs("div",{className:"absolute right-2 top-2 z-30 inline-flex items-center gap-1",children:[e.jsx("button",{type:"button",onClick:j,className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-[var(--surface-muted-foreground)] transition-colors hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",title:l?"Restore terminal panel height":"Expand terminal panel","aria-label":l?"Restore terminal panel height":"Expand terminal panel",children:l?e.jsx(Ld,{className:"h-5 w-5"}):e.jsx(ig,{className:"h-5 w-5"})}),e.jsx("button",{type:"button",onClick:()=>a(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-[var(--surface-muted-foreground)] transition-colors hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",title:"Close terminal panel","aria-label":"Close terminal panel",children:e.jsx(hs,{className:"h-6 w-6"})})]}),e.jsx("div",{className:L("relative z-10 flex h-full min-h-0 w-full flex-col transition-opacity duration-300 ease-in-out",!t&&"pointer-events-none select-none opacity-0"),"aria-hidden":!t,children:r})]})};function Ju({className:t,...s}){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),...s})}function Zx({className:t,...s}){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),...s})}function ey({className:t,...s}){return e.jsx("div",{"data-slot":"card-title",className:L("leading-none font-semibold",t),...s})}function ty({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:L("px-6",t),...s})}class Gs extends i.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,r){this.setState({error:s,errorInfo:r})}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(Ju,{className:"w-full max-w-md",children:[e.jsx(Zx,{className:"text-center",children:e.jsxs(ey,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(kl,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(ty,{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-interactive-hover/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(Me,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(jr,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}const NC=i.createContext(!1),Yr=({children:t,className:s,skipAnimation:r})=>{const n=i.useContext(NC),o=r||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",s),children:t})},Rf=(t,s)=>{const r=t[Symbol.toPrimitive];if(typeof r=="function")try{if(r()===s)return t}catch{}try{Object.defineProperty(t,"toString",{value:()=>s,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(t,Symbol.toPrimitive,{value:()=>s,enumerable:!1,configurable:!0})}catch{}return t},kC=()=>{const t=Ta(),s=gs()&&typeof window<"u",r=Bo(!1),n=Bo(!0),o=t?.lightThemeId??r.metadata.id,a=t?.darkThemeId??n.metadata.id,l=t?.availableThemes.find(p=>p.metadata.id===o)??r,c=t?.availableThemes.find(p=>p.metadata.id===a)??n,d=i.useMemo(()=>ik(l,c),[c,l]),u=i.useCallback(()=>{if(!s)return d;const p=window.__IKANBAN_VSCODE_SHIKI_THEMES__;if(p?.light&&p?.dark){const h=Rf({...p.light},`vscode-shiki-light:${String(p.light?.name??"theme")}`),g=Rf({...p.dark},`vscode-shiki-dark:${String(p.dark?.name??"theme")}`);return[h,g]}return d},[d,s]),[m,f]=i.useState(u);return i.useEffect(()=>{s&&f(u())},[u,s]),i.useEffect(()=>{if(!s)return;const p=h=>{f(u())};return window.addEventListener("ikanban:vscode-shiki-themes",p),()=>window.removeEventListener("ikanban:vscode-shiki-themes",p)},[u,s]),s?m:d},sy=t=>{const s=[],r=[],n=t.querySelector("thead");n&&n.querySelectorAll("th").forEach(l=>s.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())),r.push(d)}),{headers:s,rows:r}},ry=({headers:t,rows:s})=>{const r=o=>o.includes(",")||o.includes('"')||o.includes(`
|
|
78
|
+
`)?`"${o.replace(/"/g,'""')}"`:o,n=[];return t.length>0&&n.push(t.map(r).join(",")),s.forEach(o=>n.push(o.map(r).join(","))),n.join(`
|
|
79
|
+
`)},CC=({headers:t,rows:s})=>{const r=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return t.length>0&&n.push(t.map(r).join(" ")),s.forEach(o=>n.push(o.map(r).join(" "))),n.join(`
|
|
80
|
+
`)},MC=({headers:t,rows:s})=>{if(t.length===0)return"";const r=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${t.map(r).join(" | ")} |`),n.push(`| ${t.map(()=>"---").join(" | ")} |`),s.forEach(o=>{const a=t.map((l,c)=>r(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
|
|
81
|
+
`)},AC=(t,s,r)=>{const n=new Blob([s],{type:r}),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)},DC=({tableRef:t})=>{const[s,r]=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=sy(d),m=c==="csv"?ry(u):CC(u);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([m],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),r(!0),o(!1),setTimeout(()=>r(!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-interactive-hover/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:s?e.jsx(ss,{className:"size-3.5"}):e.jsx(Hr,{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-interactive-hover/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-interactive-hover/40",onClick:()=>l("tsv"),children:"TSV"})]})]})},IC=({tableRef:t})=>{const[s,r]=i.useState(!1),n=i.useRef(null);i.useEffect(()=>{const a=l=>{n.current&&!n.current.contains(l.target)&&r(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const l=t.current?.querySelector("table");if(l)try{const c=sy(l),d=a==="csv"?ry(c):MC(c);AC(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),r(!1)}catch(c){console.error("Failed to download table:",c)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>r(!s),className:"p-1 rounded hover:bg-interactive-hover/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(po,{className:"size-3.5"})}),s&&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-interactive-hover/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-interactive-hover/40",onClick:()=>o("markdown"),children:"Markdown"})]})]})},TC=({children:t,className:s})=>{const r=i.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:r,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(DC,{tableRef:r}),e.jsx(IC,{tableRef:r})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:L("w-full border-collapse border border-border",s),"data-streamdown":"table",children:t})})]})},EC=({children:t,className:s,style:r,...n})=>{const[o,a]=i.useState(!1),l=i.useRef(null),c=i.useMemo(()=>{if(!r)return r;const m={...r},f=g=>{if(typeof g!="string")return{value:void 0,vars:{}};const[x,...y]=g.split(";").map(v=>v.trim()).filter(Boolean),b={};for(const v of y){const j=v.indexOf(":");if(j===-1)continue;const k=v.slice(0,j).trim(),N=v.slice(j+1).trim();!k.startsWith("--")||N.length===0||(b[k]=N)}return{value:x,vars:b}},p=f(r.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(r.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},[r]),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(s),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-interactive-hover/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(ss,{className:"size-3.5"}):e.jsx(Hr,{className:"size-3.5"})})})]})},PC={pre:EC,table:TC},zr=({content:t,className:s,variant:r="assistant"})=>{const n=kC(),o=r==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:L("break-words",s),children:e.jsx(yv,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:PC,children:t})})},Ff="https://github.com/btriapitsyn/ikanban/releases";function RC(t){const s=new Date(`${t}T00:00:00`);return Number.isNaN(s.getTime())?t:new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric"}).format(s)}function FC(t){return t.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function LC(t,s){const r=t.split(".").map(o=>Number.parseInt(o,10)),n=s.split(".").map(o=>Number.parseInt(o,10));for(let o=0;o<3;o+=1){const a=Number.isFinite(r[o])?r[o]:0,l=Number.isFinite(n[o])?n[o]:0;if(a!==l)return l-a}return 0}function OC(t){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,r=[];let n;for(;(n=s.exec(t))!==null;)r.push({version:n[1]??"",date:n[2]??"",start:n.index});return r.length===0?[]:r.map((o,a)=>{const l=r[a+1]?.start??t.length,c=t.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}async function _C(){try{const t=await fetch("/api/ikanban/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 $C(t=30,s=2e3){for(let r=0;r<t;r++){try{if((await fetch("/health",{method:"GET"})).ok)return!0}catch{}await new Promise(n=>setTimeout(n,s))}return!1}const au=({open:t,onOpenChange:s,info:r,downloading:n,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=ne.useState(!1),[p,h]=ne.useState("idle"),[g,x]=ne.useState(null),y=r?.version?`${Ff}/tag/v${r.version}`:Ff,b=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",j=r?.updateCommand||"ikanban update";ne.useEffect(()=>{t||(h("idle"),x(null))},[t]);const k=async()=>{try{await navigator.clipboard.writeText(j),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},N=ne.useCallback(async()=>{h("updating"),x(null);const S=await _C();if(!S.success){h("error"),x(S.error||"Update failed");return}h("restarting"),await new Promise(D=>setTimeout(D,2e3)),h("reconnecting"),await $C()?window.location.reload():(h("error"),x("Server did not restart. Please refresh manually or run: ikanban restart"))},[]),w=p!=="idle"&&p!=="error",C=ne.useMemo(()=>{if(!r?.body)return null;const S=r.body.trim();if(!S)return null;const M=OC(S);return M.length===0?{kind:"raw",title:"What's new",content:S}:{kind:"sections",title:"What's new",sections:[...M].sort((A,P)=>LC(A.version,P.version)).map(A=>({version:A.version,dateLabel:RC(A.date),content:FC(A.raw)||S}))}},[r?.body]);return e.jsx(bs,{open:t,onOpenChange:w?void 0:s,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(js,{children:e.jsxs(Ss,{className:"flex items-center gap-2",children:[e.jsx(bv,{className:"h-5 w-5 text-primary"}),p==="restarting"||p==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(r?.currentVersion||r?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r?.currentVersion&&e.jsx("span",{className:"font-mono",children:r.currentVersion}),r?.currentVersion&&r?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),r?.version&&e.jsx("span",{className:"font-mono text-primary",children:r.version})]}),v&&w&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ol,{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."})]}),C&&!w&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between gap-3",children:e.jsx("div",{className:"typography-ui-label font-medium text-foreground/90",children:C.title})}),e.jsx(Ut,{className:L("max-h-56 rounded-md border border-border/70","bg-background/40 p-3"),fillContainer:!1,children:C.kind==="raw"?e.jsx(zr,{content:C.content,className:"typography-markdown-body text-foreground/90 leading-relaxed pr-3 break-words"}):e.jsx("div",{className:"space-y-4 pr-3",children:C.sections.map((S,M)=>e.jsxs("div",{className:L(M>0&&"border-t border-border/40 pt-3"),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:L("typography-ui-badge font-mono","bg-primary/10 text-primary","px-2 py-0.5 rounded-md"),children:["v",S.version]}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:S.dateLabel})]}),e.jsx(zr,{content:S.content,className:"typography-markdown-body text-foreground/90 leading-relaxed break-words"})]},S.version))})})]}),v&&p==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(vv,{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:j}),e.jsx("button",{onClick:k,className:L("flex items-center justify-center p-2 rounded-md","text-muted-foreground hover:text-foreground hover:bg-interactive-hover","transition-colors",m&&"text-primary"),title:m?"Copied!":"Copy command",children:m?e.jsx(ss,{className:"h-4 w-4"}):e.jsx(Cl,{className:"h-4 w-4"})})]})]}),!v&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[b,"%"]})]}),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:`${b}%`}})})]}),(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:y,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-interactive-hover","transition-colors"),children:[e.jsx(gn,{className:"h-4 w-4"}),"GitHub"]}),!v&&!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(po,{className:"h-4 w-4"}),"Download Update"]}),!v&&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(ol,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&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(jr,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!w&&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(po,{className:"h-4 w-4"}),"Update Now"]}),v&&w&&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(ol,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Lf=264,Of=200,_f=500,$f="ikanban:check-for-updates",BC=({isOpen:t,isMobile:s,children:r})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:l,toggleHelpDialog:c}=Te(),[d,u]=i.useState(!1),m=i.useRef(0),f=i.useRef(n||Lf),[p,h]=i.useState(!1),g=ac(),x=i.useRef(!1),y=g.checkForUpdates,{available:b,downloaded:v,checking:j}=g,[k,N]=i.useState(()=>typeof window>"u"?!1:!!window.__TAURI__);if(i.useEffect(()=>{typeof window>"u"||N(!!window.__TAURI__)},[]),i.useEffect(()=>{if(typeof window>"u")return;const S=()=>{window.__TAURI__&&(x.current=!0,y())};return window.addEventListener($f,S),()=>{window.removeEventListener($f,S)}},[y]),i.useEffect(()=>{x.current&&(j||(b||v?h(!0):K.success("No updates available",{description:"You are running the latest version."}),x.current=!1))},[b,v,j]),i.useEffect(()=>{if(s||!d)return;const S=D=>{const A=D.clientX-m.current,P=Math.min(_f,Math.max(Of,f.current+A));o(P)},M=()=>{u(!1)};return window.addEventListener("pointermove",S),window.addEventListener("pointerup",M,{once:!0}),()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",M)}},[s,d,o]),i.useEffect(()=>{s&&d&&u(!1)},[s,d]),s)return null;const w=t?Math.min(_f,Math.max(Of,n||Lf)):0,C=S=>{t&&(u(!0),m.current=S.clientX,f.current=w,S.preventDefault())};return e.jsxs("aside",{className:L("relative flex h-full overflow-hidden border-r border-border",k?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",d?"transition-none":"transition-[width] duration-300 ease-in-out",!t&&"border-r-0"),style:{width:`${w}px`,minWidth:`${w}px`,maxWidth:`${w}px`,overflowX:"clip"},"aria-hidden":!t||w===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",d&&"bg-primary"),onPointerDown:C,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:`${w}px`,overflowX:"hidden"},"aria-hidden":!t,children:[e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Gs,{children:r})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border h-12 px-2 bg-sidebar",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-interactive-hover","transition-all duration-200"),children:[e.jsx(Po,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[b||v?e.jsxs("button",{onClick:()=>h(!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(po,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!k&&e.jsxs(gt,{children:[e.jsx(xt,{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-interactive-hover","transition-all duration-200"),children:e.jsx(cr,{className:"h-4 w-4"})})}),e.jsx(ht,{side:"top",children:"About IKanban"})]}),e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{onClick:c,className:L("flex h-8 w-8 items-center justify-center rounded-md","text-sidebar-foreground/70","hover:text-sidebar-foreground hover:bg-interactive-hover","transition-all duration-200"),"aria-label":"Keyboard shortcuts",children:e.jsx(Fo,{className:"h-4 w-4"})})}),e.jsx(ht,{side:"top",children:"Keyboard shortcuts"})]})]})]})}),e.jsx(au,{open:p,onOpenChange:h,info:g.info,downloading:g.downloading,downloaded:g.downloaded,progress:g.progress,error:g.error,onDownload:g.downloadUpdate,onRestart:g.restartToUpdate,runtimeType:g.runtimeType})]})]})},Bf=400,zf=860,zC=({isOpen:t,isMobile:s,children:r})=>{const n=Te(f=>f.rightSidebarWidth),o=Te(f=>f.setRightSidebarWidth),[a,l]=i.useState(!1),c=i.useRef(0),d=i.useRef(n||420);if(i.useEffect(()=>{if(s||!a)return;const f=h=>{const g=c.current-h.clientX,x=Math.min(zf,Math.max(Bf,d.current+g));o(x)},p=()=>{l(!1)};return window.addEventListener("pointermove",f),window.addEventListener("pointerup",p,{once:!0}),()=>{window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",p)}},[s,a,o]),i.useEffect(()=>{s&&a&&l(!1)},[s,a]),s)return null;const u=t?Math.min(zf,Math.max(Bf,n||420)):0,m=f=>{t&&(l(!0),c.current=f.clientX,d.current=u,f.preventDefault())};return e.jsxs("aside",{className:L("relative flex h-full overflow-hidden border-l border-border bg-sidebar",a?"transition-none":"transition-[width] duration-300 ease-in-out",!t&&"border-l-0"),style:{width:`${u}px`,minWidth:`${u}px`,maxWidth:`${u}px`,overflowX:"clip"},"aria-hidden":!t||u===0,children:[t&&e.jsx("div",{className:L("absolute left-0 top-0 z-20 h-full w-[4px] cursor-col-resize hover:bg-primary/50 transition-colors",a&&"bg-primary"),onPointerDown:m,role:"separator","aria-orientation":"vertical","aria-label":"Resize right panel"}),e.jsx("div",{className:L("relative z-10 flex h-full min-h-0 w-full flex-col transition-opacity duration-300 ease-in-out",!t&&"pointer-events-none select-none opacity-0"),"aria-hidden":!t,children:t?r:null})]})};function Mi({className:t,...s}){return e.jsx(Ho,{"data-slot":"command",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:L("flex h-full w-full flex-col overflow-hidden rounded-xl",t),...s})}function UC({title:t="Command Palette",description:s="Search for a command to run...",children:r,className:n,showCloseButton:o=!0,...a}){return e.jsxs(bs,{...a,children:[e.jsxs(js,{className:"sr-only",children:[e.jsx(Ss,{children:t}),e.jsx(Is,{children:s})]}),e.jsx(vs,{className:L("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Mi,{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:r})})]})}const Ea=ne.forwardRef(({className:t,...s},r)=>e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(Rr,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Ho.Input,{ref:r,"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),...s})]}));Ea.displayName="CommandInput";function Ai({className:t,children:s,scrollbarClassName:r,disableHorizontal:n,...o}){return e.jsx(Ut,{as:Ho.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:r??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:n??!0,...o,children:s})}function Di({...t}){return e.jsx(Ho.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...t})}function hn({className:t,...s}){return e.jsx(Ho.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),...s})}function ya({className:t,...s}){return e.jsx(Ho.Separator,{"data-slot":"command-separator",className:L("bg-border -mx-1 h-px",t),...s})}function Qs({className:t,...s}){return e.jsx(Ho.Item,{"data-slot":"command-item",className:L("data-[selected=true]:bg-interactive-selection data-[selected=true]:text-interactive-selection-foreground data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_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),...s})}function $n({className:t,...s}){const r=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(xo,{className:"size-3.5"}):l==="shift"||l==="⇧"?e.jsx(ii,{className:"size-3.5"}):e.jsx("span",{className:"text-xs font-medium",children:a})},n=typeof s.children=="string"?s.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),...s,children:o.length>0?o.map((a,l)=>e.jsxs(ne.Fragment,{children:[l>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),r(a)]},`${a}-${l}`)):s.children})}const Uf=["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"],Hf=["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 ny(){const t=Uf[Math.floor(Math.random()*Uf.length)],s=Hf[Math.floor(Math.random()*Hf.length)];return`${t}-${s}`}function oy(t){return ny()}const Vf=t=>{const s=String(t||"").trim().replace(/^remotes\//,"");if(!s)return null;const r=s.indexOf("/");return r<=0||r>=s.length-1?null:{remote:s.slice(0,r),branch:s.slice(r+1)}},ba=t=>String(t||"").trim().replace(/^refs\/heads\//,"").replace(/^heads\//,"").replace(/^remotes\//,""),HC=t=>t.branchName?ba(t.branchName):t.mode==="existing"?ba(t.existingBranch||t.preferredName||""):ba(t.preferredName||""),Xu=async t=>{const s=await Wo(t);try{const n=(await _u(t)).branches?.[s]?.tracking||null,o=Vf(n);if(o?.remote)return o.remote}catch{}try{const r=await Ou(t),n=Vf(r.tracking);if(n?.remote)return n.remote}catch{}return null},VC=async(t,s)=>{const r=await Xu(t),n=ba(s);return!r||!n?null:{setUpstream:!0,upstreamRemote:r,upstreamBranch:n}},WC=async(t,s,r)=>{const n=HC(s),o=r?.resolvedRootTrackingRemote,a=o===void 0?await VC(t,n):o&&ba(n)?{setUpstream:!0,upstreamRemote:o,upstreamBranch:ba(n)}:null;return a?{...s,setUpstream:s.setUpstream??a.setUpstream,upstreamRemote:s.upstreamRemote||a.upstreamRemote,upstreamBranch:s.upstreamBranch||a.upstreamBranch}:s},gc=async(t,s,r)=>{const n=await WC(t.path,s,r);return U0(t,n)},Ua=t=>t.replace(/\\/g,"/").replace(/\/+$/,"")||t,GC=t=>{const s=Ua(t),r=ps.getState().projects;if(r.length===0)return null;const n=ps.getState().getActiveProject();if(n?.path){const l=Ua(n.path);if(s===l||s.startsWith(`${l}/`))return{id:n.id,path:n.path}}const a=r.filter(l=>{const c=Ua(l.path);return s===c||s.startsWith(`${c}/`)}).sort((l,c)=>Ua(c.path).length-Ua(l.path).length)[0];return a?{id:a.id,path:a.path}:null};let Gn=!1;async function xc(){if(Gn)return null;const t=ps.getState().getActiveProject();if(!t?.path)return K.error("No active project",{description:"Please select a project first."}),null;const s=t.path;let r=!1;try{r=await Yn(s)}catch{}if(!r)return K.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Gn=!0,Gr("Creating new worktree session...");try{const n={id:t.id,path:s},o=oy(),a=await Ia(n),l=await Wo(n.path),c=await gc(n,{preferredName:o,mode:"new",branchName:o,worktreeName:o,setupCommands:a}),d={...c,createdFromBranch:l,kind:"standard"},u=await Ni(c.path).catch(()=>{}),m=u?{...d,status:u}:d,f=Ae.getState(),p=await f.createSession(void 0,c.path);if(!p)return await fc(n,c,{deleteLocalBranch:!0}).catch(()=>{}),K.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const h=ut.getState(),g=h.agents;f.initializeNewIKanbanSession(p.id,g),f.setSessionDirectory(p.id,c.path),f.setWorktreeMetadata(p.id,m);try{const x=h.getVisibleAgents();let y;if(h.settingsDefaultAgent){const b=x.find(v=>v.name===h.settingsDefaultAgent);b&&(y=b.name)}if(y||(y=x.find(b=>b.name==="build")?.name||x[0]?.name),y){h.setAgent(y),Lt.getState().saveSessionAgentSelection(p.id,y);const b=h.settingsDefaultModel;if(b){const v=b.split("/");if(v.length===2){const[j,k]=v;if(h.getModelMetadata(j,k)){Lt.getState().saveSessionModelSelection(p.id,j,k),Lt.getState().saveAgentModelForSession(p.id,y,j,k);const w=h.settingsDefaultVariant;if(w){const M=h.providers.find(D=>D.id===j)?.models.find(D=>D.id===k)?.variants;M&&Object.prototype.hasOwnProperty.call(M,w)&&(h.setCurrentVariant(w),Lt.getState().saveAgentModelVariantForSession(p.id,y,j,k,w))}}}}}}catch{}Yt.getState().setDirectory(c.path,{showOverlay:!1});try{await f.loadSessions()}catch{}return K.success("Worktree created",{description:c.branch?`Branch: ${c.branch}`:"Ready"}),p}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return K.error("Failed to create worktree",{description:o}),null}finally{Fr(),Gn=!1}}async function ay(){if(Gn)return null;const t=ps.getState().getActiveProject();if(!t?.path)return K.error("No active project",{description:"Please select a project first."}),null;const s=t.path;let r=!1;try{r=await Yn(s)}catch{}if(!r)return K.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Gn=!0,Gr("Creating new worktree...");try{const n={id:t.id,path:s},o=oy(),a=await Ia(n),l=await gc(n,{preferredName:o,mode:"new",branchName:o,worktreeName:o,setupCommands:a}),c=await Wo(n.path).catch(()=>{}),d=await Ni(l.path).catch(()=>{}),u=l.branch||l.label||l.name;return K.success("Worktree created",{description:u?`${u}${c?` from ${c}`:""}`:d?.isDirty?"Created (dirty)":"Ready"}),await Ae.getState().loadSessions(),l.path}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree";return K.error("Failed to create worktree",{description:o}),null}finally{Fr(),Gn=!1}}async function iy(t,s,r,n){if(Gn)return null;Gn=!0,Gr("Creating worktree session...");try{const o=r?.trim()||"HEAD",a=s?.trim();if(!a)throw new Error("Branch name is required");const l=n?.kind??"standard",c=GC(t);if(!c)throw new Error("Project is not registered in IKanban");let d=!1;try{d=await Yn(c.path)}catch{}if(!d)return K.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;const u=await Ia(c),m=await Wo(c.path);try{const f=await gc(c,{preferredName:a,mode:"new",branchName:a,worktreeName:n?.worktreeName||a,startRef:o,setUpstream:n?.setUpstream,upstreamRemote:n?.upstreamRemote,upstreamBranch:n?.upstreamBranch,ensureRemoteName:n?.ensureRemoteName,ensureRemoteUrl:n?.ensureRemoteUrl,setupCommands:u}),p={...f,createdFromBranch:n?.createdFromBranch||m||o,kind:l},h=await Ni(f.path).catch(()=>{}),g=h?{...p,status:h}:p,x=Ae.getState(),y=await x.createSession(void 0,f.path);if(!y)throw await fc(c,f,{deleteLocalBranch:!0}).catch(()=>{}),new Error("Could not create a session for the worktree.");const b=ut.getState();x.initializeNewIKanbanSession(y.id,b.agents),x.setSessionDirectory(y.id,f.path),x.setWorktreeMetadata(y.id,g);try{const v=b.getVisibleAgents();let j;if(b.settingsDefaultAgent){const k=v.find(N=>N.name===b.settingsDefaultAgent);k&&(j=k.name)}if(j||(j=v.find(k=>k.name==="build")?.name||v[0]?.name),j){b.setAgent(j),Lt.getState().saveSessionAgentSelection(y.id,j);const k=b.settingsDefaultModel;if(k){const N=k.split("/");if(N.length===2){const[w,C]=N;if(b.getModelMetadata(w,C)){Lt.getState().saveSessionModelSelection(y.id,w,C),Lt.getState().saveAgentModelForSession(y.id,j,w,C);const M=b.settingsDefaultVariant;if(M){const P=b.providers.find($=>$.id===w)?.models.find($=>$.id===C)?.variants;P&&Object.prototype.hasOwnProperty.call(P,M)&&(b.setCurrentVariant(M),Lt.getState().saveAgentModelVariantForSession(y.id,j,w,C,M))}}}}}}catch{}Yt.getState().setDirectory(f.path,{showOverlay:!1});try{await x.loadSessions()}catch{}return K.success("Worktree created",{description:f.branch?`Branch: ${f.branch}`:"Ready"}),{id:y.id,branch:f.branch||a}}catch(f){const p=f instanceof Error?f.message:"Failed to create worktree session";return K.error("Failed to create worktree",{description:p}),null}}finally{Fr(),Gn=!1}}async function KC(t,s,r,n){return iy(t,s,r,{kind:n?.kind,worktreeName:n?.worktreeName,setUpstream:n?.setUpstream,upstreamRemote:n?.upstreamRemote,upstreamBranch:n?.upstreamBranch,ensureRemoteName:n?.ensureRemoteName,ensureRemoteUrl:n?.ensureRemoteUrl,createdFromBranch:n?.createdFromBranch})}const qC=()=>{const{isCommandPaletteOpen:t,setCommandPaletteOpen:s,setHelpDialogOpen:r,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:l,toggleSidebar:c}=Te(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=Ae(),f=ut(F=>F.settingsAutoCreateWorktree),{currentDirectory:p}=Yt(),{themeMode:h,setThemeMode:g}=rn(),x=()=>{s(!1)},y=async()=>{n("chat"),a(!1),d(),x()},b=F=>{u(F),x()},v=F=>{g(F),x()},j=()=>{r(!0),x()},k=()=>{x(),xc()},{isMobile:N}=ks(),w=()=>{if(N){const{isSessionSwitcherOpen:F}=Te.getState();a(!F)}else c();x()},C=()=>{n("diff"),x()},S=()=>{n("git"),x()},M=()=>{n("terminal"),x()},D=()=>{o(!0),x()},A=()=>{l(!0),x()},{projects:P,activeProjectId:$,setActiveProject:R}=ps(),O=F=>{R(F),x()},T=m(p??""),_=i.useMemo(()=>T.slice(0,5),[T]);return e.jsxs(UC,{open:t,onOpenChange:s,children:[e.jsx(Ea,{placeholder:"Type a command or search..."}),e.jsxs(Ai,{children:[e.jsx(Di,{children:"No results found."}),e.jsxs(hn,{heading:"Actions",children:[e.jsxs(Qs,{onSelect:w,children:[e.jsx(Su,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs($n,{children:[Ys()," + L"]})]}),e.jsxs(Qs,{onSelect:y,children:[e.jsx(Fs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx($n,{children:f?`Shift + ${Ys()} + N`:`${Ys()} + N`})]}),e.jsxs(Qs,{onSelect:k,children:[e.jsx(Ms,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx($n,{children:f?`${Ys()} + N`:`Shift + ${Ys()} + N`})]}),e.jsxs(Qs,{onSelect:j,children:[e.jsx(Fo,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs($n,{children:[Ys()," + ."]})]}),e.jsxs(Qs,{onSelect:C,children:[e.jsx(xn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs($n,{children:[Ys()," + 2"]})]}),e.jsxs(Qs,{onSelect:M,children:[e.jsx(fo,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs($n,{children:[Ys()," + 3"]})]}),e.jsxs(Qs,{onSelect:S,children:[e.jsx(Ms,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs($n,{children:[Ys()," + 4"]})]}),e.jsxs(Qs,{onSelect:A,children:[e.jsx(Pn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs($n,{children:[Ys()," + T"]})]}),e.jsxs(Qs,{onSelect:D,children:[e.jsx(Po,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs($n,{children:[Ys()," + ,"]})]})]}),P.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(ya,{}),e.jsx(hn,{heading:"Projects",children:P.map(F=>{const I=F.label&&F.label.trim().length>0?F.label:F.path.split("/").filter(Boolean).pop()??F.path,E=F.id===$;return e.jsxs(Qs,{onSelect:()=>O(F.id),children:[e.jsx(wv,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:I}),E&&e.jsx(ss,{className:"ml-auto h-4 w-4"})]},F.id)})})]}),e.jsx(ya,{}),e.jsxs(hn,{heading:"Theme",children:[e.jsxs(Qs,{onSelect:()=>v("light"),children:[e.jsx(jv,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx(ss,{className:"ml-auto h-4 w-4"})]}),e.jsxs(Qs,{onSelect:()=>v("dark"),children:[e.jsx(Sv,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx(ss,{className:"ml-auto h-4 w-4"})]}),e.jsxs(Qs,{onSelect:()=>v("system"),children:[e.jsx(lg,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx(ss,{className:"ml-auto h-4 w-4"})]})]}),_.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ya,{}),e.jsx(hn,{heading:"Recent Sessions",children:_.map(F=>e.jsxs(Qs,{onSelect:()=>b(F.id),children:[e.jsx(Nu,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:F.title||"Untitled Session"})]},F.id))})]})]})]})},QC=(t,s)=>{const r=t.trim().toLowerCase();return r==="ctrl"||r==="control"?e.jsx(vi,{className:"h-3.5 w-3.5"},`ctrl-${s}`):r==="⌘"||r==="cmd"||r==="command"||r==="meta"?e.jsx(xo,{className:"h-3.5 w-3.5"},`cmd-${s}`):e.jsx("span",{className:"text-xs font-medium",children:t.trim()},`key-${s}`)},YC=t=>{const s=t.split("+").map(r=>r.trim()).filter(Boolean);return s.length===0?t.trim():s.map((r,n)=>e.jsxs(i.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),QC(r,n)]},`${r}-${n}`))},JC=()=>{const{isHelpDialogOpen:t,setHelpDialogOpen:s}=Te(),r=ut(a=>a.settingsAutoCreateWorktree),n=Ys(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + P`],description:"Open Command Palette",icon:xo},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:Fo},{keys:[`${n} + H`],description:"Toggle Session Sidebar",icon:Su},{keys:[`${n} + L`],description:"Toggle Git Sidebar",icon:ag},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:Lo},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:Ja},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:Rn},{keys:[`Shift + Alt + ${n} + N`],description:"New Window (desktop only)",icon:ng}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:r?"Create New Session in Worktree":"Create New Session",icon:r?Ms:Fs},{keys:[`Shift + ${n} + N`],description:r?"Create New Session":"Create New Session in Worktree",icon:r?Fs:Ms},{keys:[`${n} + I`],description:"Focus Chat Input",icon:cg},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:li}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:Nv},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:xn},{keys:[`${n} + T`],description:"Open Timeline",icon:Pn},{keys:[`${n} + ,`],description:"Open Settings",icon:Po}]}];return e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(js,{children:[e.jsxs(Ss,{className:"flex items-center gap-2",children:[e.jsx(Po,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Is,{children:"Use these keyboard shortcuts to navigate IKanban 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:YC(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(Fo,{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," + P) 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"})]})]})]})})]})]})})},XC=()=>{const{isOpenCodeStatusDialogOpen:t,setOpenCodeStatusDialogOpen:s,openCodeStatusText:r}=Te(),n=i.useCallback(()=>{r&&navigator.clipboard.writeText(r).then(()=>{K.success("Copied",{description:"OpenCode status copied to clipboard."})}).catch(()=>{K.error("Copy failed")})},[r]);return e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"OpenCode Status"}),e.jsx(Is,{children:"Diagnostic snapshot for support and debugging."})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx("button",{type:"button",onClick:n,className:"app-region-no-drag inline-flex h-9 items-center justify-center rounded-md px-3 typography-ui-label font-medium text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:"Copy"})}),e.jsx("pre",{className:"max-h-[60vh] overflow-auto rounded-lg bg-surface-muted p-4 typography-code text-foreground whitespace-pre-wrap",children:r||"No data."})]})})},ZC={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"}},eM=t=>(t%3+Math.floor(t/3))*150,ly=({className:t,size:s="md"})=>{const r=ZC[s];return e.jsx("div",{className:L("grid grid-cols-3",r.container,t),"aria-label":"Loading",children:Array.from({length:9},(n,o)=>e.jsx("div",{className:L("rounded-full bg-current animate-grid-pulse",r.dot),style:{animationDelay:`${eM(o)}ms`}},o))})},Kc=new Set,qc=new Set,Qc=new Set,Na={onDeleteRequest(t){return Kc.add(t),()=>{Kc.delete(t)}},requestDelete(t){!t.sessions.length&&t.mode!=="worktree"||Kc.forEach(s=>s(t))},onCreateRequest(t){return qc.add(t),()=>{qc.delete(t)}},requestCreate(t){const s=t??{};qc.forEach(r=>r(s))},onDirectoryRequest(t){return Qc.add(t),()=>{Qc.delete(t)}},requestDirectoryDialog(){Qc.forEach(t=>t())}};function Zu(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)"})})}const tM=t=>{const s=t.trim();if(!s)return null;const r=s.match(/\/issues\/(\d+)(?:\b|\/|$)/i);if(r){const o=Number(r[1]);return Number.isFinite(o)&&o>0?o:null}const n=s.match(/^#?(\d+)$/);if(n){const o=Number(n[1]);return Number.isFinite(o)&&o>0?o:null}return null},sM=t=>{const s={repo:t.repo??null,issue:t.issue,comments:t.comments};return`GitHub issue context (JSON)
|
|
82
|
+
${JSON.stringify(s,null,2)}`};function rM({open:t,onOpenChange:s}){const{github:r}=Vr(),n=$r(oe=>oe.status),o=$r(oe=>oe.hasChecked),a=Te(oe=>oe.setSettingsDialogOpen),l=Te(oe=>oe.setSidebarSection),d=ps(oe=>oe.getActiveProject())?.path??null,[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,g]=i.useState(null),[x,y]=i.useState([]),[b,v]=i.useState(1),[j,k]=i.useState(!1),[N,w]=i.useState(null),[C,S]=i.useState(!1),[M,D]=i.useState(!1),[A,P]=i.useState(null),$=i.useCallback(async()=>{if(!d){g(null),P("No active project");return}if(o&&n?.connected===!1){g({connected:!1}),y([]),k(!1),v(1),P(null);return}if(!r?.issuesList){g(null),P("GitHub runtime API unavailable");return}S(!0),P(null);try{const oe=await r.issuesList(d,{page:1});g(oe),y(oe.issues??[]),v(oe.page??1),k(!!oe.hasMore),oe.connected===!1&&P(null)}catch(oe){P(oe instanceof Error?oe.message:String(oe))}finally{S(!1)}},[r,o,n,d]),R=i.useCallback(async()=>{if(d&&r?.issuesList&&!(M||C)&&j){D(!0);try{const oe=b+1,Z=await r.issuesList(d,{page:oe});g(Z),y(ce=>[...ce,...Z.issues??[]]),v(Z.page??oe),k(!!Z.hasMore)}catch(oe){const Z=oe instanceof Error?oe.message:String(oe);K.error("Failed to load more issues",{description:Z})}finally{D(!1)}}},[r,j,C,M,b,d]);i.useEffect(()=>{if(!t){m(""),p(!1),w(null),P(null),g(null),y([]),v(1),k(!1),S(!1);return}$()},[t,$]),i.useEffect(()=>{t&&o&&n?.connected===!1&&(g({connected:!1}),y([]),k(!1),v(1),P(null))},[o,n,t]);const O=o?h?.connected!==!1:!0,T=h?.repo?.url??null,_=i.useCallback(()=>{l("settings"),a(!0)},[a,l]),F=i.useMemo(()=>{const oe=u.trim().toLowerCase();return oe?x.filter(Z=>String(Z.number)===oe.replace(/^#/,"")?!0:Z.title.toLowerCase().includes(oe)):x},[x,u]),I=i.useMemo(()=>tM(u),[u]),E=i.useCallback(()=>{const oe=ut.getState(),Z=oe.getVisibleAgents();if(oe.settingsDefaultAgent){const ce=Z.find(Q=>Q.name===oe.settingsDefaultAgent);if(ce)return ce.name}return Z.find(ce=>ce.name==="build")?.name||Z[0]?.name},[]),W=i.useCallback(()=>{const oe=ut.getState(),Z=oe.settingsDefaultModel;if(!Z)return null;const ce=Z.split("/");if(ce.length!==2)return null;const[Q,Y]=ce;return!Q||!Y||!oe.getModelMetadata(Q,Y)?null:{providerID:Q,modelID:Y}},[]),V=i.useCallback((oe,Z)=>{const ce=ut.getState(),Q=ce.settingsDefaultVariant;if(!Q)return;const B=ce.providers.find(se=>se.id===oe)?.models.find(se=>se.id===Z)?.variants;if(B&&Object.prototype.hasOwnProperty.call(B,Q))return Q},[]),ve=i.useCallback(async oe=>{if(!d){K.error("No active project");return}if(!r?.issueGet||!r?.issueComments){K.error("GitHub runtime API unavailable");return}if(!N){w(oe);try{const Z=await r.issueGet(d,oe);if(Z.connected===!1){K.error("GitHub not connected");return}if(!Z.repo){K.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}const ce=Z.issue;if(!ce){K.error("Issue not found");return}const Q=await r.issueComments(d,oe);if(Q.connected===!1){K.error("GitHub not connected");return}const Y=Q.comments??[],ie=`#${ce.number} ${ce.title}`.trim(),B=await(async()=>{if(f){const Oe=`issue-${ce.number}-${ny()}`,Be=await iy(d,Oe);if(!Be?.id)throw new Error("Failed to create worktree session");return Be.id}const me=await Ae.getState().createSession(ie,d,null);if(!me?.id)throw new Error("Failed to create session");return me.id})();Ae.getState().updateSessionTitle(B,ie).catch(()=>{});try{Ae.getState().initializeNewIKanbanSession(B,ut.getState().agents)}catch{}s(!1);const se=ut.getState(),H=rs.getState().lastUsedProvider,le=W(),ge=le?.providerID||se.currentProviderId||H?.providerID,z=le?.modelID||se.currentModelId||H?.modelID,J=E()||se.currentAgentName||void 0;if(!ge||!z){K.error("No model selected");return}const je=V(ge,z);try{Lt.getState().saveSessionModelSelection(B,ge,z)}catch{}if(J){try{se.setAgent(J)}catch{}try{Lt.getState().saveSessionAgentSelection(B,J)}catch{}try{Lt.getState().saveAgentModelForSession(B,J,ge,z)}catch{}if(je!==void 0){try{se.setCurrentVariant(je)}catch{}try{Lt.getState().saveAgentModelVariantForSession(B,J,ge,z,je)}catch{}}}const X="Review this issue using the provided issue context: title, body, labels, assignees, comments, metadata.",G=`Review this issue using the provided issue context.
|
|
83
|
+
|
|
84
|
+
Process:
|
|
85
|
+
- First classify the issue type (bug / feature request / question/support / refactor / ops) and state it as: Type: <one label>.
|
|
86
|
+
- Gather any needed repository context (code, config, docs) to validate assumptions.
|
|
87
|
+
- After gathering, if anything is still unclear or cannot be verified, do not speculate—state what’s missing and ask targeted questions.
|
|
88
|
+
|
|
89
|
+
Output rules:
|
|
90
|
+
- Compact output; pick ONE template below and omit the others.
|
|
91
|
+
- No emojis. No code snippets. No fenced blocks.
|
|
92
|
+
- Short inline code identifiers allowed.
|
|
93
|
+
- Reference evidence with file paths and line ranges when applicable; if exact lines aren’t available, cite the file and say “approx” + why.
|
|
94
|
+
- Keep the entire response under ~300 words.
|
|
95
|
+
|
|
96
|
+
Templates (choose one):
|
|
97
|
+
Bug:
|
|
98
|
+
- Summary (1-2 sentences)
|
|
99
|
+
- Likely cause (max 2)
|
|
100
|
+
- Repro/diagnostics needed (max 3)
|
|
101
|
+
- Fix approach (max 4 steps)
|
|
102
|
+
- Verification (max 3)
|
|
103
|
+
|
|
104
|
+
Feature:
|
|
105
|
+
- Summary (1-2 sentences)
|
|
106
|
+
- Requirements (max 4)
|
|
107
|
+
- Unknowns/questions (max 4)
|
|
108
|
+
- Proposed plan (max 5 steps)
|
|
109
|
+
- Verification (max 3)
|
|
110
|
+
|
|
111
|
+
Question/Support:
|
|
112
|
+
- Summary (1-2 sentences)
|
|
113
|
+
- Answer/guidance (max 6 lines)
|
|
114
|
+
- Missing info (max 4)
|
|
115
|
+
|
|
116
|
+
Do not implement changes until I confirm; end with: “Next actions: <1 sentence>”.`,ae=sM({repo:Z.repo,issue:ce,comments:Y});nt.sendMessage({id:B,providerID:ge,modelID:z,agent:J,variant:je,text:X,additionalParts:[{text:G,synthetic:!0},{text:ae,synthetic:!0}]}).catch(me=>{const Oe=me instanceof Error?me.message:String(me);K.error("Failed to send issue context",{description:Oe})}),K.success("Session created from issue")}catch(Z){const ce=Z instanceof Error?Z.message:String(Z);K.error("Failed to start session",{description:ce})}finally{w(null)}}},[f,r,s,d,E,W,V,N]);return e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(js,{className:"flex-shrink-0",children:[e.jsxs(Ss,{className:"flex items-center gap-2",children:[e.jsx(ku,{className:"h-5 w-5"}),"New Session From GitHub Issue"]}),e.jsx(Is,{children:"Seeds a new session with hidden issue context (title/body/labels/comments)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Bt,{placeholder:"Search by title or #123, or paste issue URL",value:u,onChange:oe=>m(oe.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."}),r?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(Ot,{className:"h-4 w-4 animate-spin"}),"Loading issues..."]}):null,O===!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(Me,{variant:"outline",size:"sm",onClick:_,children:"Open settings"})})]}):null,A?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:A}):null,I&&d&&r&&O?e.jsxs("div",{className:L("group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",N===I&&"bg-interactive-selection/30"),onClick:()=>{ve(I)},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 #",I]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:N===I?e.jsx(Ot,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,F.length===0&&!C&&O&&r&&d?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:u?"No issues found":"No open issues found"}):null,F.map(oe=>e.jsxs("div",{className:L("group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",N===oe.number&&"bg-interactive-selection/30"),onClick:()=>{ve(oe.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0",children:["#",oe.number]}),e.jsx("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:oe.title}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:N===oe.number?e.jsx(Ot,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:oe.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(gn,{className:"h-4 w-4"})})})]},oe.number)),j&&O&&d&&r?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{R()},disabled:M||!!N,className:L("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(M||!!N)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:M?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ot,{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 flex-col gap-3 sm:flex-row sm:items-center sm:gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":f,onClick:()=>p(oe=>!oe),onKeyDown:oe=>{(oe.key===" "||oe.key==="Enter")&&(oe.preventDefault(),p(Z=>!Z))},children:[e.jsx("button",{type:"button",onClick:oe=>{oe.preventDefault(),oe.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(Kn,{className:"h-4 w-4 text-primary"}):e.jsx(qn,{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 hidden sm:inline",children:"(issue-<number>-<slug>)"})]}),e.jsx("div",{className:"hidden sm:block sm:flex-1"}),e.jsxs("div",{className:"flex items-center gap-2",children:[T?e.jsx(Me,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:T,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(Me,{variant:"outline",size:"sm",onClick:$,disabled:C||!!N,children:"Refresh"})]})]})]})]})})}const nM=t=>{const s=t.trim();if(!s)return null;const r=s.match(/\/pull\/(\d+)(?:\b|\/|$)/i);if(r){const o=Number(r[1]);return Number.isFinite(o)&&o>0?o:null}const n=s.match(/^#?(\d+)$/);if(n){const o=Number(n[1]);return Number.isFinite(o)&&o>0?o:null}return null},oM=t=>`GitHub pull request context (JSON)
|
|
117
|
+
${JSON.stringify(t,null,2)}`,aM=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64),iM=t=>{const s=t.trim();return/^git@/i.test(s)||/^ssh:\/\//i.test(s)},lM=t=>{const s=t.length>0?t:[],r=s.find(o=>o.name==="origin")||s.find(o=>o.name==="upstream")||s[0],n=r?.pushUrl||r?.fetchUrl||"";return iM(n)?"ssh":"https"},cM=(t,s)=>t?s==="ssh"?t.sshUrl||t.cloneUrl||t.url||"":t.cloneUrl||t.sshUrl||t.url||"":"";function dM({open:t,onOpenChange:s}){const{github:r}=Vr(),n=$r(z=>z.status),o=$r(z=>z.hasChecked),a=Te(z=>z.setSettingsDialogOpen),l=Te(z=>z.setSidebarSection),c=ps(z=>z.getActiveProject()),d=c?.path??null,u=i.useMemo(()=>d?{id:c?.id??`path:${d}`,path:d}:null,[c?.id,d]),[m,f]=i.useState(""),[p,h]=i.useState(!1),[g,x]=i.useState(!1),[y,b]=i.useState(null),[v,j]=i.useState([]),[k,N]=i.useState(1),[w,C]=i.useState(!1),[S,M]=i.useState(null),[D,A]=i.useState(!1),[P,$]=i.useState(!1),[R,O]=i.useState(new Map),[T,_]=i.useState([]),[F,I]=i.useState(null),E=i.useMemo(()=>lM(T),[T]),W=i.useCallback(async()=>{if(!d){b(null),I("No active project");return}if(o&&n?.connected===!1){b({connected:!1}),j([]),C(!1),N(1),I(null);return}if(!r?.prsList){b(null),I("GitHub runtime API unavailable");return}A(!0),I(null);try{const z=await r.prsList(d,{page:1});b(z),j(z.prs??[]),N(z.page??1),C(!!z.hasMore),z.connected===!1&&I(null)}catch(z){I(z instanceof Error?z.message:String(z))}finally{A(!1)}},[r,o,n,d]),V=i.useCallback(async()=>{if(d&&r?.prsList&&!(P||D)&&w){$(!0);try{const z=k+1,J=await r.prsList(d,{page:z});b(J),j(je=>[...je,...J.prs??[]]),N(J.page??z),C(!!J.hasMore)}catch(z){const J=z instanceof Error?z.message:String(z);K.error("Failed to load more PRs",{description:J})}finally{$(!1)}}},[r,w,D,P,k,d]);i.useEffect(()=>{if(!t){f(""),h(!1),x(!1),b(null),j([]),N(1),C(!1),M(null),A(!1),I(null),O(new Map),_([]);return}W()},[t,W]),i.useEffect(()=>{if(!t||!d)return;let z=!1;return g0(d).then(J=>{z||_(Array.isArray(J)?J:[])}).catch(()=>{z||_([])}),()=>{z=!0}},[t,d]);const ve=i.useCallback(async z=>{if(!u)return;const J=Array.from(new Set(z.map(G=>(G||"").trim()).filter(Boolean)));if(J.length===0)return;const je=J.filter(G=>!R.has(G));if(je.length===0)return;const X=await Promise.all(je.map(async G=>{const me=(await Jm(u,{mode:"new",branchName:G,worktreeName:G}).catch(()=>({ok:!1,errors:[{code:"validation_failed",message:"Validation failed"}]}))).errors.some(Oe=>Oe.code==="branch_in_use"||Oe.code==="branch_exists");return{head:G,blocked:me}}));O(G=>{const ae=new Map(G);for(const me of X)ae.set(me.head,me.blocked);return ae})},[u,R]);i.useEffect(()=>{t&&u&&p&&ve(v.map(z=>z.head))},[t,u,p,v,ve]),i.useEffect(()=>{t&&o&&n?.connected===!1&&(b({connected:!1}),j([]),C(!1),N(1),I(null))},[o,n,t]);const oe=o?y?.connected!==!1:!0,Z=y?.repo?.url??null,ce=i.useCallback(()=>{l("settings"),a(!0)},[a,l]),Q=i.useMemo(()=>{const z=m.trim().toLowerCase();return z?v.filter(J=>String(J.number)===z.replace(/^#/,"")?!0:J.title.toLowerCase().includes(z)):v},[v,m]),Y=i.useCallback(z=>{if(!p)return!1;const J=z.head?.trim();return J?R.get(J)===!0:!0},[p,R]),ie=i.useMemo(()=>nM(m),[m]),B=i.useCallback(()=>{const z=ut.getState(),J=z.getVisibleAgents();if(z.settingsDefaultAgent){const je=J.find(X=>X.name===z.settingsDefaultAgent);if(je)return je.name}return J.find(je=>je.name==="build")?.name||J[0]?.name},[]),se=i.useCallback(()=>{const z=ut.getState(),J=z.settingsDefaultModel;if(!J)return null;const je=J.split("/");if(je.length!==2)return null;const[X,G]=je;return!X||!G||!z.getModelMetadata(X,G)?null:{providerID:X,modelID:G}},[]),H=i.useCallback((z,J)=>{const je=ut.getState(),X=je.settingsDefaultVariant;if(!X)return;const me=je.providers.find(Oe=>Oe.id===z)?.models.find(Oe=>Oe.id===J)?.variants;if(me&&Object.prototype.hasOwnProperty.call(me,X))return X},[]),le=i.useCallback(async(z,J)=>{if(!d||!u)return null;const je=J.head,X=J.headRepo;if(!je)throw new Error("PR head ref missing");const G=!!(X?.owner&&X?.repo&&z?.owner&&z?.repo&&(X.owner!==z.owner||X.repo!==z.repo)),ae=J.head,me=G?aM(`pr-${X?.owner||"fork"}-${X?.repo||""}`)||`pr-${J.number}`:"origin",Oe=G?cM(X,E):"";if(G&&!Oe)throw new Error("PR fork remote URL missing");const Be=`${me}/${ae}`,fe=await Jm(u,{mode:"new",branchName:ae,worktreeName:ae,startRef:Be,setUpstream:!0,upstreamRemote:me,upstreamBranch:ae,ensureRemoteName:G?me:void 0,ensureRemoteUrl:G?Oe:void 0});if(!fe.ok){const He=fe.errors.find(ot=>ot.code==="branch_in_use"||ot.code==="branch_exists");throw He?new Error(He.message):new Error(fe.errors[0]?.message||"PR worktree validation failed")}if(R.get(ae)===!0)throw new Error(`Local branch already exists: ${ae}`);const q=await KC(d,ae,Be,{kind:"pr",worktreeName:ae,setUpstream:!0,upstreamRemote:me,upstreamBranch:ae,ensureRemoteName:G?me:void 0,ensureRemoteUrl:G?Oe:void 0,createdFromBranch:J.base});if(!q?.id)throw new Error("Failed to create PR worktree session");const ye=Ae.getState().worktreeMetadata.get(q.id),he=ye?.path;if(!he)throw new Error("Worktree directory not found");return Ae.getState().setWorktreeMetadata(q.id,{...ye||{path:he,projectDirectory:d,branch:ae,label:ae},path:he,projectDirectory:d,branch:ae,label:ae,createdFromBranch:J.base,kind:"pr"}),{id:q.id}},[d,u,R,E]),ge=i.useCallback(async z=>{if(!d){K.error("No active project");return}if(!r?.prContext){K.error("GitHub runtime API unavailable");return}if(!S){M(z);try{const J=await r.prContext(d,z,{includeDiff:g,includeCheckDetails:!1});if(J.connected===!1){K.error("GitHub not connected");return}if(!J.repo){K.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}if(!J.pr){K.error("PR not found");return}const je=J.pr,X=`#${je.number} ${je.title}`.trim(),G=await(async()=>p?(await le(J.repo,je))?.id||null:(await Ae.getState().createSession(X,d,null))?.id||null)();if(!G)throw new Error("Failed to create session");Ae.getState().updateSessionTitle(G,X).catch(()=>{});try{Ae.getState().initializeNewIKanbanSession(G,ut.getState().agents)}catch{}s(!1);const ae=ut.getState(),me=rs.getState().lastUsedProvider,Oe=se(),Be=Oe?.providerID||ae.currentProviderId||me?.providerID,fe=Oe?.modelID||ae.currentModelId||me?.modelID,q=B()||ae.currentAgentName||void 0;if(!Be||!fe){K.error("No model selected");return}const ye=H(Be,fe);try{Lt.getState().saveSessionModelSelection(G,Be,fe)}catch{}if(q){try{ae.setAgent(q)}catch{}try{Lt.getState().saveSessionAgentSelection(G,q)}catch{}try{Lt.getState().saveAgentModelForSession(G,q,Be,fe)}catch{}if(ye!==void 0){try{ae.setCurrentVariant(ye)}catch{}try{Lt.getState().saveAgentModelVariantForSession(G,q,Be,fe,ye)}catch{}}}const he="Review this pull request using the provided PR context: description, comments, files, diff, checks.",He=`Before reporting issues:
|
|
118
|
+
- 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.
|
|
119
|
+
- Gather any needed repository context (code, config, docs) to validate assumptions.
|
|
120
|
+
- No speculation: if something is unclear or cannot be verified, say what’s missing and ask for it instead of guessing.
|
|
121
|
+
|
|
122
|
+
Output rules:
|
|
123
|
+
- Start with a 1-2 sentence summary.
|
|
124
|
+
- Provide a single concise PR review comment.
|
|
125
|
+
- No emojis. No code snippets. No fenced blocks.
|
|
126
|
+
- Short inline code identifiers allowed, but no snippets or fenced blocks.
|
|
127
|
+
- 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.
|
|
128
|
+
- Keep the entire comment under ~300 words.
|
|
129
|
+
|
|
130
|
+
Report:
|
|
131
|
+
- Must-fix issues (blocking) — brief why and a one-line action each.
|
|
132
|
+
- Nice-to-have improvements (optional) — brief why and a one-line action each.
|
|
133
|
+
|
|
134
|
+
Quality & safety (general):
|
|
135
|
+
- Call out correctness risks, edge cases, performance regressions, security/privacy concerns, and backwards-compatibility risks.
|
|
136
|
+
- Call out missing tests/verification steps and suggest the minimal validation needed.
|
|
137
|
+
- Note readability/maintainability issues when they materially affect future changes.
|
|
138
|
+
|
|
139
|
+
Applicability (only if relevant):
|
|
140
|
+
- If changes affect multiple components/targets/environments (e.g., client/server, OSs, deployments), state what is affected vs not, and why.
|
|
141
|
+
|
|
142
|
+
Architecture:
|
|
143
|
+
- Call out breakages, missing implementations across modules/targets, boundary violations, and cross-cutting concerns (errors, logging/observability, accessibility).
|
|
144
|
+
|
|
145
|
+
Precedence:
|
|
146
|
+
- If local precedent conflicts with best practices, state it and suggest a follow-up task.
|
|
147
|
+
|
|
148
|
+
Do not implement changes until I confirm; end with a short “Next actions” sentence describing the recommended plan.
|
|
149
|
+
|
|
150
|
+
Format exactly:
|
|
151
|
+
Must-fix:
|
|
152
|
+
- <issue> — <brief why> — <file:line-range> — Action: <one-line action>
|
|
153
|
+
Nice-to-have:
|
|
154
|
+
- <issue> — <brief why> — <file:line-range> — Action: <one-line action>
|
|
155
|
+
If no issues, write:
|
|
156
|
+
Must-fix:
|
|
157
|
+
- None
|
|
158
|
+
Nice-to-have:
|
|
159
|
+
- None`,ot=oM(J);nt.sendMessage({id:G,providerID:Be,modelID:fe,agent:q,variant:ye,text:he,additionalParts:[{text:He,synthetic:!0},{text:ot,synthetic:!0}]}).catch(ue=>{const Ve=ue instanceof Error?ue.message:String(ue);K.error("Failed to send PR context",{description:Ve})}),K.success("Session created from PR")}catch(J){const je=J instanceof Error?J.message:String(J);K.error(p?"PR worktree failed":"Failed to start session",{description:je})}finally{M(null)}}},[p,le,r,g,s,d,B,se,H,S]);return e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(js,{className:"flex-shrink-0",children:[e.jsxs(Ss,{className:"flex items-center gap-2",children:[e.jsx(no,{className:"h-5 w-5"}),"New Session From GitHub PR"]}),e.jsx(Is,{children:"Seeds a new session with hidden PR context (title/body/comments/files/checks)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Bt,{placeholder:"Search by title or #123, or paste PR URL",value:m,onChange:z=>f(z.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."}),r?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"GitHub runtime API unavailable."}),D?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Ot,{className:"h-4 w-4 animate-spin"}),"Loading pull requests..."]}):null,oe===!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(Me,{variant:"outline",size:"sm",onClick:ce,children:"Open settings"})})]}):null,F?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:F}):null,ie&&d&&r&&oe?e.jsxs("div",{className:L("group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",S===ie&&"bg-interactive-selection/30"),onClick:()=>{ge(ie)},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 #",ie]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:S===ie?e.jsx(Ot,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,Q.length===0&&!D&&oe&&r&&d?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:m?"No PRs found":"No open PRs found"}):null,Q.map(z=>{const J=Y(z);return e.jsxs("div",{className:L("group flex items-start gap-2 py-1.5 rounded transition-colors",S===z.number&&"bg-interactive-selection/30",J?"opacity-50 cursor-not-allowed":"hover:bg-interactive-hover/30 cursor-pointer"),onClick:()=>{J||ge(z.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0 pt-0.5",children:["#",z.number]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"typography-small text-foreground truncate ml-0.5",children:z.title}),p&&J?e.jsxs("p",{className:"typography-micro text-muted-foreground mt-0.5 ml-0.5",children:["PR worktree disabled: branch already exists or is in use (",z.head,")"]}):null]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2 pt-0.5",children:S===z.number?e.jsx(Ot,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:z.url,target:"_blank",rel:"noopener noreferrer",className:L("hidden group-hover:flex h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors",J&&"pointer-events-none"),onClick:je=>je.stopPropagation(),"aria-label":"Open in GitHub",children:e.jsx(gn,{className:"h-4 w-4"})})})]},z.number)}),w&&oe&&d&&r?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{V()},disabled:P||!!S,className:L("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(P||!!S)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:P?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ot,{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 flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-4 sm:gap-y-2",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":p,onClick:()=>h(z=>!z),onKeyDown:z=>{(z.key===" "||z.key==="Enter")&&(z.preventDefault(),h(J=>!J))},children:[e.jsx("button",{type:"button",onClick:z=>{z.preventDefault(),z.stopPropagation(),h(J=>!J)},"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(Kn,{className:"h-4 w-4 text-primary"}):e.jsx(qn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Create in PR worktree"})]}),e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":g,onClick:()=>x(z=>!z),onKeyDown:z=>{(z.key===" "||z.key==="Enter")&&(z.preventDefault(),x(J=>!J))},children:[e.jsx("button",{type:"button",onClick:z=>{z.preventDefault(),z.stopPropagation(),x(J=>!J)},"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:g?e.jsx(Kn,{className:"h-4 w-4 text-primary"}):e.jsx(qn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Include full diff"})]})]}),e.jsx("div",{className:"hidden sm:block sm:flex-1"}),e.jsxs("div",{className:"flex items-center gap-2",children:[Z?e.jsx(Me,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:Z,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(Me,{variant:"outline",size:"sm",onClick:W,disabled:D||!!S,children:"Refresh"})]})]})]})]})})}const Xr=i.memo(function({checked:s,onChange:r,disabled:n=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(u=>{u.preventDefault(),u.stopPropagation(),n||r(!s)},[s,n,r]),d=i.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),n||r(!s))},[s,n,r]);return e.jsx("button",{type:"button",onClick:c,onKeyDown:d,disabled:n,"aria-pressed":s,"aria-label":o,className:L("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",n&&"cursor-not-allowed opacity-50",a),children:s?e.jsx(Kn,{className:L("size-4 text-primary",l)}):e.jsx(qn,{className:L("size-4",l)})})}),uM=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Wf=({projectRef:t,canCreateWorktree:s=!1,onActionComplete:r,className:n})=>{const[o,a]=i.useState(!1),[l,c]=i.useState(""),[d,u]=i.useState([]),[m,f]=i.useState(""),[p,h]=i.useState(null),g=Ae(O=>O.currentSessionId),x=Ae(O=>O.openNewSessionDraft),y=Ae(O=>O.setPendingInputText),b=Te(O=>O.setActiveMainTab),v=Te(O=>O.setSessionSwitcherOpen),j=i.useCallback(async(O,T)=>{if(!t)return!1;const _=await O0(t,{notes:O,todos:T});return _||K.error("Failed to save project notes"),_},[t]);i.useEffect(()=>{if(!t){c(""),u([]),f("");return}let O=!1;return a(!0),(async()=>{try{const T=await L0(t);if(O)return;c(T.notes),u(T.todos),f("")}catch{O||(K.error("Failed to load project notes"),c(""),u([]))}finally{O||a(!1)}})(),()=>{O=!0}},[t]);const k=i.useCallback(()=>{j(l,d)},[l,j,d]),N=i.useCallback(()=>{const O=m.trim();if(!O)return;const T=[...d,{id:uM(),text:O.slice(0,fl),completed:!1,createdAt:Date.now()}];u(T),f(""),j(l,T)},[m,l,j,d]),w=i.useCallback((O,T)=>{const _=d.map(F=>F.id===O?{...F,completed:T}:F);u(_),j(l,_)},[l,j,d]),C=i.useCallback(O=>{const T=d.filter(_=>_.id!==O);u(T),j(l,T)},[l,j,d]),S=i.useCallback(()=>{const O=d.filter(T=>!T.completed);O.length!==d.length&&(u(O),j(l,O))},[l,j,d]),M=m.slice(0,fl),D=d.reduce((O,T)=>O+(T.completed?1:0),0),A=i.useCallback(()=>{b("chat"),v(!1)},[b,v]),P=i.useCallback(O=>{t&&(A(),x({directoryOverride:t.path,initialPrompt:O}),K.success("Todo sent to new session"),r?.())},[r,x,t,A]),$=i.useCallback(O=>{if(!g){K.error("No active session selected");return}A(),y(O,"append"),K.success("Todo sent to current session"),r?.()},[g,r,A,y]),R=i.useCallback(async(O,T)=>{if(t){if(!s){K.error("Worktree actions are only available for Git repositories");return}h(O);try{const _=await ay();if(!_)return;A(),x({directoryOverride:_,initialPrompt:T}),K.success("Todo sent to new worktree session"),r?.()}finally{h(null)}}},[s,r,x,t,A]);return t?e.jsxs("div",{className:L("w-full min-w-0 space-y-3 p-3",n),children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Quick notes"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length,"/",eu]})]}),e.jsx(hr,{value:l,onChange:O=>c(O.target.value.slice(0,eu)),onBlur:k,placeholder:"Capture context, reminders, or links",className:"min-h-24 resize-none",disabled:o})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Todo"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[d.length," item",d.length===1?"":"s"]}),e.jsx("button",{type:"button",onClick:S,disabled:o||D===0,className:"typography-meta rounded-md px-1.5 py-0.5 text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",children:"Clear completed"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Bt,{value:M,onChange:O=>f(O.target.value.slice(0,fl)),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),N())},placeholder:"Add a todo",disabled:o,className:"h-8"}),e.jsx("button",{type:"button",onClick:N,disabled:o||M.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Add todo",children:e.jsx(Fs,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:d.length===0?e.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No todos yet. Add a small checklist for this project."}):e.jsx("ul",{className:"divide-y divide-border/50",children:d.map(O=>e.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[e.jsx(Xr,{checked:O.completed,onChange:T=>w(O.id,T),ariaLabel:`Mark "${O.text}" complete`}),e.jsx("span",{className:L("min-w-0 flex-1 typography-ui-label text-foreground",O.completed&&"text-muted-foreground line-through"),title:O.text,children:O.text}),e.jsx("button",{type:"button",onClick:()=>C(O.id),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete "${O.text}"`,children:e.jsx(Nr,{className:"h-3.5 w-3.5"})}),e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx("button",{type:"button",disabled:p===O.id,className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Send "${O.text}"`,children:e.jsx(kv,{className:"h-3.5 w-3.5"})})}),e.jsxs(fs,{align:"end",className:"w-56",children:[e.jsx(Et,{onClick:()=>$(O.text),children:"Send to current session"}),e.jsx(Et,{onClick:()=>P(O.text),children:"Send to new session"}),e.jsx(Et,{onClick:()=>{R(O.id,O.text)},disabled:!s,children:"Send to new worktree session"})]})]})]},O.id))})})]})]}):e.jsx("div",{className:L("w-full min-w-0 p-3",n),children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to add notes and todos."})})},mM=new Set([1,3,4,5,7]),fM=t=>t===4?"0ms":"130ms",Gf="oc.sessions.projectCollapse",Kf="oc.sessions.groupOrder",qf="oc.sessions.groupCollapse",Qf="oc.sessions.activeSessionByProject",Yf="oc.sessions.expandedParents",Jf=t=>{const s=new Date(t),r=new Date,n=(l,c)=>l.getFullYear()===c.getFullYear()&&l.getMonth()===c.getMonth()&&l.getDate()===c.getDate(),o=new Date(r);return o.setDate(r.getDate()-1),n(s,r)?"Today":n(s,o)?"Yesterday":s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},vr=t=>{if(!t)return null;const s=t.replace(/\\/g,"/").replace(/\/+$/,"");return s.length===0?"/":s},Xf=t=>t.toLowerCase().replace(/^opencode[/-]?/i,"").replace(/[-_]/g,"").trim(),pM=(t,s)=>t?Xf(t)!==Xf(s):!1,Ki=t=>{if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){const s=Number(t);if(Number.isFinite(s))return s}},hM=({transform:t,activeNodeRect:s,activatorEvent:r})=>!(r instanceof MouseEvent)||!s?t:{...t,x:t.x,y:t.y-32/2-16},qi=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase()),gM=({id:t,projectLabel:s,projectDescription:r,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:l,isDesktopShell:c,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:h,onNewWorktreeSession:g,onNewSessionFromGitHubIssue:x,onNewSessionFromGitHubPR:y,onOpenMultiRunLauncher:b,onRenameStart:v,onRenameSave:j,onRenameCancel:k,onRenameValueChange:N,renameValue:w,isRenaming:C,onClose:S,sentinelRef:M,children:D,settingsAutoCreateWorktree:A,showCreateButtons:P=!0,hideHeader:$=!1})=>{const{attributes:R,listeners:O,setNodeRef:T,isDragging:_}=dg({id:t}),[F,I]=i.useState(!1);return e.jsxs("div",{ref:T,className:L("relative",_&&"opacity-40"),children:[$?null:e.jsxs(e.Fragment,{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-hover)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onContextMenu:E=>{E.preventDefault(),C||I(!0)},children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...R,children:[C?e.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-2","data-keyboard-avoid":"true",onSubmit:E=>{E.preventDefault(),j()},children:[e.jsx("input",{value:w,onChange:E=>N(E.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename project",onKeyDown:E=>{if(E.key==="Escape"){E.stopPropagation(),k();return}(E.key===" "||E.key==="Enter")&&E.stopPropagation()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(ss,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:k,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(hs,{className:"size-4"})})]}):e.jsxs(gt,{delayDuration:1500,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...O,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:s})})}),e.jsx(ht,{side:"right",sideOffset:8,children:r})]}),C?null:e.jsxs(us,{open:F,onOpenChange:I,children:[e.jsx(ms,{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:E=>E.stopPropagation(),children:e.jsx(Qn,{className:"h-3.5 w-3.5"})})}),e.jsxs(fs,{align:"end",className:"min-w-[180px]",children:[P&&a&&!u&&A&&h&&e.jsxs(Et,{onClick:h,children:[e.jsx(Fs,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),P&&a&&!u&&!A&&g&&e.jsxs(Et,{onClick:g,children:[e.jsx(Ms,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),P&&a&&!u&&x&&e.jsxs(Et,{onClick:x,children:[e.jsx(ku,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub issue"]}),P&&a&&!u&&y&&e.jsxs(Et,{onClick:y,children:[e.jsx(no,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub PR"]}),P&&a&&!u&&e.jsxs(Et,{onClick:b,children:[e.jsx(Zu,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(Et,{onClick:v,children:[e.jsx(fn,{className:"mr-1.5 h-4 w-4"}),"Rename"]}),e.jsxs(Et,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(hs,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),P&&a&&!u&&g&&A&&!C&&e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:E=>{E.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 hover:bg-interactive-hover/50 flex-shrink-0",m?"opacity-70":"opacity-100"),"aria-label":"New session in worktree",children:e.jsx(Ms,{className:"h-4 w-4"})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session in worktree"})})]}),P&&(!A||!a)&&!C&&e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:E=>{E.stopPropagation(),h()},className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 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(Fs,{className:"h-4 w-4"})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session"})})]})]})})]}),D]})},xM=({id:t,children:s})=>{const{attributes:r,listeners:n,setNodeRef:o,transform:a,transition:l,isDragging:c}=dg({id:t});return e.jsx("div",{ref:o,style:{transform:Cv.Transform.toString(a),transition:l,willChange:"transform"},className:L("space-y-0.5 rounded-md",c&&"opacity-0"),...r,...n,children:s})},yM=i.memo(xM),bM=({label:t,showBranchIcon:s,width:r})=>e.jsxs("div",{style:r?{width:`${r}px`}:void 0,className:"h-8 min-w-[180px] max-w-[320px] rounded-sm border border-border bg-sidebar px-2 shadow-lg flex items-center gap-1.5",children:[s?e.jsx(Ms,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):null,e.jsx("p",{className:"text-[15px] font-semibold truncate text-foreground",children:t})]}),vM=i.memo(bM),Ql=({mobileVariant:t=!1,onSessionSelected:s,allowReselect:r=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,l]=i.useState(null),[c,d]=i.useState(""),[u,m]=i.useState(null),[f,p]=i.useState(""),[h,g]=i.useState(null),x=i.useRef(null),[y,b]=i.useState(new Set),[v,j]=i.useState(()=>new Map),k=i.useRef(new Set),N=i.useMemo(()=>Ws(),[]),[w,C]=i.useState(new Set),[S,M]=i.useState(new Map),[D,A]=i.useState(new Set),[P,$]=i.useState(null),[R,O]=i.useState(!1),[T,_]=i.useState(!1),[F,I]=i.useState(!1),[E,W]=i.useState(new Set),[V,ve]=i.useState(null),[oe,Z]=i.useState(()=>{try{const pe=Ws().getItem(qf);if(!pe)return new Set;const ee=JSON.parse(pe);return new Set(Array.isArray(ee)?ee.filter(xe=>typeof xe=="string"):[])}catch{return new Set}}),[ce,Q]=i.useState(()=>{try{const pe=Ws().getItem(Kf);if(!pe)return new Map;const ee=JSON.parse(pe),xe=new Map;return Object.entries(ee).forEach(([Ne,ze])=>{Array.isArray(ze)&&xe.set(Ne,ze.filter(tt=>typeof tt=="string"))}),xe}catch{return new Map}}),[Y,ie]=i.useState(()=>{try{const pe=Ws().getItem(Qf);if(!pe)return new Map;const ee=JSON.parse(pe),xe=new Map;return Object.entries(ee).forEach(([Ne,ze])=>{typeof ze=="string"&&ze.length>0&&xe.set(Ne,ze)}),xe}catch{return new Map}}),[B,se]=i.useState(null),[H,le]=i.useState(null),[ge,z]=i.useState(!1),[J,je]=i.useState(""),[X,G]=i.useState(new Map),ae=i.useRef(new Map),me=i.useRef(0),Oe=i.useRef(null),Be=i.useRef(null),fe=Yt(pe=>pe.homeDirectory),q=Yt(pe=>pe.currentDirectory),ye=Yt(pe=>pe.setDirectory),he=ps(pe=>pe.projects),He=ps(pe=>pe.activeProjectId),ot=ps(pe=>pe.addProject),ue=ps(pe=>pe.removeProject),Ve=ps(pe=>pe.setActiveProject),De=ps(pe=>pe.setActiveProjectIdOnly),we=ps(pe=>pe.renameProject),Fe=Te(pe=>pe.setActiveMainTab),Pe=ks(),$e=Te(pe=>pe.setSessionSwitcherOpen),Ze=Te(pe=>pe.openMultiRunLauncher),Ue=ut(pe=>pe.settingsAutoCreateWorktree),Ee=or(pe=>pe.directories),Re=Ae(pe=>pe.sessions),Xe=Ae(pe=>pe.sessionsByDirectory),st=Ae(pe=>pe.currentSessionId),St=Ae(pe=>!!pe.newSessionDraft?.open),mt=Ae(pe=>pe.setCurrentSession),Tt=Ae(pe=>pe.updateSessionTitle),qt=Ae(pe=>pe.shareSession),yt=Ae(pe=>pe.unshareSession),os=Ae(pe=>pe.sessionMemoryState),cs=Ae(pe=>pe.sessionStatus),ds=Ae(pe=>pe.sessionAttentionStates),de=Ae(pe=>pe.permissions),ke=Ae(pe=>pe.worktreeMetadata),We=Ae(pe=>pe.availableWorktreesByProject),qe=Ae(pe=>pe.getSessionsByDirectory),et=Ae(pe=>pe.openNewSessionDraft),ct=i.useMemo(()=>As(),[]),bt=i.useMemo(()=>Lr(),[]),at=i.useMemo(()=>gs(),[]),_t=i.useCallback(()=>{if(at)return;const pe=Be.current;if(Be.current=null,Oe.current=null,!pe)return;const{projects:ee}=ps.getState(),xe=ee.map(Ne=>({...Ne,sidebarCollapsed:pe.has(Ne.id)}));xs({projects:xe}).catch(()=>{})},[at]),Nt=i.useCallback(pe=>{typeof window>"u"||at||(Be.current=pe,Oe.current!==null&&window.clearTimeout(Oe.current),Oe.current=window.setTimeout(()=>{_t()},700))},[_t,at]);i.useEffect(()=>()=>{typeof window<"u"&&Oe.current!==null&&window.clearTimeout(Oe.current),Oe.current=null,Be.current=null},[]),i.useEffect(()=>{try{const pe=N.getItem(Yf);if(pe){const xe=JSON.parse(pe);Array.isArray(xe)&&b(new Set(xe.filter(Ne=>typeof Ne=="string")))}const ee=N.getItem(Gf);if(ee){const xe=JSON.parse(ee);Array.isArray(xe)&&C(new Set(xe.filter(Ne=>typeof Ne=="string")))}}catch{}},[N]);const Gt=i.useMemo(()=>[...Re].sort((pe,ee)=>(ee.time?.updated||0)-(pe.time?.updated||0)),[Re]);i.useEffect(()=>{let pe=!1;const ee=he.map(xe=>({id:xe.id,path:vr(xe.path)})).filter(xe=>!!xe.path);return M(new Map),ee.length===0?()=>{pe=!0}:(ee.forEach(xe=>{Yn(xe.path).then(Ne=>{pe||M(ze=>{const tt=new Map(ze);return tt.set(xe.id,Ne),tt})}).catch(()=>{pe||M(Ne=>{const ze=new Map(Ne);return ze.set(xe.id,null),ze})})}),()=>{pe=!0})},[he]);const zt=i.useMemo(()=>{const pe=new Map;return Gt.forEach(ee=>{const xe=ee.parentID;if(!xe)return;const Ne=pe.get(xe)??[];Ne.push(ee),pe.set(xe,Ne)}),pe.forEach(ee=>ee.sort((xe,Ne)=>(Ne.time?.updated||0)-(xe.time?.updated||0))),pe},[Gt]);i.useEffect(()=>{const pe=new Set;Gt.forEach(ee=>{const xe=vr(ee.directory??null);xe&&pe.add(xe)}),he.forEach(ee=>{const xe=vr(ee.path);xe&&pe.add(xe)}),pe.forEach(ee=>{const xe=v.get(ee);xe&&xe!=="unknown"||k.current.has(ee)||(k.current.add(ee),nt.listLocalDirectory(ee).then(()=>{j(Ne=>{const ze=new Map(Ne);return ze.get(ee)==="exists"?Ne:(ze.set(ee,"exists"),ze)})}).catch(async()=>{if((ee.includes("/opencode/worktree/")||ee.includes("/.opencode/data/worktree/")||ee.includes("/.local/share/opencode/worktree/"))&&await nt.probeDirectory(ee).catch(()=>!1)){j(tt=>{const kt=new Map(tt);return kt.get(ee)==="exists"?tt:(kt.set(ee,"exists"),kt)});return}j(ze=>{const tt=new Map(ze);return tt.get(ee)==="missing"?ze:(tt.set(ee,"missing"),tt)})}).finally(()=>{k.current.delete(ee)}))})},[Gt,he,v]),i.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]);const Ct=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."})]}),Qt=i.useCallback((pe,ee,xe,Ne)=>{if(!xe){if(Ne&&Ne!==He&&De(Ne),ee&&ee!==q&&ye(ee,{showOverlay:!1}),t&&(Fe("chat"),$e(!1)),pe===st){r||s?.(pe);return}mt(pe),s?.(pe)}},[He,r,q,st,t,s,Fe,De,mt,ye,$e]),Mt=i.useCallback(()=>{Fe("chat")},[Fe]),Zt=i.useCallback(async()=>{a&&c.trim()&&(await Tt(a,c.trim()),l(null),d(""))},[a,c,Tt]),jt=i.useCallback(()=>{l(null),d("")},[]),es=i.useCallback(()=>{u&&f.trim()&&(we(u,f.trim()),m(null),p(""))},[u,f,we]),Ye=i.useCallback(()=>{m(null),p("")},[]),ft=i.useCallback(async pe=>{const ee=await qt(pe.id);ee&&ee.share?.url?K.success("Session shared",{description:"You can copy the link from the menu."}):K.error("Unable to share session")},[qt]),vt=i.useCallback((pe,ee)=>{navigator.clipboard.writeText(pe).then(()=>{g(ee),x.current&&clearTimeout(x.current),x.current=window.setTimeout(()=>{g(null),x.current=null},2e3)}).catch(()=>{K.error("Failed to copy URL")})},[]),pt=i.useCallback(async pe=>{await yt(pe)?K.success("Session unshared"):K.error("Unable to unshare session")},[yt]),Rt=i.useCallback(pe=>{const ee=[],xe=Ne=>{(zt.get(Ne)??[]).forEach(tt=>{ee.push(tt),xe(tt.id)})};return xe(pe),ee},[zt]),Ft=Ae(pe=>pe.deleteSession),Pt=Ae(pe=>pe.deleteSessions),Jt=i.useCallback(async pe=>{const ee=Rt(pe.id);if(ee.length===0)await Ft(pe.id)?K.success("Session deleted",{action:{label:"OK",onClick:()=>{}}}):K.error("Failed to delete session");else{const xe=[pe.id,...ee.map(tt=>tt.id)],{deletedIds:Ne,failedIds:ze}=await Pt(xe);Ne.length>0&&K.success(`Deleted ${Ne.length} session${Ne.length===1?"":"s"}`,{action:{label:"OK",onClick:()=>{}}}),ze.length>0&&K.error(`Failed to delete ${ze.length} session${ze.length===1?"":"s"}`)}},[Rt,Ft,Pt]),Ns=i.useCallback(()=>{if(!ct||!Or()){Na.requestDirectoryDialog();return}Ks(async()=>{const{requestDirectoryAccess:pe}=await Promise.resolve().then(()=>$j);return{requestDirectoryAccess:pe}},void 0).then(({requestDirectoryAccess:pe})=>pe("")).then(pe=>{pe.success&&pe.path?ot(pe.path,{id:pe.projectId})||K.error("Failed to add project",{description:"Please select a valid directory."}):pe.error&&pe.error!=="Directory selection cancelled"&&K.error("Failed to select directory",{description:pe.error})}).catch(pe=>{console.error("Desktop: Error selecting directory:",pe),K.error("Failed to select directory")})},[ot,ct]),Ts=i.useCallback(pe=>{b(ee=>{const xe=new Set(ee);xe.has(pe)?xe.delete(pe):xe.add(pe);try{N.setItem(Yf,JSON.stringify(Array.from(xe)))}catch{}return xe})},[N]),sr=i.useCallback(pe=>{const ee=zt.get(pe.id)??[];return{session:pe,children:ee.map(xe=>sr(xe)),worktree:ke.get(pe.id)??null}},[zt,ke]),Xs=i.useCallback((pe,ee,xe,Ne,ze)=>{const tt=vr(ee??null),kt=[...pe].sort((Ke,Dt)=>(Dt.time?.updated||0)-(Ke.time?.updated||0)),re=new Map(kt.map(Ke=>[Ke.id,Ke])),Le=new Map;kt.forEach(Ke=>{const Dt=Ke.parentID;if(!Dt)return;const as=Le.get(Dt)??[];as.push(Ke),Le.set(Dt,as)}),Le.forEach(Ke=>Ke.sort((Dt,as)=>(as.time?.updated||0)-(Dt.time?.updated||0)));const Ce=new Map;xe.forEach(Ke=>{if(Ke.path){const Dt=vr(Ke.path)??Ke.path;Ce.set(Dt,Ke)}});const _e=Ke=>{const Dt=vr(Ke.directory??null),as=ke.get(Ke.id)??null;if(as)return as;if(Dt){const Xt=Ce.get(Dt)??null;if(Xt&&Dt!==tt)return Xt}return null},Qe=Ke=>{const Dt=Le.get(Ke.id)??[];return{session:Ke,children:Dt.map(as=>Qe(as)),worktree:_e(Ke)}},dt=kt.filter(Ke=>{const Dt=Ke.parentID;return Dt?!re.has(Dt):!0}),$t=new Map,be=new Map,U=Ke=>{const Dt=vr(ke.get(Ke.id)?.path??null),as=vr(Ke.directory??null),Xt=Dt??as;return Xt&&Xt!==tt&&Ce.has(Xt)?Xt:tt??"__project_root__"};dt.forEach((Ke,Dt)=>{const as=Qe(Ke),Xt=U(Ke);$t.has(Xt)||($t.set(Xt,[]),be.set(Xt,Dt)),$t.get(Xt)?.push(as)});const te=tt??"__project_root__",Se=[{id:"root",label:ze&&Ne&&Ne!=="HEAD"?`project root: ${Ne}`:"project root",branch:Ne??null,description:tt?An(tt,fe):null,isMain:!0,worktree:null,directory:tt,sessions:$t.get(te)??[]}];[...xe].sort((Ke,Dt)=>{const as=(Ke.label||Ke.branch||Ke.name||Ke.path||"").toLowerCase(),Xt=(Dt.label||Dt.branch||Dt.name||Dt.path||"").toLowerCase();return as.localeCompare(Xt)}).forEach(Ke=>{const Dt=vr(Ke.path)??Ke.path,as=Ke.label||Ke.name||vo(Dt,fe)||Dt;Se.push({id:`worktree:${Dt}`,label:as,branch:Ke.branch||null,description:An(Dt,fe),isMain:!1,worktree:Ke,directory:Dt,sessions:$t.get(Dt)??[]})});const rt=new Set(Se.map(Ke=>Ke.directory).filter(Ke=>!!Ke));return Array.from($t.keys()).filter(Ke=>!rt.has(Ke)&&Ke!==te).sort((Ke,Dt)=>(be.get(Ke)??0)-(be.get(Dt)??0)).forEach(Ke=>{Se.push({id:`worktree:orphan:${Ke}`,label:vo(Ke,fe)||Ke,branch:null,description:An(Ke,fe),isMain:!1,worktree:null,directory:Ke,sessions:$t.get(Ke)??[]})}),Se},[fe,ke]),_s=i.useCallback(pe=>{A(ee=>{const xe=new Set(ee);return xe.has(pe)?xe.delete(pe):xe.add(pe),xe})},[]),mr=i.useCallback(pe=>{me.current=Date.now()+150,C(ee=>{const xe=new Set(ee);xe.has(pe)?xe.delete(pe):xe.add(pe);try{N.setItem(Gf,JSON.stringify(Array.from(xe)))}catch{}return at||Nt(xe),xe})},[at,N,Nt]);i.useEffect(()=>{try{const pe=Object.fromEntries(ce.entries());N.setItem(Kf,JSON.stringify(pe))}catch{}},[ce,N]),i.useEffect(()=>{try{const pe=Object.fromEntries(Y.entries());N.setItem(Qf,JSON.stringify(pe))}catch{}},[Y,N]),i.useEffect(()=>{try{N.setItem(qf,JSON.stringify(Array.from(oe)))}catch{}},[oe,N]);const Zs=i.useMemo(()=>he.map(pe=>({...pe,normalizedPath:vr(pe.path)})).filter(pe=>!!pe.normalizedPath),[he]),gr=i.useMemo(()=>Zs.map(pe=>{const ee=Ee.get(pe.normalizedPath);return`${pe.id}:${ee?.status?.current??""}`}).join("|"),[Zs,Ee]);i.useEffect(()=>{let pe=!1;return(async()=>{const xe=await Promise.all(Zs.map(async Ne=>{const ze=await Wo(Ne.normalizedPath).catch(()=>null);return{id:Ne.id,branch:ze}}));pe||G(Ne=>{const ze=new Map(Ne);return xe.forEach(({id:tt,branch:kt})=>{kt&&ze.set(tt,kt)}),ze})})(),()=>{pe=!0}},[Zs,gr]);const Ie=i.useCallback(pe=>{const ee=at?[]:We.get(pe.normalizedPath)??[],xe=[pe.normalizedPath,...ee.map(tt=>vr(tt.path)??tt.path).filter(tt=>!!tt)],Ne=new Set,ze=[];return xe.forEach(tt=>{(Xe.get(tt)??qe(tt)).forEach(re=>{Ne.has(re.id)||(Ne.add(re.id),ze.push(re))})}),ze},[We,qe,Xe,at]),Ge=i.useMemo(()=>Zs.map(pe=>{const ee=Ie(pe),xe=We.get(pe.normalizedPath)??[],Ne=Xs(ee,pe.normalizedPath,xe,X.get(pe.id)??null,!!S.get(pe.id));return{project:pe,groups:Ne}}),[Zs,Ie,Xs,We,X,S]),At=i.useMemo(()=>{if(Ge.length===0)return Ge;const pe=Ge.find(ee=>ee.project.id===He);return pe?[pe]:[Ge[0]]},[Ge,He]),it=i.useMemo(()=>Zs.find(pe=>pe.id===He)??Zs[0]??null,[Zs,He]),Kt=i.useMemo(()=>it?{id:it.id,path:it.normalizedPath}:null,[it]),It=i.useMemo(()=>it?!!S.get(it.id):!1,[it,S]),Ps=!!it,Hs=t||Pe.isMobile;i.useEffect(()=>{it||I(!1)},[it]);const Es=i.useMemo(()=>{const pe=new Map,ee=new Map,xe=(Ne,ze,tt,kt)=>{pe.has(Ne)||pe.set(Ne,new Map);const re=pe.get(Ne);kt.forEach(Le=>{const Ce=vr(Le.worktree?.path??Le.session.directory??tt??ze);re.set(Le.session.id,{directory:Ce}),ee.has(Ne)||ee.set(Ne,{id:Le.session.id,directory:Ce}),Le.children.length>0&&xe(Ne,ze,Ce,Le.children)})};return Ge.forEach(Ne=>{Ne.groups.forEach(ze=>{xe(Ne.project.id,Ne.project.normalizedPath,ze.directory,ze.sessions)})}),{metaByProject:pe,firstSessionByProject:ee}},[Ge]),er=i.useRef(null),Cs=i.useRef(null);i.useLayoutEffect(()=>{if(!He)return;const pe=Cs.current,ee=!!(pe&&pe!==He);if(Cs.current=He,St&&(at||!ee)||er.current===He)return;const xe=Ge.find(Ce=>Ce.project.id===He);if(!xe)return;er.current=He;const Ne=Es.metaByProject.get(He);if(st&&Ne&&Ne.has(st)){ie(Ce=>{if(Ce.get(He)===st)return Ce;const _e=new Map(Ce);return _e.set(He,st),_e});return}if(!Ne||Ne.size===0){Fe("chat"),t&&$e(!1),et({directoryOverride:xe.project.normalizedPath});return}const ze=Y.get(He),tt=ze&&Ne.has(ze)?ze:null,kt=Es.firstSessionByProject.get(He)?.id??null,re=tt??kt;if(!re||re===st)return;const Le=Ne.get(re)?.directory??null;Qt(re,Le,!1,He)},[He,Y,st,Qt,at,St,t,et,Ge,Es,Fe,$e]),i.useEffect(()=>{if(!He||!st)return;const pe=Es.metaByProject.get(He);!pe||!pe.has(st)||ie(ee=>{if(ee.get(He)===st)return ee;const xe=new Map(ee);return xe.set(He,st),xe})},[He,st,Es]);const ar=i.useMemo(()=>{if(!st)return null;const pe=ke.get(st)?.path;if(pe)return vr(pe)??pe;const ee=Re.find(xe=>xe.id===st);return ee?vr(ee.directory??null):null},[st,Re,ke]),ir=i.useCallback((pe,ee)=>{const xe=ce.get(pe);if(!xe||xe.length===0)return ee;const Ne=new Map(ee.map(tt=>[tt.id,tt])),ze=[];return xe.forEach(tt=>{const kt=Ne.get(tt);kt&&(ze.push(kt),Ne.delete(tt))}),ee.forEach(tt=>{Ne.has(tt.id)&&ze.push(tt)}),ze},[ce]),qs=i.useCallback(()=>{it&&(je(qi(it.label?.trim()||vo(it.normalizedPath,fe)||it.normalizedPath)),z(!0))},[it,fe]),Ir=i.useCallback(()=>{if(!it)return;const pe=J.trim();pe&&(we(it.id,pe),z(!1))},[it,J,we]),fr="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";i.useEffect(()=>{if(!bt)return;const pe=new IntersectionObserver(ee=>{ee.forEach(xe=>{const Ne=xe.target.dataset.projectId;Ne&&W(ze=>{const tt=new Set(ze);return xe.isIntersecting?tt.delete(Ne):tt.add(Ne),tt})})},{threshold:0});return ae.current.forEach(ee=>{ee&&pe.observe(ee)}),()=>pe.disconnect()},[bt,Ge]);const xr=i.useCallback((pe,ee=0,xe,Ne)=>{const ze=pe.session,tt=vr(ze.directory??null)??vr(xe??null),re=(tt?v.get(tt):null)==="missing",Le=os.get(ze.id),Ce=st===ze.id,_e=ze.title||"Untitled Session",Qe=pe.children.length>0,dt=y.has(ze.id),$t=ds.get(ze.id)?.needsAttention===!0,be=ze.summary,U=be?.diffs?.reduce((Ht,ls)=>({additions:Ht.additions+(Ki(ls?.additions)??0),deletions:Ht.deletions+(Ki(ls?.deletions)??0)}),{additions:0,deletions:0}),te=Ki(be?.additions)??U?.additions,Se=Ki(be?.deletions)??U?.deletions,Je=typeof te=="number"||typeof Se=="number";if(a===ze.id)return e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1","bg-interactive-selection",ee>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:Ht=>{Ht.preventDefault(),Zt()},children:[e.jsx("input",{value:c,onChange:Ht=>d(Ht.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:Ht=>{if(Ht.key==="Escape"){Ht.stopPropagation(),jt();return}(Ht.key===" "||Ht.key==="Enter")&&Ht.stopPropagation()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(ss,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:jt,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(hs,{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:[Qe?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:dt?e.jsx(is,{className:"h-3 w-3"}):e.jsx(dr,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Jf(ze.time?.created||Date.now())}),ze.share?e.jsx(Nc,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Je&&((te??0)!==0||(Se??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,te??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Se??0)]})]}):null,Qe?e.jsxs("span",{className:"truncate",children:[pe.children.length," ",pe.children.length===1?"task":"tasks"]}):null]})]})},ze.id);const rt=cs?.get(ze.id)?.type??"idle",lt=rt==="busy"||rt==="retry",Ke=de.get(ze.id)?.length??0,as=lt||!lt&&$t&&!Ce,Xt=Le&&Le.isZombie?e.jsx(kl,{className:"h-4 w-4 text-status-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",Ce?"bg-interactive-selection":"hover:bg-interactive-hover",re?"opacity-75":"",ee>0&&"pl-[20px]"),onContextMenu:Ht=>{Ht.preventDefault(),ve(ze.id)},children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:re,onClick:()=>Qt(ze.id,tt,re,Ne),onDoubleClick:Ht=>{Ht.stopPropagation(),Mt()},className:L("flex min-w-0 flex-1 flex-col gap-0 overflow-hidden 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 w-full items-center gap-2 min-w-0 flex-1 overflow-hidden",children:[as?e.jsx("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:lt?e.jsx(ly,{size:"xs",className:"text-primary"}):e.jsx("span",{className:"grid grid-cols-3 gap-[1px] text-[var(--status-info)]","aria-label":"Unread updates",title:"Unread updates",children:Array.from({length:9},(Ht,ls)=>mM.has(ls)?e.jsx("span",{className:"h-[3px] w-[3px] rounded-full bg-current animate-attention-diamond-pulse",style:{animationDelay:fM(ls)}},ls):e.jsx("span",{className:"h-[3px] w-[3px]"},ls))})}):null,e.jsx("div",{className:"block min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:_e}),Ke>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(Mv,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:Ke})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Qe?e.jsx("span",{role:"button",tabIndex:0,onClick:Ht=>{Ht.stopPropagation(),Ts(ze.id)},onKeyDown:Ht=>{(Ht.key==="Enter"||Ht.key===" ")&&(Ht.preventDefault(),Ht.stopPropagation(),Ts(ze.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(is,{className:"h-3 w-3"}):e.jsx(dr,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Jf(ze.time?.created||Date.now())}),ze.share?e.jsx(Nc,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Je&&((te??0)!==0||(Se??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,te??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Se??0)]})]}):null,Qe?e.jsxs("span",{className:"truncate",children:[pe.children.length," ",pe.children.length===1?"task":"tasks"]}):null,re?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-status-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:[Xt,e.jsxs(us,{open:V===ze.id,onOpenChange:Ht=>ve(Ht?ze.id:null),children:[e.jsx(ms,{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:Ht=>Ht.stopPropagation(),onKeyDown:Ht=>Ht.stopPropagation(),children:e.jsx(Qn,{className:t?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(fs,{align:"end",className:"min-w-[180px]",children:[e.jsxs(Et,{onClick:()=>{l(ze.id),d(_e)},className:"[&>svg]:mr-1",children:[e.jsx(fn,{className:"mr-1 h-4 w-4"}),"Rename"]}),ze.share?e.jsxs(e.Fragment,{children:[e.jsx(Et,{onClick:()=>{ze.share?.url&&vt(ze.share.url,ze.id)},className:"[&>svg]:mr-1",children:h===ze.id?e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Hr,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(Et,{onClick:()=>pt(ze.id),className:"[&>svg]:mr-1",children:[e.jsx(Av,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(Et,{onClick:()=>ft(ze),className:"[&>svg]:mr-1",children:[e.jsx(Nc,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(Et,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Jt(ze),children:[e.jsx(Nr,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),Qe&&dt?pe.children.map(Ht=>xr(Ht,ee+1,tt??xe,Ne)):null]},ze.id)},[v,os,cs,ds,de,st,y,a,c,Zt,jt,Ts,Qt,Mt,ft,vt,pt,Jt,h,t,V]),yr=i.useCallback((pe,ee,xe,Ne)=>{const ze=D.has(ee),tt=oe.has(ee),kt=n?10:5,re=pe.sessions.length,Le=ze?pe.sessions:pe.sessions.slice(0,kt),Ce=re-Le.length,Qe=(te=>{const Se=[],Je=rt=>{rt.forEach(lt=>{Se.push(lt.session),lt.children.length>0&&Je(lt.children)})};return Je(te),Se})(pe.sessions),dt=vr(pe.directory??null),$t=!!(xe&&S.get(xe)),be=!pe.isMain&&pM(pe.branch,pe.label),U=!!(dt&&ar&&dt===ar);return Ne?e.jsx("div",{className:"oc-group",children:e.jsxs("div",{className:"oc-group-body pb-3",children:[Le.map(te=>xr(te,0,pe.directory,xe)),re===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,Ce>0&&!ze?e.jsxs("button",{type:"button",onClick:()=>_s(ee),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 ",Ce," more ",Ce===1?"session":"sessions"]}):null,ze&&re>kt?e.jsx("button",{type:"button",onClick:()=>_s(ee),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]})}):e.jsxs("div",{className:"oc-group",children:[e.jsxs("div",{className:L("group/gh flex items-center justify-between gap-2 py-1 min-w-0 rounded-sm",!Ne&&"hover:bg-interactive-hover/50 cursor-pointer"),onClick:Ne?void 0:()=>{Z(te=>{const Se=new Set(te);return Se.has(ee)?Se.delete(ee):Se.add(ee),Se})},role:Ne?void 0:"button",tabIndex:Ne?void 0:0,onKeyDown:Ne?void 0:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),Z(Se=>{const Je=new Set(Se);return Je.has(ee)?Je.delete(ee):Je.add(ee),Je}))},"aria-label":Ne?void 0:tt?`Expand ${pe.label}`:`Collapse ${pe.label}`,children:[Ne?e.jsx("div",{}):e.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 px-0",children:[tt?e.jsx(dr,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):e.jsx(is,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}),!pe.isMain||$t?e.jsx(Ms,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):null,e.jsxs("div",{className:"min-w-0 flex flex-col justify-center",children:[e.jsx("p",{className:L("text-[15px] font-semibold truncate",U?"text-primary":"text-muted-foreground"),children:pe.label}),be?e.jsx("span",{className:"text-[10px] sm:text-[11px] text-muted-foreground/80 truncate leading-tight",children:pe.branch}):null]})]}),pe.directory?e.jsxs("div",{className:"flex items-center gap-1 px-0.5",children:[!pe.isMain&&pe.worktree?e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:te=>{te.stopPropagation(),Na.requestDelete({sessions:Qe,mode:"worktree",worktree:pe.worktree})},className:L("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",t?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),"aria-label":`Delete ${pe.label}`,children:e.jsx(Nr,{className:"h-4 w-4"})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"Delete worktree"})})]}):null,e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:te=>{te.stopPropagation(),xe&&xe!==He&&Ve(xe),Fe("chat"),t&&$e(!1),et({directoryOverride:pe.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${pe.label}`,children:e.jsx(Fs,{className:"h-4 w-4"})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session"})})]})]}):null]}),tt?null:e.jsxs("div",{className:"oc-group-body pb-3",children:[Le.map(te=>xr(te,0,pe.directory,xe)),re===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,Ce>0&&!ze?e.jsxs("button",{type:"button",onClick:()=>_s(ee),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 ",Ce," more ",Ce===1?"session":"sessions"]}):null,ze&&re>kt?e.jsx("button",{type:"button",onClick:()=>_s(ee),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]})]})},[D,oe,n,ar,S,xr,_s,He,Ve,Fe,t,$e,et]),_r=Dv(gm(_v,{activationConstraint:{distance:8}}),gm(Ov,{coordinateGetter:Lv}));return e.jsxs("div",{className:L("flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-sidebar"),children:[!n&&e.jsxs("div",{className:"select-none pl-3.5 pr-2 py-1.5 flex-shrink-0 border-b border-border/60",children:[e.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[e.jsxs(us,{onOpenChange:pe=>{pe||z(!1)},children:[e.jsx(ms,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-8 min-w-0 max-w-[calc(100%-2.5rem)] items-center gap-1 rounded-md px-2 text-left text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"text-base font-semibold truncate",children:it?qi(it.label?.trim()||vo(it.normalizedPath,fe)||it.normalizedPath):"Projects"}),e.jsx(is,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(fs,{align:"start",className:"min-w-[220px] max-w-[320px]",children:[Zs.map(pe=>{const ee=qi(pe.label?.trim()||vo(pe.normalizedPath,fe)||pe.normalizedPath);return e.jsx(Et,{onClick:()=>Ve(pe.id),className:L("truncate",pe.id===He&&"text-primary"),children:e.jsx("span",{className:"truncate",children:ee})},pe.id)}),e.jsx("div",{className:"my-1 h-px bg-border/70"}),ge?e.jsx("div",{className:"px-2 py-1.5",children:e.jsxs("form",{className:"flex items-center gap-1",onSubmit:pe=>{pe.preventDefault(),Ir()},children:[e.jsx("input",{value:J,onChange:pe=>je(pe.target.value),className:"h-7 flex-1 rounded border border-border bg-transparent px-2 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50",placeholder:"Rename project",autoFocus:!0,onKeyDown:pe=>{if(pe.key==="Escape"){pe.stopPropagation(),z(!1);return}(pe.key===" "||pe.key==="Enter")&&pe.stopPropagation()}}),e.jsx("button",{type:"submit",className:"inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:text-foreground",children:e.jsx(ss,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:()=>z(!1),className:"inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:text-foreground",children:e.jsx(hs,{className:"h-4 w-4"})})]})}):e.jsxs(Et,{onClick:pe=>{pe.preventDefault(),qs()},className:"gap-2",children:[e.jsx(fn,{className:"h-4 w-4"}),"Rename project"]}),e.jsxs(Et,{onClick:()=>{it&&ue(it.id)},className:"text-destructive focus:text-destructive gap-2",children:[e.jsx(hs,{className:"h-4 w-4"}),"Close project"]})]})]}),e.jsx("button",{type:"button",onClick:Ns,className:L("inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!bt&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(Cu,{className:"h-4.5 w-4.5"})})]}),Ps?e.jsx("div",{className:"mt-1 h-8 pl-1",children:it?e.jsxs("div",{className:"inline-flex h-8 items-center gap-1.5 rounded-md pl-0 pr-1",children:[It?e.jsxs(e.Fragment,{children:[e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:async()=>{if(!it)return;it.id!==He&&Ve(it.id);const pe=await ay();pe&&(Fe("chat"),t&&$e(!1),et({directoryOverride:pe}))},className:fr,"aria-label":"New worktree",children:e.jsx(Ms,{className:"h-4.5 w-4.5"})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New worktree"})})]}),e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>O(!0),className:fr,"aria-label":"New from issue",children:e.jsx(ku,{className:"h-4.5 w-4.5"})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New from issue"})})]}),e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>_(!0),className:fr,"aria-label":"New from PR",children:e.jsx(no,{className:"h-4.5 w-4.5"})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New from PR"})})]}),e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:Ze,className:fr,"aria-label":"New multi-run",children:e.jsx(Zu,{className:"h-4.5 w-4.5"})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New multi-run"})})]})]}):null,Hs?e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>I(!0),className:fr,"aria-label":"Project notes and todos",children:e.jsx(xm,{className:"h-4.5 w-4.5"})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"Project notes"})})]}):e.jsxs(us,{open:F,onOpenChange:I,modal:!1,children:[e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:e.jsx("button",{type:"button",className:fr,"aria-label":"Project notes and todos",children:e.jsx(xm,{className:"h-4.5 w-4.5"})})})}),e.jsx(ht,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"Project notes"})})]}),e.jsx(fs,{align:"start",className:"w-[340px] p-0",children:e.jsx(Wf,{projectRef:Kt,canCreateWorktree:It,onActionComplete:()=>I(!1)})})]})]}):null}):null]}),e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:L("space-y-1 pb-1 pl-2.5 pr-1",""),children:Ge.length===0?Ct:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const pe=Ge.find(Ne=>Ne.project.id===He)??Ge[0];if(!pe)return Ct;const ee=pe.groups.find(Ne=>Ne.isMain&&Ne.sessions.length>0)??pe.groups.find(Ne=>Ne.sessions.length>0)??pe.groups.find(Ne=>Ne.isMain)??pe.groups[0];if(!ee)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const xe=`${pe.project.id}:${ee.id}`;return yr(ee,xe,pe.project.id,o)})()}):e.jsx(e.Fragment,{children:At.map(pe=>{const ee=pe.project,xe=ee.id,Ne=qi(ee.label?.trim()||vo(ee.normalizedPath,fe)||ee.normalizedPath),ze=An(ee.normalizedPath,fe),tt=w.has(xe)&&n,kt=xe===He,re=S.get(xe),Le=P===xe,Ce=ir(xe,pe.groups);return e.jsx(gM,{id:xe,projectLabel:Ne,projectDescription:ze,isCollapsed:tt,isActiveProject:kt,isRepo:!!re,isHovered:Le,isDesktopShell:bt,isStuck:E.has(xe),hideDirectoryControls:n,mobileVariant:t,onToggle:()=>mr(xe),onHoverChange:_e=>$(_e?xe:null),onNewSession:()=>{xe!==He&&Ve(xe),Fe("chat"),t&&$e(!1),et({directoryOverride:ee.normalizedPath})},onNewWorktreeSession:()=>{xe!==He&&Ve(xe),Fe("chat"),t&&$e(!1),xc()},onNewSessionFromGitHubIssue:()=>{xe!==He&&Ve(xe),O(!0)},onNewSessionFromGitHubPR:()=>{xe!==He&&Ve(xe),_(!0)},onOpenMultiRunLauncher:()=>{xe!==He&&Ve(xe),Ze()},onRenameStart:()=>{m(xe),p(ee.label?.trim()||vo(ee.normalizedPath,fe)||ee.normalizedPath)},onRenameSave:es,onRenameCancel:Ye,onRenameValueChange:p,renameValue:u===xe?f:"",isRenaming:u===xe,onClose:()=>ue(xe),sentinelRef:_e=>{ae.current.set(xe,_e)},settingsAutoCreateWorktree:Ue,showCreateButtons:!1,hideHeader:!0,children:tt?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:pe.groups.length>0?e.jsxs(Iv,{sensors:_r,collisionDetection:Tv,onDragStart:_e=>{se(String(_e.active.id));const Qe=_e.active.rect.current.initial?.width??null;le(typeof Qe=="number"?Qe:null)},onDragCancel:()=>{se(null),le(null)},onDragEnd:_e=>{const{active:Qe,over:dt}=_e;if(se(null),le(null),!dt||Qe.id===dt.id)return;const $t=Ce.findIndex(te=>te.id===Qe.id),be=Ce.findIndex(te=>te.id===dt.id);if($t===-1||be===-1||$t===be)return;const U=Fv(Ce,$t,be).map(te=>te.id);Q(te=>{const Se=new Map(te);return Se.set(xe,U),Se})},children:[e.jsx(Ev,{items:Ce.map(_e=>_e.id),strategy:Pv,children:Ce.map(_e=>{const Qe=`${xe}:${_e.id}`;return e.jsx(yM,{id:_e.id,children:yr(_e,Qe,xe)},_e.id)})}),e.jsx(Rv,{modifiers:[hM],dropAnimation:null,children:B?(()=>{const _e=Ce.find(dt=>dt.id===B);if(!_e)return null;const Qe=!_e.isMain||!!re;return e.jsx(vM,{label:_e.label,showBranchIcon:Qe,width:H??void 0})})():null})]}):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},xe)})})}),e.jsx(rM,{open:R,onOpenChange:pe=>{O(pe),!pe&&t&&(Fe("chat"),$e(!1))}}),e.jsx(dM,{open:T,onOpenChange:pe=>{_(pe),!pe&&t&&(Fe("chat"),$e(!1))}}),Hs?e.jsx(Cr,{open:F,onClose:()=>I(!1),title:"Project notes",children:e.jsx(Wf,{projectRef:Kt,canCreateWorktree:It,onActionComplete:()=>I(!1),className:"p-0"})}):null]})},yc=()=>{const[t,s]=ne.useState(!1);ne.useEffect(()=>{s(As())},[]);const r=ne.useCallback(async a=>t?await Fg(a):{success:!0,path:a},[t]),n=ne.useCallback(async a=>t?await Lg():{success:!0},[t]),o=ne.useCallback(async a=>t?await Og():{success:!0},[t]);return{isDesktop:t,requestAccess:r,startAccessing:n,stopAccessing:o}},Zf=({currentPath:t,onSelectPath:s,triggerClassName:r,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:l,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const{isMobile:f}=ks(),[p,h]=i.useState([]),[g,x]=i.useState(new Set),[y,b]=i.useState(!0),[v,j]=i.useState(!1),[k,N]=i.useState(""),[w,C]=i.useState(new Set),[S,M]=i.useState(null),[D,A]=i.useState(""),[P,$]=i.useState(!0),R=i.useRef(null),{requestAccess:O,startAccessing:T,isDesktop:_}=yc(),F=i.useRef(c),I=i.useCallback(G=>{if(!G)return G;if(G==="/"||G.length===0)return"/";let ae=G;for(;ae.length>1&&ae.endsWith("/");)ae=ae.slice(0,-1);return ae.length===0?"/":ae},[]),E=i.useMemo(()=>{if(!k)return null;const G=k.replace(/\\/g,"/");return I(G)},[k,I]),W=i.useMemo(()=>{if(typeof d=="string"&&d.length>0){const G=d.replace(/\\/g,"/"),ae=I(G);if(ae&&ae!=="/")return ae}return E&&E!=="/"?E:null},[d,E,I]),V=i.useMemo(()=>typeof u=="boolean"?!!(u&&W):!!W,[u,W]);i.useEffect(()=>{V||(b(!0),h([]))},[V]);const ve=i.useCallback(G=>{if(!G||!V||!W)return!1;const ae=G.replace(/\\/g,"/"),me=I(ae)??ae;if(me===W)return!0;const Oe=`${W}/`;return me.startsWith(Oe)},[V,W,I]),oe=async G=>{if(V){if(a==="deferred"){s(G);return}if(_){const ae=await O(G);ae.success&&ae.path?(await T(ae.path),s(ae.path)):(console.error("Failed to get directory access:",ae.error),s(G))}else s(G)}};i.useEffect(()=>{let G=!1;const ae=Be=>{if(!Be)return!1;const fe=I(Be.replace(/\\/g,"/"));return!fe||fe==="/"?!1:(N(typeof fe=="string"?fe:Be.replace(/\\/g,"/")),!0)};return d&&ae(d)||(async()=>{try{const Be=await nt.getFilesystemHome();if(!G&&ae(Be))return}catch(Be){console.warn("Failed to resolve filesystem home directory:",Be)}try{const Be=await nt.getSystemInfo();if(!G&&ae(Be?.homeDirectory))return}catch(Be){console.warn("Failed to resolve home directory from system info:",Be)}})(),()=>{G=!0}},[d,I]),i.useEffect(()=>{let G=!1;const ae=fe=>{if(G)return;const q=fe.filter(ye=>typeof ye=="string"&&ye.length>0).map(ye=>{const he=ye.replace(/\\/g,"/");return I(he)??he});C(new Set(q))},me=()=>{try{const fe=localStorage.getItem("pinnedDirectories");if(!fe)return;const q=JSON.parse(fe);Array.isArray(q)&&ae(q)}catch(fe){console.warn("Failed to load pinned directories from local storage:",fe)}},Oe=async()=>{try{let fe=[];const q=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(q.ok){const ye=await q.json();fe=Array.isArray(ye?.pinnedDirectories)?ye.pinnedDirectories:[]}if(G)return;ae(fe)}catch(fe){console.warn("Failed to load pinned directories:",fe)}};me();const Be=fe=>{const q=fe.detail;q&&Array.isArray(q.pinnedDirectories)&&ae(q.pinnedDirectories)};return window.addEventListener("ikanban:settings-synced",Be),Oe(),()=>{G=!0,window.removeEventListener("ikanban:settings-synced",Be)}},[I]);const Z=i.useRef(!0);i.useEffect(()=>{if(Z.current){Z.current=!1;return}const G={pinnedDirectories:Array.from(w)};xs(G)},[w]),i.useEffect(()=>{W&&C(G=>{const ae=Array.from(G).map(me=>I(me.replace(/\\/g,"/"))??me).filter(me=>ve(me));return new Set(ae)})},[W,ve,I]),i.useEffect(()=>{F.current!==c&&(F.current=c)},[c]);const ce=G=>{C(ae=>{if(!ve(G))return ae;const me=I(G.replace(/\\/g,"/"))??G.replace(/\\/g,"/"),Oe=new Set(ae);return Oe.has(me)?Oe.delete(me):Oe.add(me),Oe})},Q=i.useMemo(()=>Array.from(w).map(G=>I(G.replace(/\\/g,"/"))??G).filter(G=>ve(G)).map(G=>({path:G,name:G.split("/").pop()||G})).sort((G,ae)=>G.name.localeCompare(ae.name)),[w,ve,I]),Y=i.useCallback(async G=>{const ae=q=>c||!q.startsWith("."),me=W;if(!V||!me)return[];const Oe=G&&G.length>0?G:me,Be=Oe?Oe.replace(/\\/g,"/"):null,fe=Be?I(Be)??Be:null;if(fe){const q=`${me}/`;if(!(fe===me||fe.startsWith(q)))return[]}try{return(await nt.listLocalDirectory(G)).filter(ye=>{if(!ye.isDirectory||!ae(ye.name))return!1;const he=ye.path.replace(/\\/g,"/"),He=I(he)??he,ot=He===me?me:`${me}/`;return He===me||He.startsWith(ot)}).map(ye=>({name:ye.name,path:ye.path.replace(/\\/g,"/"),isDirectory:!0})).sort((ye,he)=>ye.name.localeCompare(he.name))}catch{try{const ye=await nt.getApiClient().file.list({path:".",directory:G});return ye.data?ye.data.filter(he=>{if(he.type!=="directory"||!he.name||!ae(he.name))return!1;const He=String(he.absolute||he.path||he.name).replace(/\\/g,"/"),ot=I(He)??He,ue=ot===me?me:`${me}/`;return ot===me||ot.startsWith(ue)}).map(he=>({name:he.name||"",path:String(he.absolute||he.path||he.name).replace(/\\/g,"/"),isDirectory:!0})).filter(he=>he.name!=="").sort((he,He)=>he.name.localeCompare(He.name)):[]}catch{return[]}}},[c,W,I,V]),ie=i.useRef(!1),B=i.useCallback(async()=>{if(!V||!W){b(!0),h([]);return}ie.current||b(!0);try{const G=await Y(W);h(G),ie.current=!0}catch{}finally{b(!1)}},[V,W,Y]);i.useEffect(()=>{V&&(n==="inline"||v)&&B()},[n,v,V,B]);const se=async G=>{if(!V)return;const ae=g.has(G.path),me=new Set(g);if(ae){me.delete(G.path),x(me);return}me.add(G.path),x(me);const Oe=await Y(G.path),Be=fe=>fe.map(q=>q.path===G.path?{...q,children:Oe}:q.children?{...q,children:Be(q.children)}:q);h(fe=>Be(fe))};i.useEffect(()=>{S&&R.current&&(R.current.focus(),R.current.select())},[S]);const H=(G,ae=[])=>{const me="new_directory",Oe=ae.map(ye=>ye.name);if(!Oe.includes(me))return me;let Be=1;const fe=new RegExp(`^${me}(\\d+)$`);for(const ye of Oe){const he=ye.match(fe);if(he){const He=parseInt(he[1],10);He>Be&&(Be=He)}}let q=2;for(;Oe.includes(`${me}${q}`);)q++;return`${me}${Math.max(q,Be+1)}`},le=async G=>{if(V){if(g.has(G.path)){const ae=H(G.path,G.children);A(ae)}else{const ae=new Set(g);if(ae.add(G.path),x(ae),G.children){const me=H(G.path,G.children);A(me)}else{const me=await Y(G.path),Oe=fe=>fe.map(q=>q.path===G.path?{...q,children:me}:q.children?{...q,children:Oe(q.children)}:q);h(fe=>Oe(fe));const Be=H(G.path,me);A(Be)}}M(G.path)}},ge=async()=>{if(!S||!V)return;const G=D.trim()||"new_directory",ae=`${S}/${G}`;try{await nt.createDirectory(ae,{allowOutsideWorkspace:!0});const me=await Y(S),Oe=Be=>Be.map(fe=>fe.path===S?{...fe,children:me}:fe.children?{...fe,children:Oe(fe.children)}:fe);h(Be=>Oe(Be)),M(null),A("")}catch(me){console.error("Failed to create directory:",me)}},z=()=>{M(null),A("")},J=(G,ae=0)=>{const me=g.has(G.path),Oe=G.isDirectory,Be=w.has(G.path),fe=t===G.path,q=n==="inline",ye=e.jsxs(e.Fragment,{children:[Oe&&e.jsx("button",{onClick:he=>{he.stopPropagation(),se(G)},className:L("hover:bg-interactive-hover rounded","p-0.5"),children:me?e.jsx(is,{className:f?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(dr,{className:f?"h-3.5 w-3.5":"h-3 w-3"})}),!Oe&&e.jsx("div",{className:f?"w-4.5":"w-4"}),e.jsxs("button",{onClick:he=>{he.stopPropagation(),oe(G.path),n==="dropdown"&&a==="immediate"&&j(!1)},onDoubleClick:he=>{he.stopPropagation(),l&&l(G.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",q&&fe?"text-primary":"text-foreground"),children:[e.jsx(Nn,{className:L("text-muted-foreground flex-shrink-0",f?"h-4 w-4":"h-3.5 w-3.5",q&&fe&&"text-primary")}),e.jsx("span",{className:L("font-medium truncate","typography-ui-label",q&&fe?"text-primary":"text-foreground"),children:G.name})]}),e.jsx("button",{onClick:he=>{he.stopPropagation(),le(G)},className:L("hover:bg-interactive-hover rounded transition-opacity",f?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(Fs,{className:L("text-muted-foreground",f?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:he=>{he.stopPropagation(),ce(G.path)},className:L("hover:bg-interactive-hover rounded transition-opacity",f?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:Be?"Unpin directory":"Pin directory",children:Be?e.jsx(kc,{className:L("text-primary",f?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx($v,{className:L("text-muted-foreground",f?"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",f?"px-1.5 py-1":"px-2 py-1.5",fe?"bg-primary/10 text-primary":"hover:bg-interactive-hover/50 text-foreground"),style:{paddingLeft:`${ae*(f?12:14)+(f?4:6)}px`},children:ye}),me&&e.jsxs(e.Fragment,{children:[S===G.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(ae+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Nn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Bt,{ref:R,value:D,onChange:he=>A(he.target.value),onKeyDown:he=>{he.key==="Enter"?(he.preventDefault(),he.stopPropagation(),ge()):he.key==="Escape"&&(he.preventDefault(),he.stopPropagation(),z())},onBlur:ge,className:"h-6 typography-meta flex-1 selection:bg-interactive-selection selection:text-interactive-selection-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:he=>{he.preventDefault(),he.stopPropagation(),ge()},className:"p-1 hover:bg-interactive-hover rounded",title:"Create directory",children:e.jsx(ss,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:he=>{he.preventDefault(),he.stopPropagation(),z()},className:"p-1 hover:bg-interactive-hover rounded",title:"Cancel",children:e.jsx(hs,{className:"h-3 w-3 text-muted-foreground"})})]}),G.children&&G.children.map(he=>J(he,ae+1))]})]},G.path):e.jsxs("div",{children:[e.jsxs(Et,{className:L("flex items-center gap-1 cursor-pointer group",t===G.path&&"bg-interactive-selection"),style:{paddingLeft:`${ae*12+8}px`},onSelect:he=>{he.preventDefault()},children:[Oe&&e.jsx("button",{onClick:he=>{he.stopPropagation(),se(G)},className:"p-0.5 hover:bg-interactive-hover rounded",children:me?e.jsx(is,{className:"h-3 w-3"}):e.jsx(dr,{className:"h-3 w-3"})}),!Oe&&e.jsx("div",{className:"w-4"}),ye]}),me&&e.jsxs("div",{children:[S===G.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(ae+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Nn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Bt,{ref:R,value:D,onChange:he=>A(he.target.value),onKeyDown:he=>{he.key==="Enter"?(he.preventDefault(),he.stopPropagation(),ge()):he.key==="Escape"&&(he.preventDefault(),he.stopPropagation(),z())},onBlur:ge,className:"h-6 typography-meta flex-1 selection:bg-interactive-selection selection:text-interactive-selection-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:he=>{he.preventDefault(),he.stopPropagation(),ge()},className:"p-1 hover:bg-interactive-hover rounded",title:"Create directory",children:e.jsx(ss,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:he=>{he.preventDefault(),he.stopPropagation(),z()},className:"p-1 hover:bg-interactive-hover rounded",title:"Cancel",children:e.jsx(hs,{className:"h-3 w-3 text-muted-foreground"})})]}),G.children&&G.children.map(he=>J(he,ae+1))]})]},G.path)},je=(G,ae)=>{if(n==="inline"){const me=t===ae;return e.jsxs("div",{className:L("group flex items-center gap-2 mx-1 rounded-lg transition-colors",f?"px-1.5 py-1":"px-2 py-1.5",me?"bg-primary/10":"hover:bg-interactive-hover/50"),children:[e.jsxs("button",{onClick:()=>oe(ae),onDoubleClick:Oe=>{Oe.stopPropagation(),l&&l(ae)},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",me?"text-primary":"text-foreground"),children:[e.jsx(Nn,{className:L("flex-shrink-0",f?"h-4 w-4":"h-3.5 w-3.5",me?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:L("typography-ui-label font-medium truncate flex-shrink-0",me?"text-primary":"text-foreground"),children:G}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:An(ae,k)})]}),e.jsx("button",{onClick:()=>ce(ae),className:L("hover:bg-interactive-hover rounded-md transition-opacity",f?"p-1.5 opacity-60":"p-1 opacity-0 group-hover:opacity-100"),title:"Unpin directory",children:e.jsx(kc,{className:L("text-primary","h-3.5 w-3.5")})})]},ae)}return e.jsxs(Et,{onSelect:me=>{me.preventDefault(),oe(ae),a==="immediate"&&j(!1)},className:L("flex items-start gap-2 cursor-pointer group py-2",t===ae&&"bg-interactive-selection"),children:[e.jsx(Nn,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium",children:G}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:An(ae,k)})]}),e.jsx("button",{onClick:me=>{me.stopPropagation(),me.preventDefault(),ce(ae)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-interactive-hover rounded transition-opacity",title:"Unpin directory",children:e.jsx(kc,{className:"h-3 w-3 text-primary"})})]},ae)},X=e.jsx(e.Fragment,{children:V?e.jsxs(e.Fragment,{children:[Q.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>$(G=>!G),className:L("flex w-full items-center gap-1.5 typography-meta font-medium text-muted-foreground/80 hover:bg-interactive-hover/30 rounded transition-colors uppercase tracking-wide",f?"px-1.5 py-1":"px-2 py-1.5"),children:[P?e.jsx(is,{className:f?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(dr,{className:f?"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:Q.length})]}),P&&Q.map(({name:G,path:ae})=>je(G,ae)),n==="dropdown"&&e.jsx(lr,{}),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",f?"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..."}):p.map(G=>J(G)),!y&&p.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No directories found"})]}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Locating home directory..."})});return n==="inline"?e.jsx("div",{className:L("overflow-hidden flex flex-col",o),children:e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:X})}):e.jsxs(us,{open:v,onOpenChange:j,children:[e.jsx(ms,{asChild:!0,children:e.jsxs(Me,{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",r),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(Nn,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:t,children:An(t,k)})]}),e.jsx(is,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(fs,{align:"start",className:"w-[350px]",children:e.jsx(Ut,{outerClassName:"h-full",className:"w-full",children:X})})]})},bc=(t,s=200)=>{const[r,n]=ne.useState(t);return ne.useEffect(()=>{const o=window.setTimeout(()=>{n(t)},s);return()=>{window.clearTimeout(o)}},[t,s]),r},cy=i.forwardRef(({inputValue:t,homeDirectory:s,onSelectSuggestion:r,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,w)=>{const C=N.trim().toLowerCase();if(!C)return 0;const S=w.toLowerCase();let M=0,D=-1,A=0;for(let P=0;P<C.length;P+=1){const $=C[P];if(!$||$===" ")continue;const R=S.indexOf($,D+1);if(R===-1)return null;const O=R-D-1;if(O===0?A+=1:A=0,M+=10,M+=Math.max(0,18-R),M-=Math.max(0,O),R===0)M+=12;else{const T=S[R-1];(T==="/"||T==="_"||T==="-"||T==="."||T===" ")&&(M+=10)}M+=A>0?12:0,D=R}return M+=Math.max(0,24-Math.round(S.length/3)),M},[]),y=i.useCallback(N=>N.startsWith("~")&&s?N.replace(/^~/,s):N,[s]),b=i.useCallback(N=>{const w=y(N);if(w.endsWith("/"))return w;const C=w.lastIndexOf("/");return C===-1?"":C===0?"/":w.substring(0,C+1)},[y]),v=i.useCallback(N=>{const w=y(N);if(w.endsWith("/"))return"";const C=w.lastIndexOf("/");return C===-1?w:w.substring(C+1)},[y]),j=bc(t,150);i.useEffect(()=>{if(!n||!j){d([]);return}const N=b(j),w=v(j).toLowerCase();if(!N){d([]);return}let C=!1;return m(!0),nt.listLocalDirectory(N).then(S=>{if(C)return;const M=S.filter(A=>!(!A.isDirectory||!a&&A.name.startsWith("."))),D=w?M.map(A=>{const P=x(w,A.name);return P!==null?{entry:A,score:P}:null}).filter(A=>A!==null).sort((A,P)=>P.score-A.score||A.entry.name.localeCompare(P.entry.name)).map(A=>A.entry):M.sort((A,P)=>A.name.localeCompare(P.name));d(D.slice(0,10)),p(0)}).catch(()=>{C||d([])}).finally(()=>{C||m(!1)}),()=>{C=!0}},[n,j,b,v,a,x]),i.useEffect(()=>{g.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),i.useEffect(()=>{if(!n)return;const N=w=>{const C=w.target;!C||!h.current||h.current.contains(C)||o()};return document.addEventListener("pointerdown",N,!0),()=>{document.removeEventListener("pointerdown",N,!0)}},[n,o]);const k=i.useCallback(N=>{const w=N.path.endsWith("/")?N.path:N.path+"/";r(w)},[r]);return i.useImperativeHandle(l,()=>({handleKeyDown:N=>{if(!n||c.length===0)return!1;const w=c.length;if(N.key==="Tab"){if(N.preventDefault(),N.shiftKey)p(C=>(C-1+w)%w);else if(w===1){const C=c[0];C&&k(C)}else p(C=>(C+1)%w);return!0}if(N.key==="ArrowDown")return N.preventDefault(),p(C=>(C+1)%w),!0;if(N.key==="ArrowUp")return N.preventDefault(),p(C=>(C-1+w)%w),!0;if(N.key==="Enter"){N.preventDefault();const C=(f%w+w)%w,S=c[C];return S&&k(S),o(),!0}return N.key==="Escape"?(N.preventDefault(),o(),!0):!1}}),[n,c,f,k,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(Mr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:c.map((N,w)=>{const C=f===w;return e.jsxs("div",{ref:S=>{g.current[w]=S},className:L("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",C&&"bg-interactive-selection"),onClick:()=>{k(N),o()},onMouseEnter:()=>p(w),children:[e.jsx(Fn,{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"})]})});cy.displayName="DirectoryAutocomplete";const wM=({open:t,onOpenChange:s})=>{const{currentDirectory:r,homeDirectory:n,isHomeReady:o}=Yt(),{addProject:a,getActiveProject:l}=ps(),[c,d]=i.useState(null),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,g]=i.useState(!1),x=wi(),{isDesktop:y,requestAccess:b,startAccessing:v}=yc(),{isMobile:j}=ks(),[k,N]=i.useState(!1),w=i.useRef(null),C=i.useCallback(Z=>Z?An(Z,n):"",[n]);i.useEffect(()=>{if(t){p(!1),g(!1),N(!1);const ce=l()?.path||r||n||"";d(ce),m(C(ce))}},[t,r,n,C,l]),i.useEffect(()=>{!t||f||c||n&&o&&(d(n),p(!0),m("~"))},[t,f,c,n,o]);const S=i.useCallback(()=>{s(!1)},[s]),M=i.useCallback(async Z=>{if(!(!Z||h)){g(!0);try{let ce=Z,Q;if(y){const ie=await b(Z);if(!ie.success){K.error("Unable to access directory",{description:ie.error||"Desktop denied directory access."});return}ce=ie.path??Z,Q=ie.projectId;const B=await v(ce);if(!B.success){K.error("Failed to open directory",{description:B.error||"Desktop could not grant file access."});return}}if(!a(ce,{id:Q})){K.error("Failed to add project",{description:"Please select a valid directory path."});return}S()}catch(ce){K.error("Failed to select directory",{description:ce instanceof Error?ce.message:"Unknown error occurred."})}finally{g(!1)}}},[a,S,y,b,v,h]),D=i.useCallback(async()=>{const Z=u.trim()||c;Z&&await M(Z)},[M,u,c]),A=i.useCallback(Z=>{d(Z),p(!0),m(C(Z))},[C]),P=i.useCallback(async Z=>{d(Z),p(!0),m(C(Z)),await M(Z)},[M,C]),$=i.useCallback(Z=>{const ce=Z.target.value;if(m(ce),p(!0),N(ce.startsWith("/")||ce.startsWith("~")),ce.startsWith("/")||ce.startsWith("~")){const Q=ce.startsWith("~")&&n?ce.replace(/^~/,n):ce;d(Q)}},[n]),R=i.useCallback(Z=>{w.current?.handleKeyDown(Z)||Z.key==="Enter"&&(Z.preventDefault(),D())},[D]),O=i.useCallback(Z=>{d(Z),p(!0),m(C(Z))},[C]),T=i.useCallback(()=>{N(!1)},[]),_=i.useCallback(()=>{Pu(!x)},[x]),F=e.jsxs("button",{type:"button",onClick:_,className:"flex items-center gap-2 px-2 py-1 rounded-lg hover:bg-interactive-hover/40 transition-colors typography-meta text-muted-foreground flex-shrink-0",children:[x?e.jsx(Kn,{className:"h-4 w-4 text-primary"}):e.jsx(qn,{className:"h-4 w-4"}),"Show hidden"]}),I=e.jsxs(js,{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(Ss,{children:"Add project directory"}),e.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[e.jsx(Is,{className:"flex-1",children:"Choose a folder to add as a project."}),F]})]}),E=e.jsxs("div",{className:"relative",children:[e.jsx(Bt,{value:u,onChange:$,onKeyDown:R,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(cy,{ref:w,inputValue:u,homeDirectory:n,onSelectSuggestion:O,visible:k,onClose:T,showHidden:x})]}),W=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(Zf,{variant:"inline",currentPath:c??r,onSelectPath:A,onDoubleClickPath:P,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:x,rootDirectory:o?n:null,isRootReady:o})}),V=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:E}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:F}),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(Zf,{variant:"inline",currentPath:c??r,onSelectPath:A,onDoubleClickPath:P,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:x,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),ve=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[E,W]}),oe=()=>e.jsxs(e.Fragment,{children:[e.jsx(Me,{variant:"ghost",onClick:S,disabled:h,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(Me,{onClick:D,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 j?e.jsx(Cr,{open:t,onClose:()=>s(!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:oe()}),children:V}):e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{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:Z=>{Z.preventDefault()},children:[I,ve,e.jsx(Js,{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:oe()})]})})},Ha=t=>t?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,So=t=>{if(!t)return"";const s=t.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},jM=()=>{const[t,s]=i.useState(!1),[r,n]=i.useState(!1),[o,a]=i.useState(null),[l,c]=i.useState([]),[d,u]=i.useState(!1),[m,f]=i.useState(!1),[p,h]=i.useState(!1),[g,x]=i.useState(!1),[y,b]=i.useState(new Set),{deleteSession:v,deleteSessions:j,loadSessions:k,getWorktreeMetadata:N}=Ae(),{currentDirectory:w,homeDirectory:C,isHomeReady:S}=Yt(),{projects:M,addProject:D,activeProjectId:A}=ps(),{requestAccess:P,startAccessing:$}=yc(),{isMobile:R,isTablet:O,hasTouchInput:T}=ks(),_=R||O||T,F=i.useMemo(()=>{const ae=(A?M.find(me=>me.id===A)??null:null)?.path??w;return So(ae)},[A,w,M]),I=i.useCallback(G=>{const me=So(G.projectDirectory)||F;return{id:(M.find(Be=>So(Be.path)===me)??null)?.id??`path:${me}`,path:me}},[F,M]),E=g&&y.size>0,W=i.useMemo(()=>{const G=o?.worktree;return G&&typeof G.branch=="string"&&G.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:ae})=>typeof ae.branch=="string"&&ae.branch.trim().length>0)},[o?.worktree,l]),V=o?.mode==="worktree",ve=V,oe=p||!V||!W,Z=p||!V;i.useEffect(()=>{k()},[k,w]);const ce=i.useMemo(()=>M.map(G=>`${G.id}:${G.path}`).join("|"),[M]),Q=i.useRef(ce);i.useEffect(()=>{ce!==Q.current&&(Q.current=ce,k())},[k,ce]),i.useEffect(()=>{if(!(r||!S||M.length>0)){if(n(!0),As()&&Or()){P("").then(async G=>{if(!G.success||!G.path){G.error&&G.error!=="Directory selection cancelled"&&K.error("Failed to select directory",{description:G.error});return}const ae=await $(G.path);if(!ae.success){K.error("Failed to open directory",{description:ae.error||"Desktop could not grant file access."});return}D(G.path,{id:G.projectId})||K.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(G=>{console.error("Desktop: Error selecting directory:",G),K.error("Failed to select directory")});return}s(!0)}},[D,r,S,M.length,P,$]);const Y=i.useCallback(G=>{a({sessions:G.sessions,dateLabel:G.dateLabel,mode:G.mode??"session",worktree:G.worktree??null})},[]),ie=i.useCallback(()=>{a(null),c([]),u(!1),f(!1),h(!1),x(!1),b(new Set)},[]);i.useEffect(()=>Na.onDeleteRequest(G=>{Y(G)}),[Y]),i.useEffect(()=>Na.onDirectoryRequest(()=>{s(!0)}),[]),i.useEffect(()=>{if(!o){c([]),u(!1),f(!1),x(!1),b(new Set);return}const G=o.sessions.map(Oe=>{const Be=N(Oe.id);return Be?{session:Oe,metadata:Be}:null}).filter(Oe=>!!Oe);c(G),u(!1),x(!1),b(new Set);const ae=new Map;if(o.worktree?.path&&ae.set(So(o.worktree.path),o.worktree),G.forEach(({metadata:Oe})=>{Oe.path&&ae.set(So(Oe.path),Oe)}),ae.size===0){x(!0);return}let me=!1;return(async()=>{const Oe=new Map,Be=new Set;await Promise.all(Array.from(ae.entries()).map(async([fe,q])=>{try{const ye=await Ni(q.path);Oe.set(fe,ye),ye?.isDirty&&Be.add(fe)}catch{q.status&&(Oe.set(fe,q.status),q.status.isDirty&&Be.add(fe))}})).catch(fe=>{console.warn("Failed to inspect worktree status before deletion:",fe)}),!me&&(b(Be),x(!0),a(fe=>{if(!fe?.worktree?.path)return fe;const q=So(fe.worktree.path),ye=Oe.get(q);if(!ye)return fe;const he=fe.worktree.status;return he?.isDirty===ye.isDirty&&he?.ahead===ye.ahead&&he?.behind===ye.behind&&he?.upstream===ye.upstream?fe:{...fe,worktree:{...fe.worktree,status:ye}}}),c(fe=>fe.map(q=>{const ye=So(q.metadata.path),he=Oe.get(ye);return he?{session:q.session,metadata:{...q.metadata,status:he}}:q})))})(),()=>{me=!0}},[o,N]),i.useEffect(()=>{W||u(!1)},[W]);const B=i.useCallback(async(G,ae)=>{const me=d&&W;try{return await fc(I(G),G,{deleteRemoteBranch:me,deleteLocalBranch:ae}),!0}catch(Oe){return K.error("Failed to remove worktree",{description:Ha(Oe instanceof Error?Oe.message:"Please try again.")}),!1}},[W,d,I]),se=i.useCallback(async()=>{if(o){h(!0);try{const G=ve,ae=G&&d,me=G&&m;if(o.sessions.length===0&&V&&o.worktree){if(!await B(o.worktree,me)){ie();return}const fe=d&&W?"Worktree and remote branch removed.":"Worktree removed.";K.success("Worktree removed",{description:Ha(fe)}),ie(),k();return}if(o.sessions.length===1){const Oe=o.sessions[0];if(!await v(Oe.id,{archiveWorktree:V?!1:G,deleteRemoteBranch:ae,deleteLocalBranch:me})){K.error("Failed to delete session"),h(!1);return}const fe=!V&&G?ae?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;K.success("Session deleted",{description:Ha(fe),action:{label:"OK",onClick:()=>{}}})}else{const Oe=o.sessions.map(q=>q.id),{deletedIds:Be,failedIds:fe}=await j(Oe,{archiveWorktree:V?!1:G,deleteRemoteBranch:ae,deleteLocalBranch:me});if(V&&o.worktree&&fe.length===0&&await B(o.worktree,me)&&await k(),Be.length>0){const q=!V&&G?ae?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,he=[fe.length>0?`${fe.length} session${fe.length===1?"":"s"} could not be deleted.`:o.dateLabel?`Removed all sessions from ${o.dateLabel}.`:void 0,q].filter(Boolean).join(" ");K.success(`Deleted ${Be.length} session${Be.length===1?"":"s"}`,{description:Ha(he||void 0),action:{label:"OK",onClick:()=>{}}})}if(fe.length>0&&(K.error(`Failed to delete ${fe.length} session${fe.length===1?"":"s"}`,{description:Ha("Please try again in a moment.")}),Be.length===0)){h(!1);return}}V&&o.sessions.length===1&&o.worktree&&await B(o.worktree,me)&&await k(),ie()}finally{h(!1)}}},[o,d,m,v,j,ie,ve,V,W,B,k]),H=o?.worktree??l[0]?.metadata??null,le=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}`:""}.`:"",ge=o?e.jsxs("div",{className:L(V?"space-y-3":"space-y-2"),children:[o.sessions.length>0&&e.jsxs("div",{className:L(V?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[V&&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(V?"mt-2 space-y-1":"space-y-0.5"),children:[o.sessions.slice(0,5).map(G=>e.jsxs("li",{className:L(V?"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(!V&&"hidden"),children:"•"}),e.jsx("span",{className:"truncate",children:G.title||"Untitled Session"})]},G.id)),o.sessions.length>5&&e.jsxs("li",{className:L(V?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",o.sessions.length-5," more"]})]})]}),V?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(Ms,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),H?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:H.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:H?An(H.path,C):"Worktree path unavailable."}),E&&e.jsx("p",{className:"typography-micro text-status-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,z=V?W?e.jsxs("button",{type:"button",onClick:()=>{oe||u(G=>!G)},disabled:oe,className:L("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",oe?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[d?e.jsx(Kn,{className:"size-4 text-primary"}):e.jsx(qn,{className:"size-4"}),"Delete remote branch"]}):e.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,J=V?e.jsxs("button",{type:"button",onClick:()=>{Z||f(G=>!G)},disabled:Z,className:L("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",Z?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[m?e.jsx(Kn,{className:"size-4 text-primary"}):e.jsx(qn,{className:"size-4"}),"Delete local branch"]}):null,je=V?e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[J,z]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{variant:"ghost",onClick:ie,disabled:p,children:"Cancel"}),e.jsx(Me,{variant:"destructive",onClick:se,disabled:p,children:p?"Deleting…":"Delete worktree"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Me,{variant:"ghost",onClick:ie,disabled:p,children:"Cancel"}),e.jsx(Me,{variant:"destructive",onClick:se,disabled:p,children:p?"Deleting…":o?.sessions.length===1?"Delete session":"Delete sessions"})]}),X=V?"Delete worktree":o?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[_?e.jsx(Cr,{open:!!o,onClose:()=>{p||ie()},title:X,footer:e.jsx("div",{className:"flex justify-end gap-2",children:je}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[le&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:le}),ge]})}):e.jsx(bs,{open:!!o,onOpenChange:G=>{if(!G){if(p)return;ie()}},children:e.jsxs(vs,{className:L(V?"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(js,{children:[e.jsxs(Ss,{className:L(V&&"flex items-center gap-2"),children:[V&&e.jsx(Nr,{className:"h-5 w-5"}),X]}),le&&e.jsx(Is,{children:le})]}),e.jsx("div",{className:L(V&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:ge}),e.jsx(Js,{className:"mt-2 gap-2 pt-1 pb-1",children:je})]})}),e.jsx(wM,{open:t,onOpenChange:s})]})},iu=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),SM=(t,s)=>{const r=iu(t),n=iu(s);return`${r}-${n}`.substring(0,60)},ep=(t,s)=>`${t}/${s}`,NM=()=>{const t=ps.getState(),s=t.activeProjectId;if(!s)return null;const r=t.projects.find(o=>o.id===s);if(r?.path)return{id:r.id,path:r.path};const n=Yt.getState().currentDirectory??null;if(n&&n.trim().length>0){const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n;return{id:`path:${o}`,path:o}}return null},ni=Ls()(Us(t=>({isLoading:!1,error:null,createMultiRun:async s=>{const r=s.name.trim(),n=s.prompt.trim(),{models:o,agent:a,files:l,setupCommands:c}=s;if(!r)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=NM();if(!d)return t({error:"Select a project",isLoading:!1}),null;const u=d.path;if(!await Yn(u))return t({error:"Not in a git repository",isLoading:!1}),null;const f=iu(r),p=await Wo(u),h=await Xu(u),g=[],x=c?.filter(w=>w.trim().length>0)??[],y=new Map;for(const w of o){const C=`${w.providerID}:${w.modelID}`;y.set(C,(y.get(C)||0)+1)}const b=new Map;for(const w of o){const C=`${w.providerID}:${w.modelID}`,S=y.get(C)||1,M=(b.get(C)||0)+1;b.set(C,M);const D=SM(w.providerID,w.modelID),A=S>1?ep(f,`${D}/${M}`):ep(f,D);try{const P=await gc(d,{preferredName:A,mode:"new",branchName:A,worktreeName:A,startRef:s.worktreeBaseBranch||"HEAD",setupCommands:x},{resolvedRootTrackingRemote:h}),$={...P,createdFromBranch:p,kind:"standard"},R=S>1?`${f}/${w.providerID}/${w.modelID}/${M}`:`${f}/${w.providerID}/${w.modelID}`,O=await nt.withDirectory(P.path,()=>nt.createSession({title:R}));Wt.getState().setWorktreeMetadata(O.id,$),g.push({sessionId:O.id,worktreePath:P.path,providerID:w.providerID,modelID:w.modelID,variant:w.variant})}catch(P){console.warn("[MultiRun] Failed to create session:",P)}}const v=c?.filter(w=>w.trim().length>0)??[];v.length>0&&xx(d,v).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const j=g.map(w=>w.sessionId),k=g[0]?.sessionId??null;if(j.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const N=l?.map(w=>({type:"file",mime:w.mime,filename:w.filename,url:w.url}));try{await Wt.getState().loadSessions()}catch{}return(async()=>{try{await Promise.allSettled(g.map(async w=>{try{await nt.withDirectory(w.worktreePath,()=>nt.sendMessage({id:w.sessionId,providerID:w.providerID,modelID:w.modelID,variant:w.variant,text:n,agent:a,files:N}))}catch(C){console.warn("[MultiRun] Failed to start run:",C)}}))}catch(w){console.warn("[MultiRun] Failed to start runs:",w)}})(),t({isLoading:!1}),{groupSlug:f,sessionIds:j,firstSessionId:k}}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 $s({...t}){return e.jsx(Bv,{"data-slot":"select",...t})}function bl({...t}){return e.jsx(Kv,{"data-slot":"select-group",...t})}function Sr({...t}){return e.jsx(Hv,{"data-slot":"select-value",...t})}function Bs({className:t,size:s="default",children:r,...n}){return e.jsxs(zv,{"data-slot":"select-trigger","data-size":s,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 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-interactive-hover data-[state=open]:bg-interactive-active 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:[r,e.jsx(Uv,{asChild:!0,children:e.jsx(is,{className:"size-4 opacity-50"})})]})}function zs({className:t,children:s,position:r="popper",fitContent:n=!1,...o}){return e.jsx(Vv,{children:e.jsx(Wv,{"data-slot":"select-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:L("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-2 border-border/60 shadow-md transform-gpu will-change-transform",r==="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:r,...o,children:e.jsx(Ut,{as:Gv,outerClassName:L("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:L("p-1",r==="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:s})})})}function Yc({className:t,...s}){return e.jsx(qv,{"data-slot":"select-label",className:L("text-muted-foreground px-2 py-1.5 typography-meta",t),...s})}function ns({className:t,children:s,...r}){return e.jsxs(Qv,{"data-slot":"select-item",className:L("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[state=checked]:bg-interactive-selection data-[state=checked]:text-interactive-selection-foreground [&_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),...r,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(Yv,{children:e.jsx(ss,{className:"size-4"})})}),e.jsx(Jv,{children:s})]})}function tp({className:t,...s}){return e.jsx(Xv,{"data-slot":"select-separator",className:L("bg-border pointer-events-none -mx-1 my-1 h-px",t),...s})}const em=t=>t.nativeEvent.isComposing||t.nativeEvent.keyCode===229,vc=()=>{const{providers:t}=ut(),{favoriteModels:s,recentModels:r}=Te(),n=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),[s,t]),o=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).filter(({providerID:a,modelID:l})=>!s.some(c=>c.providerID===a&&c.modelID===l)),[r,t,s]);return{favoriteModelsList:n,recentModelsList:o}},dy="h-7",Yl=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,kM=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),CM=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const s=kM.format(t);return s.endsWith(".0")?s.slice(0,-2):s},MM=({model:t,instanceIndex:s,totalSameModel:r,onRemove:n})=>{const o=t.displayName||`${t.providerID}/${t.modelID}`,a=r>1?`${o} (${s})`:o;return e.jsxs("div",{className:L("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",dy),children:[e.jsx(Os,{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(hs,{className:"h-3.5 w-3.5"})})]})},uy=({selectedModels:t,onAdd:s,onRemove:r,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:l=!0,maxModels:c})=>{const{providers:d,modelsMetadata:u}=ut(),{favoriteModelsList:m,recentModelsList:f}=vc(),[p,h]=i.useState(!1),[g,x]=i.useState(""),[y,b]=i.useState(0),[v,j]=i.useState(null),k=i.useRef(null),N=i.useRef(null),w=i.useRef(null),C=i.useRef([]),S=i.useMemo(()=>{const F=new Map;for(const I of t){const E=`${I.providerID}:${I.modelID}`;F.set(E,(F.get(E)||0)+1)}return F},[t]),M=i.useCallback(F=>t.filter(E=>E.providerID===F.providerID&&E.modelID===F.modelID).findIndex(E=>E.instanceId===F.instanceId)+1,[t]),D=(F,I)=>{const E=`${F}/${I}`;return u.get(E)},A=F=>{const I=F?.name||F?.id||"",E=String(I);return E.length>40?E.substring(0,37)+"...":E},P=i.useCallback((F,I)=>{if(!g.trim())return!0;const E=g.toLowerCase();return F.toLowerCase().includes(E)||I.toLowerCase().includes(E)},[g]),$=i.useMemo(()=>m.filter(({model:F,providerID:I})=>{const W=d.find(ve=>ve.id===I)?.name||I,V=A(F);return P(V,W)}),[m,d,P]),R=i.useMemo(()=>f.filter(({model:F,providerID:I})=>{const W=d.find(ve=>ve.id===I)?.name||I,V=A(F);return P(V,W)}),[f,d,P]),O=i.useMemo(()=>d.map(F=>{const E=(Array.isArray(F.models)?F.models:[]).filter(W=>{const V=A(W);return P(V,F.name||F.id||"")});return{...F,models:E}}).filter(F=>F.models.length>0),[d,P]),T=$.length>0||R.length>0||O.length>0;i.useEffect(()=>{if(p&&w.current){const I=w.current.getBoundingClientRect().top-100;j(Math.max(150,Math.min(400,I)))}},[p]),i.useEffect(()=>{p&&k.current&&k.current.focus()},[p]),i.useEffect(()=>{if(!p)return;const F=I=>{N.current&&!N.current.contains(I.target)&&(h(!1),x(""),b(0))};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[p]),i.useEffect(()=>{b(0)},[g]);const _=(F,I,E,W,V,ve)=>{const oe=`${I}:${E}`,Z=S.get(oe)||0,ce=D(I,E),Q=CM(ce?.limit?.context),Y=W==="fav"||W==="recent";return e.jsxs("button",{ref:ie=>{C.current[V]=ie},type:"button",onClick:()=>{s({providerID:I,modelID:E,displayName:F.name||E,instanceId:Yl()})},onMouseEnter:()=>b(V),className:L("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",ve?"bg-interactive-selection":"hover:bg-interactive-hover/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[Y&&e.jsx(Os,{providerId:I,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(F)}),Q&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:Q})]}),Z>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",Z]})]},`${W}-${oe}`)};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(Me,{ref:w,type:"button",variant:"outline",size:"sm",className:dy,onClick:()=>h(!p),children:[e.jsx(Fs,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const F=[];$.forEach(({model:V,providerID:ve,modelID:oe})=>{F.push({model:V,providerID:ve,modelID:oe,section:"fav"})}),R.forEach(({model:V,providerID:ve,modelID:oe})=>{F.push({model:V,providerID:ve,modelID:oe,section:"recent"})}),O.forEach(V=>{V.models.forEach(ve=>{F.push({model:ve,providerID:V.id,modelID:ve.id,section:"provider"})})});const I=F.length,E=V=>{if(!em(V))if(V.key==="ArrowDown"){V.preventDefault(),V.stopPropagation();const ve=(y+1)%Math.max(1,I);b(ve),setTimeout(()=>{C.current[ve]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(V.key==="ArrowUp"){V.preventDefault(),V.stopPropagation();const ve=(y-1+Math.max(1,I))%Math.max(1,I);b(ve),setTimeout(()=>{C.current[ve]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(V.key==="Enter"){V.preventDefault(),V.stopPropagation();const ve=F[y];ve&&s({providerID:ve.providerID,modelID:ve.modelID,displayName:ve.model.name||ve.modelID,instanceId:Yl()})}else V.key==="Escape"&&(V.preventDefault(),V.stopPropagation(),h(!1),x(""),b(0))};let W=0;return e.jsxs("div",{style:{backgroundColor:"var(--surface-elevated)"},className:"absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden 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(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Bt,{ref:k,type:"text",placeholder:"Search models",value:g,onChange:V=>x(V.target.value),onKeyDown:E,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(Ut,{outerClassName:"flex-1",style:{maxHeight:v?`${v}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!T&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),$.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[e.jsx(Mn,{className:"h-4 w-4 text-primary"}),"Favorites"]}),$.map(({model:V,providerID:ve,modelID:oe})=>{const Z=W++;return _(V,ve,oe,"fav",Z,y===Z)})]}),R.length>0&&e.jsxs(e.Fragment,{children:[$.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[e.jsx(Pn,{className:"h-4 w-4"}),"Recent"]}),R.map(({model:V,providerID:ve,modelID:oe})=>{const Z=W++;return _(V,ve,oe,"recent",Z,y===Z)})]}),($.length>0||R.length>0)&&O.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),O.map((V,ve)=>e.jsxs(i.Fragment,{children:[ve>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[e.jsx(Os,{providerId:V.id,className:"h-4 w-4 flex-shrink-0"}),V.name]}),V.models.map(oe=>{const Z=W++;return _(oe,V.id,oe.id,"provider",Z,y===Z)})]},V.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((F,I)=>{const E=`${F.providerID}:${F.modelID}`,W=S.get(E)||1,V=M(F),oe=d.find(ie=>ie.id===F.providerID)?.models.find(ie=>ie.id===F.modelID),Z=oe?.variants?Object.keys(oe.variants):[],ce=Z.length>0,Q="__default__",Y=F.variant??Q;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(MM,{model:F,instanceIndex:V,totalSameModel:W,onRemove:()=>r(I)}),ce&&e.jsxs($s,{value:Y,onValueChange:ie=>{if(!n)return;n(I,{...F,variant:ie===Q?void 0:ie})},children:[e.jsxs(Bs,{size:"chip",className:"px-2 gap-1.5 rounded-md bg-interactive-selection/20 border-border/30 hover:bg-interactive-hover/30 typography-meta font-medium text-foreground",children:[e.jsx(Rn,{className:L("h-3.5 w-3.5 flex-shrink-0",Y===Q?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(Sr,{placeholder:"Thinking"})]}),e.jsxs(zs,{fitContent:!0,children:[e.jsx(ns,{value:Q,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),Z.map(ie=>e.jsx(ns,{value:ie,className:"pr-2 [&>span:first-child]:hidden",children:ie},ie))]})]})]},F.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`:"","."]})]})},AM=t=>{const s=String(t||"").trim().replace(/^remotes\//,"");if(!s)return null;const r=s.indexOf("/");return r<=0?null:s.slice(0,r)};function tm(t){const[s,r]=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),r([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),l(null),(async()=>{try{const d=await Yn(t);if(c)return;if(l(d),!d){r([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await _u(t).catch(()=>null);if(c)return;const m=await Xu(t).catch(()=>null);if(c)return;const f=[],p=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";f.push({value:"HEAD",label:p,group:"special"}),u&&(u.all.filter(x=>!x.startsWith("remotes/")).filter(x=>{if(!m)return!0;const y=u.branches?.[x]?.tracking,b=AM(y);return b?b===m:!0}).sort((x,y)=>x.localeCompare(y)).forEach(x=>{f.push({value:x,label:x,group:"local"})}),u.all.filter(x=>x.startsWith("remotes/")).map(x=>x.replace(/^remotes\//,"")).filter(x=>{if(!m)return!0;const y=x.indexOf("/");return y<=0?!1:x.slice(0,y)===m}).sort((x,y)=>x.localeCompare(y)).forEach(x=>{f.push({value:x,label:x,group:"remote"})})),r(f)}finally{c||o(!1)}})(),()=>{c=!0}},[t]),{branches:s,isLoading:n,isGitRepository:a}}const my=({directory:t,value:s,onChange:r,className:n,disabled:o,id:a})=>{const{branches:l,isLoading:c,isGitRepository:d}=tm(t),u=i.useMemo(()=>l.find(f=>f.value===s)?.label??null,[l,s]);i.useEffect(()=>{!l.some(p=>p.value===s)&&l.length>0&&r("HEAD")},[l,s,r]);const m=o||!d||c;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs($s,{value:s,onValueChange:r,disabled:m,children:[e.jsx(Bs,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(Sr,{children:u}):e.jsx(Sr,{placeholder:c?"Loading branches…":"Select a branch"})}),e.jsxs(zs,{fitContent:!0,children:[e.jsxs(bl,{children:[e.jsx(Yc,{children:"Default"}),l.filter(f=>f.group==="special").map(f=>e.jsx(ns,{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(tp,{}),e.jsxs(bl,{children:[e.jsx(Yc,{children:"Local branches"}),l.filter(f=>f.group==="local").map(f=>e.jsx(ns,{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(tp,{}),e.jsxs(bl,{children:[e.jsx(Yc,{children:"Remote branches"}),l.filter(f=>f.group==="remote").map(f=>e.jsx(ns,{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."})]})},fy=({value:t,onChange:s,className:r,disabled:n,id:o})=>{const a=ut(f=>f.getVisibleAgents),l=ut(f=>f.loadAgents),c=ut(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)){s(p);return}const h=u[0]?.name;h&&s(h)},[c,n,s,u,t]);const m=t.trim().length>0?t:void 0;return e.jsxs($s,{value:m,onValueChange:s,disabled:n,children:[e.jsx(Bs,{id:o,size:"lg",className:r??"max-w-full typography-meta text-foreground",children:e.jsx(Sr,{placeholder:"Select an agent"})}),e.jsx(zs,{fitContent:!0,children:u.length>0&&e.jsx(bl,{children:u.map(f=>e.jsx(ns,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},DM=10*1024*1024,sp=5,rp=({initialPrompt:t,onCreated:s,onCancel:r})=>{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,y]=i.useState([]),[b,v]=i.useState(!1),[j,k]=i.useState(!1),N=i.useRef(null),w=Yt(H=>H.currentDirectory??null),C=i.useMemo(()=>{if(typeof window>"u")return null;const H=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof H=="string"&&H.trim().length>0?H.trim():null},[]),S=ps(H=>H.activeProjectId),M=ps(H=>H.projects),D=i.useMemo(()=>{if(S){const le=M.find(ge=>ge.id===S);if(le?.path)return{id:le.id,path:le.path}}const H=w??C;return H?{id:`path:${H}`,path:H}:null},[S,M,w,C]),[A,P]=i.useState(()=>typeof window>"u"?!1:Lr()),$=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{typeof window>"u"||P(Lr())},[]);const R=i.useMemo(()=>{if(typeof window>"u")return null;const H=window.__IKANBAN_MACOS_MAJOR__;if(typeof H=="number"&&Number.isFinite(H)&&H>0)return H;if(typeof navigator>"u")return null;const le=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!le)return null;const ge=Number.parseInt(le[1],10),z=Number.parseInt(le[2],10);return Number.isNaN(ge)?null:ge===10?z:ge},[]),O=i.useMemo(()=>A&&$?"pl-[5.5rem]":"pl-3",[A,$]),T=i.useMemo(()=>!A||!$||R===null?"":R>=26?"h-12":R<=15?"h-14":"",[A,$,R]),_=i.useCallback(async H=>{if(!H.target.closest("button, a, input, select, textarea")&&H.button===0&&A)try{const{getCurrentWindow:le}=await Ks(async()=>{const{getCurrentWindow:z}=await import("@tauri-apps/api/window");return{getCurrentWindow:z}},[]);await le().startDragging()}catch{}},[A]);i.useEffect(()=>{if(!r)return;const H=le=>{le.key==="Escape"&&(le.preventDefault(),le.stopPropagation(),r())};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[r]);const[F,I]=i.useState("HEAD"),{isLoading:E,isGitRepository:W}=tm(w),V=ni(H=>H.createMultiRun),ve=ni(H=>H.error),oe=ni(H=>H.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&l(H=>H.trim().length>0?H:t)},[t]),i.useEffect(()=>{if(!D)return;let H=!1;return k(!0),(async()=>{try{const le=await Ia(D);H||y(le)}catch{}finally{H||k(!1)}})(),()=>{H=!0}},[D]);const Z=H=>{c.length>=sp||(d(le=>[...le,H]),oe())},ce=H=>{d(le=>le.filter((ge,z)=>z!==H)),oe()},Q=i.useCallback((H,le)=>{d(ge=>ge.map((z,J)=>J===H?le:z))},[]),Y=async H=>{const le=H.target.files;if(!le)return;let ge=0;for(let z=0;z<le.length;z++){const J=le[z];if(J.size>DM){K.error(`File "${J.name}" is too large (max 10MB)`);continue}try{const je=await new Promise((G,ae)=>{const me=new FileReader;me.onload=()=>G(me.result),me.onerror=ae,me.readAsDataURL(J)}),X={id:Yl(),filename:J.name,mimeType:J.type||"application/octet-stream",size:J.size,dataUrl:je};p(G=>[...G,X]),ge++}catch(je){console.error("File attach failed",je),K.error(`Failed to attach "${J.name}"`)}}ge>0&&K.success(`Attached ${ge} file${ge>1?"s":""}`),N.current&&(N.current.value="")},ie=H=>{p(le=>le.filter(ge=>ge.id!==H))},B=async H=>{if(H.preventDefault(),!!a.trim()&&!(c.length<2)){g(!0),oe();try{const le=c.map(({instanceId:X,...G})=>G),ge=f.map(X=>({mime:X.mimeType,filename:X.filename,url:X.dataUrl})),z=x.filter(X=>X.trim().length>0),J={name:n.trim(),prompt:a.trim(),models:le,agent:u||void 0,worktreeBaseBranch:F,files:ge.length>0?ge:void 0,setupCommands:z.length>0?z:void 0},je=await V(J);je&&(je.firstSessionId&&Ae.getState().setCurrentSession(je.firstSessionId),s?.())}finally{g(!1)}}},se=!!(n.trim()&&a.trim()&&c.length>=2&&W&&!E);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{onMouseDown:_,className:L("relative flex h-12 items-center justify-center border-b app-region-drag select-none",O,T),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"}),r&&e.jsx("div",{className:"absolute right-0 flex items-center pr-3",children:e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:r,"aria-label":"Close (Esc)",className:"inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:e.jsx(hs,{className:"h-5 w-5"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Close (Esc)"})})]})})]}),e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"chat-column py-6",children:e.jsxs("form",{onSubmit:B,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(Bt,{id:"group-name",value:n,onChange:H=>o(H.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(my,{directory:w,value:F,onChange:I,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(tn,{open:b,onOpenChange:v,children:[e.jsxs(On,{className:"w-full flex items-center justify-between py-1 hover:bg-[var(--interactive-hover)] rounded-md px-1 -mx-1 transition-colors",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",x.filter(H=>H.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",x.filter(H=>H.trim()).length," configured)"]})]}),e.jsx(is,{className:L("h-4 w-4 text-muted-foreground transition-transform duration-200",b&&"rotate-180")})]}),e.jsx(sn,{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."]}),j?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[x.map((H,le)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Bt,{value:H,onChange:ge=>{const z=[...x];z[le]=ge.target.value,y(z)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const ge=x.filter((z,J)=>J!==le);y(ge)},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(hs,{className:"h-4 w-4"})})]},le)),e.jsxs("button",{type:"button",onClick:()=>y([...x,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Fs,{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(fy,{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(hr,{id:"prompt",value:a,onChange:H=>l(H.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(Me,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>N.current?.click(),children:[e.jsx(Ml,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(H=>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:[H.mimeType.startsWith("image/")?e.jsx(Ln,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(In,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:H.filename,children:H.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",H.size<1024?`${H.size}B`:H.size<1024*1024?`${(H.size/1024).toFixed(1)}KB`:`${(H.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>ie(H.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(hs,{className:"h-3.5 w-3.5"})})]},H.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(uy,{selectedModels:c,onAdd:Z,onRemove:ce,onUpdate:Q,minModels:2,maxModels:sp})]}),ve&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:ve}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(Me,{type:"button",variant:"outline",onClick:r,children:"Cancel"}),e.jsx(Me,{type:"submit",disabled:!se||h,children:h?"Creating...":e.jsxs(e.Fragment,{children:["Start (",c.length," models)"]})})]})]})})})]})},IM=(t={})=>{const{edgeThreshold:s=30,minSwipeDistance:r=50,maxSwipeTime:n=300,enabled:o=!0}=t,{isMobile:a,setSessionSwitcherOpen:l,isSessionSwitcherOpen:c}=Te(),d=ne.useRef(null),u=ne.useRef(null);return ne.useEffect(()=>{if(!o||!a)return;const m=g=>{const x=g.touches[0];if(!x){d.current=null;return}x.clientX<=s?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:y,y:b,time:v}=d.current,{x:j,y:k,time:N}=u.current,w=j-y,C=k-b,S=N-v,M=Math.abs(C)<Math.abs(w),D=S<=n,A=Math.abs(C)<r;w>=r&&M&&D&&A&&!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,s,r,n,l,c]),null};function TM(){const t=Ae(o=>o.currentSessionId),s=Ae(o=>t?o.messages.get(t):void 0),r=Ae(o=>t?o.permissions.get(t):void 0),n=ne.useRef(0);ne.useEffect(()=>{},[t,s]),ne.useEffect(()=>{!t||!r||r.length},[t,r]),ne.useEffect(()=>{n.current=0},[t])}function EM({children:t}){return TM(),e.jsx(e.Fragment,{children:t})}class PM{recognition=null;isListening=!1;currentLang="en-US";onResultCallback=null;onErrorCallback=null;restartOnEnd=!1;conversationMode=!1;isSpeaking=!1;audioContext=null;audioUnlockRequired=!1;isSupported(){const s="SpeechRecognition"in window||"webkitSpeechRecognition"in window,r="speechSynthesis"in window;return s&&r}getSupportDetails(){return{recognition:"SpeechRecognition"in window||"webkitSpeechRecognition"in window,synthesis:"speechSynthesis"in window,prefixed:!("SpeechRecognition"in window)&&"webkitSpeechRecognition"in window,secureContext:window.isSecureContext}}setConversationMode(s){this.conversationMode=s,s||(this.restartOnEnd=!1)}isConversationMode(){return this.conversationMode}pauseListening(){if(this.restartOnEnd=!1,this.recognition)try{this.recognition.stop()}catch{}this.isListening=!1}resumeListening(){if(console.log("[BrowserVoiceService] resumeListening called:",{conversationMode:this.conversationMode,hasCallback:!!this.onResultCallback,isSpeaking:this.isSpeaking,currentLang:this.currentLang}),this.conversationMode&&this.onResultCallback&&!this.isSpeaking)try{console.log("[BrowserVoiceService] Resuming listening..."),this.startListeningSync(this.currentLang,this.onResultCallback,this.onErrorCallback||void 0)}catch(s){console.error("[BrowserVoiceService] Failed to resume listening:",s)}else console.log("[BrowserVoiceService] Not resuming - conditions not met")}async checkMicrophonePermission(){try{return"permissions"in navigator?(await navigator.permissions.query({name:"microphone"})).state==="granted":!1}catch{return!1}}async prepareListening(){if(!this.isSupported())throw new Error("Web Speech API not supported in this browser");if(typeof navigator>"u"||typeof navigator.mediaDevices?.getUserMedia!="function")return!0;try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(r=>r.stop()),!0}catch(s){const r=typeof s=="object"&&s&&"name"in s?String(s.name):"";if(r==="NotAllowedError")throw new Error("Microphone permission denied");if(r==="NotFoundError")throw new Error("No microphone found");const n=s instanceof Error?s.message:"Unable to access microphone";throw new Error(n)}}startListeningSync(s,r,n){if(!this.isSupported()){const a="Web Speech API not supported in this browser";throw n?.(a),new Error(a)}this.stopListening();const o=window.SpeechRecognition||window.webkitSpeechRecognition;this.recognition=new o,this.currentLang=s,this.onResultCallback=r,this.onErrorCallback=n||null,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.lang=s,this.recognition.onstart=()=>{console.log("[BrowserVoiceService] Recognition started"),this.isListening=!0,this.restartOnEnd=!0},this.recognition.onaudiostart=()=>{console.log("[BrowserVoiceService] Audio recording started")},this.recognition.onsoundstart=()=>{console.log("[BrowserVoiceService] Sound detected")},this.recognition.onresult=a=>{console.log("[BrowserVoiceService] Got result:",a.results.length,"results");let l="",c="";for(let d=a.resultIndex;d<a.results.length;d++){const u=a.results[d];u.isFinal?l+=u[0].transcript:c+=u[0].transcript}console.log("[BrowserVoiceService] Transcripts - interim:",c,"final:",l),c&&(console.log("[BrowserVoiceService] Calling onResultCallback with interim"),this.onResultCallback?.(c,!1)),l&&(console.log("[BrowserVoiceService] Calling onResultCallback with final"),this.onResultCallback?.(l,!0))},this.recognition.onerror=a=>{if(a.error==="aborted")return;const l=this.getErrorMessage(a.error);this.onErrorCallback?.(l),(a.error==="not-allowed"||a.error==="service-not-allowed")&&(this.restartOnEnd=!1,this.isListening=!1)},this.recognition.onend=()=>{if(this.isListening=!1,this.restartOnEnd&&this.recognition&&!this.isSpeaking)try{this.recognition.start()}catch{}};try{this.recognition.start()}catch(a){const l=a instanceof Error?a.message:"Failed to start speech recognition";throw n?.(l),new Error(l)}}async startListening(s,r,n){this.startListeningSync(s,r,n)}stopListening(){if(this.restartOnEnd=!1,this.recognition){try{this.recognition.stop()}catch{}this.recognition=null}this.isListening=!1}getIsListening(){return this.isListening}getCurrentLang(){return this.currentLang}async resumeAudioContext(){this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext.state==="suspended"&&await this.audioContext.resume()}isAudioUnlockRequired(){return this.audioUnlockRequired}async unlockAudio(){try{const s=new Audio;if(s.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA",s.volume=.01,await s.play(),await this.resumeAudioContext(),this.isMobileDevice()&&"speechSynthesis"in window){const r=new SpeechSynthesisUtterance("");r.volume=0,window.speechSynthesis.speak(r),window.speechSynthesis.cancel(),console.log("[BrowserVoiceService] Speech synthesis unlocked for mobile")}return this.audioUnlockRequired=!1,console.log("[BrowserVoiceService] Audio unlocked successfully"),!0}catch(s){return console.error("[BrowserVoiceService] Failed to unlock audio:",s),!1}}async speakText(s,r,n,o){if(!("speechSynthesis"in window))throw new Error("Speech synthesis not supported");await this.resumeAudioContext();const a=await this.waitForVoices();await new Promise(d=>setTimeout(d,50)),this.isSpeaking=!0,this.pauseListening(),window.speechSynthesis.cancel();const l=new SpeechSynthesisUtterance(s);l.lang=r,l.rate=o?.rate??1,l.pitch=o?.pitch??1,l.volume=o?.volume??1;let c=null;return o?.voiceName&&(c=a.find(d=>d.name===o.voiceName)||null,c?console.log(`[BrowserVoiceService] Using selected voice: ${c.name} (${c.lang})`):console.warn(`[BrowserVoiceService] Selected voice "${o.voiceName}" not found, falling back to language match`)),c||(c=this.findBestVoice(a,r),c?console.log(`[BrowserVoiceService] Using language-matched voice: ${c.name} (${c.lang})`):console.warn(`[BrowserVoiceService] No voice found for language: ${r}, using default`)),c&&(l.voice=c),console.log(`[BrowserVoiceService] Speaking text (${s.length} chars) in ${r}`),new Promise((d,u)=>{let m=!1;l.onstart=()=>{m=!0,console.log("[BrowserVoiceService] Speech started"),d()},l.onend=()=>{this.isSpeaking=!1,console.log("[BrowserVoiceService] Speech ended"),n?.()},l.onerror=f=>{this.isSpeaking=!1,console.error("[BrowserVoiceService] Speech synthesis error:",f.error),(f.error==="not-allowed"||f.error==="interrupted")&&(this.audioUnlockRequired=!0);let p=`Speech synthesis error: ${f.error||"unknown"}`;f.error==="not-allowed"?p="Audio blocked by browser autoplay policy. Please interact with the page first.":f.error==="interrupted"&&(p="Speech was interrupted. Please try again."),u(new Error(p))},setTimeout(()=>{m||(console.warn("[BrowserVoiceService] Speech start timeout - audio may be blocked"),this.audioUnlockRequired=!0)},2e3),window.speechSynthesis.speak(l)})}cancelSpeech(){"speechSynthesis"in window&&window.speechSynthesis.cancel()}getVoices(){return"speechSynthesis"in window?window.speechSynthesis.getVoices():[]}async waitForVoices(){if(!("speechSynthesis"in window))return[];const s=window.speechSynthesis.getVoices();return s.length>0?s:new Promise(r=>{const n=()=>{r(window.speechSynthesis.getVoices()),window.speechSynthesis.onvoiceschanged=null};window.speechSynthesis.onvoiceschanged=n,setTimeout(()=>{r(window.speechSynthesis.getVoices()),window.speechSynthesis.onvoiceschanged=null},1e3)})}findBestVoice(s,r){let n=s.find(o=>o.lang===r);if(!n){const o=r.split("-")[0];n=s.find(a=>a.lang.startsWith(o))}return n||(n=s.find(o=>o.lang.startsWith(r.split("-")[0])&&o.localService)),n||null}isMobileDevice(){if(typeof navigator>"u")return!1;const s=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod|android|mobile|webos|blackberry|iemobile|opera mini/i.test(s)}isIOSSafari(){if(typeof navigator>"u")return!1;const s=navigator.userAgent.toLowerCase(),r=/iphone|ipad|ipod/i.test(s),n=/safari/i.test(s)&&!/chrome|crios|crmo/i.test(s);return r&&n}getErrorMessage(s){const r=this.isMobileDevice(),n=this.isIOSSafari();return{"no-speech":"No speech detected",aborted:"Speech recognition aborted","audio-capture":"No microphone found",network:"Network error - check connection","not-allowed":r?"Microphone permission denied. Check Settings > Safari > Microphone":"Microphone permission denied","service-not-allowed":n?"Speech recognition requires a user gesture. Please tap the microphone button again.":"Speech recognition service not allowed","bad-grammar":"Grammar error","language-not-supported":"Language not supported"}[s]||`Speech recognition error: ${s}`}}const ws=new PM;let Jc=null;function np(){return Jc||(Jc=new(window.AudioContext||window.webkitAudioContext)),Jc}function py(){const[t,s]=ne.useState(!1),[r,n]=ne.useState(!1),[o,a]=ne.useState(null),l=ne.useRef(null),c=ne.useRef(null),{currentProviderId:d,currentModelId:u,summarizeCharacterThreshold:m,summarizeMaxLength:f,openaiApiKey:p,settingsZenModel:h}=ut(),g=ne.useCallback(async()=>{try{const v=await fetch("/api/tts/status");if(v.ok){const k=(await v.json()).available,N=p&&p.trim().length>0,w=k||N;return n(w),w}return n(!1),!1}catch(v){return console.error("[useServerTTS] Failed to check availability:",v),n(!1),!1}},[p]);ne.useEffect(()=>{g()},[g]);const x=ne.useCallback(()=>{if(l.current){try{l.current.stop()}catch{}l.current=null}c.current&&(c.current.abort(),c.current=null),s(!1)},[]),y=ne.useCallback(async()=>{try{const v=np();v.state==="suspended"&&(await v.resume(),console.log("[useServerTTS] AudioContext resumed"));const j=v.createBuffer(1,1,22050),k=v.createBufferSource();k.buffer=j,k.connect(v.destination),k.start(0),console.log("[useServerTTS] Audio unlocked for mobile playback")}catch(v){console.error("[useServerTTS] Failed to unlock audio:",v)}},[]),b=ne.useCallback(async(v,j)=>{if(x(),!v.trim()){a("No text to speak"),j?.onError?.("No text to speak");return}a(null);try{const k=np();k.state==="suspended"&&(await k.resume(),console.log("[useServerTTS] AudioContext resumed"));const N=k.createBuffer(1,1,22050),w=k.createBufferSource();w.buffer=N,w.connect(k.destination),w.start(0),c.current=new AbortController;const C=j?.voice||"nova";console.log("[useServerTTS] Speaking with voice:",C,"options:",j);const S=await fetch("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:v.trim(),voice:C,speed:j?.speed||.9,instructions:j?.instructions,summarize:j?.summarize??!0,providerId:j?.providerId||d||void 0,modelId:j?.modelId||u||void 0,threshold:j?.threshold??m??200,maxLength:f??500,apiKey:p||void 0,...h?{zenModel:h}:{}}),signal:c.current.signal});if(!S.ok){const $=await S.json().catch(()=>({error:"Unknown error"}));throw new Error($.error||`HTTP ${S.status}`)}const D=await(await S.blob()).arrayBuffer();console.log("[useServerTTS] Decoding audio data...");const A=await k.decodeAudioData(D),P=k.createBufferSource();P.buffer=A,P.connect(k.destination),l.current=P,P.onended=()=>{console.log("[useServerTTS] Audio playback ended"),s(!1),l.current=null,j?.onEnd?.()},console.log("[useServerTTS] Starting audio playback via Web Audio API..."),s(!0),j?.onStart?.(),P.start(0)}catch(k){if(k.name==="AbortError")return;const N=k instanceof Error?k.message:"Failed to speak";console.error("[useServerTTS] Error:",N),a(N),j?.onError?.(N),s(!1)}},[x,d,u,m,f,p,h]);return ne.useEffect(()=>()=>{x()},[x]),{isPlaying:t,isAvailable:r,error:o,speak:b,stop:x,checkAvailability:g,unlockAudio:y}}let Xc=null;function op(){return Xc||(Xc=new(window.AudioContext||window.webkitAudioContext)),Xc}function hy(){const[t,s]=ne.useState(!1),[r,n]=ne.useState(!1),[o,a]=ne.useState([]),[l,c]=ne.useState(null),d=ne.useRef(null),u=ne.useRef(null),m=ne.useCallback(async()=>{try{const g=op();g.state==="suspended"&&(await g.resume(),console.log("[useSayTTS] AudioContext resumed"));const x=g.createBuffer(1,1,22050),y=g.createBufferSource();y.buffer=x,y.connect(g.destination),y.start(0),console.log("[useSayTTS] Audio unlocked for mobile playback")}catch(g){console.error("[useSayTTS] Failed to unlock audio:",g)}},[]),f=ne.useCallback(async()=>{try{const g=await fetch("/api/tts/say/status");if(g.ok){const x=await g.json();return n(x.available),x.voices&&a(x.voices),x.available}return n(!1),!1}catch(g){return console.error("[useSayTTS] Failed to check availability:",g),n(!1),!1}},[]);ne.useEffect(()=>{f()},[f]);const p=ne.useCallback(()=>{if(d.current){try{d.current.stop()}catch{}d.current=null}u.current&&(u.current.abort(),u.current=null),s(!1)},[]),h=ne.useCallback(async(g,x)=>{if(p(),!g.trim()){c("No text to speak"),x?.onError?.("No text to speak");return}c(null);try{u.current=new AbortController;const y=await fetch("/api/tts/say/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:g.trim(),voice:x?.voice||"Samantha",rate:x?.rate||200}),signal:u.current.signal});if(!y.ok){const w=await y.json().catch(()=>({error:"Unknown error"}));throw new Error(w.error||`HTTP ${y.status}`)}const b=await y.blob(),v=await b.arrayBuffer();console.log("[useSayTTS] Received audio:",b.size,"bytes");const j=op();j.state==="suspended"&&(await j.resume(),console.log("[useSayTTS] AudioContext resumed before playback")),console.log("[useSayTTS] Decoding audio data...");const k=await j.decodeAudioData(v),N=j.createBufferSource();N.buffer=k,N.connect(j.destination),d.current=N,N.onended=()=>{console.log("[useSayTTS] Audio playback ended"),s(!1),d.current=null,x?.onEnd?.()},console.log("[useSayTTS] Starting audio playback via Web Audio API..."),s(!0),x?.onStart?.(),N.start(0)}catch(y){if(y.name==="AbortError")return;const b=y instanceof Error?y.message:"Failed to speak";console.error("[useSayTTS] Error:",b),c(b),x?.onError?.(b),s(!1)}},[p]);return ne.useEffect(()=>()=>{p()},[p]),{isPlaying:t,isAvailable:r,voices:o,error:l,speak:h,stop:p,checkAvailability:f,unlockAudio:m}}async function gy(t,s){const r=ut.getState(),n=s?.threshold??r.summarizeCharacterThreshold,o=s?.maxLength??r.summarizeMaxLength;if(t.length<=n)return t;try{const a=r.settingsZenModel,l=await fetch("/api/tts/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t,threshold:n,maxLength:o,...a?{zenModel:a}:{}})});if(!l.ok){const d=await l.text();throw console.error(`[summarize] HTTP error ${l.status}:`,d),new Error(`Summarization failed: ${l.status}`)}const c=await l.json();return c.summarized&&c.summary?c.summary:t}catch(a){return console.error("[summarize] Failed to summarize:",a),t}}function xy(t,s){const r=ut.getState();return(s==="message"?r.summarizeMessageTTS:r.summarizeVoiceConversation)?t.length>r.summarizeCharacterThreshold:!1}function yy(t){return t?t.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"").replace(/[*_~#]/g,"").replace(/https?:\/\/[^\s]+/g,"").replace(/\/[\w\-./]+/g,"").replace(/^\s*[$#>]\s*/gm,"").replace(/[[\]{}()<>|&;]/g," ").replace(/\\/g,"").replace(/\s+/g," ").trim():""}const Qi="browserVoiceLanguage",Zc="browserVoiceConversationMode",ed="ikanban:voice-language-changed",td="ikanban:voice-conversation-mode-changed",RM=1200,FM=700,ap=new Set(["ru","ru-RU"]),Va=t=>{const s=(t||"").trim();if(!s)return"en-US";const r=s.split("-")[0].toLowerCase();return ap.has(s)||ap.has(r)?"en-US":s};function by(){const[t,s]=ne.useState("idle"),[r,n]=ne.useState(null),[o,a]=ne.useState(()=>{if(typeof window<"u"){const X=localStorage.getItem(Qi);if(X)return Va(X)}return Va(navigator.language||"en-US")}),[l,c]=ne.useState(()=>typeof window<"u"?localStorage.getItem(Zc)==="true":!1),d=ws.isSupported(),u=ne.useMemo(()=>{if(typeof navigator>"u")return!1;const X=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod|android|mobile|webos|blackberry|iemobile|opera mini/i.test(X)},[]),m=ne.useRef(!1),f=ne.useRef(!1),p=ne.useRef(""),h=ne.useRef(new Map),g=ne.useRef(!1),x=ne.useRef(""),y=ne.useRef(null),b=ne.useRef(null),v=Ae(X=>X.currentSessionId),j=Ae(X=>X.sendMessage),k=Ae(X=>X.setPendingInputText),N=Ae(X=>X.messages),w=Ae(X=>X.createSession),{currentProviderId:C,currentModelId:S,currentAgentName:M,voiceProvider:D,speechRate:A,speechPitch:P,speechVolume:$,sayVoice:R,browserVoice:O,openaiVoice:T,summarizeVoiceConversation:_,summarizeCharacterThreshold:F}=ut(),{speak:I,stop:E,isAvailable:W,unlockAudio:V}=py(),{speak:ve,stop:oe,isAvailable:Z,unlockAudio:ce}=hy();ne.useEffect(()=>{if(v){const X=N.get(v);X&&(h.current=new Map(X.map(G=>[G.info.id,G])))}},[N,v]);const Q=ne.useRef(null);ne.useEffect(()=>{Q.current!==null&&Q.current!==v&&m.current&&(console.log("[useBrowserVoice] Session changed, stopping voice"),m.current=!1,f.current=!1,ws.stopListening(),ws.cancelSpeech(),s("idle"),n(null)),Q.current=v},[v]);const Y=ne.useCallback(X=>{const G=Va(X);a(G),typeof window<"u"&&(localStorage.setItem(Qi,G),window.dispatchEvent(new CustomEvent(ed,{detail:G})))},[]);ne.useEffect(()=>{if(typeof window>"u")return;const X=ae=>{const Oe=Va(ae.detail||localStorage.getItem(Qi)||"en-US");a(Be=>Be===Oe?Be:Oe)},G=ae=>{if(ae.key!==Qi||!ae.newValue)return;const me=Va(ae.newValue);a(Oe=>Oe===me?Oe:me)};return window.addEventListener(ed,X),window.addEventListener("storage",G),()=>{window.removeEventListener(ed,X),window.removeEventListener("storage",G)}},[]);const ie=ne.useCallback(()=>{c(X=>{const G=!X;return ws.setConversationMode(G),typeof window<"u"&&(localStorage.setItem(Zc,String(G)),window.dispatchEvent(new CustomEvent(td,{detail:G}))),G})},[]);ne.useEffect(()=>{if(typeof window>"u")return;const X=ae=>{const Oe=ae.detail;typeof Oe=="boolean"&&c(Be=>Be===Oe?Be:Oe)},G=ae=>{if(ae.key!==Zc||ae.newValue==null)return;const me=ae.newValue==="true";c(Oe=>Oe===me?Oe:me)};return window.addEventListener(td,X),window.addEventListener("storage",G),()=>{window.removeEventListener(td,X),window.removeEventListener("storage",G)}},[]),ne.useEffect(()=>{ws.setConversationMode(l)},[l]);const B=ne.useRef(null),se=ne.useRef(null),H=ne.useCallback(X=>{if(!m.current){console.log("[useBrowserVoice] Ignoring error after voice stopped:",X);return}const G=X.toLowerCase();if(G.includes("aborted")){console.log("[useBrowserVoice] Ignoring non-fatal aborted error"),n(null),s("listening");return}const ae=typeof document<"u"&&document.visibilityState!=="visible",me=G.includes("permission")||G.includes("not allowed")||G.includes("service not allowed");if(ae&&me&&l){console.log("[useBrowserVoice] Suppressing permission error while app hidden; will resume on visibility"),g.current=!0,n(null),s("idle");return}console.error("[useBrowserVoice] Recognition error:",X),n(X),s("error"),!X.includes("permission")&&!X.includes("not allowed")&&setTimeout(()=>{m.current&&(s("listening"),n(null),ws.startListening(o,se.current,H))},1e3)},[o,l]);ne.useEffect(()=>{B.current=H},[H]);const le=ne.useCallback(async X=>{if(!(!X.trim()||!m.current)&&X.trim()!==p.current){if(p.current=X.trim(),!C||!S){n("No provider or model configured. Please configure them in settings."),s("error");return}if(ws.stopListening(),!l){k(X.trim(),"replace"),f.current=!1,m.current=!1,s("idle");return}s("processing"),f.current=!0;try{let G=v;if(!G){console.log("[useBrowserVoice] No active session, creating new session...");const me=await w();if(!me){n("Failed to create session"),s("error"),f.current=!1;return}G=me.id,console.log("[useBrowserVoice] Created new session:",G)}await j(X.trim(),C,S,M??void 0);const ae=async()=>{if(!m.current)return;const me=h.current,Oe=Array.from(me.values()).filter(Be=>Be.info.role==="assistant").sort((Be,fe)=>{const q=Be.info.time?.created??0;return(fe.info.time?.created??0)-q});if(Oe.length>0){const fe=Oe[0].parts.filter(q=>q.type==="text").map(q=>q.text).join(" ");if(fe.trim()){s("speaking");try{let q=fe;_&&xy(fe,"voice")?(console.log("[useBrowserVoice] Summarizing AI response before speaking..."),q=await gy(fe,{threshold:F})):q=yy(fe);const ye=()=>{if(m.current&&l){if(typeof document<"u"&&document.visibilityState!=="visible"){g.current=!0,s("idle");return}if(s("listening"),u)try{ws.startListeningSync(o,se.current,B.current)}catch(He){console.error("[useBrowserVoice] Failed to restart listening:",He)}else ws.startListening(o,se.current,B.current)}else m.current=!1,s("idle")};if(D==="openai"&&W)console.log("[useBrowserVoice] Using OpenAI server TTS with voice:",T),await I(q,{voice:T,speed:A,onStart:()=>console.log("[useBrowserVoice] Server TTS started"),onEnd:()=>{console.log("[useBrowserVoice] Server TTS ended"),ye()},onError:he=>{console.error("[useBrowserVoice] Server TTS error:",he),n(`OpenAI voice failed: ${he}. Please check your OpenAI API key or switch to Browser voice.`),s("error"),ye()}});else if(D==="say"&&Z){console.log("[useBrowserVoice] Using macOS Say TTS with voice:",R);const he=Math.round(100+(A-.5)*200);await ve(q,{voice:R,rate:he,onStart:()=>console.log("[useBrowserVoice] Say TTS started"),onEnd:()=>{console.log("[useBrowserVoice] Say TTS ended"),ye()},onError:He=>{console.error("[useBrowserVoice] Say TTS error:",He),ye()}})}else console.log("[useBrowserVoice] Using browser TTS"),D==="openai"&&!W&&(console.warn("[useBrowserVoice] OpenAI voice selected but unavailable, falling back to browser voice"),n("OpenAI voice unavailable (API key not configured). Using browser voice instead.")),await ws.waitForVoices(),await ws.resumeAudioContext(),await ws.speakText(q,o,()=>{ye()},{rate:A,pitch:P,volume:$,voiceName:O||void 0})}catch(q){const ye=q instanceof Error?q.message:"Speech failed";if(!m.current){console.log("[useBrowserVoice] Ignoring speech error after voice stopped:",ye);return}if(console.error("[useBrowserVoice] Speech error:",ye),(ye.includes("not-allowed")||ye.includes("autoplay"))&&n("Audio blocked by browser. Please click the voice button again to enable audio."),l)if(s("listening"),u)try{ws.startListeningSync(o,se.current,B.current)}catch(he){console.error("[useBrowserVoice] Failed to restart listening after speech error:",he)}else ws.startListening(o,se.current,B.current);else m.current=!1,s("idle")}return}}setTimeout(ae,500)};setTimeout(ae,1e3)}catch(G){console.error("[useBrowserVoice] Send message error:",G),n(G instanceof Error?G.message:"Failed to send message"),s("error"),f.current=!1}}},[v,C,S,M,o,j,k,w,A,P,$,u,W,I,Z,ve,D,R,O,T,_,F,l]),ge=ne.useCallback(async(X,G)=>{if(!m.current)return;const ae=X.trim();!G||!ae||(x.current=ae,y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null;const me=x.current.trim();x.current="",me&&le(me)},RM))},[le]);ne.useEffect(()=>{if(typeof document>"u")return;const X=()=>{if(document.visibilityState==="visible"&&g.current){if(!m.current||!l){g.current=!1;return}g.current=!1,s("listening");try{u?ws.startListeningSync(o,se.current,B.current):ws.startListening(o,se.current,B.current)}catch(G){const ae=G instanceof Error?G.message:"Failed to resume voice";n(ae),s("error")}}};return document.addEventListener("visibilitychange",X),()=>{document.removeEventListener("visibilitychange",X)}},[l,u,o]),ne.useEffect(()=>{if(typeof navigator>"u")return;const X=navigator.mediaDevices;if(!X||typeof X.addEventListener!="function")return;const G=()=>{!m.current||t!=="listening"||(b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{if(b.current=null,!m.current||t!=="listening")return;if(typeof document<"u"&&document.visibilityState!=="visible"){g.current=!0,s("idle");return}try{ws.stopListening(),u?ws.startListeningSync(o,se.current,B.current):ws.startListening(o,se.current,B.current)}catch(me){const Oe=me instanceof Error?me.message:"Microphone source changed. Tap mic to continue.";n(Oe),s("error"),m.current=!1}},FM))};return X.addEventListener("devicechange",G),()=>{X.removeEventListener("devicechange",G),b.current&&(clearTimeout(b.current),b.current=null)}},[u,o,t]),ne.useEffect(()=>{se.current=ge},[ge]);const z=ne.useCallback(async()=>{if(!d)return!1;try{return await ws.prepareListening(),!0}catch(X){const G=X instanceof Error?X.message:"Microphone permission denied";return n(G),!1}},[d]),J=ne.useCallback(async()=>{if(!d){n("Browser voice not supported"),s("error");return}if(!v){n("No active session"),s("error");return}if(m.current=!0,p.current="",n(null),s("listening"),u)try{ws.unlockAudio().catch(()=>{}),V().catch(()=>{}),ce().catch(()=>{}),ws.startListeningSync(o,ge,H)}catch(X){const G=X instanceof Error?X.message:"Failed to start voice";console.error("[useBrowserVoice] Mobile voice start error:",G),n(G),s("error"),m.current=!1}else try{await ws.startListening(o,ge,H)}catch(X){const G=X instanceof Error?X.message:"Failed to start voice";console.error("[useBrowserVoice] Desktop voice start error:",G),n(G),s("error"),m.current=!1}},[d,v,o,ge,H,u,V,ce]),je=ne.useCallback(()=>{m.current=!1,f.current=!1,g.current=!1,b.current&&(clearTimeout(b.current),b.current=null),x.current="",y.current&&(clearTimeout(y.current),y.current=null),ws.stopListening(),ws.cancelSpeech(),E(),oe(),s("idle"),n(null)},[E,oe]);return ne.useEffect(()=>()=>{m.current=!1,b.current&&(clearTimeout(b.current),b.current=null),x.current="",y.current&&(clearTimeout(y.current),y.current=null),ws.setConversationMode(!1),ws.stopListening(),ws.cancelSpeech()},[]),{status:t,isSupported:d,error:r,language:o,setLanguage:Y,startVoice:J,stopVoice:je,conversationMode:l,toggleConversationMode:ie,prepareVoice:z,isMobile:u,voiceProvider:D}}const LM={sm:{icon:"w-4 h-4",container:"gap-1.5"},md:{icon:"w-5 h-5",container:"gap-2"},lg:{icon:"w-6 h-6",container:"gap-2.5"}},OM={idle:{icon:ug,color:"text-muted-foreground",label:"Voice Ready"},listening:{icon:Od,color:"text-primary",label:"Listening...",animation:"animate-pulse"},processing:{icon:Ot,color:"text-primary",label:"Processing...",animation:"animate-spin"},speaking:{icon:ma,color:"text-green-500",label:"Speaking..."},error:{icon:tc,color:"text-destructive",label:"Voice Error"}};function ip({status:t,showLabel:s=!1,size:r="md",className:n="",conversationMode:o=!1}){const a=OM[t],l=a.icon,c=LM[r],d=s?c.container:"";return e.jsxs("div",{className:`flex items-center ${d} ${n}`,children:[e.jsxs("div",{className:"relative",children:[e.jsx(l,{className:`
|
|
160
|
+
${c.icon}
|
|
161
|
+
${a.color}
|
|
162
|
+
${a.animation||""}
|
|
163
|
+
`,"aria-hidden":"true"}),o&&t==="idle"&&e.jsx("span",{className:"absolute -top-0.5 -right-0.5 w-2 h-2 bg-green-500 rounded-full","aria-label":"Conversation mode active"})]}),s&&e.jsx("span",{className:`typography-meta ${a.color}`,children:a.label})]})}const _M={idle:"Start Voice",listening:"Listening",processing:"Processing",speaking:"AI Speaking",error:"Voice Error"},$M=()=>{if(typeof navigator>"u")return!1;const t=navigator.userAgent.toLowerCase(),s=/iphone|ipad|ipod/i.test(t),r=/safari/i.test(t)&&!/chrome|crios|crmo/i.test(t);return s&&r},lp=t=>t.includes("getUserMedia")||t.includes("mediaDevices")||t.includes("Cannot read properties of undefined")?typeof window<"u"&&!window.isSecureContext?"Voice requires a secure connection (HTTPS) or localhost. Please use HTTPS or access via localhost.":"Microphone access is unavailable in this runtime. On desktop, check System Settings -> Privacy & Security -> Microphone for IKanban.":t;function cp(){const t=ut(_=>_.voiceModeEnabled),{status:s,isSupported:r,error:n,startVoice:o,stopVoice:a,conversationMode:l,toggleConversationMode:c,isMobile:d}=by(),[u,m]=ne.useState(!1),f=gs(),p=d?"h-8 w-8 min-h-[32px] min-w-[32px]":f?"h-5 w-5":"h-6 w-6",h=d?"h-[18px] w-[18px]":f?"h-4 w-4":"h-[18px] w-[18px]",g="size-[18px]",x="bg-transparent hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent",y=ne.useRef(!1),b=ne.useRef(!1),v=ne.useRef(null),j=ne.useRef(!1),k=ne.useRef(null);ne.useEffect(()=>{b.current=$M()},[]);const N=s==="listening"||s==="speaking"||s==="processing",w=s==="error",C=s==="idle",S=s==="speaking";ne.useEffect(()=>{if(w&&n){if(k.current===n)return;k.current=n;const _=lp(n);K.error(_,{duration:5e3})}w||(k.current=null)},[w,n]);const M=w?n||"Voice Error":l&&s==="idle"?"Start Voice (Continuous mode on)":_M[s]||"Start Voice",D=()=>w&&n?lp(n):N?"Stop voice conversation":d?"Start voice conversation":"Start voice conversation (Shift+Click for continuous mode) • Cmd/Ctrl+Shift+V to toggle",A=ne.useCallback(async()=>{if(N)a();else if(s!=="error")if(d)o();else try{await o()}catch(_){console.error("Failed to start voice:",_)}else if(d)o();else try{await o()}catch(_){console.error("Failed to start voice:",_)}},[N,s,o,a,d]),P=ne.useCallback(async _=>{if(y.current){y.current=!1;return}if(_.shiftKey){c();return}await A()},[A,c]),$=ne.useCallback(_=>{_.preventDefault(),y.current=!0,j.current=!1,m(!0),v.current=setTimeout(()=>{j.current=!0,c(),navigator.vibrate&&navigator.vibrate(50),m(!1)},500)},[c]),R=ne.useCallback(()=>{v.current&&(clearTimeout(v.current),v.current=null),j.current||A(),m(!1)},[A]),O=ne.useCallback(()=>{v.current&&(clearTimeout(v.current),v.current=null),m(!1)},[]),T=ne.useCallback(_=>{_.preventDefault(),_.stopPropagation(),c()},[c]);if(!t)return null;if(!r){const _=ws.getSupportDetails(),F=_.secureContext?_.recognition?_.synthesis?"Voice not supported in this browser":"Speech synthesis not supported in this browser.":"Speech recognition not supported in this browser. Try Chrome, Edge, or Safari.":"Voice requires HTTPS or localhost. Please use a secure connection.";return e.jsx(Vd,{children:e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{size:"icon",variant:"ghost",disabled:!0,"aria-label":F,className:`${p} p-0 ${x}`,children:e.jsx(ug,{className:`${h} opacity-50`})})}),e.jsx(ht,{side:"bottom",align:"center",children:e.jsx("p",{className:"max-w-[200px] text-center",children:F})})]})})}return e.jsxs("div",{className:`flex items-center ${d?"gap-1":"gap-1.5"}`,children:[N&&!d&&e.jsx(ip,{status:s,showLabel:!0,size:"sm",className:"mr-1"}),e.jsx(Vd,{children:e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{size:"icon",variant:"ghost",onClick:P,onTouchStart:$,onTouchEnd:R,onTouchCancel:O,"aria-label":M,className:`
|
|
164
|
+
relative
|
|
165
|
+
${p}
|
|
166
|
+
p-0
|
|
167
|
+
${x}
|
|
168
|
+
touch-manipulation
|
|
169
|
+
${u?"scale-95 opacity-80":""}
|
|
170
|
+
${l&&C&&d?"ring-1 ring-primary/50":""}
|
|
171
|
+
`,style:{WebkitTapHighlightColor:"transparent",touchAction:"manipulation"},children:N?S?e.jsx(ma,{className:`${h} text-green-400 animate-pulse`}):e.jsx(Zv,{className:`${h} text-[var(--status-error)]`}):e.jsx(ip,{status:w?"idle":s,size:d||f?"sm":"md"})})}),e.jsx(ht,{side:"bottom",align:"center",children:e.jsx("p",{className:"max-w-[200px] text-center",children:D()})})]})}),(s==="idle"||s==="error")&&e.jsx(Me,{size:"icon",variant:"ghost",onPointerDownCapture:_=>_.stopPropagation(),onClick:T,"aria-label":l?"Continuous mode on":"Continuous mode off",title:l?"Continuous mode on":"Continuous mode off",className:`${p} p-0 ${x} ${l?"text-[var(--status-info)] hover:text-[var(--status-info)]":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(ew,{className:g})})]})}function BM(t){const{fileLabel:s,startLine:r,endLine:n,side:o,language:a,code:l,text:c}=t;return t.source==="diff"&&o?`Comment on \`${s}\` lines ${r}-${n} (${o}):
|
|
172
|
+
\`\`\`${a}
|
|
173
|
+
${l}
|
|
174
|
+
\`\`\`
|
|
175
|
+
|
|
176
|
+
${c}`:`Comment on \`${s}\` lines ${r}-${n}:
|
|
177
|
+
\`\`\`${a}
|
|
178
|
+
${l}
|
|
179
|
+
\`\`\`
|
|
180
|
+
|
|
181
|
+
${c}`}function zM(t){return t.length===0?"":t.map(BM).join(`
|
|
182
|
+
|
|
183
|
+
`)}function Yi(t,s){if(s.length===0)return t;const r=zM(s);return t.trim()?`${t}
|
|
184
|
+
|
|
185
|
+
${r}`:r}ne.memo(()=>{const t=ne.useRef(null),{addAttachedFile:s}=Ae(),{isMobile:r}=Te(),n=Ex(),o=r?"h-9 w-9":"h-7 w-7",a=r?"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=Ae.getState().attachedFiles.length;try{await s(p),Ae.getState().attachedFiles.length>h&&m++}catch(g){console.error("File attach failed",g),K.error(g instanceof Error?g.message:"Failed to attach file")}}m>0&&K.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(`
|
|
186
|
+
`);K.error(`Some files were skipped:
|
|
187
|
+
${g}`)}const h=f.map(g=>{if(!g?.dataUrl)return null;try{const[x,y]=g.dataUrl.split(","),b=g.mimeType||x?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!y)return null;const v=atob(y),j=new Uint8Array(v.length);for(let N=0;N<v.length;N++)j[N]=v.charCodeAt(N);const k=new Blob([j],{type:b});return new File([k],g.name||"file",{type:b})}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),K.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(Ml,{className:L(a,"text-current")})})]})});const UM=ne.memo(({file:t,onRemove:s})=>{const r=()=>t.mimeType.startsWith("image/")?e.jsx(Ln,{className:"h-3.5 w-3.5"}):t.mimeType.includes("text")||t.mimeType.includes("code")?e.jsx(In,{className:"h-3.5 w-3.5"}):t.mimeType.includes("json")||t.mimeType.includes("xml")?e.jsx(sc,{className:"h-3.5 w-3.5"}):e.jsx(In,{className:"h-3.5 w-3.5"}),n=c=>!Number.isFinite(c)||c<=0?"...":c<1024?c+" B":c<1048576?(c/1024).toFixed(1)+" KB":(c/1048576).toFixed(1)+" MB",a=(c=>{const u=c.replace(/\\/g,"/").split("/");return u[u.length-1]||c})(t.filename);return t.source!=="server"&&t.mimeType.startsWith("image/")&&typeof t.dataUrl=="string"&&t.dataUrl.startsWith("data:image/")?e.jsxs("div",{className:"relative h-12 w-12 sm:h-14 sm:w-14 overflow-hidden rounded-lg border border-border/40 bg-muted/10 flex-shrink-0",children:[e.jsx("img",{src:t.dataUrl,alt:a,className:"h-full w-full object-cover",loading:"lazy"}),e.jsx("button",{onClick:s,className:"absolute top-1 right-1 h-5 w-5 rounded-full bg-background/80 text-foreground hover:text-destructive flex items-center justify-center focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",title:"Remove image","aria-label":`Remove ${a}`,children:e.jsx(hs,{className:"h-3 w-3"})})]}):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(tw,{className:"h-3 w-3 text-primary flex-shrink-0"}):e.jsx(lg,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"})}),r(),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:s,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(hs,{className:"h-4 w-4 sm:h-3 sm:w-3"})})]})}),HM=ne.memo(()=>{const{attachedFiles:t,removeAttachedFile:s}=Ae();return t.length===0?null:e.jsx("div",{className:"pb-2 overflow-hidden",children:e.jsx("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:t.map(r=>e.jsx(UM,{file:r,onRemove:()=>s(r.id)},r.id))})})}),vy=ne.memo(({files:t,onShowPopup:s,compact:r=!1})=>{const n=t.filter(m=>m.type==="file"&&(m.mime||m.url)),o=m=>{if(!m)return"Unnamed file";const p=m.replace(/\\/g,"/").split("/");return p[p.length-1]||m},a=m=>m?m.startsWith("image/")?e.jsx(Ln,{className:"h-3.5 w-3.5"}):m.includes("text")||m.includes("code")?e.jsx(In,{className:"h-3.5 w-3.5"}):m.includes("json")||m.includes("xml")?e.jsx(sc,{className:"h-3.5 w-3.5"}):e.jsx(In,{className:"h-3.5 w-3.5"}):e.jsx(In,{className:"h-3.5 w-3.5"}),l=n.filter(m=>m.mime?.startsWith("image/")&&m.url),c=n.filter(m=>!m.mime?.startsWith("image/")),d=i.useMemo(()=>l.flatMap(m=>{if(!m.url)return[];const f=o(m.filename)||"Image";return[{url:m.url,mimeType:m.mime,filename:f,size:m.size}]}),[l]),u=i.useCallback(m=>{if(!s)return;const f=d[m];if(!f?.url)return;const p=f.filename||"Image",h={open:!0,title:p,content:"",metadata:{tool:"image-preview",filename:p,mime:f.mimeType,size:f.size},image:{url:f.url,mimeType:f.mimeType,filename:p,size:f.size,gallery:d,index:m}};s(h)},[d,s]);return n.length===0?null:e.jsxs("div",{className:L(r?"space-y-1.5 mt-1.5":"space-y-2 mt-2"),children:[c.length>0&&e.jsx("div",{className:L("flex flex-wrap",r?"gap-1.5":"gap-2"),children:c.map((m,f)=>e.jsxs("div",{className:L("inline-flex items-center bg-muted/30 border border-border/30 typography-meta",r?"gap-1 px-2 py-0.5 rounded-lg":"gap-1.5 px-2.5 py-1 rounded-xl"),children:[a(m.mime),e.jsx("div",{className:L("overflow-hidden",r?"max-w-[140px]":"max-w-[200px]"),children:e.jsx("span",{className:"truncate block",title:o(m.filename),children:o(m.filename)})})]},`file-${f}`))}),l.length>0&&e.jsx("div",{className:L("overflow-x-auto -mx-1 px-1 scrollbar-thin",r?"py-0.5":"py-1"),children:e.jsx("div",{className:L("flex snap-x snap-mandatory",r?"gap-2":"gap-3"),children:l.map((m,f)=>{const p=o(m.filename)||"Image";return e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>u(f),className:L("relative flex-none 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",r?"h-12 w-12 sm:h-14 sm:w-14 md:h-16 md:w-16 rounded-lg":"aspect-square w-16 sm:w-20 md:w-24 rounded-xl"),"aria-label":p,children:[m.url?e.jsx("img",{src:m.url,alt:p,className:"h-full w-full object-cover",loading:"lazy",onError:h=>{const g=h.target;g.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(Ln,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:p})]})}),e.jsx(ht,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:p})]},`img-${f}`)})})})]})}),wy=ne.memo(({message:t,sessionId:s,onEdit:r})=>{const n=Dn(l=>l.removeFromQueue),o=i.useMemo(()=>{const l=t.content.split(`
|
|
188
|
+
`),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(sw,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>r(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(s,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(hs,{className:"h-3 w-3"})})]})});wy.displayName="QueuedMessageChip";const dp=[],jy=ne.memo(({onEditMessage:t})=>{const s=Ae(a=>a.currentSessionId),r=Dn(i.useCallback(a=>s?a.queuedMessages[s]??dp:dp,[s])),n=Dn(a=>a.popToInput),o=i.useCallback(a=>{if(!s)return;const l=n(s,a.id);if(l){if(l.attachments&&l.attachments.length>0){const c=Jr.getState().attachedFiles;Jr.setState({attachedFiles:[...c,...l.attachments]})}t(l.content,l.attachments)}},[s,n,t]);return r.length===0||!s?null:e.jsx("div",{className:"pb-2",children:e.jsx("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:r.map(a=>e.jsx(wy,{message:a,sessionId:s,onEdit:o},a.id))})})});jy.displayName="QueuedMessageChips";const VM=i.forwardRef(({searchQuery:t,onFileSelect:s,onClose:r,showTabs:n,activeTab:o="files",onTabSelect:a},l)=>{const{currentDirectory:c}=Yt(),{addServerFile:d}=Ae(),u=cc(_=>_.searchFiles),m=bc(t,180),f=wi(),p=lc(),[h,g]=i.useState([]),[x,y]=i.useState(!1),[b,v]=i.useState(0),[j,k]=i.useState(360),[N,w]=i.useState({}),[C,S]=i.useState({}),M=i.useRef([]),D=i.useRef([]),A=i.useRef([]),P=i.useRef(null),$=i.useRef(!1),R=i.useCallback((_,F)=>{const I=_.trim().toLowerCase();if(!I)return 0;const E=F.toLowerCase();let W=0,V=-1,ve=0;for(let oe=0;oe<I.length;oe+=1){const Z=I[oe];if(!Z||Z===" ")continue;const ce=E.indexOf(Z,V+1);if(ce===-1)return null;const Q=ce-V-1;if(Q===0?ve+=1:ve=0,W+=10,W+=Math.max(0,18-ce),W-=Math.max(0,Q),ce===0)W+=12;else{const Y=E[ce-1];(Y==="/"||Y==="_"||Y==="-"||Y==="."||Y===" ")&&(W+=10)}W+=ve>0?12:0,V=ce}return W+=Math.max(0,24-Math.round(E.length/3)),W},[]);i.useEffect(()=>{const _=F=>{const I=F.target;!I||!P.current||P.current.contains(I)||r()};return document.addEventListener("pointerdown",_,!0),()=>{document.removeEventListener("pointerdown",_,!0)}},[r]),i.useEffect(()=>{if(!c){g([]);return}const F=(m??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();let I=!1;return y(!0),u(c,F,80,{includeHidden:f,respectGitignore:!p}).then(E=>{if(I)return;const W=F?E.map(V=>{const ve=V.relativePath||V.name||V.path,oe=R(F,ve);return oe===null?null:{file:V,score:oe,labelLength:ve.length}}).filter(Boolean):E.map(V=>({file:V,score:0,labelLength:(V.relativePath||V.name||V.path).length}));W.sort((V,ve)=>ve.score-V.score||V.labelLength-ve.labelLength||V.file.path.localeCompare(ve.file.path)),g(W.slice(0,15).map(V=>V.file))}).catch(()=>{I||g([])}).finally(()=>{I||y(!1)}),()=>{I=!0}},[c,m,R,u,f,p]),i.useEffect(()=>{v(0),w({}),S({})},[h]),i.useEffect(()=>{M.current[b]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[b]),i.useEffect(()=>{let _=null;const F=()=>{_!==null&&cancelAnimationFrame(_),_=requestAnimationFrame(()=>{const I={},E={};D.current.forEach((W,V)=>{if(!W)return;const oe=A.current[V]?.offsetWidth??W.scrollWidth,Z=Math.max(0,oe-W.clientWidth),ce=Z>8;if(I[V]=ce,ce){const Q=Math.max(.6,Z/110);E[V]=Q}}),w(I),S(E)})};return F(),window.addEventListener("resize",F),()=>{_!==null&&cancelAnimationFrame(_),window.removeEventListener("resize",F)}},[h]),i.useEffect(()=>{const _=D.current[b];if(!_)return;const F=()=>{const E=_.clientWidth;E>0&&k(E)};if(F(),typeof ResizeObserver>"u")return;const I=new ResizeObserver(F);return I.observe(_),()=>{I.disconnect()}},[b]);const O=i.useCallback(async _=>{await d(_.path,_.name),s(_)},[d,s]);i.useImperativeHandle(l,()=>({handleKeyDown:_=>{if(_==="Escape"){r();return}const F=h.length;if(F!==0){if(_==="ArrowDown"){v(I=>(I+1)%F);return}if(_==="ArrowUp"){v(I=>(I-1+F)%F);return}if(_==="Enter"||_==="Tab"){const I=(b%F+F)%F,E=h[I];E&&O(E)}}}}),[h,b,r,O]);const T=_=>{switch(_.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(xn,{className:"h-3.5 w-3.5 text-[var(--status-info)]"});case"json":return e.jsx(xn,{className:"h-3.5 w-3.5 text-[var(--status-warning)]"});case"md":case"mdx":return e.jsx(In,{className:"h-3.5 w-3.5 text-muted-foreground"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Ln,{className:"h-3.5 w-3.5 text-[var(--status-success)]"});default:return e.jsx(sc,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:P,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border-2 border-border/60 rounded-xl shadow-md bottom-full mb-2 left-0 flex flex-col",children:[n?e.jsx("div",{className:"px-2 pt-2 pb-1 border-b border-border/60",children:e.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-elevated)] p-1",children:[{id:"commands",label:"Commands"},{id:"agents",label:"Agents"},{id:"files",label:"Files"}].map(_=>e.jsx("button",{type:"button",className:L("flex-1 px-2.5 py-1 rounded-md typography-meta font-semibold transition-none",o===_.id?"bg-interactive-selection text-interactive-selection-foreground shadow-sm":"text-muted-foreground hover:bg-interactive-hover/50"),onPointerDown:F=>{F.pointerType==="touch"&&(F.preventDefault(),F.stopPropagation(),$.current=!0,a?.(_.id))},onClick:()=>{if($.current){$.current=!1;return}a?.(_.id)},children:_.label},_.id))})}):null,e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:"px-0",children:x?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Mr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[h.map((_,F)=>{const I=_.relativePath||_.name,E=Vg(I,{maxLength:45}),W=b===F,V=N[F]??!1,ve=C[F]??2.6,oe=e.jsxs("div",{ref:Z=>{M.current[F]=Z},className:L("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",W&&"bg-interactive-selection"),onClick:()=>O(_),onMouseEnter:()=>v(F),children:[T(_),e.jsxs("span",{ref:Z=>{D.current[F]=Z},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:W?{"--file-mention-marquee-width":`${j}px`,"--file-mention-marquee-duration":`${ve}s`}:void 0,"aria-label":I,children:[e.jsx("span",{ref:Z=>{A.current[F]=Z},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:I}),V&&W?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:I}):e.jsx("span",{className:"block truncate",children:E})]})]});return e.jsx(i.Fragment,{children:oe},_.path)}),h.length>0&&e.jsx("div",{className:"h-2"}),h.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"})]})}),Sy=i.forwardRef(({searchQuery:t,onCommandSelect:s,onClose:r,showTabs:n,activeTab:o="commands",onTabSelect:a},l)=>{const{hasMessagesInCurrentSession:c,currentSessionId:d}=Ae(oo(M=>{const D=M.currentSessionId;return{hasMessagesInCurrentSession:(D?M.messages.get(D)?.length??0:0)>0,currentSessionId:D}})),u=!!d,[m,f]=i.useState([]),[p,h]=i.useState(!1),{commands:g,loadCommands:x}=yo(),[y,b]=i.useState(0),v=i.useRef([]),j=i.useRef(null),k=i.useRef(!1),N=i.useRef(null),w=i.useRef(!1),C=i.useRef(!1);i.useEffect(()=>{const M=D=>{const A=D.target;!A||!j.current||j.current.contains(A)||r()};return document.addEventListener("pointerdown",M,!0),()=>{document.removeEventListener("pointerdown",M,!0)}},[r]),i.useEffect(()=>{x()},[x]),i.useEffect(()=>{(async()=>{h(!0);try{const D=g.map(T=>({name:T.name,description:T.description,agent:T.agent??void 0,model:T.model??void 0,isBuiltIn:T.name==="init"||T.name==="review",scope:T.scope})),A=[...u&&!c?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...u?[{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}],P=new Map;A.forEach(T=>P.set(T.name,T)),D.forEach(T=>P.set(T.name,T));const $=Array.from(P.values()),R=!c,O=(t?$.filter(T=>ao(T.name,t)||T.description&&ao(T.description,t)):$).filter(T=>R||T.name!=="init");O.sort((T,_)=>{const F=T.name.toLowerCase().startsWith(t.toLowerCase()),I=_.name.toLowerCase().startsWith(t.toLowerCase());return F&&!I?-1:!F&&I?1:T.name.localeCompare(_.name)}),f(O)}catch{const D=!c,A=[...u&&!c?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...u?[{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}],P=(t?A.filter($=>ao($.name,t)||$.description&&ao($.description,t)):A).filter($=>D||$.name!=="init");f(P)}finally{h(!1)}})()},[t,c,u,g]),i.useEffect(()=>{b(0)},[m]),i.useEffect(()=>{v.current[y]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[y]),i.useImperativeHandle(l,()=>({handleKeyDown:M=>{const D=m.length;if(M==="Escape"){r();return}if(D!==0){if(M==="ArrowDown"){b(A=>(A+1)%D);return}if(M==="ArrowUp"){b(A=>(A-1+D)%D);return}if(M==="Enter"||M==="Tab"){const A=(y%D+D)%D,P=m[A];P&&s(P)}}}}),[m,y,r,s]);const S=M=>{switch(M.name){case"init":return e.jsx(In,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(Oo,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(ow,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(Pn,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(nw,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(fo,{className:"h-3.5 w-3.5 text-cyan-500"});default:return M.isBuiltIn?e.jsx(rw,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(xo,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:j,className:"absolute z-[100] min-w-0 w-full max-w-[450px] max-h-64 bg-background border-2 border-border/60 rounded-xl shadow-md bottom-full mb-2 left-0 flex flex-col",children:[n?e.jsx("div",{className:"px-2 pt-2 pb-1 border-b border-border/60",children:e.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-elevated)] p-1",children:[{id:"commands",label:"Commands"},{id:"agents",label:"Agents"},{id:"files",label:"Files"}].map(M=>e.jsx("button",{type:"button",className:L("flex-1 px-2.5 py-1 rounded-md typography-meta font-semibold transition-none",o===M.id?"bg-interactive-selection text-interactive-selection-foreground shadow-sm":"text-muted-foreground hover:bg-interactive-hover/50"),onPointerDown:D=>{D.pointerType==="touch"&&(D.preventDefault(),D.stopPropagation(),C.current=!0,a?.(M.id))},onClick:()=>{if(C.current){C.current=!1;return}a?.(M.id)},children:M.label},M.id))})}):null,e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",children:p?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Mr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[m.map((M,D)=>{const A=M.isBuiltIn,P=M.scope==="project";return e.jsxs("div",{ref:$=>{v.current[D]=$},className:L("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",D===y&&"bg-interactive-selection"),onPointerDown:$=>{$.pointerType==="touch"&&(N.current={x:$.clientX,y:$.clientY},w.current=!1)},onPointerMove:$=>{if($.pointerType!=="touch"||!N.current)return;const R=$.clientX-N.current.x,O=$.clientY-N.current.y;Math.hypot(R,O)>6&&(w.current=!0)},onPointerUp:$=>{if($.pointerType!=="touch")return;const R=w.current;N.current=null,w.current=!1,!R&&($.preventDefault(),$.stopPropagation(),k.current=!0,s(M,{dismissKeyboard:!0}))},onPointerCancel:()=>{N.current=null,w.current=!1},onClick:()=>{if(k.current){k.current=!1;return}s(M)},onMouseEnter:()=>b(D),children:[e.jsx("div",{className:"mt-0.5",children:S(M)}),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:["/",M.name]}),A?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"}):M.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",P?"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:M.scope}):null,M.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:M.agent})]}),M.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:M.description})]})]},M.name)}),m.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"})]})});Sy.displayName="CommandAutocomplete";const WM=t=>t?t!=="primary":!1,Ny=i.forwardRef(({searchQuery:t,onAgentSelect:s,onClose:r,showTabs:n,activeTab:o="agents",onTabSelect:a},l)=>{const c=i.useRef(null),[d,u]=i.useState(0),[m,f]=i.useState([]),p=i.useRef([]),h=i.useRef(!1),{getVisibleAgents:g}=ut(),{agents:x,loadAgents:y}=bo();i.useEffect(()=>{x.length===0&&y()},[y,x.length]),i.useEffect(()=>{const j=g().filter(w=>WM(w.mode)).map(w=>{const C=x.find(S=>S.name===w.name);return{name:w.name,description:w.description,mode:w.mode??void 0,scope:C?.scope,isBuiltIn:C?Mo(C):!1}}),k=t.trim(),N=k.length?j.filter(w=>ao(w.name,k)):j;N.sort((w,C)=>w.name.localeCompare(C.name)),f(N),u(0)},[g,t,x]),i.useEffect(()=>{p.current[d]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[d]),i.useEffect(()=>{const v=j=>{const k=j.target;!k||!c.current||c.current.contains(k)||r()};return document.addEventListener("pointerdown",v,!0),()=>{document.removeEventListener("pointerdown",v,!0)}},[r]),i.useImperativeHandle(l,()=>({handleKeyDown:v=>{if(v==="Escape"){r();return}if(m.length){if(v==="ArrowDown"){u(j=>(j+1)%m.length);return}if(v==="ArrowUp"){u(j=>(j-1+m.length)%m.length);return}if(v==="Enter"||v==="Tab"){const j=m[(d+m.length)%m.length];j&&s(j.name)}}}}),[m,s,r,d]);const b=(v,j)=>{const k=v.isBuiltIn,N=v.scope==="project";return e.jsx("div",{ref:w=>{p.current[j]=w},className:L("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",j===d&&"bg-interactive-selection"),onClick:()=>s(v.name),onMouseEnter:()=>u(j),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:["#",v.name]}),k?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"}):v.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:v.scope}):null]}),v.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:v.description})]})},v.name)};return e.jsxs("div",{ref:c,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border-2 border-border/60 rounded-xl shadow-md bottom-full mb-2 left-0 flex flex-col",children:[n?e.jsx("div",{className:"px-2 pt-2 pb-1 border-b border-border/60",children:e.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-elevated)] p-1",children:[{id:"commands",label:"Commands"},{id:"agents",label:"Agents"},{id:"files",label:"Files"}].map(v=>e.jsx("button",{type:"button",className:L("flex-1 px-2.5 py-1 rounded-md typography-meta font-semibold transition-none",o===v.id?"bg-interactive-selection text-interactive-selection-foreground shadow-sm":"text-muted-foreground hover:bg-interactive-hover/50"),onPointerDown:j=>{j.pointerType==="touch"&&(j.preventDefault(),j.stopPropagation(),h.current=!0,a?.(v.id))},onClick:()=>{if(h.current){h.current=!1;return}a?.(v.id)},children:v.label},v.id))})}):null,e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",children:m.length?e.jsx("div",{children:m.map((v,j)=>b(v,j))}):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"})]})});Ny.displayName="AgentMentionAutocomplete";const ky=i.forwardRef(({searchQuery:t,onSkillSelect:s,onClose:r},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{skills:m,loadSkills:f}=pn();i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const h=t.trim(),x=[...h.length?m.filter(y=>ao(y.name,h)):m].sort((y,b)=>y.scope==="project"&&b.scope!=="project"?-1:y.scope!=="project"&&b.scope==="project"?1:y.name.localeCompare(b.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)||r()};return document.addEventListener("pointerdown",h,!0),()=>{document.removeEventListener("pointerdown",h,!0)}},[r]),i.useImperativeHandle(n,()=>({handleKeyDown:h=>{if(h==="Escape"){r();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&&s(g.name)}}}}),[c,s,r,a]);const p=(h,g)=>{const x=h.scope==="project";return e.jsx("div",{ref:y=>{u.current[g]=y},className:L("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",g===a&&"bg-interactive-selection"),onClick:()=>s(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-2 border-border/60 rounded-xl shadow-md bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(Ut,{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"})]})});ky.displayName="SkillAutocomplete";function GM({className:t,children:s,...r}){return e.jsxs(aw,{"data-slot":"scroll-area",className:L("relative",t),...r,children:[e.jsx(iw,{"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:s}),e.jsx(KM,{}),e.jsx(lw,{})]})}function KM({className:t,orientation:s="vertical",...r}){return e.jsx(cw,{"data-slot":"scroll-area-scrollbar",orientation:s,className:L("flex touch-none p-px select-none",s==="vertical"&&"h-full w-2.5 border-l border-l-transparent",s==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",t),...r,children:e.jsx(dw,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const qM=({onFilesSelected:t,multiSelect:s=!1,children:r,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:l}=ks(),c=l,{currentDirectory:d}=Yt(),u=cc(fe=>fe.searchFiles),m=wi(),f=lc(),[p,h]=i.useState(!1),[g,x]=i.useState(0),[y,b]=i.useState(!1),[v,j]=i.useState(""),k=bc(v,200),[N,w]=i.useState(new Set),[C,S]=i.useState(new Set),[M,D]=i.useState({}),A=i.useRef(new Set),P=i.useRef(new Set),[$,R]=i.useState([]),[O,T]=i.useState(!1),[_,F]=i.useState(!1),[I,E]=i.useState(!1),[W,V]=i.useState(null),ve=n??p,oe=o??h,Z=i.useCallback(fe=>fe.slice().sort((q,ye)=>q.type!==ye.type?q.type==="directory"?-1:1:q.name.localeCompare(ye.name)),[]),ce=i.useCallback((fe,q)=>Z(q.filter(ye=>m||!ye.name.startsWith(".")).map(ye=>{const he=ye.name,He=!ye.isDirectory&&he.includes(".")?he.split(".").pop()?.toLowerCase():void 0;return{name:he,path:ye.path||`${fe}/${he}`,type:ye.isDirectory?"directory":"file",size:0,extension:He}})),[Z,m]),Q=i.useCallback(async fe=>{F(!0),V(null);try{const q=await nt.listLocalDirectory(fe,{respectGitignore:!f}),ye=ce(fe,q.map(he=>({name:he.name,path:he.path,isDirectory:he.isDirectory})));A.current=new Set([fe]),P.current=new Set,D({[fe]:ye}),S(new Set)}catch{V("Failed to load directory contents"),A.current=new Set([fe]),P.current=new Set,D({[fe]:[]}),S(new Set)}finally{F(!1)}},[ce,f]),Y=i.useCallback(async fe=>{const q=fe.trim();if(!q)return;const ye=`${q}::${g}`;if(!A.current.has(ye)&&!P.current.has(ye)){P.current=new Set(P.current),P.current.add(ye);try{const he=await nt.listLocalDirectory(q,{respectGitignore:!f}),He=ce(q,he.map(ot=>({name:ot.name,path:ot.path,isDirectory:ot.isDirectory})));A.current=new Set(A.current),A.current.add(ye),D(ot=>({...ot,[q]:He}))}catch{D(he=>he[q]?he:{...he,[q]:[]})}finally{P.current=new Set(P.current),P.current.delete(ye)}}},[ce,f,g]);i.useEffect(()=>{(ve||y)&&d&&Q(d)},[ve,y,d,Q]),i.useEffect(()=>{x(fe=>fe+1)},[m,f]),i.useEffect(()=>{if(!(ve||y)||!d){R([]),T(!1);return}const fe=k.trim().replace(/^\.\//,"").replace(/^\/+/,"");if(!fe){R([]),T(!1);return}const q=fe.toLowerCase();let ye=!1;return T(!0),u(d,q,150,{includeHidden:m,respectGitignore:!f}).then(he=>{if(ye)return;const He=he.map(ot=>({name:ot.name,path:ot.path,type:"file",extension:ot.extension,relativePath:ot.relativePath,size:0}));R(He)}).catch(()=>{ye||R([])}).finally(()=>{ye||T(!1)}),()=>{ye=!0}},[ve,y,d,k,u,m,f]),i.useEffect(()=>{!ve&&!y&&(w(new Set),j(""),R([]),T(!1),A.current=new Set,P.current=new Set,D({}),S(new Set))},[ve,y]);const ie=fe=>{if(fe.type==="directory")return C.has(fe.path)?e.jsx(Nn,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(Nn,{className:"h-3.5 w-3.5 text-primary/60"});switch(fe.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(xn,{className:"h-3.5 w-3.5 text-[var(--status-info)]"});case"json":return e.jsx(xn,{className:"h-3.5 w-3.5 text-[var(--status-warning)]"});case"md":case"mdx":return e.jsx(Eo,{className:"h-3.5 w-3.5 text-muted-foreground"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Ln,{className:"h-3.5 w-3.5 text-[var(--status-success)]"});default:return e.jsx(Eo,{className:"h-3.5 w-3.5 text-muted-foreground"})}},B=async fe=>{C.has(fe)?S(ye=>{const he=new Set(ye);return he.delete(fe),he}):(S(ye=>{const he=new Set(ye);return he.add(fe),he}),await Y(fe))},se=fe=>{w(s?q=>{const ye=new Set(q);return ye.has(fe)?ye.delete(fe):ye.add(fe),ye}:new Set([fe]))},H=async()=>{const fe=new Map;Object.values(M).forEach(he=>{he.forEach(He=>{He.type==="file"&&fe.set(He.path,He)})});const q=new Map($.map(he=>[he.path,he])),ye=Array.from(N).map(he=>fe.get(he)??q.get(he)).filter(he=>!!he);E(!0);try{await t(ye),w(new Set),oe(!1),b(!1)}finally{E(!1)}},le=i.useMemo(()=>d?M[d]??[]:[],[M,d]),ge=v.trim().length>0,z=fe=>M[fe]??[],J=fe=>{if(d&&fe.startsWith(d)){const q=fe.substring(d.length);return q.startsWith("/")?q.substring(1):q}return fe.split("/").pop()||fe},je=(fe,q)=>{const ye=ge?fe.relativePath||J(fe.path):fe.name,he=ge&&ye.includes("/")&&ye.length>45,He=he?Vg(ye,{maxLength:c?42:48}):ye,ot=e.jsxs("div",{className:L("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded hover:bg-interactive-hover cursor-pointer typography-ui-label text-foreground text-left",fe.type==="file"&&N.has(fe.path)&&"bg-primary/10"),style:{paddingLeft:`${q*12}px`},onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),fe.type==="file"&&se(fe.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ie(fe)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":ye,children:He})]}),fe.type==="file"&&N.has(fe.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return he?e.jsxs(gt,{delayDuration:120,children:[e.jsx(xt,{asChild:!0,children:ot}),e.jsx(ht,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:ye})})]},fe.path):i.cloneElement(ot,{key:fe.path})},X=(fe,q)=>{const ye=fe.type==="directory",he=ye?z(fe.path):[],He=C.has(fe.path),ot=ye&&He&&P.current.has(fe.path)&&he.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",!ye&&N.has(fe.path)&&"bg-primary/10"),style:{paddingLeft:`${q*12}px`},onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),ye?B(fe.path):se(fe.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ie(fe)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:fe.name}),!ye&&N.has(fe.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),ye&&He&&he.length>0&&e.jsx("div",{children:he.map(ue=>X(ue,q+1))}),ye&&He&&ot&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(q+1)*12}px`},children:"Loading…"})]},fe.path)},G=N.size>0?`${N.size} file${N.size!==1?"s":""} selected`:"No files selected",ae=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:G}),e.jsx(Me,{size:"sm",onClick:H,disabled:N.size===0||I,className:"h-6 typography-meta",children:I?"Attaching...":"Attach Files"})]}),me=c?"flex-1 min-h-[240px]":"h-[300px]",Oe=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(Rr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Bt,{value:v,onChange:fe=>j(fe.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:fe=>fe.stopPropagation()}),v&&e.jsx("button",{onClick:fe=>{fe.stopPropagation(),j("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-interactive-hover rounded",children:e.jsx(hs,{className:"h-3 w-3"})})]})}),e.jsxs(GM,{className:me,children:[_&&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..."})}),W&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:W})}),!_&&!W&&e.jsxs("div",{className:"py-1 px-2",children:[ge?O?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):$.map(fe=>je(fe,0)):le.map(fe=>X(fe,0)),!ge&&le.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),ge&&!O&&$.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),Be=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),b(!0)},children:r});return a==="modal"?e.jsxs(e.Fragment,{children:[r?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),oe(!0)},children:r}):null,e.jsx(Cr,{open:ve,onClose:()=>oe(!1),title:"Select Project Files",footer:ae,children:e.jsx("div",{className:"flex flex-col gap-0",children:Oe})})]}):c?e.jsxs(e.Fragment,{children:[Be,e.jsx(Cr,{open:y,onClose:()=>b(!1),title:"Select Project Files",footer:ae,children:e.jsx("div",{className:"flex flex-col gap-0",children:Oe})})]}):e.jsxs(us,{open:ve,onOpenChange:oe,children:[e.jsx(ms,{asChild:!0,children:r}),e.jsxs(fs,{className:L("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[Oe,e.jsx(lr,{}),ae]})]})};function Cy({children:t,className:s,interval:r=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:l=!0,mode:c="popLayout"}){const[d,u]=ne.useState(0),m=ne.Children.toArray(t);ne.useEffect(()=>{if(!l)return;const p=r*1e3,h=setInterval(()=>{u(g=>{const x=(g+1)%m.length;return a?.(x),x})},p);return()=>clearInterval(h)},[m.length,r,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",s),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(uw,{mode:c,initial:!1,children:e.jsx(ra.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const Ji=[{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 mn(t){if(!t||t==="build")return Ji[0];let s=0;for(let n=0;n<t.length;n++){const o=t.charCodeAt(n);s=(s<<5)-s+o,s=s&s}const r=1+Math.abs(s)%(Ji.length-1);return Ji[r]}const QM=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,YM=typeof window<"u"?i.useLayoutEffect:i.useEffect,JM=(t,s=[])=>{const[r,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 YM(()=>{o()},[o,...s]),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]),r},lu=t=>{if(!Array.isArray(t))return null;const s=[];for(const r of t){if(!r||typeof r!="object")continue;const n=r;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||s.push({permission:n.permission,pattern:n.pattern,action:n.action})}return s},sd=(t,s)=>{const r=lu(t);if(!(!r||r.length===0)){for(let n=r.length-1;n>=0;n-=1){const o=r[n];if(o.permission===s&&o.pattern==="*")return o.action}for(let n=r.length-1;n>=0;n-=1){const o=r[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},XM=[{key:"tool_call",icon:rc,label:"Tool calling",isActive:t=>t?.tool_call===!0},{key:"reasoning",icon:Rn,label:"Reasoning",isActive:t=>t?.reasoning===!0}],ZM={text:{icon:cg,label:"Text"},image:{icon:Ln,label:"Image"},video:{icon:fw,label:"Video"},audio:{icon:mw,label:"Audio"},pdf:{icon:sc,label:"PDF"}},eA=t=>t.trim().toLowerCase(),Wa=(t,s)=>{const r=s==="input"?t?.modalities?.input:t?.modalities?.output;return!Array.isArray(r)||r.length===0?[]:Array.from(new Set(r.map(o=>eA(o)))).map(o=>{const a=ZM[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},tA=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),sA=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),on=t=>{if(typeof t!="number"||Number.isNaN(t))return"—";if(t===0)return"0";const s=tA.format(t);return s.endsWith(".0")?s.slice(0,-2):s},io=t=>typeof t!="number"||!Number.isFinite(t)?"—":sA.format(t),rA=t=>{if(!t?.cost)return null;const s=t.cost.input,r=t.cost.output,n=typeof s=="number"&&Number.isFinite(s),o=typeof r=="number"&&Number.isFinite(r);return n&&o?`In ${io(s)} · Out ${io(r)}`:n?`In ${io(s)}`:o?`Out ${io(r)}`:null},rd=t=>XM.filter(s=>s.isActive(t)).map(s=>({key:s.key,icon:s.icon,label:s.label})),up=t=>{if(!t)return"—";const s=t.match(/^(\d{4})-(\d{2})$/);if(s){const r=Number.parseInt(s[1],10),n=Number.parseInt(s[2],10)-1,o=new Date(Date.UTC(r,n,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return t},mp=t=>{if(!t)return"—";const s=new Date(t);return Number.isNaN(s.getTime())?t:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(s)},fp=({className:t,mobilePanel:s,onMobilePanelChange:r,onMobilePanelSelection:n,onAgentPanelSelection:o})=>{const{providers:a,currentProviderId:l,currentModelId:c,currentVariant:d,currentAgentName:u,settingsDefaultVariant:m,settingsDefaultAgent:f,setProvider:p,setModel:h,setCurrentVariant:g,getCurrentModelVariants:x,setAgent:y,getCurrentProvider:b,getModelMetadata:v,getCurrentAgent:j,getVisibleAgents:k}=ut(),N=k(),w=i.useMemo(()=>N.filter(ee=>ee.mode==="primary"),[N]),{currentSessionId:C,messages:S,saveSessionAgentSelection:M,saveAgentModelForSession:D,getAgentModelForSession:A,saveAgentModelVariantForSession:P,getAgentModelVariantForSession:$,analyzeAndSaveExternalSessionChoices:R}=Ae(),O=Lt(ee=>ee.hasHydrated),T=Lt(ee=>C?ee.sessionAgentSelections.get(C)??null:null),_=i.useRef(null);i.useEffect(()=>{if(!C){_.current=null;return}T&&(_.current=T)},[C,T]);const F=C?_.current:null,I=C&&(T||F)||u,E=C??"__global__",W=Lt(ee=>{if(I)return ee.getSessionAgentEditMode(E,I,"ask")}),V=Lt(ee=>ee.setSessionAgentEditMode),{toggleFavoriteModel:ve,isFavoriteModel:oe,addRecentModel:Z,addRecentAgent:ce,addRecentEffort:Q,isModelSelectorOpen:Y,setModelSelectorOpen:ie}=Te(),[B,se]=i.useState(!1),{favoriteModelsList:H,recentModelsList:le}=vc(),{isMobile:ge}=ks(),z=i.useMemo(()=>Lr(),[]),J=Ex(),je=ge,[X,G]=i.useState(null),ae=s!==void 0&&typeof r=="function",me=ae?s:X,Oe=ae?r:G,[Be,fe]=i.useState(null),[q,ye]=i.useState(""),he=i.useRef(!1),He=i.useCallback(()=>Oe(null),[Oe]),ot=i.useCallback(()=>fe(null),[]),ue=i.useRef(void 0),[Ve,De]=i.useState(()=>{const ee=new Set;return l&&ee.add(l),ee}),we=Y,Fe=ie,[Pe,$e]=i.useState(""),[Ze,Ue]=i.useState(0),Ee=i.useRef([]);i.useEffect(()=>{me==="model"&&De(()=>{const ee=new Set;return l&&ee.add(l),ee})},[me,l]),i.useEffect(()=>{me!=="model"&&ye("")},[me]);const Re=i.useRef(Y);i.useEffect(()=>{const ee=Re.current;Re.current=Y,Y||($e(""),Ue(0),ee&&!je&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[Y,je]);const[Xe,st]=i.useState(""),St=i.useRef(B);i.useEffect(()=>{const ee=St.current;St.current=B,B||(st(""),ee&&!je&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[B,je]),i.useEffect(()=>{Ue(0)},[Pe]);const mt=i.useMemo(()=>N.filter(ee=>ee.mode!=="subagent"),[N]),Tt=i.useMemo(()=>{const ee=[...mt].sort((xe,Ne)=>xe.name.localeCompare(Ne.name));return Xe.trim()?ee.filter(xe=>ao(xe.name,Xe)||xe.description&&ao(xe.description,Xe)):ee},[mt,Xe]),qt=i.useMemo(()=>{if(f){const xe=mt.find(Ne=>Ne.name===f);if(xe)return xe.name}const ee=mt.find(xe=>xe.name==="build");return ee?ee.name:mt[0]?.name},[f,mt]),yt=i.useMemo(()=>I?N.find(ee=>ee.name===I):j?.(),[N,j,I]),os=i.useMemo(()=>yt?sd(yt.permission,"edit")??"allow":"deny",[yt]),cs=!!I,ds=os==="ask",de=ds?W==="allow"||W==="full":os==="allow",ke=!cs||!ds,We=ge?"mobile":J?"vscode":"default",qe=We==="mobile"?"h-9":We==="vscode"?"h-6":"h-8",et=We==="mobile"?"h-5 w-5":"h-4 w-4",ct=We==="mobile"?"h-5 w-5":"h-4 w-4",bt=je?"typography-micro":"typography-meta",at=We==="mobile"?"gap-x-1":We==="vscode"?"gap-x-2":"gap-x-3",_t=i.useCallback((ee,xe=et)=>{const Ne=L(xe,"flex-shrink-0"),ze=QM(ee),kt={color:ze?ze.text:"var(--foreground)"};return ee==="full"?e.jsx(fn,{className:Ne,style:kt}):ee==="allow"?e.jsx(al,{className:Ne,style:kt}):ee==="deny"?e.jsx(li,{className:Ne,style:kt}):e.jsx(Fo,{className:Ne,style:kt})},[et]),Nt=i.useCallback(ee=>{!cs||!u||!ds||V(E,u,ee?"allow":"ask","ask")},[ds,u,cs,V,E]),Gt=b(),zt=Array.isArray(Gt?.models)?Gt.models:[],Ct=l&&c?v(l,c):void 0,Qt=rd(Ct),Mt=Wa(Ct,"input"),Zt=Wa(Ct,"output"),jt=i.useMemo(()=>x(),[x]),es=jt.length>0,Ye=[{label:"Input",value:io(Ct?.cost?.input)},{label:"Output",value:io(Ct?.cost?.output)},{label:"Cache read",value:io(Ct?.cost?.cache_read)},{label:"Cache write",value:io(Ct?.cost?.cache_write)}],ft=[{label:"Context",value:on(Ct?.limit?.context)},{label:"Output",value:on(Ct?.limit?.output)}],vt=i.useRef(void 0),pt=C?S.get(C)?.length??-1:-1,Rt=i.useRef(null);i.useEffect(()=>{if(!C)return;const ee=Rt.current;!ee||ee.sessionId!==C||T&&N.some(xe=>xe.name===T)&&(ee.resolved=!0,ee.inFlight=!1)},[N,C,T]);const Ft=i.useCallback((ee,xe,Ne)=>{if(!ee||!xe)return"model-missing";const ze=a.find(re=>re.id===ee);return ze?(Array.isArray(ze.models)?ze.models:[]).find(re=>re.id===xe)?(p(ee),h(xe),C&&Ne&&D(C,Ne,ee,xe),"applied"):"model-missing":"provider-missing"},[a,p,h,C,D]);i.useEffect(()=>{if(!C){Rt.current=null;return}if(!O||a.length===0||N.length===0)return;(!Rt.current||Rt.current.sessionId!==C)&&(Rt.current={sessionId:C,resolved:!1,inFlight:!1});const ee=Rt.current;if(!ee||ee.resolved||ee.inFlight)return;let xe=!1;const Ne=()=>{if(xe)return;const re=Rt.current;re&&re.sessionId===C&&(re.resolved=!0,re.inFlight=!1)},ze=()=>{const re=C?Lt.getState().getSessionAgentSelection(C)||_.current:null;if(re){u!==re&&y(re);const Le=A(C,re);if(Le){const Ce=Ft(Le.providerId,Le.modelId,re);if(Ce==="applied")return"resolved";if(Ce==="provider-missing")return"waiting"}else return"resolved"}for(const Le of N){const Ce=A(C,Le.name);if(!Ce)continue;u!==Le.name&&y(Le.name),Lt.getState().getSessionAgentSelection(C)||_.current||M(C,Le.name);const Qe=Ft(Ce.providerId,Ce.modelId,Le.name);if(Qe==="applied")return"resolved";if(Qe==="provider-missing")return"waiting"}return"continue"},tt=()=>{if(N.length===0)return;const re=C?Lt.getState().getSessionAgentSelection(C)||_.current:null,Le=(C?Lt.getState().getSessionAgentSelection(C)||_.current:null)||u;if(Le&&N.some(_e=>_e.name===Le)){u!==Le&&y(Le);return}const Ce=N.find(_e=>_e.name==="build")||w[0]||N[0];Ce&&(re||M(C,Ce.name),u!==Ce.name&&y(Ce.name),Ce.model?.providerID&&Ce.model?.modelID&&Ft(Ce.model.providerID,Ce.model.modelID,Ce.name))};return(async()=>{try{const re=ze();if(re==="resolved"){Ne();return}if(re==="waiting"||pt===-1)return;if(pt>0){ee.inFlight=!0;try{const Le=await R(C,N);if(xe)return;if(Le.size>0){let Ce=null,_e=-1/0;for(const[Qe,dt]of Le)dt.timestamp>_e&&(_e=dt.timestamp,Ce=Qe);if(Ce){const Qe=Lt.getState().getSessionAgentSelection(C)||_.current;if(Qe&&Qe!==Ce){Ne();return}Qe||M(C,Ce),u!==Ce&&y(Ce);const dt=Le.get(Ce);if(dt){const $t=Ft(dt.providerId,dt.modelId,Ce);if($t==="applied"){Ne();return}if($t==="provider-missing")return}else{Ne();return}}}}catch(Le){xe||console.error("[ModelControls] Error resolving session from messages:",Le)}finally{const Le=Rt.current;!xe&&Le&&Le.sessionId===C&&(Le.inFlight=!1)}}if(xe)return;tt(),Ne()}catch(re){xe||console.error("[ModelControls] Error in session switch:",re)}})(),()=>{xe=!0}},[C,pt,N,w,u,A,y,Ft,R,M,O,a,T]),i.useEffect(()=>{if(!O||!C||a.length===0||N.length===0)return;const ee=T||u;if(!ee)return;const xe=A(C,ee);if(!xe)return;const Ne=a.find(re=>re.id===xe.providerId);if(!Ne||!(Array.isArray(Ne.models)?Ne.models.some(re=>re.id===xe.modelId):!1))return;const tt=l===xe.providerId,kt=c===xe.modelId;tt&&kt||(ee!==u&&y(ee),Ft(xe.providerId,xe.modelId,ee))},[O,C,u,l,c,a,N,A,Ft,y,T]),i.useEffect(()=>{if(!O)return;(async()=>{try{if(u!==vt.current&&(vt.current=u,u&&C)){await new Promise(ze=>setTimeout(ze,50));const xe=A(C,u);if(xe){const ze=Ft(xe.providerId,xe.modelId,u);if(ze==="applied"||ze==="provider-missing")return}const Ne=N.find(ze=>ze.name===u);if(Ne?.model?.providerID&&Ne?.model?.modelID&&Ft(Ne.model.providerID,Ne.model.modelID,u)==="provider-missing")return}}catch(xe){console.error("[ModelControls] Agent change error:",xe)}})()},[u,C,A,Ft,N,O]),i.useEffect(()=>{if(!O||!u){he.current=!1,g(void 0);return}if(!l||!c){he.current=!1,g(void 0);return}if(jt.length===0){he.current=!1,g(void 0);return}if(d&&!jt.includes(d)){g(void 0);return}if(!C){if(!d&&!he.current){const Ne=m&&jt.includes(m)?m:void 0;g(Ne)}return}const ee=$(C,u,l,c),xe=ee&&jt.includes(ee)?ee:void 0;g(xe),he.current=!1},[jt,O,C,u,l,c,d,$,g,m]),i.useEffect(()=>{he.current=!1},[l,c]);const Pt=i.useCallback(ee=>{he.current=!0,g(ee),l&&c&&Q(l,c,ee),C&&u&&l&&c&&P(C,u,l,c,ee)},[Q,u,c,l,C,P,g]),Jt=ee=>{try{if(y(ee),ce(ee),Fe(!1),C&&M(C,ee),je){He();const xe=o||n;xe&&requestAnimationFrame(()=>{xe()})}}catch(xe){console.error("[ModelControls] Handle agent change error:",xe)}},Ns=(ee,xe)=>{try{const Ne=Ft(ee,xe,u||void 0);if(Ne!=="applied"){Ne==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",ee):Ne==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:ee,modelId:xe});return}Z(ee,xe),Fe(!1),je&&(He(),n&&requestAnimationFrame(()=>{n()})),(!je||!n)&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(Ne){console.error("[ModelControls] Handle model change error:",Ne)}},Ts=ee=>{const xe=typeof ee?.name=="string"?ee.name:typeof ee?.id=="string"?ee.id:"";return xe.length>40?xe.substring(0,37)+"...":xe},sr=()=>a.find(xe=>xe.id===l)?.name||l,Xs=()=>{if(!l||!c||zt.length===0)return"Not selected";const ee=zt.find(xe=>xe.id===c);return Ts(ee)},_s=Xs(),mr=i.useRef(null),Zs=JM(mr,[_s,je]),gr=()=>{if(!I){const Ne=w.find(ze=>ze.name==="build")||w[0];return Ne?Ie(Ne.name):"Select Agent"}const ee=N.find(xe=>xe.name===I);return Ie(ee?ee.name:I)},Ie=ee=>ee.charAt(0).toUpperCase()+ee.slice(1),Ge=(ee,xe,Ne)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:xe,"aria-label":xe,role:"img",children:e.jsx(ee,{className:"h-3.5 w-3.5"})},Ne),At=i.useCallback(ee=>{De(xe=>{const Ne=new Set(xe);return Ne.has(ee)?Ne.delete(ee):Ne.add(ee),Ne})},[]),it=i.useCallback(ee=>{ue.current&&clearTimeout(ue.current),ue.current=setTimeout(()=>{fe(ee)},500)},[]),Kt=i.useCallback(()=>{ue.current&&clearTimeout(ue.current)},[]);i.useEffect(()=>()=>{ue.current&&clearTimeout(ue.current)},[]);const It=()=>!je||Be!=="model"?null:e.jsx(Cr,{open:!0,onClose:ot,title:Ct?.name||Xs(),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:sr()})]}),Qt.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:Qt.map(({key:ee,icon:xe,label:Ne})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ge(xe,Ne,`cap-${ee}`),e.jsx("span",{className:"typography-meta text-foreground",children:Ne})]},ee))})]}),(Mt.length>0||Zt.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:[Mt.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:Mt.map(({key:ee,icon:xe,label:Ne})=>Ge(xe,`${Ne} input`,`input-${ee}`))})]}),Zt.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:Zt.map(({key:ee,icon:xe,label:Ne})=>Ge(xe,`${Ne} output`,`output-${ee}`))})]})]})]}),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:on(Ct?.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:on(Ct?.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:up(Ct?.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:mp(Ct?.release_date)})]})]})]})]})}),Ps=()=>{if(!je||Be!=="agent"||!yt)return null;const ee=!!(yt.prompt&&yt.prompt.trim().length>0),xe=yt.model?.providerID&&yt.model?.modelID,Ne=yt.temperature!==void 0||yt.topP!==void 0,ze=Le=>{const Ce=lu(yt.permission)??[],_e=Ce.some(dt=>dt.permission===Le&&dt.pattern!=="*"),Qe=sd(Ce,Le)??"ask";return _e?{mode:"ask",label:"Custom"}:Qe==="allow"?{mode:"allow",label:"Allow"}:Qe==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},tt=ze("edit"),kt=ze("bash"),re=ze("webfetch");return e.jsx(Cr,{open:!0,onClose:ot,title:Ie(yt.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[yt.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:yt.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:yt.mode==="primary"?"Primary":yt.mode==="subagent"?"Subagent":yt.mode==="all"?"All":"—"})]}),(xe||Ne)&&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"}),xe&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[yt.model.providerID," / ",yt.model.modelID]}),Ne&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[yt.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:yt.temperature})]}),yt.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:yt.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:[_t(tt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:tt.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:[_t(kt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:kt.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:[_t(re.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:re.label})]})]})]})]}),ee&&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(al,{className:"h-4 w-4 text-foreground"})]})})]})})},Hs=i.useCallback(ee=>{const xe=ee.toLowerCase().trim(),Ne=xe.replace(/[^a-z0-9]/g,""),ze=xe.split(/[^a-z0-9]+/).filter(Boolean);return{lower:xe,compact:Ne,tokens:ze}},[]),Es=i.useCallback((ee,xe)=>{const Ne=Hs(xe);if(!Ne.lower)return!0;const ze=Hs(ee);return ze.lower.includes(Ne.lower)||Ne.compact.length>=2&&ze.compact.includes(Ne.compact)?!0:Ne.tokens.length===0?!1:Ne.tokens.every(tt=>ze.tokens.some(kt=>kt.startsWith(tt)||kt.includes(tt)))},[Hs]),er=()=>{if(!je)return null;const ee=q.trim(),xe=a.map(Ne=>{const ze=Array.isArray(Ne.models)?Ne.models:[],tt=ee.length===0?!0:Es(Ne.name,ee)||Es(Ne.id,ee),kt=ee.length===0?ze:ze.filter(re=>{const Le=Ts(re),Ce=typeof re.id=="string"?re.id:"";return Es(Le,ee)||Es(Ce,ee)});return{provider:Ne,providerModels:kt,matchesProvider:tt}}).filter(({matchesProvider:Ne,providerModels:ze})=>Ne||ze.length>0);return e.jsx(Cr,{open:me==="model",onClose:He,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(Rr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Bt,{value:q,onChange:Ne=>ye(Ne.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-[var(--surface-elevated)] typography-meta"}),q&&e.jsx("button",{type:"button",onClick:()=>ye(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(li,{className:"h-4 w-4"})})]})}),xe.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."}),!q&&H.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] 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(Mn,{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:H.map(({model:Ne,providerID:ze,modelID:tt})=>{const kt=ze===l&&tt===c,re=v(ze,tt);return e.jsxs("button",{type:"button",onClick:()=>Ns(ze,tt),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",kt?"bg-interactive-selection/15 text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Os,{providerId:ze,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ts(Ne)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(re?.limit?.context||re?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[re?.limit?.context?`${on(re?.limit?.context)} ctx`:"",re?.limit?.context&&re?.limit?.output?" • ":"",re?.limit?.output?`${on(re?.limit?.output)} out`:""]})})]},`fav-mobile-${ze}-${tt}`)})})]}),!q&&le.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] 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(Pn,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:le.map(({model:Ne,providerID:ze,modelID:tt})=>{const kt=ze===l&&tt===c,re=v(ze,tt);return e.jsxs("button",{type:"button",onClick:()=>Ns(ze,tt),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",kt?"bg-interactive-selection/15 text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Os,{providerId:ze,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ts(Ne)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(re?.limit?.context||re?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[re?.limit?.context?`${on(re?.limit?.context)} ctx`:"",re?.limit?.context&&re?.limit?.output?" • ":"",re?.limit?.output?`${on(re?.limit?.output)} out`:""]})})]},`recent-mobile-${ze}-${tt}`)})})]}),xe.map(({provider:Ne,providerModels:ze})=>{if(ze.length===0&&!ee.length)return null;const tt=Ne.id===l,kt=Ve.has(Ne.id)||ee.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>At(Ne.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":kt,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{providerId:Ne.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ne.name}),tt&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),kt?e.jsx(is,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(dr,{className:"h-3 w-3 text-muted-foreground"})]}),kt&&ze.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:ze.map(re=>{const Le=tt&&re.id===c,Ce=v(Ne.id,re.id),_e=rd(Ce).slice(0,3),Qe=Wa(Ce,"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",!Le&&"hover:bg-interactive-hover",Le?"bg-interactive-selection/15 text-interactive-selection-foreground":""),children:[e.jsxs("button",{type:"button",onClick:()=>Ns(Ne.id,re.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:Ts(re)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Ce?.limit?.context||Ce?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Ce?.limit?.context?e.jsxs("span",{children:[on(Ce?.limit?.context)," ctx"]}):null,Ce?.limit?.context&&Ce?.limit?.output?e.jsx("span",{children:"•"}):null,Ce?.limit?.output?e.jsxs("span",{children:[on(Ce?.limit?.output)," out"]}):null]}),(_e.length>0||Qe.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[..._e,...Qe].map(({key:dt,icon:$t,label:be})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:be,"aria-label":be,children:e.jsx($t,{className:"h-3 w-3"})},`meta-${Ne.id}-${re.id}-${dt}`))})]})]}),e.jsx("button",{type:"button",onClick:dt=>{dt.preventDefault(),dt.stopPropagation(),ve(Ne.id,re.id)},className:L("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-primary/80 flex-shrink-0",oe(Ne.id,re.id)?"text-primary":"text-muted-foreground"),"aria-label":oe(Ne.id,re.id)?"Unfavorite":"Favorite",title:oe(Ne.id,re.id)?"Remove from favorites":"Add to favorites",children:oe(Ne.id,re.id)?e.jsx(Mn,{className:"h-4 w-4"}):e.jsx(Do,{className:"h-4 w-4"})})]},re.id)})})]},Ne.id)})]})})},Cs=()=>{if(!je||!es)return null;const ee=!d,xe=Ne=>{if(Pt(Ne),He(),n){requestAnimationFrame(()=>{n()});return}requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(Cr,{open:me==="variant",onClose:He,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",ee?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>xe(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),ee&&e.jsx(ss,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),jt.map(Ne=>{const ze=d===Ne,tt=Ne.charAt(0).toUpperCase()+Ne.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",ze?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>xe(Ne),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:tt}),ze&&e.jsx(ss,{className:"h-4 w-4 text-primary flex-shrink-0"})]},Ne)})]})})},ar=()=>je?e.jsx(Cr,{open:me==="agent",onClose:He,title:"Select agent",contentMaxHeightClassName:"max-h-[min(52dvh,360px)]",footer:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:L("typography-meta font-medium",ke?"text-muted-foreground":"text-foreground"),children:"Auto-approve edits"}),e.jsx(nr,{checked:de,disabled:ke,onCheckedChange:Nt})]}),children:e.jsx("div",{className:"flex flex-col gap-2",children:mt.map(ee=>{const xe=ee.name===I,Ne=mn(ee.name);return e.jsxs("button",{type:"button",className:L("flex w-full flex-col gap-1.5 rounded-xl border px-3 py-2.5 text-left","focus:outline-none focus-visible:ring-2 focus-visible:ring-primary","touch-manipulation cursor-pointer transition-colors","active:bg-interactive-hover",xe?"border-primary/50 bg-interactive-selection/20":"border-border/40 hover:bg-interactive-hover/50"),onClick:()=>Jt(ee.name),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:L("h-2.5 w-2.5 rounded-full flex-shrink-0",Ne.class)}),e.jsx("span",{className:"typography-ui-label font-semibold",style:xe?{color:`var(${Ne.var})`}:void 0,children:Ie(ee.name)}),xe&&e.jsx(ss,{className:"h-4 w-4 text-primary ml-auto flex-shrink-0"})]}),ee.description&&e.jsx("span",{className:"typography-meta text-muted-foreground pl-4.5",children:ee.description})]},ee.name)})})}):null,ir=()=>e.jsx(ht,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ct?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:Ct.name||Xs()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:sr()})]}),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:Qt.length>0?Qt.map(({key:ee,icon:xe,label:Ne})=>Ge(xe,Ne,`cap-${ee}`)):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:Mt.length>0?Mt.map(({key:ee,icon:xe,label:Ne})=>Ge(xe,`${Ne} input`,`input-${ee}`)):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:Zt.length>0?Zt.map(({key:ee,icon:xe,label:Ne})=>Ge(xe,`${Ne} output`,`output-${ee}`)):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)"}),Ye.map(ee=>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:ee.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ee.value})]},ee.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"}),ft.map(ee=>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:ee.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ee.value})]},ee.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:up(Ct.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:mp(Ct.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),qs=(ee,xe,Ne,ze,tt,kt)=>{const re=v(xe,Ne),Le=rd(re).map(Xt=>({...Xt,id:`cap-${Xt.key}`})),Ce=[...Wa(re,"input"),...Wa(re,"output")],_e=Array.from(new Map(Ce.map(Xt=>[Xt.key,Xt])).values()).map(Xt=>({...Xt,id:`mod-${Xt.key}`})),Qe=[...Le,..._e],dt=on(re?.limit?.context),$t=l===xe&&c===Ne,be=oe(xe,Ne),U=ze==="fav"||ze==="recent",te=rA(re),Se=te!==null,Je=Qe.length>0,rt=[];Se&&rt.push(e.jsx("span",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:te},"price")),Je&&rt.push(e.jsx("div",{className:"flex items-center gap-0.5",children:Qe.map(({id:Xt,icon:Ht,label:ls})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":ls,role:"img",title:ls,children:e.jsx(Ht,{className:"h-2.5 w-2.5"})},Xt))},"capabilities"));const lt=!J,Ke=lt&&rt.length>1&&(kt||$t),as=rt[!lt&&Je&&Se?1:0];return e.jsxs("div",{ref:Xt=>{Ee.current[tt]=Xt},className:L("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",kt?"bg-interactive-selection":"hover:bg-interactive-hover/50"),onClick:()=>Ns(xe,Ne),onMouseEnter:()=>Ue(tt),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[U&&e.jsx(Os,{providerId:xe,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Ts(ee)}),re?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:dt}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[rt.length>0&&e.jsx("div",{className:L("items-center",Ke?"flex w-[140px] justify-end":kt||$t?"flex":"hidden group-hover:flex"),children:Ke?e.jsx(Cy,{interval:2.1,transition:{duration:.25},trigger:Ke,children:rt}):e.jsx(e.Fragment,{children:as})}),$t&&e.jsx(ss,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:Xt=>{Xt.preventDefault(),Xt.stopPropagation(),ve(xe,Ne)},className:L("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-primary/80",be?"text-primary":"text-muted-foreground"),"aria-label":be?"Unfavorite":"Favorite",title:be?"Remove from favorites":"Add to favorites",children:be?e.jsx(Mn,{className:"h-3.5 w-3.5"}):e.jsx(Do,{className:"h-3.5 w-3.5"})})]})]},`${ze}-${xe}-${Ne}`)},Ir=(ee,xe,Ne)=>Ne.trim()?Es(ee,Ne)||Es(xe,Ne):!0,fr=()=>{const ee=H.filter(({model:Ce,providerID:_e})=>{const dt=a.find(be=>be.id===_e)?.name||_e,$t=Ts(Ce);return Ir($t,dt,Pe)}),xe=le.filter(({model:Ce,providerID:_e})=>{const dt=a.find(be=>be.id===_e)?.name||_e,$t=Ts(Ce);return Ir($t,dt,Pe)}),Ne=a.map(Ce=>{const Qe=(Array.isArray(Ce.models)?Ce.models:[]).filter(dt=>{const $t=Ts(dt);return Ir($t,Ce.name||Ce.id||"",Pe)});return{...Ce,models:Qe}}).filter(Ce=>Ce.models.length>0),ze=ee.length>0||xe.length>0||Ne.length>0,tt=[];ee.forEach(({model:Ce,providerID:_e,modelID:Qe})=>{tt.push({model:Ce,providerID:_e,modelID:Qe,section:"fav"})}),xe.forEach(({model:Ce,providerID:_e,modelID:Qe})=>{tt.push({model:Ce,providerID:_e,modelID:Qe,section:"recent"})}),Ne.forEach(Ce=>{Ce.models.forEach(_e=>{tt.push({model:_e,providerID:Ce.id,modelID:_e.id,section:"provider"})})});const kt=tt.length,re=Ce=>{if(Ce.stopPropagation(),Ce.key==="ArrowDown")Ce.preventDefault(),Ue(_e=>(_e+1)%Math.max(1,kt)),setTimeout(()=>{const _e=(Ze+1)%Math.max(1,kt);Ee.current[_e]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Ce.key==="ArrowUp")Ce.preventDefault(),Ue(_e=>(_e-1+Math.max(1,kt))%Math.max(1,kt)),setTimeout(()=>{const _e=(Ze-1+Math.max(1,kt))%Math.max(1,kt);Ee.current[_e]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Ce.key==="Enter"){Ce.preventDefault();const _e=tt[Ze];_e&&Ns(_e.providerID,_e.modelID)}else Ce.key==="Escape"&&(Ce.preventDefault(),Fe(!1))};let Le=0;return e.jsxs(gt,{delayDuration:1e3,children:[je?e.jsxs("button",{type:"button",onClick:()=>Oe("model"),onTouchStart:()=>it("model"),onTouchEnd:Kt,onTouchCancel:Kt,className:L("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:bg-transparent hover:opacity-70",qe),children:[l?e.jsx(Os,{providerId:l,className:L(ct,"flex-shrink-0")}):e.jsx(fn,{className:L(ct,"text-muted-foreground")}),e.jsx("span",{ref:mr,className:L("model-controls__model-label typography-micro font-medium overflow-hidden min-w-0",ge?"max-w-[120px]":"max-w-[220px]"),children:e.jsx("span",{className:L("marquee-text",Zs&&"marquee-text--active"),children:_s})})]}):e.jsxs(us,{open:we,onOpenChange:Fe,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:e.jsxs("div",{className:L("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:bg-transparent hover:opacity-70 min-w-0",qe),children:[l?e.jsxs(e.Fragment,{children:[e.jsx(Os,{providerId:l,className:L(ct,"flex-shrink-0")}),e.jsx(fn,{className:L(ct,"text-primary/60 hidden")})]}):e.jsx(fn,{className:L(ct,"text-muted-foreground")}),e.jsx("span",{ref:mr,className:L("model-controls__model-label overflow-hidden",bt,"font-medium whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:e.jsx("span",{className:L("marquee-text",Zs&&"marquee-text--active"),children:_s})},`${l}-${c}`)]})})}),e.jsxs(fs,{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(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Bt,{type:"text",placeholder:"Search models",value:Pe,onChange:Ce=>$e(Ce.target.value),onKeyDown:re,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(Ut,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!ze&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),ee.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Wr,{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[e.jsx(Mn,{className:"h-4 w-4 text-primary"}),"Favorites"]}),ee.map(({model:Ce,providerID:_e,modelID:Qe})=>{const dt=Le++;return qs(Ce,_e,Qe,"fav",dt,Ze===dt)})]}),xe.length>0&&e.jsxs(e.Fragment,{children:[ee.length>0&&e.jsx(lr,{}),e.jsxs(Wr,{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[e.jsx(Pn,{className:"h-4 w-4"}),"Recent"]}),xe.map(({model:Ce,providerID:_e,modelID:Qe})=>{const dt=Le++;return qs(Ce,_e,Qe,"recent",dt,Ze===dt)})]}),(ee.length>0||xe.length>0)&&Ne.length>0&&e.jsx(lr,{}),Ne.map((Ce,_e)=>e.jsxs(i.Fragment,{children:[_e>0&&e.jsx(lr,{}),e.jsxs(Wr,{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[e.jsx(Os,{providerId:Ce.id,className:"h-4 w-4 flex-shrink-0"}),Ce.name]}),Ce.models.map(Qe=>{const dt=Le++;return qs(Qe,Ce.id,Qe.id,"provider",dt,Ze===dt)})]},Ce.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"})]})]}),ir()]})},xr=()=>{if(!yt)return e.jsx(ht,{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 ee=!!(yt.prompt&&yt.prompt.trim().length>0),xe=yt.model?.providerID&&yt.model?.modelID,Ne=yt.temperature!==void 0||yt.topP!==void 0,ze=Le=>{const Ce=lu(yt.permission)??[],_e=Ce.some(dt=>dt.permission===Le&&dt.pattern!=="*"),Qe=sd(Ce,Le)??"ask";return _e?{mode:"ask",label:"Custom"}:Qe==="allow"?{mode:"allow",label:"Allow"}:Qe==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},tt=ze("edit"),kt=ze("bash"),re=ze("webfetch");return e.jsx(ht,{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:Ie(yt.name)}),yt.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:yt.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:yt.mode==="primary"?"Primary":yt.mode==="subagent"?"Subagent":yt.mode==="all"?"All":"—"})]}),(xe||Ne)&&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"}),xe?e.jsxs("span",{className:"typography-meta text-foreground",children:[yt.model.providerID," / ",yt.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),Ne&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[yt.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:yt.temperature})]}),yt.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:yt.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:[_t(tt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:tt.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:[_t(kt.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:kt.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:[_t(re.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:re.label})]})]})]}),ee&&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(al,{className:"h-4 w-4 text-foreground"})]})]})})},yr=()=>{if(!es)return null;const ee=d??"Default",xe=!d,Ne=xe?"text-muted-foreground":"text-[color:var(--status-info)]";return je?e.jsxs("button",{type:"button",onClick:()=>Oe("variant"),className:L("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",qe,"cursor-pointer hover:bg-transparent hover:opacity-70"),children:[e.jsx(Rn,{className:L(ct,"flex-shrink-0",Ne)}),e.jsx("span",{className:L("model-controls__variant-label",bt,"font-medium truncate min-w-0",ge&&"max-w-[60px]",Ne),children:ee})]}):e.jsxs(gt,{delayDuration:800,children:[e.jsxs(us,{children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:e.jsxs("div",{className:L("model-controls__variant-trigger flex items-center gap-1.5 transition-colors cursor-pointer hover:bg-transparent hover:opacity-70 min-w-0",qe),children:[e.jsx(Rn,{className:L(ct,"flex-shrink-0",Ne)}),e.jsx("span",{className:L("model-controls__variant-label",bt,"font-medium min-w-0 truncate",z?"max-w-[180px]":void 0,Ne),children:ee})]})})}),e.jsxs(fs,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Wr,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(Et,{className:"typography-meta",onSelect:()=>Pt(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"}),xe&&e.jsx(ss,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),jt.length>0&&e.jsx(lr,{}),jt.map(ze=>{const tt=d===ze,kt=ze.charAt(0).toUpperCase()+ze.slice(1);return e.jsx(Et,{className:"typography-meta",onSelect:()=>Pt(ze),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:kt}),tt&&e.jsx(ss,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},ze)})]})]}),e.jsx(ht,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",ee]})})]})},_r=()=>je?e.jsxs("button",{type:"button",onClick:()=>Oe("agent"),onTouchStart:()=>it("agent"),onTouchEnd:Kt,onTouchCancel:Kt,className:L("model-controls__agent-trigger flex items-center gap-1.5 transition-colors min-w-0 focus:outline-none",qe,"cursor-pointer hover:bg-transparent hover:opacity-70"),children:[e.jsx(Lo,{className:L(ct,"flex-shrink-0",I?"":"text-muted-foreground"),style:I?{color:`var(${mn(I).var})`}:void 0}),e.jsx("span",{className:L("model-controls__agent-label",bt,"font-medium truncate min-w-0",ge&&"max-w-[60px]"),style:I?{color:`var(${mn(I).var})`}:void 0,children:gr()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(gt,{delayDuration:1e3,children:[e.jsxs(us,{open:B,onOpenChange:se,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:e.jsxs("div",{className:L("flex items-center gap-1.5 transition-colors cursor-pointer hover:bg-transparent hover:opacity-70 min-w-0",qe),children:[e.jsx(Lo,{className:L(ct,"flex-shrink-0",I?"":"text-muted-foreground"),style:I?{color:`var(${mn(I).var})`}:void 0}),e.jsx("span",{className:L("model-controls__agent-label",bt,"font-medium min-w-0 truncate",z?"max-w-[220px]":void 0),style:I?{color:`var(${mn(I).var})`}:void 0,children:gr()})]})})}),e.jsxs(fs,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))] p-0 flex flex-col",children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Bt,{type:"text",placeholder:"Search agents",value:Xe,onChange:ee=>st(ee.target.value),onKeyDown:ee=>{ee.stopPropagation()},className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(Ut,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!Xe.trim()&&qt&&e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"typography-meta",onSelect:()=>Jt(qt),children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Oo,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:"Reset to default"})]})}),e.jsx(lr,{})]}),Tt.length===0?e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No agents found"}):Tt.map(ee=>e.jsx(Et,{className:"typography-meta",onSelect:()=>Jt(ee.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",mn(ee.name).class)}),e.jsx("span",{className:"font-medium",children:Ie(ee.name)})]}),ee.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:ee.description})]})},ee.name))]})}),e.jsx(lr,{}),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",ke?"text-muted-foreground":"text-foreground"),children:"Auto-approve edits"}),e.jsx(nr,{checked:de,disabled:ke,onCheckedChange:Nt})]})})})]})]}),xr()]})}),pe=L("@container/model-controls flex items-center min-w-0",ge&&"w-full",t);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:pe,children:e.jsxs("div",{className:L("flex items-center min-w-0 flex-1 justify-end",at,ge&&"overflow-hidden"),children:[yr(),fr(),_r()]})}),er(),Cs(),ar(),It(),Ps()]})},nA=t=>t==="primary"||t==="all"||t===void 0||t===null,vl=t=>t.charAt(0).toUpperCase()+t.slice(1),oA=(t,s)=>{if(s){const a=t.find(l=>l.name===s);return vl(a?a.name:s)}const r=t.filter(a=>nA(a.mode)),o=r.find(a=>a.name==="build")||r[0]||t[0];return o?vl(o.name):"Select agent"},aA=(t,s)=>{if(!t||!s)return"Not selected";const n=(Array.isArray(t.models)?t.models:[]).find(o=>o.id===s);return typeof n?.name=="string"&&n.name.trim().length>0?n.name:typeof n?.id=="string"&&n.id.trim().length>0?n.id:s},iA=t=>{if(!t||t.trim().length===0)return"Default";const s=t.trim();return/^\d+(\.\d+)?$/.test(s)?s:vl(s)},lA="default",cA=t=>t===lA?void 0:t,nd={max:6,maximum:6,xhigh:5,high:4,medium:3,default:2,low:1,min:0,minimal:0},pp=t=>{if(!t||t.trim().length===0)return nd.default;const s=t.trim().toLowerCase();if(Object.prototype.hasOwnProperty.call(nd,s))return nd[s];const r=Number.parseFloat(s);return Number.isFinite(r)?r:0},dA=t=>{const s=new Map;s.set("default",void 0);for(const a of t)s.set(a,a);const r=Array.from(s.values()).sort((a,l)=>pp(l)-pp(a));if(r.length<=4)return r;const n=r.slice(0,3),o=r[r.length-1];return n.some(a=>a===o)?n:[...n,o]},uA=new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}),hp=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const s=uA.format(t);return s.endsWith(".0")?s.slice(0,-2):s},mA=({open:t,onClose:s,onOpenModel:r,onOpenEffort:n})=>{const{providers:o,currentProviderId:a,currentModelId:l,currentVariant:c,setProvider:d,setModel:u,setCurrentVariant:m,getCurrentModelVariants:f,getModelMetadata:p}=ut(),{addRecentModel:h,addRecentEffort:g,recentEfforts:x}=Te(),{recentModelsList:y}=vc(),{currentSessionId:b,saveAgentModelForSession:v,saveAgentModelVariantForSession:j}=Ae(),k=Lt(E=>b?E.getSessionAgentSelection(b):null),N=b&&k||null,w=y.slice(0,4),C=w.some(E=>E.providerID===a&&E.modelID===l),S=i.useMemo(()=>{if(C||!a||!l)return w;const E=o.find(V=>V.id===a),W=E?.models?.find(V=>V.id===l);return W?[{providerID:a,modelID:l,provider:E,model:W},...w.slice(0,3)]:w},[w,C,a,l,o]),M=f(),D=M.length>0,A=a&&l?`${a}/${l}`:null,$=(A?x[A]??[]:[]).map(E=>cA(E)).filter(E=>!E||M.includes(E)),R=dA(M),O=R.length>0?R:$,T=i.useMemo(()=>{const E=O.slice(0,4),W=$.slice().reverse();for(const V of W)E.some(ve=>ve===V)||(E.unshift(V),E.splice(4));return E.some(V=>V===c)||(E.length>0?E[0]=c:E.push(c)),E.some(V=>V===void 0)||(E.push(void 0),E.splice(4)),E},[O,c,$]),_=M.length+1>T.length,F=(E,W)=>{const V=o.find(ce=>ce.id===E);if(!V||!(Array.isArray(V.models)?V.models:[]).some(ce=>ce.id===W))return;const Z=y.some(ce=>ce.providerID===E&&ce.modelID===W);d(E),u(W),Z||h(E,W),b&&N&&v(b,N,E,W)},I=E=>{m(E),a&&l&&g(a,l,E),b&&N&&a&&l&&j(b,N,a,l,E)};return e.jsx(Cr,{open:t,onClose:s,title:"Controls",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Model"}),e.jsxs("div",{className:"rounded-xl border border-border/40 overflow-hidden",children:[S.length===0&&!C&&e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"No recent models"}),S.map(({providerID:E,modelID:W,model:V})=>{const ve=E===a&&W===l,oe=typeof V?.name=="string"&&V.name.trim().length>0?V.name:W,Z=p(E,W),ce=hp(Z?.limit?.context),Q=hp(Z?.limit?.output);return e.jsxs("button",{type:"button",onClick:()=>F(E,W),className:L("flex min-h-[44px] w-full items-center gap-2 border-b border-border/30 px-3 py-2 text-left last:border-b-0",ve?"bg-primary/10":""),children:[e.jsx(Os,{providerId:E,className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0 flex-1",children:oe}),(ce||Q)&&e.jsxs("span",{className:"typography-micro text-muted-foreground whitespace-nowrap flex-shrink-0",children:[ce&&`${ce} ctx`,ce&&Q&&" • ",Q&&`${Q} out`]})]},`recent-${E}-${W}`)}),e.jsx("button",{type:"button",onClick:r,className:"flex min-h-[44px] w-full items-center justify-center border-t border-border/30 px-3 py-2 typography-meta font-medium text-muted-foreground","aria-label":"More models",children:"..."})]})]}),D&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Effort"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[T.map(E=>{const W=E===c||!E&&!c;return e.jsx("button",{type:"button",onClick:()=>I(E),className:L("inline-flex items-center rounded-full border px-2.5 py-1 typography-meta font-medium",W?"border-primary/30 bg-primary/10 text-foreground":"border-border/40 text-muted-foreground hover:bg-interactive-hover/50"),"aria-pressed":W,children:iA(E)},E??"default")}),_&&e.jsx("button",{type:"button",onClick:n,className:"inline-flex items-center rounded-full border border-border/40 px-2.5 py-1 typography-meta font-medium text-muted-foreground hover:bg-interactive-hover/50","aria-label":"More effort options",children:"..."})]})]})]})})},fA=t=>t?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(t):!0,gp=(t,s)=>{if(typeof t!="string"||t.length===0)return{sanitizedText:t,mention:null};const r=s.filter(o=>o.mode&&o.mode!=="primary");if(r.length===0||!t.includes("#"))return{sanitizedText:t,mention:null};let n=null;for(const o of r){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(!fA(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}},My=t=>({id:t.id,content:t.content,status:t.status||"pending",priority:t.priority||"medium"}),cu=Ls()(Us((t,s)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async r=>{if(r){t({isLoading:!0});try{const n=Ae.getState().getDirectoryForSession(r),a=(n?await nt.withDirectory(n,()=>nt.getSessionTodos(r)):await nt.getSessionTodos(r)).map(My);t(l=>{const c=new Map(l.sessionTodos);return c.set(r,a),{sessionTodos:c,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),t({isLoading:!1})}}},updateTodos:(r,n)=>{t(o=>{const a=new Map(o.sessionTodos);return a.set(r,n),{sessionTodos:a}})},getTodosForSession:r=>s().sessionTodos.get(r)||[],clearTodos:r=>{t(n=>{const o=new Map(n.sessionTodos);return o.delete(r),{sessionTodos:o}})}}),{name:"todo-store"})),pA=(t,s)=>{const r=s.map(My);cu.getState().updateTodos(t,r)},xp=[{variant:"shine",component:({children:t,className:s,...r})=>e.jsx(ra.span,{...r,className:L("bg-[linear-gradient(110deg,color-mix(in_srgb,var(--surface-muted-foreground)_45%,transparent),35%,var(--surface-foreground),50%,color-mix(in_srgb,var(--surface-muted-foreground)_45%,transparent),75%,color-mix(in_srgb,var(--surface-muted-foreground)_45%,transparent))]","bg-[length:200%_100%] bg-clip-text text-transparent",s),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:s,...r})=>typeof t!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:t.split("").map((n,o)=>ne.createElement(ra.span,{...r,key:n+String(o),className:L("inline-block whitespace-pre text-primary-foreground",s),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:s,...r})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...r,className:L("invisible",s),children:t}),e.jsx("span",{...r,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",s),children:t}),e.jsx("span",{...r,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",s),children:t})]})},{variant:"hover-enter",component:({children:t,className:s,...r})=>{if(typeof t!="string")return null;const n=.25,o=.025,a=t.split("").map(l=>l===" "?" ":l);return e.jsxs(ra.span,{...r,className:L("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",s),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((l,c)=>e.jsx(ra.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(ra.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:s,...r})=>e.jsx("span",{...r,className:L("text-primary-muted hover:animate-text-shake",s),children:t})},{variant:"hover-decoration",component:({children:t,className:s,...r})=>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",{...r,className:L("text-primary-muted",s),children:t})})}];function hA({variant:t="shine",className:s,...r}){const a=xp.find(l=>l.variant===t)?.component||xp[0].component;return e.jsx(Jh,{children:e.jsx(a,{...r,className:s})})}const yp=1200;function gA({isWorking:t,statusText:s,isGenericStatus:r,isWaitingForPermission:n}){const[o,a]=i.useState(null),[l,c]=i.useState(!1),d=i.useRef(0),u=i.useRef(null),m=i.useRef(null),f=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null)},[]),p=i.useCallback((y,b)=>{f(),u.current=null,a(y),c(b),d.current=Date.now()},[f]),h=i.useCallback(()=>{if(m.current)return;const y=Date.now()-d.current,b=Math.max(0,yp-y);m.current=setTimeout(()=>{m.current=null;const v=u.current;v&&p(v.text,v.permission)},b)},[p]);if(i.useEffect(()=>{if(!t){f(),u.current=null,a(null),c(!1);return}const y=n?"waiting for permission":s,b=!!n,v=!!r&&!b;if(!y)return;if(!o){p(y,b);return}if(y===o&&b===l||v)return;if(Date.now()-d.current>=yp){p(y,b);return}u.current={text:y,permission:b},h()},[t,s,r,n,o,l,f,p,h]),i.useEffect(()=>()=>f(),[f]),!t||!o)return null;const g=o.charAt(0).toUpperCase()+o.slice(1),x=`${g}...`;return e.jsx("div",{className:"flex h-full items-center text-muted-foreground pl-[2ch]",role:"status","aria-live":l?"assertive":"polite","aria-label":g,"data-waiting":l?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:e.jsx(hA,{variant:"shine",className:"typography-ui-header",children:x})})})}const bp={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},xA=({todo:t})=>{const s=bp[t.status]||bp.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",s.textClassName),children:t.content})})},vp=[],yA=({isWorking:t,statusText:s,isGenericStatus:r,isWaitingForPermission:n,wasAborted:o,abortActive:a,showAbort:l,onAbort:c,showAbortStatus:d})=>{const[u,m]=i.useState(!1),f=Ae(D=>D.currentSessionId),p=cu(D=>f?D.sessionTodos.get(f)??vp:vp),h=cu(D=>D.loadTodos),{isMobile:g}=Te(),x=g||gs();i.useEffect(()=>{f&&h(f)},[f,h]);const y=i.useMemo(()=>{const D={in_progress:0,pending:1,completed:2,cancelled:3};return[...p].filter(A=>A.status!=="cancelled").sort((A,P)=>D[A.status]-D[P.status])},[p]),b=i.useMemo(()=>y.find(D=>D.status==="in_progress")||y.find(D=>D.status==="pending")||null,[y]),v=i.useMemo(()=>{const D=p.filter(P=>P.status!=="cancelled").length;return{completed:p.filter(P=>P.status==="completed").length,total:D}},[p]),j=y.some(D=>D.status==="in_progress"||D.status==="pending"),k=!d&&(o||!a),N=t||!!o||!!d||j,w=i.useRef(null);if(i.useEffect(()=>{if(!u)return;const D=A=>{w.current&&!w.current.contains(A.target)&&m(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[u]),!N)return null;const C=()=>m(D=>!D),S=l&&c?e.jsx("button",{type:"button",onClick:c,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(li,{size:18,"aria-hidden":"true"})}):null,M=j?e.jsxs("button",{type:"button",onClick:C,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!x&&b?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:b.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[v.completed,"/",v.total]}),u?e.jsx(vi,{className:"h-3.5 w-3.5"}):e.jsx(is,{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:d?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(li,{size:16,"aria-hidden":"true"}),"Aborted"]})}):k?e.jsx(gA,{isWorking:t,statusText:s,isGenericStatus:r,isWaitingForPermission:n},f??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:w,children:[S,M,u&&j&&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:[v.completed,"/",v.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:y.map(D=>e.jsx(xA,{todo:D},D.id))})]})]})]})})},bA=({onOpenAgentPanel:t,className:s})=>{const{currentAgentName:r,getVisibleAgents:n}=ut(),o=Ae(m=>m.currentSessionId),a=Ae(m=>o?m.getSessionAgentSelection(o):null),l=n(),c=o&&a||r,d=oA(l,c),u=mn(c);return e.jsx("button",{type:"button",onClick:t,className:L("inline-flex min-w-0 items-center select-none","rounded-lg border border-border/50 px-1.5","typography-micro font-medium","focus:outline-none hover:bg-[var(--interactive-hover)]","touch-manipulation active:scale-95 transition-transform",s),style:{height:"26px",maxHeight:"26px",minHeight:"26px",color:`var(${u.var})`},title:d,children:e.jsx("span",{className:"min-w-0 max-w-full overflow-x-auto whitespace-nowrap scrollbar-hidden",children:d})})},vA=({onOpenModel:t,className:s})=>{const{currentModelId:r,getCurrentProvider:n}=ut(),o=n(),a=aA(o,r);return e.jsx("button",{type:"button",onClick:t,className:L("inline-flex min-w-0 items-center justify-center","rounded-lg border border-border/50 px-1.5","typography-micro font-medium text-foreground/80","focus:outline-none hover:bg-[var(--interactive-hover)]",s),style:{height:"26px",maxHeight:"26px",minHeight:"26px"},title:a,children:e.jsx("span",{className:"min-w-0 max-w-full overflow-x-auto whitespace-nowrap scrollbar-hidden",children:a})})};function wA(t,s,r){const n=i.useMemo(()=>{const f=new Map,p=new Set(t.map(h=>h.id));return t.forEach(h=>{const g=h.parentID;g&&p.has(g)&&f.set(g,[...f.get(g)||[],h])}),f},[t]),o=i.useCallback(f=>{const p=s?.get(f);return p?.type==="busy"||p?.type==="retry"?p.type:"idle"},[s]),a=i.useCallback(f=>(n.get(f)||[]).some(h=>o(h.id)!=="idle"),[n,o]),l=i.useCallback(f=>(n.get(f)||[]).filter(h=>o(h.id)!=="idle").length,[n,o]),c=i.useCallback(f=>(n.get(f)||[]).filter(h=>o(h.id)!=="idle").map(h=>({session:h,isRunning:!0})).slice(0,3),[n,o]),d=i.useMemo(()=>{const f=t.filter(x=>{const y=x.parentID;return!y||!new Set(t.map(b=>b.id)).has(y)}),p=[],h=[];f.forEach(x=>{const y=o(x.id),b=a(x.id),v=r?.get(x.id)?.needsAttention??!1,j={...x,_statusType:y,_hasRunningChildren:b,_runningChildrenCount:l(x.id),_childIndicators:c(x.id)};y!=="idle"||b||v?p.push(j):h.push(j)});const g=(x,y)=>{const b=x.time?.updated??0;return(y.time?.updated??0)-b};return p.sort(g),h.sort(g),[...p,...h]},[t,o,a,l,c,r]),u=d.reduce((f,p)=>{const h=p._statusType!=="idle"?1:0;return f+h+(p._runningChildrenCount??0)},0),m=d.filter(f=>r?.get(f.id)?.needsAttention??!1).length;return{sessions:d,totalRunning:u,totalUnread:m,totalCount:d.length}}function jA(t,s,r){const n=i.useCallback(c=>{const d=c.agent;if(d)return d;const u=Ae.getState().getSessionAgentSelection(c.id);return u||(t[0]?.name??"agent")},[t]),o=i.useCallback(c=>{const d=c.title;return d&&d.trim()?d:"New session"},[]),a=i.useCallback(c=>{const d=s?.get(c);return d?.type==="busy"||d?.type==="retry"},[s]),l=i.useCallback(c=>r?.get(c)?.needsAttention??!1,[r]);return{getSessionAgentName:n,getSessionTitle:o,isRunning:a,needsAttention:l}}function SA({isRunning:t,needsAttention:s}){return t?e.jsx(Ot,{className:"h-2.5 w-2.5 animate-spin text-[var(--status-info)]"}):s?e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-[var(--status-error)]"}):e.jsx("div",{className:"h-1.5 w-1.5 rounded-full border border-[var(--surface-mutedForeground)]"})}function NA({count:t}){return t===0?null:e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-[var(--status-info)]",children:[e.jsx(Ot,{className:"h-3 w-3 animate-spin"}),t," running"]})}function kA({count:t}){return t===0?null:e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-[var(--status-error)]",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-[var(--status-error)]"}),t," unread"]})}function CA({session:t,isCurrent:s,getSessionAgentName:r,getSessionTitle:n,onClick:o,onDoubleClick:a,needsAttention:l}){const c=r(t),d=mn(c),u=(t._runningChildrenCount||0)+(t._statusType!=="idle"?1:0)-1-(t._childIndicators?.length||0);return e.jsxs("button",{type:"button",onClick:o,onDoubleClick:m=>{m.stopPropagation(),a?.()},className:L("flex items-center gap-0.5 px-1.5 py-px text-left transition-colors","hover:bg-[var(--interactive-hover)] active:bg-[var(--interactive-selection)]",s&&"bg-[var(--interactive-selection)]/30"),children:[e.jsx("div",{className:"flex-shrink-0 w-3 flex items-center justify-center",children:e.jsx(SA,{isRunning:t._statusType!=="idle",needsAttention:l(t.id)})}),e.jsx("div",{className:"flex-shrink-0 h-1.5 w-1.5 rounded-full",style:{backgroundColor:`var(${d.var})`}}),e.jsx("span",{className:L("text-[13px] truncate leading-tight",s?"text-[var(--interactive-selection-foreground)] font-medium":"text-[var(--surface-foreground)]"),children:n(t)}),(t._childIndicators?.length||0)>0&&e.jsxs("div",{className:"flex items-center gap-0.5 text-[var(--surface-mutedForeground)]",children:[e.jsx("span",{className:"text-[10px]",children:"["}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[t._childIndicators.map(({session:m})=>{const f=mn(r(m));return e.jsx("div",{className:"flex-shrink-0",title:`Sub-session: ${n(m)}`,children:e.jsx(Ot,{className:"h-2.5 w-2.5 animate-spin",style:{color:`var(${f.var})`}})},m.id)}),u>0&&e.jsxs("span",{className:"text-[10px] text-[var(--surface-mutedForeground)]",children:["+",u]})]}),e.jsx("span",{className:"text-[10px]",children:"]"})]})]})}function Ay({currentSessionTitle:t,runningCount:s,unreadCount:r,onToggle:n}){const o=s>0||r>0;return e.jsx("button",{type:"button",onClick:n,className:"w-full flex items-center justify-between px-2 py-0 text-left transition-colors hover:bg-[var(--interactive-hover)]",children:e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 mr-2",children:[e.jsx("span",{className:"text-xs text-[var(--surface-foreground)] truncate flex-1 leading-tight",children:t}),o&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(NA,{count:s}),e.jsx(kA,{count:r})]})]})})}function MA({runningCount:t,unreadCount:s,currentSessionTitle:r,onToggle:n,onNewSession:o,cornerRadius:a}){return e.jsxs("div",{className:"w-full flex items-center justify-between px-2 border-b border-[var(--interactive-border)] bg-[var(--surface-muted)] order-first text-left overflow-hidden",style:{borderTopLeftRadius:a,borderTopRightRadius:a},children:[e.jsx("div",{className:"flex-1 min-w-0 mr-2",children:e.jsx(Ay,{currentSessionTitle:r,runningCount:t,unreadCount:s,onToggle:n})}),e.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),o()},className:"flex items-center gap-0.5 px-1.5 py-1 text-[11px] leading-tight !min-h-0 rounded border border-border/50 text-[var(--surface-foreground)] hover:bg-[var(--interactive-hover)] flex-shrink-0 self-center",children:"New"})]})}function AA({sessions:t,currentSessionId:s,runningCount:r,unreadCount:n,currentSessionTitle:o,isExpanded:a,onToggleCollapse:l,onToggleExpand:c,onNewSession:d,onSessionClick:u,onSessionDoubleClick:m,getSessionAgentName:f,getSessionTitle:p,needsAttention:h,cornerRadius:g}){const x=i.useRef(null),[y,b]=i.useState(null),[v,j]=i.useState(!1);i.useEffect(()=>{x.current&&!v&&!a&&(b(x.current.offsetHeight),j(!0))},[v,a]);const k=y??void 0,N=v||a?t:t.slice(0,3);return e.jsxs("div",{className:"w-full border-b border-[var(--interactive-border)] bg-[var(--surface-muted)] order-first overflow-hidden",style:{borderTopLeftRadius:g,borderTopRightRadius:g},children:[e.jsxs("div",{className:"flex items-center justify-between px-2 py-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-2",children:e.jsx(Ay,{currentSessionTitle:o,runningCount:r,unreadCount:n,onToggle:l})}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("button",{type:"button",onClick:w=>{w.stopPropagation(),d()},className:"flex items-center gap-0.5 px-1.5 py-1 text-[11px] leading-tight !min-h-0 rounded border border-border/50 text-[var(--surface-foreground)] hover:bg-[var(--interactive-hover)] self-start",children:"New"}),e.jsx("button",{type:"button",onClick:w=>{w.stopPropagation(),c()},className:"text-[11px] leading-tight px-1.5 py-1 !min-h-0 rounded border border-border/50 text-[var(--surface-mutedForeground)] hover:text-[var(--surface-foreground)] hover:bg-[var(--interactive-hover)] self-start",children:a?"Less":"More"})]})]}),e.jsx("div",{ref:x,className:"flex flex-col overflow-y-auto",style:{maxHeight:a?"60vh":k},children:N.map(w=>e.jsx(CA,{session:w,isCurrent:w.id===s,getSessionAgentName:f,getSessionTitle:p,onClick:()=>u(w.id),onDoubleClick:m,needsAttention:h},w.id))})]})}const DA=({onSessionSwitch:t,cornerRadius:s})=>{const r=Ae(A=>A.sessions),n=Ae(A=>A.currentSessionId),o=Ae(A=>A.sessionStatus),a=Ae(A=>A.sessionAttentionStates),l=Ae(A=>A.setCurrentSession),c=Ae(A=>A.createSession),d=ut(A=>A.agents),{isMobile:u,isMobileSessionStatusBarCollapsed:m,setIsMobileSessionStatusBarCollapsed:f}=Te(),p=Te(A=>A.setActiveMainTab),[h,g]=i.useState(!1),{sessions:x,totalRunning:y,totalUnread:b,totalCount:v}=wA(r,o,a),{getSessionAgentName:j,getSessionTitle:k,needsAttention:N}=jA(d,o,a),w=r.find(A=>A.id===n),C=w?k(w):"New session";if(!u||v===0)return null;const S=A=>{l(A),t?.(A),g(!1)},M=()=>{p("chat")},D=async()=>{const A=await c();A&&(l(A.id),t?.(A.id))};return m?e.jsx(MA,{runningCount:y,unreadCount:b,currentSessionTitle:C,onToggle:()=>f(!1),onNewSession:D,cornerRadius:s}):e.jsx(AA,{sessions:x,currentSessionId:n??"",runningCount:y,unreadCount:b,currentSessionTitle:C,isExpanded:h,onToggleCollapse:()=>{f(!0),g(!1)},onToggleExpand:()=>g(!h),onNewSession:D,onSessionClick:S,onSessionDoubleClick:M,getSessionAgentName:j,getSessionTitle:k,needsAttention:N,cornerRadius:s})},wl=t=>!t||typeof t!="object"?!1:!!t.synthetic,wp=t=>!Array.isArray(t)||t.length===0?!1:t.every(s=>wl(s)),IA=t=>!Array.isArray(t)||t.length===0?[]:t.some(r=>!wl(r))&&t.some(n=>wl(n))?t.filter(n=>!wl(n)):t,TA={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function EA(t){const s=Ae(r=>!t||!r.sessionStatus?"idle":r.sessionStatus.get(t)?.type??"idle");return i.useMemo(()=>s==="idle"?TA:{phase:s,isWorking:s==="busy"||s==="retry",isBusy:s==="busy",isCooldown:!1},[s])}function sm(){const t=Ae(s=>s.currentSessionId);return EA(t)}const PA={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},jp=t=>t.role==="assistant",RA=t=>t.type==="reasoning",Dy=t=>t.type==="text",Sp=t=>{if(Dy(t))return t.text;const s=t;if(typeof s.text=="string")return s.text;if(typeof s.content=="string")return s.content;if(typeof s.value=="string")return s.value},Np=t=>(Dy(t)||RA(t),t.time),FA=t=>{if(t.tool)return t.tool;const s=t;return typeof s.name=="string"?s.name:"tool"};function Iy(){const{currentSessionId:t,messages:s,permissions:r,sessionAbortFlags:n}=Ae(oo(p=>({currentSessionId:p.currentSessionId,messages:p.messages,permissions:p.permissions,sessionAbortFlags:p.sessionAbortFlags}))),{phase:o,isWorking:a}=sm(),l=i.useMemo(()=>t?s.get(t)??[]:[],[t,s]),c=i.useMemo(()=>{if(l.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const p=l.filter(S=>jp(S.info)&&!wp(S.parts));if(p.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=[...p].sort((S,M)=>{const D=typeof S.info.time?.created=="number"?S.info.time.created:null,A=typeof M.info.time?.created=="number"?M.info.time.created:null;return D!==null&&A!==null&&D!==A?D-A:S.info.id.localeCompare(M.info.id)}),g=h[h.length-1];let x,y;const b=new Set(["edit","write","apply_patch"]);for(let S=(g.parts??[]).length-1;S>=0;S-=1){const M=g.parts?.[S];if(M)switch(M.type){case"reasoning":{const D=M.time??Np(M);(!D||typeof D.end>"u")&&!x&&(x="reasoning");break}case"tool":{const D=M.state?.status;if((D==="running"||D==="pending")&&!x){const A=FA(M);b.has(A)?x="editing":(x="tool",y=A)}break}case"text":{const D=Sp(M)??"";if(typeof D=="string"&&D.trim().length>0){const A=Np(M);(!A||typeof A.end>"u")&&!x&&(x="text")}break}}}const v={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"},j=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],k=S=>v[S]??`using ${S}`,N=()=>j[Math.floor(Math.random()*j.length)],w=x===void 0,C=x==="editing"?"editing file":x==="tool"&&y?k(y):x==="reasoning"?"thinking":x==="text"?"composing":N();return{activePartType:x,activeToolName:y,statusText:C,isGenericStatus:w}},[l]),d=i.useMemo(()=>{const p=t,h=p?n?.get(p)??null:null,g=!!(h&&!h.acknowledged);return{wasAborted:g,abortActive:g}},[t,n]),u=i.useMemo(()=>{if(d.wasAborted)return{...PA,wasAborted:!0,abortActive:d.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const p=a,h=o==="busy",g=!1;let x="idle";return p&&(c.activePartType==="tool"||c.activePartType==="editing"?x="tooling":x="streaming"),{activity:x,hasWorkingContext:p,hasActiveTools:c.activePartType==="tool"||c.activePartType==="editing",isWorking:p,isStreaming:h,isCooldown:g,lifecyclePhase:h?"streaming":g?"cooldown":null,statusText:p?c.statusText:null,isGenericStatus:p?c.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:p,compactionDeadline:null,activePartType:p?c.activePartType:void 0,activeToolName:p?c.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1}},[o,a,c,d]),m=i.useMemo(()=>{const p=a&&c.activePartType==="text";if(!p||l.length===0)return{isActive:p,characterCount:0};const h=l.filter(y=>jp(y.info)&&!wp(y.parts));if(h.length===0)return{isActive:p,characterCount:0};const g=h[h.length-1];let x=0;return(g.parts??[]).forEach(y=>{if(y.type!=="text")return;const b=Sp(y)??"";typeof b=="string"&&b.trim().length>0&&(x+=b.length)}),{isActive:p,characterCount:x}},[l,a,c.activePartType]),f=i.useMemo(()=>{if(u.wasAborted||u.abortActive)return u;const p=t;return(p?r?.get(p)??[]:[]).length>0?{...u,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:u},[t,r,u]);return{forming:m,working:f}}function LA(t){return e.jsxs("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:"M208,56V200a8,8,0,0,1-8,8H56a8,8,0,0,1-8-8V56a8,8,0,0,1,8-8H200A8,8,0,0,1,208,56Z",opacity:"0.2"}),e.jsx("path",{d:"M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z"})]})}const OA=8,kp=[],Ya="ikanban_chat_input_draft",_A=()=>{try{return localStorage.getItem(Ya)??""}catch{return""}},Xi=({onOpenSettings:t,scrollToBottom:s})=>{const r=i.useRef(null),[n,o]=i.useState(()=>{const U=_A();return U&&(r.current=U),U}),[a,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,g]=i.useState(""),[x,y]=i.useState(!1),[b,v]=i.useState(""),[j,k]=i.useState("commands"),[N,w]=i.useState(!1),[C,S]=i.useState(""),[M,D]=i.useState(null),[A,P]=i.useState(!1),[$,R]=i.useState(null),[O,T]=i.useState(-1),[_,F]=i.useState(""),I=i.useRef(null),E=i.useRef(null),W=i.useRef(!1),V=i.useRef(null),ve=i.useRef(null),oe=i.useRef(null),Z=i.useRef(null),ce=Ae(U=>U.sendMessage),Q=Ae(U=>U.currentSessionId),Y=Ae(U=>U.newSessionDraft?.open),ie=Ae(U=>U.abortCurrentOperation),B=Ae(U=>U.acknowledgeSessionAbort),se=Ae(U=>U.abortPromptSessionId),H=Ae(U=>U.clearAbortPrompt),le=Ae(U=>U.sessionAbortFlags),ge=Ae(U=>U.attachedFiles),z=Ae(U=>U.addAttachedFile),J=Ae(U=>U.addServerFile),je=Ae(U=>U.clearAttachedFiles),X=Ae(U=>U.saveSessionAgentSelection),G=Ae(U=>U.consumePendingInputText),ae=Ae(U=>U.pendingInputText),me=Ae(U=>U.consumePendingSyntheticParts),{currentProviderId:Oe,currentModelId:Be,currentVariant:fe,currentAgentName:q,setAgent:ye,getVisibleAgents:he}=ut(),He=he(),ot=i.useMemo(()=>He.filter(U=>U.mode==="primary"),[He]),{isMobile:ue,inputBarOffset:Ve,isKeyboardOpen:De,setTimelineDialogOpen:we,cornerRadius:Fe,persistChatDraft:Pe}=Te(),{working:$e}=Iy(),{currentTheme:Ze}=rn(),[Ue,Ee]=i.useState(!1),Re=i.useRef(null),Xe=i.useRef(!1),st=i.useRef(!1),St=Dn(U=>U.queueModeEnabled),mt=Dn(i.useCallback(U=>Q?U.queuedMessages[Q]??kp:kp,[Q])),Tt=Dn(U=>U.addToQueue),qt=Dn(U=>U.clearQueue),yt=Br(i.useCallback(U=>{const te=Q??(Y?"draft":"");return te?(U.drafts[te]??[]).length:0},[Q,Y])),os=Br(U=>U.consumeDrafts),cs=yt>0,ds=rs(i.useCallback(U=>Q?U.messages.get(Q):void 0,[Q])),de=i.useMemo(()=>ds?ds.filter(U=>U.info.role==="user").map(U=>{const te=U.parts.find(Se=>Se.type==="text");return te&&"text"in te?String(te.text):""}).filter(U=>U.length>0).reverse():[],[ds]),ke=i.useRef(!1);i.useEffect(()=>{if(!(ke.current||(ke.current=!0,!r.current)))if(Pe)requestAnimationFrame(()=>{I.current?.select()});else{o("");try{localStorage.removeItem(Ya)}catch{}}},[Pe]);const We=i.useRef(Q);i.useEffect(()=>{We.current!==Q&&(We.current=Q,Pe?n&&requestAnimationFrame(()=>{I.current?.select()}):o(""))},[Q,Pe,n]);const qe=i.useRef(Y);i.useEffect(()=>{!qe.current&&Y&&requestAnimationFrame(()=>{ue?I.current?.focus({preventScroll:!0}):I.current?.focus()}),qe.current=Y},[Y,ue]),i.useEffect(()=>{if(!Pe){try{localStorage.removeItem(Ya)}catch{}return}try{n?localStorage.setItem(Ya,n):localStorage.removeItem(Ya)}catch{}},[n,Pe]);const{phase:et}=sm(),ct=i.useRef(et),bt=i.useRef(!1),at=i.useCallback(U=>{if(!ue||U.pointerType!=="touch")return;const te=I.current;if(!te||document.activeElement===te)return;U.preventDefault(),U.stopPropagation();const Se=document.scrollingElement;Se&&Se.scrollTop!==0&&(Se.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{te.focus({preventScroll:!0})}catch{te.focus()}const Je=te.value.length;try{te.setSelectionRange(Je,Je)}catch{}},[ue]),_t=i.useCallback(()=>{if(ue){if(A){P(!1);return}if(R(null),De){I.current?.blur(),requestAnimationFrame(()=>{P(!0)});return}P(!0)}},[ue,De,A]),Nt=i.useCallback(()=>{P(!1)},[]),Gt=i.useCallback(U=>{ue&&(P(!1),I.current?.blur(),requestAnimationFrame(()=>{R(U)}))},[ue]),zt=i.useCallback(()=>{ue&&(R(null),requestAnimationFrame(()=>{P(!0)}))},[ue]);i.useEffect(()=>{if(ae!==null){const U=G();U?.text&&(U.mode==="append"?o(te=>{const Se=U.text.trim();if(!Se)return te;const Je=te.trimEnd();return Je.trim()?`${Je} ${Se}`:Se}):o(U.text),setTimeout(()=>{I.current?.focus()},0))}},[ae,G]);const Ct=n.trim()||ge.length>0||cs,Qt=mt.length>0,Mt=Ct||Qt,Zt=$e.isWorking,jt=i.useRef(async()=>{}),es=i.useCallback(()=>{if(!Ct||!Q)return;const U=os(Q);let te=n.replace(/^\n+|\n+$/g,"");U.length>0&&(te=Yi(te,U));const Se=ge.map(Je=>({...Je}));Tt(Q,{content:te,attachments:Se.length>0?Se:void 0}),o(""),Se.length>0&&je(),ue||I.current?.focus()},[Ct,Q,n,ge,Tt,je,ue,os]),Ye=async U=>{const te=U?.queuedOnly??!1;if(te){if(!Qt||!Q)return}else if(!Mt||!Q&&!Y)return;if(s?.({instant:!0,force:!0}),!Oe||!Be){console.warn("Cannot send message: provider or model not selected");return}let Se="",Je=[],rt;const lt=[],Ke=me();for(let ls=0;ls<mt.length;ls++){const Rs=mt[ls],{sanitizedText:ys,mention:br}=gp(Rs.content,He);!rt&&br?.name&&(rt=br.name),ls===0?(Se=ys,Je=Rs.attachments??[]):lt.push({text:ys,attachments:Rs.attachments})}if(!te&&Ct){const ls=n.replace(/^\n+|\n+$/g,""),{sanitizedText:Rs,mention:ys}=gp(ls,He),br=ge.map(Kr=>({...Kr}));!rt&&ys?.name&&(rt=ys.name),mt.length===0?(Se=Rs,Je=br):lt.push({text:Rs,attachments:br.length>0?br:void 0})}const Dt=Q??(Y?"draft":null);let as=[];if(!te&&Dt&&(as=os(Dt)),as.length>0)if(mt.length===0)Se=Yi(Se,as);else if(lt.length>0){const ls=lt[lt.length-1];ls.text=Yi(ls.text,as)}else Se=Yi(Se,as);if(Ke&&Ke.length>0)for(const ls of Ke)lt.push({text:ls.text,synthetic:!0});if(!Se&<.length===0)return;Q&&Qt&&qt(Q),te||(o(""),T(-1),F(""),ge.length>0&&je()),ue&&I.current?.blur();const Xt=Se.trimStart();if(Xt.startsWith("/")){const ls=Xt.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(ls==="undo"&&Q){await Ae.getState().handleSlashUndo(Q),s?.({instant:!0,force:!0});return}else if(ls==="redo"&&Q){await Ae.getState().handleSlashRedo(Q),s?.({instant:!0,force:!0});return}else if(ls==="timeline"&&Q){we(!0),o("");return}else if(ls==="compact"&&Q){try{const{opencodeClient:Rs}=await Ks(async()=>{const{opencodeClient:Kr}=await Promise.resolve().then(()=>Xj);return{opencodeClient:Kr}},void 0),ys=Rs.getDirectory();if((await Rs.getApiClient().session.summarize({sessionID:Q,directory:ys||void 0,providerID:Oe,modelID:Be})).error)throw new Error("Failed to compact session");s?.({instant:!0,force:!0})}catch(Rs){console.error("Failed to compact session:",Rs),K.error("Failed to compact session")}o("");return}}const Ht=[...Je,...lt.flatMap(ls=>ls.attachments??[])];ce(Se,Oe,Be,q,Je,rt,lt.length>0?lt:void 0,fe).catch(ls=>{const Rs=ls instanceof Error?ls.message:typeof ls=="string"?ls:String(ls??""),ys=Rs.toLowerCase();console.error("Message send failed:",Rs||ls);const br=ys.includes("timeout")||ys.includes("timed out")||ys.includes("may still be processing")||ys.includes("being processed")||ys.includes("failed to fetch")||ys.includes("networkerror")||ys.includes("network error")||ys.includes("gateway timeout")||ys==="failed to send message";if(ys.includes("payload too large")||ys.includes("413")||ys.includes("entity too large")){K.error("Attachments are too large to send. Please try reducing the number or size of images."),Ht.length>0&&Jr.setState({attachedFiles:Ht});return}if(br){Ht.length>0&&(Jr.setState({attachedFiles:Ht}),K.error("Failed to send attachments. Try fewer files or smaller images."));return}Ht.length>0&&Jr.setState({attachedFiles:Ht}),K.error(Rs||"Message failed to send. Attachments restored.")}),ue||I.current?.focus()};jt.current=Ye;const ft=i.useCallback(()=>{St&&(Ct&&Q&&et!=="idle")?es():jt.current()},[Ct,Q,et,St,es]);i.useEffect(()=>{const U=ct.current==="busy"||ct.current==="retry",te=et==="idle",Se=Q&&le.has(Q)&&(()=>{const Je=le.get(Q);return Je?Date.now()-Je.timestamp<2e3:!1})();U&&te&&mt.length>0&&!bt.current&&!Se&&(bt.current=!0,setTimeout(()=>{Q&&Oe&&Be&&jt.current({queuedOnly:!0}),bt.current=!1},100)),ct.current=et},[et,mt.length,Q,Oe,Be,le]);const vt=U=>{if(em(U))return;if(f&&ve.current&&(U.key==="Enter"||U.key==="ArrowUp"||U.key==="ArrowDown"||U.key==="Escape"||U.key==="Tab")){U.preventDefault(),ve.current.handleKeyDown(U.key);return}if(x&&oe.current&&(U.key==="Enter"||U.key==="ArrowUp"||U.key==="ArrowDown"||U.key==="Escape"||U.key==="Tab")){U.preventDefault(),oe.current.handleKeyDown(U.key);return}if(N&&Z.current&&(U.key==="Enter"||U.key==="ArrowUp"||U.key==="ArrowDown"||U.key==="Escape"||U.key==="Tab")){U.preventDefault(),Z.current.handleKeyDown(U.key);return}if(c&&V.current&&(U.key==="Enter"||U.key==="ArrowUp"||U.key==="ArrowDown"||U.key==="Escape"||U.key==="Tab")){U.preventDefault(),V.current.handleKeyDown(U.key);return}if(U.key==="Tab"&&!f&&!x&&!c){U.preventDefault(),Ft();return}const te=f||x||N||c,Se=I.current?.selectionStart===0&&I.current?.selectionEnd===0,Je=I.current?.selectionStart===n.length&&I.current?.selectionEnd===n.length,rt=!te&&(n.length===0||Se),lt=!te&&(n.length===0||Je);if(U.key==="ArrowUp"&&rt&&de.length>0){if(U.preventDefault(),O===-1)F(n),T(0),o(de[0]);else if(O<de.length-1){const Ke=O+1;T(Ke),o(de[Ke])}requestAnimationFrame(()=>{I.current?.setSelectionRange(0,0)});return}if(U.key==="ArrowDown"&<&&O>=0){if(U.preventDefault(),O===0)T(-1),o(_),F("");else{const Ke=O-1;T(Ke),o(de[Ke])}return}if(U.key==="Escape"&&!te){U.preventDefault(),I.current?.blur();return}if(U.key==="Enter"&&!U.shiftKey&&!ue){U.preventDefault();const Ke=U.ctrlKey||U.metaKey,Dt=Ct&&Q&&et!=="idle";St?Ke||!Dt?Ye():es():Ke&&Dt?es():Ye()}},pt=i.useCallback(()=>{Re.current&&(clearTimeout(Re.current),Re.current=null),Ee(!0),Re.current=setTimeout(()=>{Ee(!1),Re.current=null},1800)},[]),Rt=i.useCallback(()=>{H(),pt(),ie()},[ie,H,pt]),Ft=i.useCallback(()=>{if(ot.length<=1)return;const te=(ot.findIndex(Je=>Je.name===q)+1)%ot.length,Se=ot[te];ye(Se.name),Q&&X(Q,Se.name)},[ot,q,Q,ye,X]),Pt=i.useCallback(()=>{const U=I.current;if(!U)return;U.style.height="auto";const te=U.ownerDocument?.defaultView,Se=te?te.getComputedStyle(U):null,Je=Se?parseFloat(Se.lineHeight):NaN,rt=Se?parseFloat(Se.paddingTop):NaN,lt=Se?parseFloat(Se.paddingBottom):NaN,Ke=22,as=Number.isNaN(rt)||Number.isNaN(lt)?16:rt+lt,Ht=(Number.isNaN(Je)?Ke:Je)*OA+as,ls=U.scrollHeight||U.offsetHeight,Rs=Math.min(ls,Ht);U.style.height=`${Rs}px`,U.style.maxHeight=`${Ht}px`,D(ys=>ys&&ys.height===Rs&&ys.maxHeight===Ht?ys:{height:Rs,maxHeight:Ht})},[]);i.useLayoutEffect(()=>{Pt()},[Pt,n,ue]);const Jt=i.useCallback((U,te)=>{if(U.startsWith("/")){const Ke=U.indexOf(" "),Dt=U.indexOf(`
|
|
189
|
+
`),as=Math.min(Ke===-1?U.length:Ke,Dt===-1?U.length:Dt);if(te<=as&&Ke===-1){const Xt=U.substring(1,as);g(Xt),k("commands"),p(!0),d(!1),y(!1),w(!1);return}}p(!1);const Se=U.substring(0,te),Je=Se.lastIndexOf("#");if(Je!==-1){const Ke=Je>0?Se[Je-1]:null,Dt=Se.substring(Je+1),as=Dt.includes(" ")||Dt.includes(`
|
|
190
|
+
`);if((!Ke||/\s/.test(Ke))&&!as){v(Dt),k("agents"),y(!0),d(!1);return}}y(!1),v("");const rt=Se.lastIndexOf("/");if(rt!==-1){const Ke=rt>0?Se[rt-1]:null,Dt=Se.substring(rt+1),as=Dt.includes(" ")||Dt.includes(`
|
|
191
|
+
`);if((!Ke||/\s/.test(Ke))&&!as){S(Dt),w(!0),d(!1),y(!1);return}}w(!1),S("");const lt=Se.lastIndexOf("@");if(lt!==-1){const Ke=Se.substring(lt+1);!Ke.includes(" ")&&!Ke.includes(`
|
|
192
|
+
`)?(m(Ke),k("files"),d(!0)):d(!1)}else d(!1)},[v,k,g,m,y,p,d,w,S]),Ns=i.useCallback(U=>{const te=n.length===0?U:n[0]==="/"||n[0]==="#"||n[0]==="@"?`${U}${n.slice(1)}`:`${U}${n}`;o(te),requestAnimationFrame(()=>{if(I.current){const Se=Math.min(te.length,I.current.value.length);I.current.selectionStart=Se,I.current.selectionEnd=Se}Pt(),Jt(te,te.length)})},[Pt,n,o,Jt]),Ts=i.useCallback(U=>{const te=I.current;if(ue&&te){try{te.focus({preventScroll:!0})}catch{te.focus()}const Se=te.value.length;try{te.setSelectionRange(Se,Se)}catch{}}k(U),g(""),v(""),m(""),U==="commands"&&Ns("/"),U==="agents"&&Ns("#"),U==="files"&&Ns("@"),w(!1),p(U==="commands"),y(U==="agents"),d(U==="files")},[Ns,ue,v,k,g,m,y,p,d,w]),sr=i.useCallback(()=>{if(!ue)return;const U=I.current;if(U){try{U.focus({preventScroll:!0})}catch{U.focus()}const te=U.value.length;try{U.setSelectionRange(te,te)}catch{}}Ns("/"),g(""),k("commands"),p(!0),y(!1),d(!1),w(!1)},[Ns,ue,k,g,y,p,d,w]),Xs=i.useCallback(U=>{if(!U)return;const te=I.current;if(!te){const Ke=n+U;o(Ke),Jt(Ke,Ke.length),requestAnimationFrame(()=>Pt());return}const Se=te.selectionStart??n.length,Je=te.selectionEnd??n.length,rt=`${n.substring(0,Se)}${U}${n.substring(Je)}`;o(rt);const lt=Se+U.length;requestAnimationFrame(()=>{const Ke=I.current;Ke&&(Ke.selectionStart=lt,Ke.selectionEnd=lt),Pt()}),Jt(rt,lt)},[Pt,n,Jt]),_s=U=>{const te=U.target.value,Se=U.target.selectionStart??te.length;o(te),Pt(),Jt(te,Se)},mr=i.useCallback(async U=>{const te=new Map;Array.from(U.clipboardData.files||[]).forEach(lt=>{lt.type.startsWith("image/")&&te.set(`${lt.name}-${lt.size}`,lt)}),Array.from(U.clipboardData.items||[]).forEach(lt=>{if(lt.kind==="file"&<.type.startsWith("image/")){const Ke=lt.getAsFile();Ke&&te.set(`${Ke.name}-${Ke.size}`,Ke)}});const Se=Array.from(te.values());if(Se.length===0||!Q&&!Y)return;U.preventDefault();const Je=U.clipboardData.getData("text");Je&&Xs(Je);let rt=0;for(const lt of Se){const Ke=Ae.getState().attachedFiles.length;try{await z(lt),Ae.getState().attachedFiles.length>Ke&&(rt+=1)}catch(Dt){console.error("Clipboard image attach failed",Dt),K.error(Dt instanceof Error?Dt.message:"Failed to attach image from clipboard")}}rt>0&&K.success(`Attached ${rt} image${rt>1?"s":""} from clipboard`)},[z,Q,Y,Xs]),Zs=U=>{const te=U.relativePath||U.name,Se=I.current?.selectionStart||0,rt=n.substring(0,Se).lastIndexOf("@");if(rt!==-1){const lt=n.substring(0,rt)+te+n.substring(Se);o(lt)}else if(I.current){const lt=n.substring(0,Se)+`@${te} `+n.substring(Se);o(lt);const Ke=Se+te.length+2;requestAnimationFrame(()=>{I.current&&(I.current.selectionStart=Ke,I.current.selectionEnd=Ke),Pt(),Jt(lt,Ke)})}d(!1),m(""),I.current?.focus()},gr=U=>{const Se=I.current?.selectionStart??n.length,rt=n.substring(0,Se).lastIndexOf("#");if(rt!==-1){const lt=n.substring(0,rt)+`#${U} `+n.substring(Se);o(lt);const Ke=rt+U.length+2;requestAnimationFrame(()=>{I.current&&(I.current.selectionStart=Ke,I.current.selectionEnd=Ke),Pt(),Jt(lt,Ke)})}else if(I.current){const lt=n.substring(0,Se)+`#${U} `+n.substring(Se);o(lt);const Ke=Se+U.length+2;requestAnimationFrame(()=>{I.current&&(I.current.selectionStart=Ke,I.current.selectionEnd=Ke),Pt(),Jt(lt,Ke)})}y(!1),v(""),I.current?.focus()},Ie=U=>{const Se=I.current?.selectionStart??n.length,rt=n.substring(0,Se).lastIndexOf("/");if(rt!==-1){const lt=n.substring(0,rt)+`${U} `+n.substring(Se);o(lt);const Ke=rt+U.length+1;requestAnimationFrame(()=>{I.current&&(I.current.selectionStart=Ke,I.current.selectionEnd=Ke),Pt(),Jt(lt,Ke)})}w(!1),S(""),I.current?.focus()},Ge=U=>{o(`/${U.name} `);const te=I.current;te&&(te._commandMetadata=U),p(!1),g("");const Se=()=>{if(I.current){try{I.current.focus({preventScroll:!0})}catch{I.current.focus()}I.current.setSelectionRange(I.current.value.length,I.current.value.length)}};requestAnimationFrame(()=>{Se(),requestAnimationFrame(Se)}),setTimeout(Se,60)};i.useEffect(()=>{if(ue)return;const U=te=>{const Se=I.current;if(!Se)return;const Je=document.activeElement===Se;if(te.key==="i"&&!Je&&!te.ctrlKey&&!te.metaKey&&!te.altKey){const rt=document.activeElement,lt=rt?.tagName?.toLowerCase();if(lt==="input"||lt==="textarea"||rt?.isContentEditable)return;te.preventDefault(),Se.focus();return}te.key==="c"&&te.ctrlKey&&!te.metaKey&&!te.altKey&&Je&&Zt&&(te.preventDefault(),Rt())};return document.addEventListener("keydown",U),()=>{document.removeEventListener("keydown",U)}},[ue,Zt,Rt]),i.useEffect(()=>{ue||(P(!1),R(null))},[ue]),i.useEffect(()=>{se&&se!==Q&&H()},[se,Q,H]),i.useEffect(()=>{W.current=!!(Q||Y)},[Q,Y]);const At=i.useCallback(U=>U?U.files&&U.files.length>0?!0:U.types?Array.from(U.types).includes("Files"):!1:!1,[]),it=i.useCallback(U=>{if(!U)return[];const te=Array.from(U.files||[]);return te.length>0?te:Array.from(U.items||[]).filter(Je=>Je.kind==="file").map(Je=>Je.getAsFile()).filter(Je=>!!Je)},[]),Kt=i.useCallback(U=>{const te=U.trim();if(!te.toLowerCase().startsWith("file://"))return te;try{let Se=decodeURIComponent(new URL(te).pathname||"");return/^\/[A-Za-z]:\//.test(Se)&&(Se=Se.slice(1)),Se||te}catch{const Se=te.replace(/^file:\/\//i,"");try{return decodeURIComponent(Se)}catch{return Se}}},[]),It=U=>{At(U.dataTransfer)&&(U.preventDefault(),U.stopPropagation(),(Q||Y)&&!a&&l(!0))},Ps=U=>{At(U.dataTransfer)&&(U.preventDefault(),U.stopPropagation(),U.dataTransfer.dropEffect="copy",(Q||Y)&&!a&&l(!0))},Hs=U=>{U.preventDefault(),U.stopPropagation(),U.currentTarget===U.target&&l(!1)},Es=async U=>{if(!At(U.dataTransfer)||(U.preventDefault(),U.stopPropagation(),l(!1),!Q&&!Y))return;const te=it(U.dataTransfer);let Se=0;if(te.length>0)for(const Je of te){const rt=Ae.getState().attachedFiles.length;try{await z(Je),Ae.getState().attachedFiles.length>rt&&(Se+=1)}catch(lt){console.error("File attach failed",lt),K.error(lt instanceof Error?lt.message:"Failed to attach file")}}Se>0&&K.success(`Attached ${Se} file${Se>1?"s":""}`)};i.useEffect(()=>{if(!As())return;let U=!1,te=null;return(async()=>{try{const{getCurrentWebviewWindow:Se}=await Ks(async()=>{const{getCurrentWebviewWindow:lt}=await import("@tauri-apps/api/webviewWindow");return{getCurrentWebviewWindow:lt}},[]),rt=await Se().onDragDropEvent(async lt=>{if(!W.current)return;const Ke=lt.payload;if(!Ke||typeof Ke!="object")return;const Dt=Ke,as=Dt.type,Xt=Dt.position?.x,Ht=Dt.position?.y,ls=E.current;let Rs=!1;if(ls&&typeof Xt=="number"&&typeof Ht=="number"){const ys=ls.getBoundingClientRect();if(Rs=Xt>=ys.left&&Xt<=ys.right&&Ht>=ys.top&&Ht<=ys.bottom,!Rs&&window.devicePixelRatio>1){const br=Xt/window.devicePixelRatio,Kr=Ht/window.devicePixelRatio;Rs=br>=ys.left&&br<=ys.right&&Kr>=ys.top&&Kr<=ys.bottom}}if(as==="enter"||as==="over"){l(Rs);return}if(as==="leave"){l(!1);return}if(as==="drop"){if(l(!1),!Rs)return;const ys=Array.isArray(Dt.paths)?Dt.paths.filter(Kr=>typeof Kr=="string"):[];if(ys.length===0)return;let br=0;for(const Kr of ys){const Mb=Ae.getState().attachedFiles.length;try{const Go=Kt(Kr),fm=Go.split(/[\\/]/).pop()||Go;let jc;if(As()&&!Or()){const{invoke:Pa}=await Ks(async()=>{const{invoke:qo}=await import("@tauri-apps/api/core");return{invoke:qo}},[]),Ko=await Pa("desktop_read_file",{path:Go}),Sc=atob(Ko.base64),pm=new Array(Sc.length);for(let qo=0;qo<Sc.length;qo++)pm[qo]=Sc.charCodeAt(qo);const Ab=new Uint8Array(pm),Db=new Blob([Ab],{type:Ko.mime||"application/octet-stream"});jc=new File([Db],fm,{type:Ko.mime||"application/octet-stream"})}else{const Pa=await fetch(`/api/fs/raw?path=${encodeURIComponent(Go)}`);if(!Pa.ok)throw new Error(`Failed to read dropped file (${Pa.status})`);const Ko=await Pa.blob();jc=new File([Ko],fm,{type:Ko.type||"application/octet-stream"})}await z(jc),Ae.getState().attachedFiles.length>Mb&&br++}catch(Go){console.error("Failed to attach dropped file:",Kr,Go),K.error(`Failed to attach ${Kr.split(/[\\/]/).pop()||"file"}`)}}br>0&&K.success(`Attached ${br} file${br>1?"s":""}`)}});if(U){rt();return}te=rt}catch(Se){U||console.warn("Failed to register Tauri drag-drop listener:",Se)}})(),()=>{U=!0,te&&te()}},[z,Kt]);const er=i.useCallback(async U=>{let te=0;for(const Se of U){const Je=Ae.getState().attachedFiles.length;try{await J(Se.path,Se.name),Ae.getState().attachedFiles.length>Je&&(te+=1)}catch(rt){console.error("Server file attach failed",rt),K.error(rt instanceof Error?rt.message:"Failed to attach file")}}te>0&&K.success(`Attached ${te} file${te>1?"s":""}`)},[J]),Cs=i.useRef(null),[ar,ir]=i.useState(!1),qs=i.useCallback(async U=>{let te=0;const Se=Array.isArray(U)?U:Array.from(U);for(const Je of Se){const rt=Ae.getState().attachedFiles.length;try{await z(Je),Ae.getState().attachedFiles.length>rt&&(te+=1)}catch(lt){console.error("File attach failed",lt),K.error(lt instanceof Error?lt.message:"Failed to attach file")}}te>0&&K.success(`Attached ${te} file${te>1?"s":""}`)},[z]),Ir=i.useCallback(async()=>{try{const te=await(await fetch("/api/vscode/pick-files")).json(),Se=Array.isArray(te?.files)?te.files:[],Je=Array.isArray(te?.skipped)?te.skipped:[];if(Je.length>0){const lt=Je.map(Ke=>`${Ke?.name||"file"}: ${Ke?.reason||"skipped"}`).join(`
|
|
193
|
+
`);K.error(`Some files were skipped:
|
|
194
|
+
${lt}`)}const rt=Se.map(lt=>{if(!lt?.dataUrl)return null;try{const[Ke,Dt]=lt.dataUrl.split(","),as=lt.mimeType||Ke?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Dt)return null;const Xt=atob(Dt),Ht=new Uint8Array(Xt.length);for(let Rs=0;Rs<Xt.length;Rs++)Ht[Rs]=Xt.charCodeAt(Rs);const ls=new Blob([Ht],{type:as});return new File([ls],lt.name||"file",{type:as})}catch(Ke){return console.error("Failed to decode VS Code picked file",Ke),null}}).filter(Boolean);rt.length>0&&await qs(rt)}catch(U){console.error("VS Code file pick failed",U),K.error(U instanceof Error?U.message:"Failed to pick files in VS Code")}},[qs]),fr=i.useCallback(()=>{if(gs()){Ir();return}Cs.current?.click()},[Ir]),xr=i.useCallback(async U=>{const te=U.target.files;te&&(await qs(te),U.target.value="")},[qs]),yr="gap-x-1.5 gap-y-0",_r=gs(),pe=ue?"px-1.5 py-1.5":_r?"px-1.5 py-1":"px-2.5 py-1.5",ee=ue?"h-8 w-8":_r?"h-5 w-5":"h-6 w-6",xe=ue?"h-4 w-4":_r?"h-3.5 w-3.5":"h-4 w-4",Ne=ue?"h-6 w-6":_r?"h-4 w-4":"h-5 w-5",ze=ue?"h-[18px] w-[18px]":_r?"h-4 w-4":"h-[18px] w-[18px]",tt="flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",kt=L(tt,ee),re=e.jsx("button",{type:ue?"button":"submit",disabled:!Mt||!Q&&!Y,onPointerDownCapture:U=>{!ue||U.pointerType!=="touch"||!Mt||!Q&&!Y||(st.current=!0,U.preventDefault(),U.stopPropagation(),ft())},onClick:U=>{if(ue){if(st.current){st.current=!1;return}U.preventDefault(),ft()}},className:L(kt,Mt&&(Q||Y)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(_d,{className:L(xe)})}),Le=e.jsx("button",{type:"button",disabled:!Ct||!Q,onPointerDownCapture:U=>{!ue||U.pointerType!=="touch"||!Ct||!Q||(st.current=!0,U.preventDefault(),U.stopPropagation(),es())},onClick:U=>{if(ue){if(st.current){st.current=!1;return}U.preventDefault()}es()},className:L(kt,"absolute bottom-full left-1/2 -translate-x-1/2 mb-1",Ct&&Q?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Queue message",children:e.jsx(_d,{className:L(xe,"-rotate-90")})}),Ce=e.jsx("button",{type:"button",onClick:Rt,className:L(kt,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(LA,{className:L(Ne)})}),_e=Zt?e.jsxs("div",{className:"relative",children:[Ct&&Le,Ce]}):re,Qe=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Cs,type:"file",multiple:!0,className:"hidden",onChange:xr,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(qM,{onFilesSelected:er,multiSelect:!0,presentation:ue?"modal":"dropdown",open:ar,onOpenChange:ir,children:ue?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx("button",{type:"button",className:kt,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(mg,{className:L(ze,"text-current")})})}),e.jsxs(fs,{align:"start",children:[e.jsxs(Et,{onSelect:()=>{requestAnimationFrame(()=>fr())},children:[e.jsx(Ml,{}),"Attach files"]}),e.jsxs(Et,{onSelect:()=>{requestAnimationFrame(()=>{ir(!0)})},children:[e.jsx(pw,{}),"Attach from project"]})]})]})]})]}),dt=t?e.jsx("button",{type:"button",onClick:t,className:kt,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(Lo,{className:L(ze,"text-current")})}):null,$t=e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[ue?e.jsx("button",{type:"button",className:L(kt,"rounded-md text-muted-foreground","hover:bg-interactive-hover/40 hover:text-foreground"),onPointerDownCapture:U=>{U.pointerType==="touch"&&(U.preventDefault(),U.stopPropagation())},onClick:sr,title:"Commands","aria-label":"Commands",children:e.jsx(xo,{className:L(ze)})}):null,Qe,dt]}),be=$e.statusText;return i.useEffect(()=>{const U=!!$e.wasAborted;!Xe.current&&U&&!Ue&&(pt(),Q&&B(Q)),Xe.current=U},[B,Q,Ue,pt,$e.wasAborted]),i.useEffect(()=>()=>{Re.current&&(clearTimeout(Re.current),Re.current=null)},[]),e.jsxs("form",{onSubmit:U=>{U.preventDefault(),ft()},className:L("relative pt-0 pb-4",ue&&De?"ios-keyboard-safe-area":"bottom-safe-area"),"data-keyboard-avoid":"true",style:ue&&Ve>0&&!De?{marginBottom:`${Ve}px`}:void 0,children:[e.jsx("div",{className:"absolute bottom-full left-0 right-0",children:e.jsx(yA,{isWorking:$e.isWorking,statusText:be,isGenericStatus:$e.isGenericStatus,isWaitingForPermission:$e.isWaitingForPermission,wasAborted:$e.wasAborted,abortActive:$e.abortActive,showAbortStatus:Ue})}),e.jsxs("div",{className:"chat-column relative overflow-visible",children:[e.jsx(HM,{}),e.jsx(jy,{onEditMessage:U=>{o(U),setTimeout(()=>{I.current?.focus()},0)}}),cs&&e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-xl border",style:{backgroundColor:Ze?.colors?.surface?.elevated,borderColor:Ze?.colors?.interactive?.border},children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Review comments:"}),e.jsx("span",{className:"text-xs font-semibold",style:{color:Ze?.colors?.status?.info},children:yt})]})}),e.jsxs("div",{className:L("flex flex-col relative overflow-visible","border border-border/80","focus-within:ring-1 focus-within:ring-primary/50",a&&"ring-2 ring-primary ring-offset-2"),style:{borderRadius:Fe,backgroundColor:Ze?.colors?.surface?.subtle},ref:E,onDragEnter:It,onDragOver:Ps,onDragLeave:Hs,onDrop:Es,children:[a&&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:tt,onClick:()=>fr(),title:"Attach files","aria-label":"Attach files",children:e.jsx(Ml,{className:L(ze,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),f&&e.jsx(Sy,{ref:ve,searchQuery:h,onCommandSelect:Ge,showTabs:ue,activeTab:j,onTabSelect:Ts,onClose:()=>p(!1)}),x&&e.jsx(Ny,{ref:oe,searchQuery:b,onAgentSelect:gr,showTabs:ue,activeTab:j,onTabSelect:Ts,onClose:()=>y(!1)}),N&&e.jsx(ky,{ref:Z,searchQuery:C,onSkillSelect:Ie,onClose:()=>w(!1)}),c&&e.jsx(VM,{ref:V,searchQuery:u,onFileSelect:Zs,showTabs:ue,activeTab:j,onTabSelect:Ts,onClose:()=>d(!1)}),e.jsx(hr,{ref:I,"data-chat-input":"true",value:n,onChange:_s,onKeyDown:vt,onPaste:mr,onDragEnter:It,onDragOver:Ps,onDrop:Es,onPointerDownCapture:at,placeholder:Q||Y?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!Q&&!Y,autoCorrect:ue?"on":"off",autoCapitalize:ue?"sentences":"off",spellCheck:ue,outerClassName:"focus-within:ring-0",className:L("min-h-[52px] resize-none border-0 px-3 rounded-b-none appearance-none hover:border-transparent bg-transparent",ue?"py-2.5":"pt-4 pb-2"),style:{flex:"none",height:M?`${M.height}px`:void 0,maxHeight:M?`${M.maxHeight}px`:void 0,borderTopLeftRadius:Fe,borderTopRightRadius:Fe},rows:1}),e.jsx("div",{className:L("bg-transparent",pe,ue?"flex items-center gap-x-1.5":L("flex items-center justify-between",yr)),style:{borderBottomLeftRadius:Fe,borderBottomRightRadius:Fe},"data-chat-input-footer":"true",children:ue?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-x-1.5",children:[e.jsx("div",{className:"flex items-center gap-x-1",children:$t}),e.jsxs("div",{className:"flex items-center min-w-0 gap-x-1 justify-end",children:[e.jsxs("div",{className:"flex items-center gap-x-1 min-w-0 max-w-[60vw] flex-shrink",children:[e.jsx(vA,{onOpenModel:_t,className:"min-w-0 flex-shrink"}),e.jsx(bA,{onOpenAgentPanel:()=>R("agent"),className:"min-w-0 flex-shrink"})]}),e.jsxs("div",{className:"flex items-center gap-x-1 flex-shrink-0",children:[e.jsx(cp,{}),_e]})]})]}),e.jsx(fp,{className:"hidden",mobilePanel:$,onMobilePanelChange:R,onMobilePanelSelection:zt,onAgentPanelSelection:()=>R(null)}),e.jsx(mA,{open:A,onClose:Nt,onOpenModel:()=>Gt("model"),onOpenEffort:()=>Gt("variant")})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:L("flex items-center flex-shrink-0",yr),children:$t}),e.jsxs("div",{className:L("flex items-center flex-1 justify-end",yr,"md:gap-x-3"),children:[e.jsx(fp,{className:L("flex-1 min-w-0 justify-end")}),e.jsx(cp,{}),_e]})]})}),ue&&e.jsx(DA,{cornerRadius:Fe})]})]})]})};function od({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:L("bg-accent animate-pulse rounded-xl",t),...s})}const Cp=(t,s,r,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=(v,j,k)=>v+(j-v)*k,h=(v,j,k,N,w,C)=>{const S=p(v,j,w),M=p(N,k,w);return p(S,M,C)},g={x:h(t.x,s.x,r.x,n.x,d,m),y:h(t.y,s.y,r.y,n.y,d,m)},x={x:h(t.x,s.x,r.x,n.x,u,m),y:h(t.y,s.y,r.y,n.y,u,m)},y={x:h(t.x,s.x,r.x,n.x,u,f),y:h(t.y,s.y,r.y,n.y,u,f)},b={x:h(t.x,s.x,r.x,n.x,d,f),y:h(t.y,s.y,r.y,n.y,d,f)};a.push({path:`M${g.x} ${g.y} L${x.x} ${x.y} L${y.x} ${y.y} L${b.x} ${b.y} Z`,row:l,col:c})}return a},rm=({className:t="",width:s=70,height:r=70,isAnimated:n=!1})=>{const o=Ta();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const l=ne.useMemo(()=>{if(typeof window<"u"){const D=getComputedStyle(document.documentElement).getPropertyValue("--splash-stroke").trim();if(D)return D}return a?"white":"black"},[a]),c=ne.useMemo(()=>{if(typeof window<"u"){const D=getComputedStyle(document.documentElement).getPropertyValue("--splash-face-fill").trim();if(D)return D}return a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)"},[a]),d=ne.useMemo(()=>{if(typeof window<"u"){const D=getComputedStyle(document.documentElement).getPropertyValue("--splash-cell-fill").trim();if(D)return D}return a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)"},[a]),u=l,m=48,f=.866,p=.5,h=50,g={x:50,y:h-m},x={x:50-m*f,y:h-m*p},y={x:50+m*f,y:h-m*p},b={x:50,y:h},v={x:50-m*f,y:h+m*p},j={x:50+m*f,y:h+m*p},k={x:50,y:h+m},w=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(g.y+x.y+b.y+y.y)/4})`,C=Cp(x,b,k,v),S=Cp(b,y,j,k),M=ne.useMemo(()=>{const D=[];for(let A=0;A<32;A++)D.push(.1+Math.random()*.5);return D},[]);return e.jsxs("svg",{width:s,height:r,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,role:"img","aria-label":"IKanban logo",children:[e.jsx("path",{d:`M${b.x} ${b.y} L${x.x} ${x.y} L${v.x} ${v.y} L${k.x} ${k.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),C.map((D,A)=>e.jsx("path",{d:D.path,fill:d,opacity:M[A]},`left-${A}`)),e.jsx("path",{d:`M${b.x} ${b.y} L${y.x} ${y.y} L${j.x} ${j.y} L${k.x} ${k.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),S.map((D,A)=>e.jsx("path",{d:D.path,fill:d,opacity:M[A+16]},`right-${A}`)),e.jsx("path",{d:`M${g.x} ${g.y} L${x.x} ${x.y} L${b.x} ${b.y} L${y.x} ${y.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:`${w} 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:u}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:u,fillOpacity:"0.4"})]})]})]})},$A=["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"],BA=()=>{const{currentTheme:t}=rn(),s=t?.colors?.surface?.mutedForeground||"var(--muted-foreground)";return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[e.jsx(rm,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(Cy,{className:"text-body-md",interval:4,transition:{duration:.5},children:$A.map(r=>e.jsxs("span",{style:{color:s},children:['"',r,'…"']},r))})]})},ad=i.memo(BA),zA={'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"}},UA={'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 lo{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return lo.instance||(lo.instance=new lo),lo.instance}recordSessionStart(s){this.sessionStartTimes.set(s,Date.now())}getSessionStartTime(s){return this.sessionStartTimes.get(s)}shouldAnimateMessage(s,r){if(s.role!=="assistant"||this.seenMessageIds.has(s.id))return!1;const n=this.sessionStartTimes.get(r);if(!n)return this.seenMessageIds.add(s.id),this.messageCreationTimes.set(s.id,s.time.created),!1;const o=s.time.created>n-5e3;return o||(this.seenMessageIds.add(s.id),this.messageCreationTimes.set(s.id,s.time.created)),o}clearSession(s){this.sessionStartTimes.delete(s)}hasSessionTiming(s){return this.sessionStartTimes.has(s)}hasBeenAnimated(s){return this.seenMessageIds.has(s)}markMessageAsAnimated(s,r){this.seenMessageIds.add(s),this.messageCreationTimes.set(s,r)}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 wc(t){const s=t.colors.syntax,r=t.colors.surface;return{'code[class*="language-"]':{color:s.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:s.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:s.base.comment,fontStyle:"italic"},prolog:{color:s.base.comment},doctype:{color:s.base.comment},cdata:{color:s.base.comment},punctuation:{color:s.tokens?.punctuation||r.mutedForeground},property:{color:s.tokens?.variableProperty||s.base.variable},tag:{color:s.tokens?.tag||s.base.keyword},"attr-name":{color:s.tokens?.tagAttribute||s.base.variable},"attr-value":{color:s.tokens?.tagAttributeValue||s.base.string},boolean:{color:s.tokens?.boolean||s.base.number},number:{color:s.base.number},constant:{color:s.tokens?.constant||s.base.number},symbol:{color:s.tokens?.constant||s.base.number},string:{color:s.base.string},char:{color:s.base.string},function:{color:s.base.function},builtin:{color:s.tokens?.functionBuiltin||s.base.function},"class-name":{color:s.tokens?.className||s.base.type},namespace:{color:s.tokens?.namespace||s.base.type,opacity:.8},keyword:{color:s.base.keyword},atrule:{color:s.base.keyword},selector:{color:s.base.function},operator:{color:s.base.operator},variable:{color:s.base.variable},regex:{color:s.tokens?.regex||s.base.string},url:{color:s.base.function,textDecoration:"underline"},entity:{color:s.base.function,cursor:"help"},".language-css .token.string":{color:s.base.string},".style .token.string":{color:s.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:s.base.string},"code-snippet":{color:s.base.string},list:{color:s.base.variable},hr:{color:r.mutedForeground},table:{color:s.base.function},blockquote:{color:r.mutedForeground,fontStyle:"italic"},important:{color:s.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:s.tokens?.decorator||s.base.function},annotation:{color:s.tokens?.decorator||s.base.function}}}const HA=({isUser:t,providerID:s,agentName:r,modelName:n,variant:o,isDarkTheme:a})=>{const{src:l,onError:c,hasLogo:d}=qx(s);return e.jsx(Yr,{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(en,{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:`${s} 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(Rn,{className:"h-4 w-4",style:{color:`var(${mn(r).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&&r&&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)]",mn(r).class),children:[e.jsx(Lo,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:r})]}),!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(Rn,{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})]})]})]})})})})},VA=i.memo(HA),WA=t=>`https://opencode.ai/docs/agents/#${encodeURIComponent(t)}`,GA=({part:t,messageId:s,agentMention:r})=>{const o=t,a=o.text,l=typeof a=="string"?a:o.content||o.value||"",[c,d]=i.useState(!1),[u,m]=i.useState(!1),[f,p]=i.useState(0),h=i.useRef(null),g=i.useCallback(b=>{if(typeof window>"u")return!1;const v=window.getSelection();if(!v||v.isCollapsed||v.rangeCount===0)return!1;const j=v.getRangeAt(0);return b.contains(j.startContainer)||b.contains(j.endContainer)},[]);i.useEffect(()=>{const b=h.current;if(!b)return;const v=()=>{c||m(b.scrollHeight>b.clientHeight);const k=window.getComputedStyle(b),N=Number.parseFloat(k.lineHeight),w=Number.parseFloat(k.fontSize),C=Number.isFinite(w)?w*1.4:20,S=Number.isFinite(N)?N:C;p(Math.max(1,Math.round(S*2)))};v();const j=new ResizeObserver(v);return j.observe(b),()=>j.disconnect()},[l,c]);const x=i.useCallback(b=>{const v=h.current;if(!v||g(v))return;if(!c){u&&d(!0);return}b.clientY-v.getBoundingClientRect().top<=f&&d(!1)},[f,g,c,u]);if(!l||l.trim().length===0)return null;const y=()=>{if(!r?.token||!l.includes(r.token))return l;const b=l.indexOf(r.token),v=l.slice(0,b),j=l.slice(b+r.token.length);return e.jsxs(e.Fragment,{children:[v,e.jsx("a",{href:WA(r.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:k=>k.stopPropagation(),children:r.token}),j]})};return e.jsx("div",{className:"relative",children:e.jsx("div",{className:L("break-words whitespace-pre-wrap font-sans typography-markdown",!c&&"line-clamp-2",u&&!c&&"cursor-pointer"),ref:h,onClick:x,children:y()})},t.id||`${s}-user-text`)},KA=i.memo(GA),qA=t=>{let s=t.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return s=s.replace(/^\s*\d{5}\|\s?/gm,""),s.trim()},QA=t=>t?t.includes("<file_diagnostics>")||t.includes("This file has errors")||t.includes("please fix"):!1,YA=t=>t?t.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Mp=(t,s)=>!t||typeof t!="object"?String(t):QN(t,s||""),id=(t,s,r)=>{let n=qA(t);if((s==="edit"||s==="multiedit")&&QA(n)&&(n=YA(n)),(s==="edit"||s==="multiedit")&&n.trim().length===0&&r?.diff){const o=r.diff;return typeof o=="string"?o:String(o)}return n},JA=(t,s)=>{try{const r=t.trim().split(`
|
|
195
|
+
`).filter(Boolean);if(r.length===0)return null;const n=[];return r.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",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Un.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}},XA=(t,s,r)=>{try{const n=t.trim().split(`
|
|
196
|
+
`).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",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Un.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",s?"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",s?"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}},ZA=(t,s,r)=>{try{const n=t.trim().split(`
|
|
197
|
+
`).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",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Un.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",s?"typography-micro":"typography-code"),children:[l,"/"]}),e.jsx("div",{className:L("pl-4 grid gap-1",s?"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",s?"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}},e1=(t,s)=>{try{const r=JSON.parse(t);if(!Array.isArray(r))return null;const n={in_progress:r.filter(a=>a.status==="in_progress"),pending:r.filter(a=>a.status==="pending"),completed:r.filter(a=>a.status==="completed"),cancelled:r.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",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Un.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: ",r.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(ss,{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(ss,{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}},t1=(t,s,r)=>{try{return e.jsx("div",{className:L("typography-code max-w-none w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:Un.tool.popup,children:e.jsx(zr,{content:t,variant:"tool"})})}catch{return null}},Ty=t=>{const s=t.split(`
|
|
198
|
+
`);let r="";const n=[];let o=0;for(;o<s.length;){const a=s[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(r=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<s.length&&!s[p].startsWith("@@")&&!s[p].startsWith("Index:");){const h=s[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:r,oldStart:c,newStart:d,lines:u}),o=p;continue}o++}return n},du=(t,s,r)=>KN(s,t,r),Ey=t=>{const s="h-3.5 w-3.5 flex-shrink-0",r=t.toLowerCase();return r==="edit"||r==="multiedit"||r==="apply_patch"||r==="str_replace"||r==="str_replace_based_edit_tool"?e.jsx(wu,{className:s}):r==="write"||r==="create"||r==="file_write"?e.jsx(fg,{className:s}):r==="read"||r==="view"||r==="file_read"||r==="cat"?e.jsx(Eo,{className:s}):r==="bash"||r==="shell"||r==="cmd"||r==="terminal"?e.jsx(fo,{className:s}):r==="list"||r==="ls"||r==="dir"||r==="list_files"?e.jsx(Nn,{className:s}):r==="search"||r==="grep"||r==="find"||r==="ripgrep"?e.jsx(hw,{className:s}):r==="glob"?e.jsx(gw,{className:s}):r==="fetch"||r==="curl"||r==="wget"||r==="webfetch"?e.jsx($d,{className:s}):r==="web-search"||r==="websearch"||r==="search_web"||r==="codesearch"||r==="google"||r==="bing"||r==="duckduckgo"||r==="perplexity"?e.jsx($d,{className:s}):r==="todowrite"||r==="todoread"?e.jsx(pg,{className:s}):r==="skill"?e.jsx(hg,{className:s}):r==="question"?e.jsx(xw,{className:s}):r==="plan_enter"?e.jsx(yw,{className:s}):r==="plan_exit"?e.jsx(bw,{className:s}):r.startsWith("git")?e.jsx(Ms,{className:s}):e.jsx(rc,{className:s})},s1=(t,s,r=Date.now())=>{const o=(s?s-t:r-t)/1e3;return`${(o<.05&&s!==void 0?.1:o).toFixed(1)}s`},r1=({start:t,end:s,active:r})=>{const[n,o]=i.useState(()=>Date.now());return i.useEffect(()=>{if(!r)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[r]),e.jsx(e.Fragment,{children:s1(t,s,n)})},n1=t=>{if(!t?.diff||typeof t.diff!="string")return null;const s=t.diff.split(`
|
|
199
|
+
`);let r=0,n=0;for(const o of s)o.startsWith("+")&&!o.startsWith("+++")&&r++,o.startsWith("-")&&!o.startsWith("---")&&n++;return r===0&&n===0?null:{added:r,removed:n}},jl=(t,s,r)=>{if(r)return t.split("/").pop()||t;if(t.startsWith(s)){const n=t.substring(s.length);return n.startsWith("/")?n.substring(1):n}return t},o1=t=>{const s=t.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!s)return null;const r=[],n=s[1],o=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let a;for(;(a=o.exec(n))!==null;)r.push({question:a[1],answer:a[2]});return r.length>0?r:null},a1=(t,s,r,n)=>{const o=s,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"?jl(m,n,r):"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 jl(d,n,r)}if((t.tool==="read"||t.tool==="write")&&l){const d=l?.filePath||l?.file_path||l?.path;if(typeof d=="string")return jl(d,n,r)}if(t.tool==="bash"&&l?.command&&typeof l.command=="string"){const d=l.command.split(`
|
|
200
|
+
`)[0];return r?d.substring(0,50):d.substring(0,100)}if(t.tool==="task"&&l?.description&&typeof l.description=="string")return r?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 s&&s.title||"";return typeof c=="string"?c:""},uu=({children:t,maxHeightClass:s="max-h-[60vh]",className:r,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(Ut,{outerClassName:L("w-full min-w-0 flex-none overflow-hidden",s,n),className:L("tool-output-surface p-2 rounded-xl w-full min-w-0 bg-transparent",r),style:{borderWidth:"1px",borderColor:"var(--tools-border)"},disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:t})}),i1=t=>{const s=t.state?.title;return typeof s=="string"&&s.trim().length>0?s:typeof t.tool=="string"&&t.tool.trim().length>0?t.tool:"tool"},l1=t=>t.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),c1=({entries:t,isExpanded:s,hasPrevTool:r,hasNextTool:n,output:o,sessionId:a})=>{const l=Ae(x=>x.setCurrentSession),c=i.useMemo(()=>t.filter(x=>x.state?.status==="completed"),[t]),d=typeof o=="string"?l1(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=s?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-[""]',r?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[c.length>0?e.jsx(uu,{maxHeightClass:s?"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,y)=>{const b=typeof x.tool=="string"&&x.tool.trim().length>0?x.tool:"tool",v=i1(x),j=Gu(b).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:Ey(b)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:j}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:v})]},x.id??`${b}-${y}`)})]})}):null,a&&e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:x=>x.stopPropagation(),onClick:p,children:[e.jsx(gn,{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(y=>!y)},children:[m?e.jsx(is,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(dr,{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(uu,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(zr,{content:d,variant:"tool"})})}):null]}):null]})},Py=i.memo(({diff:t,syntaxTheme:s,input:r})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Ty(t).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 last:border-b-0",style:{borderBottomWidth:"1px",borderBottomColor:"var(--tools-border)"},children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground break-words -mx-1",style:{borderBottomWidth:"1px",borderBottomColor:"var(--tools-border)"},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:"w-10 flex-shrink-0 text-right pr-3 select-none border-r mr-3 -my-0.5 py-0.5",style:{color:"var(--tools-edit-line-number)",borderColor:"var(--tools-border)"},children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Vn,{style:s,language:Jn(typeof r?.file_path=="string"?r.file_path:typeof r?.filePath=="string"?r.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",color:a.type==="removed"?"var(--tools-edit-removed)":a.type==="added"?"var(--tools-edit-added)":"inherit"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit",color:a.type==="removed"?"var(--tools-edit-removed)":a.type==="added"?"var(--tools-edit-added)":"inherit"}},children:a.content})})]},l))})]},o))}));Py.displayName="DiffPreview";const Ry=i.memo(({content:t,syntaxTheme:s,filePath:r,displayPath:n})=>{const o=i.useMemo(()=>t.split(`
|
|
201
|
+
`),[t]),a=i.useMemo(()=>Jn(r??"")||du(t,"write",r?{filePath:r}:void 0),[t,r]),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 rounded-lg mb-1",style:{borderWidth:"1px",borderColor:"var(--tools-border)"},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:"w-10 flex-shrink-0 text-right pr-3 select-none border-r mr-3 -my-0.5 py-0.5",style:{color:"var(--tools-edit-line-number)",borderColor:"var(--tools-border)"},children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Vn,{style:s,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))})]})});Ry.displayName="WriteInputPreview";const Fy=i.memo(({content:t,filePath:s,displayPath:r})=>{const n=su(s),o=s.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 rounded-lg mb-2",style:{borderWidth:"1px",borderColor:"var(--tools-border)"},children:r}),e.jsx("div",{className:"flex justify-center p-4 bg-muted/10 rounded-lg",style:{borderWidth:"1px",borderColor:"var(--tools-border)"},children:e.jsx("img",{src:a,alt:r,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})});Fy.displayName="ImagePreview";const Ly=i.memo(({part:t,state:s,syntaxTheme:r,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:l})=>{const c=s,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,y=t.tool==="write"&&!!x,b=g?xi(g):!1,v=y?g?jl(g,o,n):"New file":null,j=i.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&t.tool==="bash"?Mp(u,t.tool):typeof u.content=="string"?u.content??"":Mp(u,t.tool),[u,t.tool]),k=t.tool!=="apply_patch"&&j.trim().length>0,N=(C,S)=>e.jsx(uu,{maxHeightClass:S?.maxHeightClass,className:S?.className,disableHorizontal:S?.disableHorizontal,outerClassName:S?.outerClassName,children:C}),w=()=>{if(t.tool==="question"){if(s.status==="completed"&&f){const C=o1(p);if(C&&C.length>0)return N(e.jsx("div",{className:"space-y-2",children:C.map((S,M)=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:S.question}),e.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:S.answer})]},M))}),{maxHeightClass:"max-h-[40vh]"})}return s.status==="error"&&"error"in s?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:s.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(t.tool==="todowrite"||t.tool==="todoread"){if(s.status==="completed"&&f){const C=e1(p,{unstyled:!0});return N(C??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return s.status==="error"&&"error"in s?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:s.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(t.tool==="list"&&f){const C=JA(p,{unstyled:!0});return N(C??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 C=XA(p,n,{unstyled:!0});return N(C??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 C=ZA(p,n,{unstyled:!0});return N(C??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(zr,{content:p,variant:"tool"})}));if((t.tool==="web-search"||t.tool==="websearch"||t.tool==="search_web")&&f){const C=t1(p,r,{unstyled:!0});return N(C??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(zr,{content:p,variant:"tool"})}));if(t.tool==="skill"&&f)return N(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(zr,{content:p,variant:"tool"})}));if((t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch")&&h)return N(e.jsx(Py,{diff:h,syntaxTheme:r,input:u}),{className:"p-1"});if(f&&p.trim()){if(t.tool==="read"){const C=id(p,t.tool,d),S=C.split(`
|
|
202
|
+
`),M=typeof u?.offset=="number"?u.offset:0,D=typeof u?.limit=="number"?u.limit:void 0,A=P=>P.trim().startsWith("(");return N(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:S.map((P,$)=>{const R=A(P),O=M+$+1,T=!R&&(D===void 0||$<D);return e.jsxs("div",{className:L("typography-code font-mono flex w-full min-w-0",R&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"w-10 flex-shrink-0 text-right pr-3 select-none border-r mr-3 -my-0.5 py-0.5",style:{color:"var(--tools-edit-line-number)",borderColor:"var(--tools-border)"},children:T?O:""}),e.jsx("div",{className:"flex-1 min-w-0",children:R?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:P}):e.jsx(Vn,{style:r,language:du(C,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:P})})]},$)})}),{className:"p-1"})}return N(e.jsx(Vn,{style:r,language:du(id(p,t.tool,d),t.tool,u),PreTag:"div",customStyle:{...cl.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:id(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.jsxs("div",{className:L("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]"),children:[e.jsx("div",{className:"absolute left-[0.4375rem] w-px",style:{backgroundColor:"var(--tools-border)",top:a?"-0.45rem":"-0.25rem",bottom:l?"-0.6rem":"0",width:"1px"}}),t.tool==="todowrite"||t.tool==="todoread"||t.tool==="question"?w():e.jsxs(e.Fragment,{children:[y&&b?e.jsx("div",{className:"my-1",children:N(e.jsx(Fy,{content:x,filePath:g,displayPath:v??"New file"}))}):y?e.jsx("div",{className:"my-1",children:N(e.jsx(Ry,{content:x,syntaxTheme:r,filePath:g,displayPath:v??"New file"}))}):k?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:j}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,t.tool!=="write"&&s.status==="completed"&&"output"in s&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),w()]}),s.status==="error"&&"error"in s&&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:s.error})]})]})]})});Ly.displayName="ToolExpandedContent";const mu=({part:t,isExpanded:s,onToggle:r,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:l=!1,hasNextTool:c=!1})=>{const d=t.state,u=Yt(_=>_.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(s);i.useEffect(()=>{!f&&!m||g.current!==s&&(g.current=s,typeof s=="boolean"&&a?.("structural"))},[s,f,m,a]);const x=d,y=x.metadata,b=x.input,v=x.time,j=i.useRef({}),k=i.useRef(t.id);if(k.current!==t.id&&(k.current=t.id,j.current={}),m){if(typeof v?.start=="number"){const _=j.current.start;(typeof _!="number"||v.start<_)&&(j.current.start=v.start)}typeof v?.end=="number"&&(j.current.end=v.end)}const N=m?j.current.start??v?.start:v?.start,w=m?j.current.end??v?.end:v?.end,C=i.useMemo(()=>{if(!m)return;const _=y;return typeof _?.sessionId=="string"?_.sessionId:void 0},[m,y]),S=i.useMemo(()=>{if(!m)return[];const _=y?.summary;return Array.isArray(_)?_.filter(F=>typeof F=="object"&&F!==null):[]},[m,y]),M=i.useRef(S.length);i.useEffect(()=>{m&&M.current!==S.length&&(M.current=S.length,a?.("structural"))},[m,a,S.length]);const D=t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch"?n1(y):null,A=a1(t,d,o,u),P=Gu(t.tool).displayName,$=Te(_=>_.showTextJustificationActivity),R=i.useMemo(()=>{if(!$)return null;const _=x.title;if(typeof _=="string"&&_.trim().length>0)return _;const F=b?.description;return typeof F=="string"&&F.trim().length>0?F:null},[$,x,b]),O=i.useContext(Vu),T=_=>{if(m||!O?.editor){r(t.id);return}let F;if(t.tool==="edit"||t.tool==="multiedit")F=b?.filePath||b?.file_path||b?.path||y?.filePath||y?.file_path||y?.path;else if(t.tool==="apply_patch"){const E=(Array.isArray(y?.files)?y?.files:[])[0];F=E?.relativePath||E?.filePath}else["write","create","file_write","read","view","file_read","cat"].includes(t.tool)&&(F=b?.filePath||b?.file_path||b?.path||y?.filePath||y?.file_path||y?.path);if(typeof F=="string"){_.stopPropagation();let I=F;F.startsWith("/")||(I=u.endsWith("/")?u+F:u+"/"+F),O.editor.openFile(I)}else r(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:T,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:_=>{_.stopPropagation(),r(t.id)},children:[e.jsx("div",{className:L("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),style:!m&&h?{color:"var(--status-error)"}:{color:"var(--tools-icon)"},children:Ey(t.tool)}),e.jsx("div",{className:L("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(is,{className:"h-3.5 w-3.5"}):e.jsx(dr,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{color:"var(--tools-title)"},children:P})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta",style:{color:"var(--tools-description)"},children:[R&&e.jsx("span",{className:L("truncate italic",o&&"max-w-[120px]"),style:{color:"var(--tools-description)",opacity:.8},children:R}),!R&&A&&e.jsx("span",{className:L("truncate",o&&"max-w-[120px]"),children:A}),D&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",D.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",D.removed]})]}),typeof N=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(r1,{start:N,end:typeof w=="number"?w:void 0,active:!!(m&&p&&typeof w!="number")})})]})]}),m&&(S.length>0||p||f||C)?e.jsx(c1,{entries:S,isExpanded:s,hasPrevTool:l,hasNextTool:c,output:typeof x.output=="string"?x.output:void 0,sessionId:C}):null,!m&&s?e.jsx(Ly,{part:t,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:l,hasNextTool:c}):null]})},d1={thinking:{label:"Thinking",Icon:Rn},justification:{label:"Justification",Icon:Nu}},u1=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
|
|
203
|
+
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
204
|
+
`).trim(),m1=t=>{if(!t)return"";const s=t.trim(),r=s.indexOf(`
|
|
205
|
+
`),n=s.indexOf("."),o=[r>=0?r:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?s.substring(0,a).trim():s},Oy=({text:t,variant:s,onContentChange:r,blockId:n})=>{const[o,a]=i.useState(!1),l=i.useMemo(()=>m1(t),[t]),{label:c,Icon:d}=d1[s];return i.useEffect(()=>{t.trim().length!==0&&r?.("structural")},[r,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(is,{className:"h-3.5 w-3.5"}):e.jsx(dr,{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(Ut,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:t})})]})},_y=({part:t,onContentChange:s,messageId:r})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>u1(o),[o]);return!a||a.trim().length===0?null:e.jsx(Oy,{text:a,variant:"thinking",onContentChange:s,blockId:t.id||`${r}-reasoning`})},f1=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
|
|
206
|
+
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
207
|
+
`).trim(),p1=({part:t,messageId:s,onContentChange:r})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>f1(o),[o]);return!a||a.trim().length===0?null:e.jsx(Oy,{text:a,variant:"justification",onContentChange:r,blockId:t.id||`${s}-justification`})},h1=i.memo(p1),Ap=6,g1=t=>[...t].sort((s,r)=>{const n=typeof s.endedAt=="number"?s.endedAt:void 0,o=typeof r.endedAt=="number"?r.endedAt:void 0;return n===void 0&&o===void 0?0:n===void 0?1:o===void 0?-1:n-o}),Dp=t=>{const s={},r=t.filter(n=>n.kind==="tool");return r.forEach((n,o)=>{const a=n.part.id;a&&(s[a]={hasPrev:o>0,hasNext:o<r.length-1})}),s},x1=({parts:t,isExpanded:s,onToggle:r,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:l,onContentChange:c,diffStats:d})=>{const u=i.useRef(s),[m,f]=i.useState(!1),[p,h]=i.useState(0),g=i.useRef(new Set);i.useEffect(()=>{if(u.current===s)return;const S=u.current===!1;if(u.current=s,c?.("structural"),s&&S){h(D=>D+1),f(!0),g.current.clear();const M=setTimeout(()=>f(!1),50);return()=>clearTimeout(M)}else f(!1)},[s,c]);const x=i.useMemo(()=>g1(t),[t]),y=Dp(x),b=i.useMemo(()=>x.slice(-Ap),[x]),v=i.useMemo(()=>{const S=new Set;return b.forEach(M=>{M.part.id&&S.add(M.part.id)}),S},[b]),j=i.useMemo(()=>Dp(b),[b]),k=Math.max(0,x.length-Ap);if(x.length===0)return null;const N=s?x:b,w=s?y:j,C=k>0;return e.jsx(Yr,{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",C&&"cursor-pointer"),onClick:C?r: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:C?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:L("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),style:{color:"var(--tools-icon)"},children:e.jsx(Ro,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:L("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(is,{className:"h-3.5 w-3.5"}):e.jsx(dr,{className:"h-3.5 w-3.5"})})]}):e.jsx(Ro,{className:"h-3.5 w-3.5",style:{color:"var(--tools-icon)"}})}),e.jsx("span",{className:"typography-meta font-medium",style:{color:"var(--tools-title)"},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]"),children:[e.jsx("div",{className:"absolute left-[0.4375rem] w-px top-[-0.25rem] bottom-0",style:{backgroundColor:"var(--tools-border)",borderWidth:"0",width:"1px"}}),!s&&k>0&&e.jsxs("div",{className:"typography-micro text-muted-foreground/70 mb-1 cursor-pointer hover:text-muted-foreground",onClick:r,children:["+",k," more..."]}),N.map((S,M)=>{const D=S.part.id||`group-part-${M}`,A=w[D],P=`${D}-exp${p}`,$=S.part.id?v.has(S.part.id):!1;let R=!1;switch(m&&$?R=!0:!s&&S.part.id&&(g.current.has(S.part.id)?R=!0:g.current.add(S.part.id)),S.kind){case"tool":return e.jsx(Yr,{skipAnimation:R,children:e.jsx(mu,{part:S.part,isExpanded:a.has(D),onToggle:l,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:A?.hasPrev??!1,hasNextTool:A?.hasNext??!1})},P);case"reasoning":return e.jsx(Yr,{skipAnimation:R,children:e.jsx(_y,{part:S.part,messageId:S.messageId,onContentChange:c})},P);case"justification":return e.jsx(Yr,{skipAnimation:R,children:e.jsx(h1,{part:S.part,messageId:S.messageId,onContentChange:c})},P);default:return null}})]})]})})},y1=i.memo(x1),nm=t=>{const s=t,r=s.text;return typeof r=="string"?r:s.content||s.value||""},$y=t=>{if(t.type!=="text")return!1;const s=nm(t);return!s||s.trim().length===0},b1=(t,s={})=>{const{includeReasoning:r=!0}=s,n=t.some(o=>!o.synthetic);return t.filter(o=>{const l=!!o.synthetic;return l&&o.type==="text"&&nm(o).includes("<system-reminder>")||l&&n||!r&&o.type==="reasoning"?!1:!(o.type==="patch")})};function v1(){const[t,s]=ne.useState(!1),{voiceProvider:r,speechRate:n,speechPitch:o,speechVolume:a,sayVoice:l,browserVoice:c,openaiVoice:d,summarizeMessageTTS:u,summarizeCharacterThreshold:m}=ut(),{speak:f,stop:p,isAvailable:h}=py(),{speak:g,stop:x,isAvailable:y}=hy(),b=ne.useCallback(()=>{s(!1),p(),x(),ws.cancelSpeech()},[p,x]),v=ne.useCallback(async j=>{if(j.trim()){b(),s(!0);try{let k=j;if(u&&xy(j,"message")?k=await gy(j,{threshold:m}):k=yy(j),r==="openai"&&h)await f(k,{voice:d,speed:n,summarize:!1,onEnd:()=>s(!1),onError:()=>s(!1)});else if(r==="say"&&y){const N=Math.round(100+(n-.5)*200);await g(k,{voice:l,rate:N,onEnd:()=>s(!1),onError:()=>s(!1)})}else await ws.waitForVoices(),await ws.resumeAudioContext(),await ws.speakText(k,navigator.language||"en-US",()=>s(!1),{rate:n,pitch:o,volume:a,voiceName:c||void 0})}catch(k){console.error("[useMessageTTS] Playback error:",k),s(!1)}}},[r,n,o,a,l,c,d,u,m,h,y,f,g,b]);return{isPlaying:t,play:v,stop:b}}const w1=200,j1=({containerRef:t})=>{const[s,r]=i.useState({x:0,y:0,show:!1}),[n,o]=i.useState(""),[a,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState(!1),f=i.useRef(null),p=i.useRef(null),h=i.useRef(null),g=i.useRef(null),x=Ae(S=>S.createSession),y=Ae(S=>S.setPendingInputText),b=Te(S=>S.isMobile);i.useEffect(()=>()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),g.current!==null&&(window.cancelAnimationFrame(g.current),g.current=null)},[]);const v=i.useCallback(()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),g.current!==null&&(window.cancelAnimationFrame(g.current),g.current=null),m(!1),d(!0),h.current=window.setTimeout(()=>{r(S=>({...S,show:!1})),o(""),p.current=null,d(!1),h.current=null},w1)},[]),j=i.useCallback(()=>{if(!p.current)return;h.current!==null&&(window.clearTimeout(h.current),h.current=null),d(!1);const{text:S,rect:M}=p.current,D=!s.show,A=M.left+M.width/2,P=M.top-10;o(S),r({x:A,y:P,show:!0}),D&&(m(!0),g.current!==null&&window.cancelAnimationFrame(g.current),g.current=window.requestAnimationFrame(()=>{m(!1),g.current=null}))},[s.show]),k=i.useCallback(()=>{const S=window.getSelection(),M=t.current;if(!S||!M){a||v();return}const D=S.toString().trim();if(!D){a||v();return}const A=S.getRangeAt(0);if(!M.contains(A.commonAncestorContainer)){a||v();return}const P=A.getBoundingClientRect();p.current={text:D,rect:P},a||j()},[t,v,j,a]);i.useEffect(()=>{const S=t.current;if(!S)return;const M=()=>{l(!0),v()},D=()=>{l(!1),p.current&&setTimeout(()=>{const P=window.getSelection();P&&P.toString().trim()?j():v()},10)};document.addEventListener("selectionchange",k),S.addEventListener("mousedown",M),document.addEventListener("mouseup",D);const A=P=>{f.current&&!f.current.contains(P.target)&&!window.getSelection()?.toString().trim()&&v()};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("selectionchange",k),S.removeEventListener("mousedown",M),document.removeEventListener("mouseup",D),document.removeEventListener("mousedown",A)}},[t,k,v,j]);const N=i.useCallback(()=>{n&&(y(n,"append"),v(),window.getSelection()?.removeAllRanges())},[n,y,v]),w=i.useCallback(async()=>{if(!n)return;await x(void 0,null,null)&&y(n,"replace"),v(),window.getSelection()?.removeAllRanges()},[n,x,y,v]),C=i.useCallback(async()=>{if(n){try{await navigator.clipboard.writeText(n)}catch(S){console.error("Failed to copy:",S)}v(),window.getSelection()?.removeAllRanges()}},[n,v]);return s.show?b?co.createPortal(e.jsxs("div",{ref:f,className:L("fixed left-0 right-0 bottom-0 z-50","flex items-center justify-center gap-4","bg-[var(--surface-elevated)] border-t border-[var(--interactive-border)]","px-3 py-2","safe-area-bottom","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",c?"opacity-0 translate-y-[4px] pointer-events-none":u?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0"),style:{paddingBottom:"calc(0.5rem + env(safe-area-inset-bottom, 0px))"},children:[e.jsxs("button",{onClick:N,className:L("flex items-center gap-2 px-3 py-2 rounded-lg","text-sm font-medium","bg-[var(--primary-base)] text-[var(--primary-foreground)]","active:opacity-80","transition-opacity duration-150"),type:"button",children:[e.jsx(Fs,{className:"h-5 w-5"}),e.jsx("span",{children:"Add to chat"})]}),e.jsxs("button",{onClick:w,className:L("flex items-center gap-2 px-3 py-2 rounded-lg","text-sm font-medium","bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]","active:opacity-80","transition-opacity duration-150"),type:"button",children:[e.jsx(Bd,{className:"h-5 w-5"}),e.jsx("span",{children:"New session"})]}),e.jsxs("button",{onClick:C,className:L("flex items-center gap-2 px-3 py-2 rounded-lg","text-sm font-medium","bg-[var(--surface-muted)] text-[var(--surface-foreground)]","active:opacity-80","transition-opacity duration-150"),type:"button",children:[e.jsx(Hr,{className:"h-5 w-5"}),e.jsx("span",{children:"Copy"})]})]}),document.body):co.createPortal(e.jsx("div",{ref:f,className:"fixed z-50",style:{left:s.x,top:s.y,transform:"translate(-50%, -100%)"},children:e.jsxs("div",{className:L("flex items-center gap-1","rounded-lg border border-[var(--interactive-border)]","bg-[var(--surface-elevated)] shadow-lg","px-1.5 py-1","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",c?"opacity-0 translate-y-[4px] pointer-events-none":u?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0"),children:[e.jsxs("button",{onClick:N,className:L("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),title:"Add to current chat",type:"button",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx("span",{children:"Add to chat"})]}),e.jsx("div",{className:"w-px h-4 bg-[var(--interactive-border)]"}),e.jsxs("button",{onClick:w,className:L("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),title:"Create new session with selection",type:"button",children:[e.jsx(Bd,{className:"h-4 w-4"}),e.jsx("span",{children:"New session"})]})]})}),document.body):null},S1=t=>{const s=t/1e3;if(s<60)return`${s.toFixed(1)}s`;const r=Math.floor(s/60),n=Math.round(s%60);return`${r}m ${n}s`},N1=new Set(["task"]),Zi=t=>typeof t=="string"&&N1.has(t.toLowerCase()),k1=({messageId:t,parts:s,isMobile:r,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(()=>s.filter(S=>S.type!=="text"?!1:!$y(S)),[s]),x=d?.token;let y=!1;const b=!!a,v=!!l,j=!!(n??r),k=!!o,N=i.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),w=i.useCallback(()=>{!j||!b||!k||typeof window>"u"||(N(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[b,N,k,j]);i.useEffect(()=>{k||(p(!1),N())},[N,k]);const C=i.useCallback(S=>{!a||!k||(S.stopPropagation(),S.preventDefault(),a(),j&&w())},[k,j,a,w]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:j&&b&&k?w:void 0,children:[e.jsx("div",{className:"leading-relaxed overflow-hidden text-foreground/90 text-base",children:g.map((S,M)=>{let D;return d&&x&&!y&&nm(S).includes(x)&&(D=d,y=!0),e.jsx(Yr,{children:e.jsx(KA,{part:S,messageId:t,isMobile:r,agentMention:D})},`user-text-${M}`)})}),e.jsx(vy,{files:s,onShowPopup:c,compact:!0}),b&&k||u||m?e.jsx("div",{className:L("absolute top-full left-0 right-0 z-10 group/user-actions",r?"pt-2 pb-3":"pt-5"),children:e.jsxs("div",{className:L("flex translate-x-5 items-center justify-end gap-1",r?"pointer-events-auto opacity-100":"pointer-events-none opacity-0 transition-opacity duration-150 group-hover/message:pointer-events-auto group-hover/message:opacity-100 group-hover/user-actions:pointer-events-auto group-hover/user-actions:opacity-100"),children:[u&&e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 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:S=>S.stopPropagation(),onClick:S=>{S.stopPropagation(),u()},children:e.jsx(Oo,{className:"h-3 w-3"})})}),e.jsx(ht,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 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:S=>S.stopPropagation(),onClick:S=>{S.stopPropagation(),m()},children:e.jsx(Ms,{className:"h-3 w-3"})})}),e.jsx(ht,{sideOffset:6,children:"Fork from here"})]}),b&&k&&e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{type:"button",variant:"ghost",size:"icon","data-visible":f||v?"true":void 0,className:"h-6 w-6 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:S=>S.stopPropagation(),onClick:C,onFocus:()=>p(!0),onBlur:()=>{v||p(!1)},children:v?e.jsx(ss,{className:"h-3 w-3 text-[color:var(--status-success)]"}):e.jsx(Hr,{className:"h-3 w-3"})})}),e.jsx(ht,{sideOffset:6,children:"Copy message"})]})]})}):null]})},C1=({messageId:t,parts:s,isMessageCompleted:r,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:y=!1,onAuxiliaryContentComplete:b,showReasoningTraces:v=!1,turnGroupingContext:j,errorMessage:k})=>{const[N,w]=i.useState(!1),C=i.useRef(null),S=i.useRef(null),M=!!x,D=!!y,A=!!(c??l),P=!r,$=i.useMemo(()=>s.filter(ke=>!$y(ke)).filter(ke=>ke.type!=="compaction"),[s]),R=i.useMemo(()=>$.filter(ke=>ke.type==="tool"),[$]),O=i.useMemo(()=>$.filter(ke=>ke.type==="text"),[$]),T=Ae(ke=>ke.createSessionFromAssistantMessage),_=Te(ke=>ke.openMultiRunLauncherWithPrompt),F=j?.isLastAssistantInTurn??!1,I=n==="stop",{isPlaying:E,play:W,stop:V}=v1(),ve=ut(ke=>ke.showMessageTTSButtons),oe=ut(ke=>ke.voiceProvider),Z=i.useMemo(()=>E?"Stop speaking":`Read aloud (${oe==="browser"?"Browser":oe==="openai"?"OpenAI":"Say"} voice)`,[E,oe]),ce=R.length>0,Q=i.useMemo(()=>R.some(ke=>{const qe=(ke.state??{})?.status;return qe==="pending"||qe==="running"||qe==="started"}),[R]),Y=i.useCallback(ke=>{const We=ke.state??{},qe=We?.status;if(qe==="pending"||qe==="running"||qe==="started")return!1;const et=We?.time??{},ct=typeof et?.end=="number"?et.end:void 0,bt=typeof et?.start=="number"?et.start:void 0;return!(typeof ct!="number"||typeof bt=="number"&&ct<bt)},[]),ie=i.useMemo(()=>R.length===0?!0:Q?!1:R.every(ke=>Y(ke)),[R,Q,Y]),B=i.useMemo(()=>$.filter(ke=>ke.type==="reasoning"),[$]),se=i.useMemo(()=>B.length===0?!0:B.every(ke=>typeof ke.time?.end=="number"),[B]),H=typeof n!="string",le=B.length>0&&ce&&(Q||H||!ie),ge=P||ce&&(Q||H||!ie),z=P||le,J=ce||B.length>0,je=O.length===0,X=J&&je&&!ge&&!z&&ie&&se,G=i.useRef(!1),ae=i.useRef(!1);i.useEffect(()=>{ae.current=!1},[t]),i.useEffect(()=>{if(!X){G.current=!1;return}G.current||(G.current=!0,b?.())},[X,b]),i.useEffect(()=>{if(P){ae.current=!1;return}if(ce){ae.current=!1;return}B.length!==0&&(z||!se||ae.current||(ae.current=!0,h?.("structural")))},[P,ce,h,se,B.length,z]);const me=!!g&&!P,Oe=i.useCallback(()=>{C.current!==null&&typeof window<"u"&&(window.clearTimeout(C.current),C.current=null)},[]),Be=i.useCallback(()=>{!A||!M||!me||typeof window>"u"||(Oe(),w(!0),C.current=window.setTimeout(()=>{w(!1),C.current=null},1800))},[M,Oe,me,A]);i.useEffect(()=>{me||(w(!1),Oe())},[Oe,me]);const fe=i.useCallback(ke=>{!x||!me||(ke.stopPropagation(),ke.preventDefault(),x(),A&&Be())},[me,A,x,Be]),q=i.useCallback(ke=>{ke.stopPropagation(),ke.preventDefault(),T&&T(t)},[T,t]),ye=i.useCallback(ke=>{ke.stopPropagation(),ke.preventDefault();const We=Ul(O);if(!We.trim())return;const qe=`${Y0}
|
|
208
|
+
|
|
209
|
+
${We}`;_(qe)},[O,_]),he=i.useCallback(ke=>{if(ke.stopPropagation(),ke.preventDefault(),E){V();return}const We=Ul(O);We.trim()&&W(We)},[O,E,W,V]);i.useEffect(()=>()=>{Oe()},[Oe]);const He=i.useMemo(()=>{const ke={},We=R.filter(qe=>Zi(qe.tool)||ge?!1:Y(qe));return We.forEach((qe,et)=>{ke[qe.id]={hasPrev:et>0,hasNext:et<We.length-1}}),ke},[R,ge,Y]),ot=i.useMemo(()=>j?.activityParts??[],[j]),ue=i.useMemo(()=>j?ot.filter(ke=>ke.messageId===t):[],[ot,t,j]),Ve=i.useMemo(()=>j?j.activityGroupSegments.filter(ke=>ke.anchorMessageId===t):[],[t,j]),De=i.useMemo(()=>{const ke=new Map;return ue.forEach(We=>{ke.set(We.part,We)}),ke},[ue]),we=i.useMemo(()=>j?(v?ot:ot.filter(We=>We.kind!=="reasoning")).filter(We=>{if(We.kind!=="tool")return!0;const qe=We.part.tool;return!Zi(qe)}):[],[ot,v,j]),[Fe,Pe]=i.useState(!1);i.useEffect(()=>{if(!j)return;const ke=j.activityGroupSegments.some(qe=>qe.afterToolPartId!==null),We=we.some(qe=>qe.kind==="reasoning");(we.length>1||ke&&we.length>0||We)&&Pe(!0)},[j,we]);const $e=!!(j&&Fe),Ze=!!(j&&$e&&we.length>0&&Ve.length>0),Ue=i.useMemo(()=>R.filter(ke=>Zi(ke.tool)),[R]),Ee=i.useMemo(()=>{const ke=[],We=et=>{!j||!Ze||Ve.filter(ct=>(ct.afterToolPartId??null)===et).forEach(ct=>{const bt=v?ct.parts:ct.parts.filter(at=>at.kind!=="reasoning");bt.length!==0&&ke.push(e.jsx(y1,{parts:bt,isExpanded:j.isGroupExpanded,onToggle:j.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,diffStats:j.diffStats},`progressive-group-${ct.id}`))})};We(null),Ue.forEach(et=>{ke.push(e.jsx(Yr,{children:e.jsx(mu,{part:et,isExpanded:d.has(et.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${et.id}`)),We(et.id)});const qe=[];return $.forEach((et,ct)=>{const bt=De.get(et);if(!bt||!j)return;let at=null,_t=null;if(!$e){if(bt.kind==="tool"){const Nt=et;if(Zi(Nt.tool))return;const zt=Nt.state?.time,Ct=Y(Nt);if(!(!ge&&Ct))return;const Mt=He[Nt.id];_t=e.jsx(Yr,{children:e.jsx(mu,{part:Nt,isExpanded:d.has(Nt.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:Mt?.hasPrev??!1,hasNextTool:Mt?.hasNext??!1})},`tool-${Nt.id}`),at=Ct&&typeof zt?.end=="number"?zt.end:null}else if(bt.kind==="reasoning"&&v){const Nt=et.time,Gt=typeof Nt?.end=="number"?Nt.end:null;_t=e.jsx(Yr,{children:e.jsx(_y,{part:et,messageId:t,onContentChange:h})},`reasoning-${bt.id}`),at=Gt}_t&&qe.push({part:et,index:ct,endTime:at,element:_t})}}),qe.sort((et,ct)=>et.endTime===null&&ct.endTime===null?et.index-ct.index:et.endTime===null?1:ct.endTime===null?-1:et.endTime-ct.endTime),qe.forEach(({element:et})=>{ke.push(et)}),ke},[De,Ve,d,l,Y,t,h,m,u,ge,$e,v,a,He,j,$,Ue,Ze]),Re=j?.turnId,Xe=Ae(ke=>ke.currentSessionId),st=rs(ke=>{if(!Re||!Xe)return;const We=ke.messages.get(Xe);if(!We)return;const qe=We.find(bt=>bt.info?.id===Re);if(!qe)return;const ct=qe.info.summary?.body;return typeof ct=="string"&&ct.trim().length>0?ct:void 0}),St=typeof j?.summaryBody=="string"&&j.summaryBody.trim().length>0?j.summaryBody:st,mt=i.useRef(void 0);St&&St.trim().length>0&&(mt.current=St);const Tt=i.useRef(Re);Tt.current!==Re&&(Tt.current=Re,mt.current=void 0);const qt=mt.current,yt=j?.isLastAssistantInTurn&&qt&&qt.trim().length>0,os=!!k,cs=F&&g&&(I||!!k),ds=i.useMemo(()=>{if(!F||!I)return;const ke=j?.userMessageCreatedAt;if(!(typeof ke!="number"||typeof o!="number")&&!(o<=ke))return S1(o-ke)},[F,I,j?.userMessageCreatedAt,o]),de=e.jsxs(e.Fragment,{children:[x&&e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{type:"button",variant:"ghost",size:"icon","data-visible":N||D?"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",!me&&"opacity-50"),disabled:!me,"aria-label":"Copy message text","aria-hidden":!me,onPointerDown:ke=>ke.stopPropagation(),onClick:fe,onFocus:()=>{me&&w(!0)},onBlur:()=>{D||w(!1)},children:D?e.jsx(ss,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Hr,{className:"h-3.5 w-3.5"})})}),e.jsx(ht,{sideOffset:6,children:"Copy answer"})]}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{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:q,children:e.jsx(Bd,{className:"h-4 w-4"})})}),e.jsx(ht,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{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:ye,children:e.jsx(Zu,{className:"h-4 w-4"})})}),e.jsx(ht,{sideOffset:6,children:"Start new multi-run from this answer"})]}),ve&&me&&e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:L("h-8 w-8 bg-transparent hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",E?"text-green-500":"text-muted-foreground hover:text-foreground"),"aria-label":E?"Stop speaking":"Read aloud",onPointerDown:ke=>ke.stopPropagation(),onClick:he,children:E?e.jsx(il,{className:"h-3.5 w-3.5"}):e.jsx(ma,{className:"h-3.5 w-3.5"})})}),e.jsx(ht,{sideOffset:6,children:Z})]})]});return e.jsxs("div",{ref:S,className:L("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:A&&M&&me?Be:void 0,children:[e.jsx(j1,{containerRef:S}),e.jsxs("div",{children:[e.jsxs("div",{className:"message-content-text leading-relaxed overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Ee,os&&e.jsx(Yr,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(zr,{content:k??""})})},"assistant-error"),yt&&e.jsx(Yr,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",children:[e.jsx(zr,{content:qt}),cs&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:de}),ds?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(ym,{className:"h-3.5 w-3.5"}),ds]}):null]})]})},"summary-body")]}),e.jsx(vy,{files:s,onShowPopup:m}),!yt&&cs&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:de}),ds?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(ym,{className:"h-3.5 w-3.5"}),ds]}):null]})]})]})},M1=({isUser:t,...s})=>t?e.jsx(k1,{messageId:s.messageId,parts:s.parts,isMobile:s.isMobile,hasTouchInput:s.hasTouchInput,hasTextContent:s.hasTextContent,onCopyMessage:s.onCopyMessage,copiedMessage:s.copiedMessage,onShowPopup:s.onShowPopup,agentMention:s.agentMention,onRevert:s.onRevert,onFork:s.onFork}):e.jsx(C1,{...s}),Ip=i.memo(M1),ld=t=>{const s=t,r=s?.clientRole,n=s?.role;return s?.userMessageMarker===!0||r==="user"||n==="user"||s?.origin==="user"||s?.source==="user"?{role:"user",isUser:!0}:{role:r||n||"assistant",isUser:!1}},A1=i.lazy(()=>Ks(()=>import("./ToolOutputDialog-omrlEaN1.js"),__vite__mapDeps([2,0,1,3,4]))),D1=new Set(["task","edit","multiedit","write","bash"]),Tp=t=>typeof t=="string"&&D1.has(t.toLowerCase());function cd(t){const s=i.useRef({hasValue:!1,value:void 0});return t!=null&&(!s.current.hasValue||s.current.value!==t)&&(s.current={hasValue:!0,value:t}),s.current.hasValue?s.current.value:t}const qr=(t,s)=>{if(typeof t=="object"&&t!==null)return t[s]},I1=({message:t,previousMessage:s,nextMessage:r,onContentChange:n,animationHandlers:o,turnGroupingContext:a})=>{const{isMobile:l,hasTouchInput:c}=ks(),{currentTheme:d}=rn(),u=i.useRef(null),m=Ae(oo(Ye=>({lifecyclePhase:Ye.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const ft=t.info.sessionID??Ye.currentSessionId??null;return ft?(Ye.streamingMessageIds.get(ft)??null)===t.info.id:!1})(),currentSessionId:Ye.currentSessionId,getAgentModelForSession:Ye.getAgentModelForSession,getSessionModelSelection:Ye.getSessionModelSelection,revertToMessage:Ye.revertToMessage,forkFromMessage:Ye.forkFromMessage}))),{lifecyclePhase:f,isStreamingMessage:p,currentSessionId:h,getAgentModelForSession:g,getSessionModelSelection:x,revertToMessage:y,forkFromMessage:b}=m,v=ut(Ye=>Ye.providers),{showReasoningTraces:j,toolCallExpansion:k}=Te(oo(Ye=>({showReasoningTraces:Ye.showReasoningTraces,toolCallExpansion:Ye.toolCallExpansion})));i.useEffect(()=>{h&&lo.getInstance().recordSessionStart(h)},[h]);const[N,w]=i.useState(null),[C,S]=i.useState(!1),[M,D]=i.useState(new Set),[A,P]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{D(new Set)},[t.info.id,k]);const R=i.useMemo(()=>ld(t.info),[t.info]).isUser,O=t.info.sessionID,{currentContextAgent:T,savedSessionAgentSelection:_}=Lt(oo(Ye=>({currentContextAgent:O?Ye.currentAgentContext.get(O):void 0,savedSessionAgentSelection:O?Ye.sessionAgentSelections.get(O):void 0}))),F=i.useMemo(()=>{if(!R)return t.parts;const Ye=ft=>{const vt=ft.trim();return!!(vt.startsWith("User has requested to enter plan mode")||vt.startsWith("The plan at "))};return t.parts.filter(ft=>{if(!(ft?.synthetic===!0))return!0;if(ft.type!=="text")return!1;const pt=ft?.text;return typeof pt=="string"?Ye(pt):!1}).map(ft=>ft.type==="compaction"?{type:"text",text:"/compact"}:ft)},[R,t.parts]),I=i.useMemo(()=>{if(R||!s)return null;const Ye=qr(s.info,"clientRole"),ft=qr(s.info,"role");if((typeof Ye=="string"?Ye:typeof ft=="string"?ft:void 0)!=="user")return null;const pt=qr(s.info,"mode"),Rt=qr(s.info,"agent"),Ft=qr(s.info,"providerID"),Pt=qr(s.info,"modelID"),Jt=qr(s.info,"variant"),Ns=typeof pt=="string"&&pt.trim().length>0?pt:typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0,Ts=typeof Ft=="string"&&Ft.trim().length>0?Ft:void 0,sr=typeof Pt=="string"&&Pt.trim().length>0?Pt:void 0,Xs=typeof Jt=="string"&&Jt.trim().length>0?Jt:void 0;return!Ns&&!Ts&&!sr&&!Xs?null:{agentName:Ns,providerId:Ts,modelId:sr,variant:Xs}},[R,s]),E=i.useMemo(()=>{if(R||!s)return!1;const Ye=Array.isArray(s.parts)?s.parts:[];for(let ft=0;ft<Ye.length;ft++){const vt=Ye[ft];if(vt?.type!=="text"||vt?.synthetic!==!0)continue;const pt=typeof vt.text=="string"?vt.text.trim():"";if(pt.startsWith("User has requested to enter plan mode")||pt.startsWith("The plan at "))return!0}return!1},[R,s]),W=i.useMemo(()=>{if(R)return;const Ye=t.info.time;if(!(typeof Ye?.completed=="number"&&Ye.completed>0)&&E&&I?.agentName)return I.agentName;const vt=qr(t.info,"mode");if(typeof vt=="string"&&vt.trim().length>0)return vt;const pt=qr(t.info,"agent");if(typeof pt=="string"&&pt.trim().length>0)return pt;if(I?.agentName)return I.agentName;if(O)return T||(_??void 0)},[R,t.info,E,I,O,T,_]),V=R?null:qr(t.info,"providerID"),ve=R?null:qr(t.info,"modelID"),oe=i.useMemo(()=>{if(R||!O)return null;if(I?.providerId&&I?.modelId)return{providerId:I.providerId,modelId:I.modelId};if(W){const ft=g(O,W);if(ft?.providerId&&ft?.modelId)return ft}const Ye=x(O);return Ye?.providerId&&Ye?.modelId?Ye:null},[R,O,W,I,g,x]),Z=i.useMemo(()=>R?null:typeof V=="string"&&V.trim().length>0?V:oe?.providerId??null,[R,V,oe]),ce=i.useMemo(()=>R?null:typeof ve=="string"&&ve.trim().length>0?ve:oe?.modelId??null,[R,ve,oe]),Q=i.useMemo(()=>{if(!R&&Z&&ce&&v.length>0){const Ye=v.find(ft=>ft.id===Z);if(Ye?.models&&Array.isArray(Ye.models)){const pt=Ye.models.find(Rt=>Rt.id===ce)?.name;return typeof pt=="string"?pt:void 0}}},[R,Z,ce,v]),Y=i.useMemo(()=>{if(R||!Z||!ce)return!1;const Ye=v.find(pt=>pt.id===Z);if(!Ye?.models||!Array.isArray(Ye.models))return!1;const vt=Ye.models.find(pt=>pt.id===ce)?.variants;return!!(vt&&Object.keys(vt).length>0)},[R,ce,Z,v]),ie=cd(W),B=cd(Z??void 0),se=cd(Q),H=ie??void 0,le=B??null,ge=se??void 0,z=i.useMemo(()=>{const Ye=t.info.time;return typeof Ye?.completed=="number"?Ye.completed:null},[t.info.time]),J=i.useMemo(()=>R?!0:!!(z&&z>0),[R,z]),je=i.useMemo(()=>{const Ye=t.info.finish;return typeof Ye=="string"?Ye:void 0},[t.info]),X=i.useMemo(()=>b1(F,{includeReasoning:j}),[F,j]),G=i.useMemo(()=>R||J?X:[],[R,J,X]),ae=i.useMemo(()=>R?[]:X.filter(Ye=>Ye.type==="text"),[R,X]),me=i.useMemo(()=>R?[]:X.filter(ft=>ft.type==="tool"),[R,X]),Oe=i.useMemo(()=>{if(k==="collapsed"||k==="activity")return M;const Ye=new Set;for(const vt of me){const pt=vt.tool;vt.id&&Tp(pt)&&Ye.add(vt.id)}if(a?.isFirstAssistantInTurn)for(const vt of a.activityParts){if(vt.kind!=="tool")continue;const pt=vt.part;pt.id&&Tp(pt.tool)&&Ye.add(pt.id)}const ft=new Set(Ye);for(const vt of M)ft.has(vt)?ft.delete(vt):ft.add(vt);return ft},[M,k,me,a]),Be=i.useMemo(()=>{if(!R)return;const Ye=t.parts.find(Rt=>Rt.type==="agent");if(!Ye)return;const ft=Ye,vt=typeof ft.name=="string"?ft.name:void 0;if(!vt)return;const pt=ft.source&&typeof ft.source.value=="string"&&ft.source.value.trim().length>0?ft.source.value:`#${vt}`;return{name:vt,token:pt}},[R,t.parts]),fe=typeof je!="string",q=i.useMemo(()=>R?!1:ae.length===0||me.length===0?fe:!0,[ae.length,me.length,fe,R]),ye=d?.metadata.variant,he=i.useMemo(()=>ye?ye==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[ye]),He=i.useMemo(()=>d?wc(d):he?zA:UA,[d,he]),ot=i.useMemo(()=>R?!1:lo.getInstance().shouldAnimateMessage(t.info,h||t.info.sessionID),[t.info,h,R]),ue=i.useRef(!1),Ve=i.useMemo(()=>s?ld(s.info):null,[s]),De=i.useMemo(()=>r?ld(r.info):null,[r]),we=i.useMemo(()=>R||!De?!1:!De.isUser&&De.role==="assistant",[R,De]),Fe=i.useMemo(()=>J?"completed":f||(p?"streaming":"completed"),[J,f,p]),Pe=i.useMemo(()=>{if(R)return!0;const Ye=a?.headerMessageId;if(Ye){if(t.info.id===Ye){if(Fe==="completed")return!0;const vt=Fe==="streaming"||Fe==="cooldown",pt=ue.current;return vt&&!pt&&(ue.current=!0),pt||vt}return!1}return Ve?Ve.isUser:!0},[R,Ve,a,Fe,t.info]),$e=i.useCallback(Ye=>{navigator.clipboard.writeText(Ye),w(Ye),setTimeout(()=>w(null),2e3)},[]),Ze=a?.turnId,{assistantSummaryFromStore:Ue,variantFromTurnStore:Ee}=rs(oo(Ye=>{if(!Ze||!t.info.sessionID)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const ft=Ye.messages.get(t.info.sessionID);if(!ft)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const vt=ft.find(Pt=>Pt.info?.id===Ze);if(!vt)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const Rt=vt.info.summary?.body,Ft=vt.info.variant;return{assistantSummaryFromStore:typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0,variantFromTurnStore:typeof Ft=="string"&&Ft.trim().length>0?Ft:void 0}})),Re=R?void 0:Ee??I?.variant,Xe=!R&&Y?Re??"Default":void 0,st=typeof a?.summaryBody=="string"&&a.summaryBody.trim().length>0?a.summaryBody:Ue,St=i.useRef(void 0);st&&st.trim().length>0&&(St.current=st);const mt=i.useRef(Ze);mt.current!==Ze&&(mt.current=Ze,St.current=void 0);const Tt=St.current,qt=i.useMemo(()=>{if(R)return;const Ye=t.info?.error;if(!Ye)return;const ft=typeof Ye.data?.message=="string"?Ye.data.message:void 0,vt=typeof Ye.message=="string"?Ye.message:void 0,pt=typeof Ye.name=="string"?Ye.name:void 0,Rt=ft||vt||pt;if(Rt)return`Opencode failed to send message with error:
|
|
210
|
+
\`${Rt}\``},[R,t.info]),yt=i.useMemo(()=>R?G.filter(vt=>vt.type==="text").map(vt=>(vt.text||vt.content||"").trim()).filter(vt=>vt.length>0).join(`
|
|
211
|
+
`).replace(/\n\s*\n+/g,`
|
|
212
|
+
`):qt&&qt.trim().length>0?qt:Tt&&Tt.trim().length>0?Tt:Ul(G),[qt,Tt,G,R]),os=yt.length>0,cs=i.useCallback(async Ye=>{if(!Ye)return!1;if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(Ye),!0}catch{}if(typeof document>"u")return!1;const ft=document.createElement("textarea");ft.value=Ye,ft.setAttribute("readonly",""),ft.style.position="fixed",ft.style.top="-1000px",ft.style.left="-1000px",document.body.appendChild(ft),ft.select(),ft.setSelectionRange(0,ft.value.length);const vt=document.execCommand("copy");return document.body.removeChild(ft),vt},[]),ds=i.useCallback(async()=>{await cs(yt)&&(S(!0),setTimeout(()=>S(!1),2e3))},[cs,yt]),de=i.useCallback(()=>{!O||!t.info.id||y(O,t.info.id)},[O,t.info.id,y]),ke=i.useCallback(()=>{!O||!t.info.id||b(O,t.info.id)},[O,t.info.id,b]),We=i.useCallback(Ye=>{D(ft=>{const vt=new Set(ft);return vt.has(Ye)?vt.delete(Ye):vt.add(Ye),vt})},[]),qe=o??null,et=i.useRef(!1),ct=i.useRef(!1),bt=i.useRef(!1),at=i.useRef(!1),_t=i.useRef(!1);i.useEffect(()=>{ct.current=!1,bt.current=!1,at.current=!1,_t.current=!1,et.current=!1},[t.info.id]);const Nt=i.useCallback(()=>{R||et.current||(et.current=!0,n?.("structural"))},[R,n]),Gt=Te(Ye=>Ye.setImagePreviewOpen),zt=i.useCallback(Ye=>{Ye.image&&(P(Ye),Gt(!0))},[Gt]),Ct=i.useCallback(Ye=>{P(ft=>({...ft,open:Ye})),Gt(Ye)},[Gt]),Qt=!!qr(t.info,"animationSettled"),Mt=Fe==="streaming",Zt=i.useMemo(()=>R?!1:X.some(Ye=>Ye.type==="reasoning"),[R,X]),jt=ot&&!Qt&&!Mt,es=!R&&ot&&ae.length>0&&!q;return i.useEffect(()=>{if(qe?.onStreamingCandidate){if(!es){bt.current&&(Zt&&qe?.onReasoningBlock?qe.onReasoningBlock():qe?.onReservationCancelled&&qe.onReservationCancelled(),bt.current=!1);return}_t.current||(_t.current=!0,qe.onStreamingCandidate(),bt.current=!0)}},[qe,es,Zt]),i.useEffect(()=>{qe?.onAnimationStart&&jt&&(at.current||(qe.onAnimationStart(),at.current=!0))},[qe,jt]),i.useEffect(()=>{if(R)return;const Ye=qe?.onAnimatedHeightChange;if(!Ye||!(jt||es))return;const vt=u.current;if(!vt)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Ye(vt.getBoundingClientRect().height);return}let pt=null;const Rt=Pt=>{if(typeof window>"u"){Ye(Pt);return}pt!==null&&window.cancelAnimationFrame(pt),pt=window.requestAnimationFrame(()=>{Ye(Pt)})},Ft=new ResizeObserver(Pt=>{const Jt=Pt[0];Jt&&Rt(Jt.contentRect.height)});return Ft.observe(vt),Rt(vt.getBoundingClientRect().height),()=>{pt!==null&&(window.cancelAnimationFrame(pt),pt=null),Ft.disconnect()}},[jt,R,qe,es]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:L("group w-full",Pe?l?"pt-10":"pt-6":"pt-0",R||we?"pb-0":"pb-8"),"data-message-id":t.info.id,ref:u,children:e.jsx("div",{className:"chat-message-column relative",children:R?G.length===0?null:e.jsx(Yr,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{style:{backgroundColor:"var(--chat-user-message-bg)"},className:"max-w-[85%] rounded-2xl rounded-br-sm px-5 py-3 shadow-sm border border-primary/5",children:e.jsx(Ip,{messageId:t.info.id,parts:G,isUser:R,isMessageCompleted:J,messageFinish:je,syntaxTheme:He,isMobile:l,hasTouchInput:c,copiedCode:N,onCopyCode:$e,expandedTools:M,onToggleTool:We,onShowPopup:zt,streamPhase:Fe,allowAnimation:jt,onContentChange:n,shouldShowHeader:!1,hasTextContent:os,onCopyMessage:ds,copiedMessage:C,showReasoningTraces:j,onAuxiliaryContentComplete:Nt,agentMention:Be,onRevert:de,onFork:R?ke:void 0,errorMessage:qt})})})}):e.jsxs("div",{className:"relative",children:[Pe&&e.jsx(VA,{isUser:R,providerID:le,agentName:H,modelName:ge,variant:Xe,isDarkTheme:he}),e.jsx(Ip,{messageId:t.info.id,parts:X,isUser:R,isMessageCompleted:J,messageFinish:je,messageCompletedAt:z??void 0,syntaxTheme:He,isMobile:l,hasTouchInput:c,copiedCode:N,onCopyCode:$e,expandedTools:Oe,onToggleTool:We,onShowPopup:zt,streamPhase:Fe,allowAnimation:jt,onContentChange:n,shouldShowHeader:Pe,hasTextContent:os,onCopyMessage:ds,copiedMessage:C,onAuxiliaryContentComplete:Nt,showReasoningTraces:j,agentMention:Be,turnGroupingContext:a,errorMessage:qt})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(A1,{popup:A,onOpenChange:Ct,syntaxTheme:He,isMobile:l})})]})},By=i.memo(I1),T1=({diff:t,syntaxTheme:s,filePath:r})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Ty(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||r?.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:"w-10 flex-shrink-0 text-right pr-3 select-none border-r mr-3 -my-0.5 py-0.5",style:{color:"var(--tools-edit-line-number)",borderColor:"var(--tools-border)"},children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Vn,{style:s,language:Jn(r||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))}),E1=({content:t,syntaxTheme:s,filePath:r})=>{const n=t.split(`
|
|
213
|
+
`),o=Jn(r??"")||"text",a=r?.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:"w-10 flex-shrink-0 text-right pr-3 select-none border-r mr-3 -my-0.5 py-0.5",style:{color:"var(--tools-edit-line-number)",borderColor:"var(--tools-border)"},children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Vn,{style:s,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))})]})},P1=t=>{const s="h-3 w-3",r=t.toLowerCase();return r==="edit"||r==="multiedit"||r==="str_replace"||r==="str_replace_based_edit_tool"?e.jsx(fn,{className:s}):r==="write"||r==="create"||r==="file_write"?e.jsx(fg,{className:s}):r==="bash"||r==="shell"||r==="cmd"||r==="terminal"||r==="shell_command"?e.jsx(fo,{className:s}):r==="webfetch"||r==="fetch"||r==="curl"||r==="wget"?e.jsx($d,{className:s}):e.jsx(rc,{className:s})},R1=t=>{const s=t.toLowerCase();return s==="edit"||s==="multiedit"||s==="str_replace"||s==="str_replace_based_edit_tool"?"edit":s==="write"||s==="create"||s==="file_write"?"write":s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?"bash":s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?"webfetch":t},F1=({permission:t,onResponse:s})=>{const[r,n]=i.useState(!1),[o,a]=i.useState(!1),{respondToPermission:l}=Ae(),{currentTheme:c}=rn(),d=i.useMemo(()=>wc(c),[c]),u=async b=>{n(!0);try{await l(t.sessionID,t.id,b),a(!0),s?.(b)}catch{}finally{n(!1)}};if(o)return null;const m=t.permission||"unknown",f=m.toLowerCase(),p=(b,v="")=>{const j=t.metadata[b];return typeof j=="string"?j:typeof j=="number"?String(j):v},h=b=>{const v=t.metadata[b];return typeof v=="number"?v:void 0},g=b=>!!t.metadata[b],x=R1(m),y=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const j=p("command")||p("cmd")||p("script"),k=p("description"),N=p("cwd")||p("working_directory")||p("directory")||p("path"),w=h("timeout");return e.jsxs(e.Fragment,{children:[k&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:k}),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})]}),w&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",w,"ms"]}),j&&e.jsx("div",{children:e.jsx(Vn,{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:j})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const j=p("path")||p("file_path")||p("filename")||p("filePath"),k=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"})}),k&&e.jsx(Ut,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(T1,{diff:k,syntaxTheme:d,filePath:j})})]})}if(f==="write"||f==="create"||f==="file_write"){const j=p("path")||p("file_path")||p("filename")||p("filePath"),k=p("content")||p("text")||p("data");return k?e.jsx(Ut,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(E1,{content:k,syntaxTheme:d,filePath:j})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const j=p("url")||p("uri")||p("endpoint"),k=p("method")||"GET",N=t.metadata.headers&&typeof t.metadata.headers=="object"?t.metadata.headers:void 0,w=p("body")||p("data")||p("payload"),C=h("timeout"),S=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[j&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Request:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded",children:k}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:j})]})]}),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(Ut,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(Vn,{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)})})]}),w&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(Ut,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(Vn,{language:typeof w=="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 w=="object"?JSON.stringify(w,null,2):String(w)})})]}),(C||S)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[C&&e.jsxs("span",{children:["Timeout: ",C,"ms"]}),C&&S&&e.jsx("span",{children:" • "}),S&&e.jsxs("span",{children:["Response format: ",S]})]})]})}const b=p("command")||p("content")||p("action")||p("operation"),v=p("description");return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),b&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(Ut,{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(b)})})]}),Object.keys(t.metadata).length>0&&!b&&!v&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(Ut,{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(Fo,{className:"h-3.5 w-3.5 text-[var(--status-warning)]"}),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:[P1(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(", ")})]}),y()]}),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:r,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:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(ss,{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:r,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:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(Pn,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),(()=>{const b=t.always||t.metadata.always||[];if(b.length===0)return"Always Allow";const j=b.slice(0,2).join(", "),k=b.length>2;return e.jsx("span",{className:"truncate max-w-[180px]",children:k?`Always: ${j}...`:`Always: ${j}`})})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:r,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:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(Pn,{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:r,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:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(hs,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 flex-shrink-0"}),"Deny"]}),r&&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"})})]})]})})})},dd="summary",L1=({question:t})=>{const{respondToQuestion:s,rejectQuestion:r}=Ae(),[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]),y=n===dd,b=y?-1:Math.max(0,Math.min(x.length-1,Number(n)||0)),v=y?null:x[b],j=i.useMemo(()=>{if(y)return null;const O=v?.header?.trim();return O&&O.length>0?O:null},[v?.header,y]);i.useEffect(()=>{o("0"),m({}),p({}),g({}),d(!1)},[t.id]);const k=i.useMemo(()=>{const O=x.map((T,_)=>({value:String(_),label:T.header?.trim()||`Q${_+1}`}));return x.length>1&&O.push({value:dd,label:"Summary"}),O},[x]),N=i.useCallback(O=>{if(!!f[O])return(h[O]??"").trim()||"(no answer)";const _=u[O]??[];return _.length>0?_.join(", "):"(no answer)"},[f,h,u]),w=!!v?.multiple,C=u[b]??[],S=!!f[b],M=i.useMemo(()=>{if(x.length===0)return!1;for(let O=0;O<x.length;O+=1){if(!!f[O]){if(!(h[O]??"").trim())return!1;continue}if((u[O]??[]).length===0)return!1}return!0},[f,h,x.length,u]),D=i.useCallback(()=>{const O=[];for(let T=0;T<x.length;T+=1){if(!!f[T]){const F=(h[T]??"").trim();O.push(F?[F]:[]);continue}O.push(u[T]??[])}return O},[f,h,x.length,u]),A=i.useCallback(O=>{v&&(p(T=>({...T,[b]:!1})),m(T=>{const _=T[b]??[];if(w){const I=_.includes(O)?_.filter(E=>E!==O):[..._,O];return{...T,[b]:I}}return{...T,[b]:[O]}}))},[b,v,w]),P=i.useCallback(()=>{p(O=>({...O,[b]:!0})),m(O=>({...O,[b]:[]}))},[b]),$=i.useCallback(async()=>{if(M){l(!0);try{const O=D();await s(t.sessionID,t.id,O),d(!0)}catch{}finally{l(!1)}}},[D,t.id,t.sessionID,M,s]),R=i.useCallback(async()=>{l(!0);try{await r(t.sessionID,t.id),d(!0)}catch{}finally{l(!1)}},[t.id,t.sessionID,r]);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(Fo,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Input needed"}),j?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:j}):null]})}),e.jsxs("div",{className:"px-2 py-2",children:[k.length>1?e.jsx("div",{className:"flex items-center gap-1 mb-2 flex-wrap",children:k.map(O=>{const T=n===O.value,_=O.value===dd;return e.jsxs("button",{type:"button",onClick:()=>o(O.value),className:L("px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1",T?"bg-interactive-selection/40 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-interactive-hover/20"),children:[_?e.jsx(pg,{className:"h-3 w-3"}):null,O.label]},O.value)})}):null,y?e.jsx("div",{className:"space-y-2",children:x.map((O,T)=>{const _=N(T),F=_!=="(no answer)";return e.jsxs("button",{type:"button",onClick:()=>o(String(T)),className:"w-full text-left rounded px-1.5 py-1 hover:bg-interactive-hover/20 transition-colors",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:O.header||`Question ${T+1}`}),e.jsx("div",{className:L("typography-meta",F?"text-foreground":"text-muted-foreground/50 italic"),children:_})]},T)})}):v?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:v.question}),w?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:[v.options.map((O,T)=>{const _=C.includes(O.label),F=/\(recommended\)/i.test(O.label);return e.jsx("button",{type:"button",onClick:()=>A(O.label),disabled:a,className:L("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-interactive-hover/30",_?"bg-interactive-selection/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:e.jsx(Xr,{checked:_,onChange:()=>A(O.label),disabled:a})}),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",_?"text-foreground font-medium":"text-foreground/80"),children:O.label}),F?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),O.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:O.description}):null]})]})},`${T}:${O.label}`)}),e.jsx("button",{type:"button",onClick:P,disabled:a,className:L("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-interactive-hover/30",S?"bg-interactive-selection/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(go,{className:L("h-3.5 w-3.5",S?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:L("typography-meta",S?"text-foreground font-medium":"text-muted-foreground"),children:"Other…"})]})}),S?e.jsx("div",{className:"pl-6 pr-1 pt-0.5",children:e.jsx("textarea",{ref:O=>{if(O){O.style.height="auto";const T=20,_=T*2,F=T*4;O.style.height=`${Math.min(Math.max(O.scrollHeight,_),F)}px`}},value:h[b]??"",onChange:O=>{const T=O.target;T.style.height="auto";const _=20,F=_*2,I=_*4;T.style.height=`${Math.min(Math.max(T.scrollHeight,F),I)}px`,g(E=>({...E,[b]:T.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:$,disabled:a||!M,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(ss,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:R,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(hs,{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]})]})})})},zy=t=>{const s=[];let r=null;return t.forEach(n=>{const o=n.info.clientRole??n.info.role;o==="user"?(r={turnId:n.info.id,userMessage:n,assistantMessages:[]},s.push(r)):o==="assistant"&&r&&r.assistantMessages.push(n)}),s},Ii=i.createContext(null),om=i.createContext(null),Uy=i.createContext(null);let Ep=null;const Zo=new Map,O1=t=>{const s=i.useContext(Ii),r=i.useContext(om),n=i.useContext(Uy);return i.useMemo(()=>{if(!s||!r||!n)return;Ep!==s&&(Zo.clear(),Ep=s);const o=s.messageToTurn.get(t);if(!o||!o.assistantMessages.some(P=>P.info.id===t))return;const l=s.lastTurnId===o.turnId,c=l?`${n.lastTurnActivityInfo?.activityParts.length??0}:${n.lastTurnActivityInfo?.summaryBody??""}`:"",u=(r.turnUiStates.get(o.turnId)??{isExpanded:s.defaultActivityExpanded}).isExpanded,m=l?`${t}-${u}-${n.sessionIsWorking}-${c}`:`${t}-${u}`,f=Zo.get(m);if(f)return f;const p=l?n.lastTurnActivityInfo:s.turnActivityInfo.get(o.turnId),h=p?.activityParts??[],g=p?.activityGroupSegments??[],x=!!p?.hasTools,y=!!p?.hasReasoning,b=p?.summaryBody,v=p?.diffStats,j=o.assistantMessages[0]?.info.id,k=t===j,N=o.assistantMessages[o.assistantMessages.length-1]?.info.id,w=t===N,C=j,S=l&&n.sessionIsWorking,M=o.userMessage.info.time,D=typeof M?.created=="number"?M.created:void 0,A={turnId:o.turnId,isFirstAssistantInTurn:k,isLastAssistantInTurn:w,summaryBody:b,activityParts:h,activityGroupSegments:g,headerMessageId:C,hasTools:x,hasReasoning:y,diffStats:v,userMessageCreatedAt:D,isWorking:S,isGroupExpanded:u,toggleGroup:()=>r.toggleGroup(o.turnId)};if(Zo.size>500){const P=Zo.keys().next().value;P&&Zo.delete(P)}return Zo.set(m,A),A},[s,r,n,t])},Hy=t=>{const s=i.useContext(Ii);return i.useMemo(()=>s?s.messageNeighbors.get(t)??{}:{},[s,t])},Vy=()=>i.useContext(Ii)?.lastTurnMessageIds??new Set,_1=t=>{const s=i.useContext(Ii),r=i.useContext(om);return i.useMemo(()=>{if(!s||!r)return;const n=s.messageToTurn.get(t);if(!n||!n.assistantMessages.some(N=>N.info.id===t))return;const a=s.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,y=p,b=r.turnUiStates.get(n.turnId)??{isExpanded:s.defaultActivityExpanded},v=n.userMessage.info.time,j=typeof v?.created=="number"?v.created:void 0;return{turnId:n.turnId,isFirstAssistantInTurn:h,isLastAssistantInTurn:x,summaryBody:m,activityParts:l,activityGroupSegments:c,headerMessageId:y,hasTools:d,hasReasoning:u,diffStats:f,userMessageCreatedAt:j,isWorking:!1,isGroupExpanded:b.isExpanded,toggleGroup:()=>r.toggleGroup(n.turnId)}},[s,r,t])},$1=new Set(["task"]),Pp=t=>typeof t=="string"&&$1.has(t.toLowerCase()),B1=t=>{for(const s of t.assistantMessages)if(s.info.finish==="stop"){const n=s.parts.find(o=>o.type==="text");if(n){const o=n.text??n.content;if(typeof o=="string"&&o.trim().length>0)return o}}},ud=(t,s)=>{const r=B1(t);let n;const a=t.userMessage.info.summary?.diffs;if(Array.isArray(a)&&a.length>0){let j=0,k=0,N=0;a.forEach(w=>{if(!w)return;const C=typeof w.additions=="number"?w.additions:0,S=typeof w.deletions=="number"?w.deletions:0;(C!==0||S!==0)&&(N+=1),j+=C,k+=S}),N>0&&(n={additions:j,deletions:k,files:N})}let l=!1,c=!1;t.assistantMessages.forEach(j=>{j.parts.forEach(k=>{k.type==="tool"?l=!0:k.type==="reasoning"&&(c=!0)})});let d;for(let j=t.assistantMessages.length-1;j>=0;j--){const k=t.assistantMessages[j];if(!k)continue;if(k.parts.some(w=>{if(w.type!=="text")return!1;const C=w.text??w.content;return typeof C=="string"&&C.trim().length>0})){d=k.info.id;break}}const u=[];let m=0;t.assistantMessages.forEach(j=>{const k=j.info.id,N=k===d;j.parts.forEach(w=>{const C=typeof w.id=="string"&&w.id.trim().length>0?w.id:`${k}-activity-${m++}`;if(w.type==="tool"){const M=w.state?.time,D=typeof M?.end=="number"?M.end:void 0;u.push({id:C,turnId:t.turnId,messageId:k,kind:"tool",part:w,endedAt:D});return}if(w.type==="reasoning"){const S=w.text??w.content;if(typeof S!="string"||S.trim().length===0)return;const M=w.time,D=typeof M?.end=="number"?M.end:void 0;u.push({id:C,turnId:t.turnId,messageId:k,kind:"reasoning",part:w,endedAt:D});return}if(s&&w.type==="text"&&(l||c)&&!N){const S=w.text??w.content;if(typeof S!="string"||S.trim().length===0)return;const M=w.time,D=typeof M?.end=="number"?M.end:void 0;u.push({id:C,turnId:t.turnId,messageId:k,kind:"justification",part:w,endedAt:D})}})});const f=[],p=new WeakMap;u.forEach(j=>{p.set(j.part,j)});const h=new Map,g=[],x=new Map;let y=null;t.assistantMessages.forEach(j=>{const k=j.info.id;j.parts.forEach(N=>{if(N.type==="tool"){const S=N.tool;if(Pp(S)){const M=typeof N.id=="string"&&N.id.trim().length>0?N.id:`${k}-task-${g.length+1}`;h.has(M)||(h.set(M,k),g.push(M)),y=M;return}}const w=p.get(N);if(!w)return;if(w.kind==="tool"){const S=w.part.tool;if(Pp(S))return}const C=x.get(y)??[];C.push(w),x.set(y,C)})});const b=j=>{if(j.length===0)return;const k=new Map;j.forEach(C=>{k.set(C.messageId,(k.get(C.messageId)??0)+1)});let N,w=0;for(const C of t.assistantMessages){const S=k.get(C.info.id)??0;if(S>0&&!N&&(N=C.info.id),w+=S,w>=2)return C.info.id}return N};return[null,...g].forEach(j=>{const k=x.get(j)??[];if(k.length===0)return;const N=j===null?b(k):h.get(j);N&&f.push({id:`${t.turnId}:${N}:${j??"start"}`,anchorMessageId:N,afterToolPartId:j,parts:k})}),{activityParts:u,activityGroupSegments:f,hasTools:l,hasReasoning:c,summaryBody:r,diffStats:n}},z1=t=>{const s=new Map;return t.forEach((r,n)=>{s.set(r.info.id,{previousMessage:n>0?t[n-1]:void 0,nextMessage:n<t.length-1?t[n+1]:void 0})}),s},U1=t=>{const s=t.info.clientRole??t.info.role;return typeof s=="string"?s:""},H1=t=>t.length===0?"":t.map(s=>`${s.info?.id??""}:${U1(s)}`).join("|"),V1=({messages:t,children:s})=>{const{isWorking:r}=sm(),n=Te(x=>x.toolCallExpansion),o=Te(x=>x.showTextJustificationActivity),a=n==="activity"||n==="detailed",l=i.useMemo(()=>H1(t),[t]),c=i.useRef(null),d=i.useMemo(()=>{const x=c.current;if(x&&x.structureKey===l&&x.defaultActivityExpanded===a&&x.showTextJustificationActivity===o)return x.value;const y=zy(t),b=y.length>0?y[y.length-1].turnId:null,v=new Map;y.forEach(C=>{v.set(C.userMessage.info.id,C),C.assistantMessages.forEach(S=>{v.set(S.info.id,C)})});const j=new Map;y.forEach(C=>{C.turnId!==b&&j.set(C.turnId,ud(C,o))});const k=z1(t),N=new Set;if(y.length>0){const C=y[y.length-1];N.add(C.userMessage.info.id),C.assistantMessages.forEach(S=>{N.add(S.info.id)})}const w={turns:y,messageToTurn:v,turnActivityInfo:j,lastTurnId:b,lastTurnMessageIds:N,defaultActivityExpanded:a,messageNeighbors:k};return c.current={structureKey:l,defaultActivityExpanded:a,showTextJustificationActivity:o,value:w},w},[a,t,o,l]),u=i.useMemo(()=>{if(!d.lastTurnId)return;const y=d.turns,b=y.length>0?y[y.length-1]:void 0;if(!b)return;const v=t.findIndex(N=>N.info.id===b.userMessage.info.id);if(v<0)return ud(b,o);const j=t.slice(v+1).filter(N=>(N.info.clientRole??N.info.role)==="assistant"),k={...b,assistantMessages:j};return ud(k,o)},[d,t,o]),[m,f]=i.useState(()=>new Map);i.useEffect(()=>{f(new Map)},[n]);const p=i.useCallback(x=>{f(y=>{const b=new Map(y),v=b.get(x)??{isExpanded:a};return b.set(x,{isExpanded:!v.isExpanded}),b})},[a]),h=i.useMemo(()=>({turnUiStates:m,toggleGroup:p}),[m,p]),g=i.useMemo(()=>({sessionIsWorking:r,lastTurnActivityInfo:u}),[u,r]);return e.jsx(Ii.Provider,{value:d,children:e.jsx(om.Provider,{value:h,children:e.jsx(Uy.Provider,{value:g,children:s})})})},am=i.memo(({message:t,onContentChange:s,animationHandlers:r,scrollToBottom:n})=>{const{previousMessage:o,nextMessage:a}=Hy(t.info.id),l=_1(t.info.id);return e.jsx(By,{message:t,previousMessage:o,nextMessage:a,onContentChange:s,animationHandlers:r,scrollToBottom:n,turnGroupingContext:l})});am.displayName="StaticMessageRow";const im=i.memo(({message:t,onContentChange:s,animationHandlers:r,scrollToBottom:n})=>{const{previousMessage:o,nextMessage:a}=Hy(t.info.id),l=O1(t.info.id);return e.jsx(By,{message:t,previousMessage:o,nextMessage:a,onContentChange:s,animationHandlers:r,scrollToBottom:n,turnGroupingContext:l})});im.displayName="DynamicMessageRow";const Wy=({turn:t,onMessageContentChange:s,getAnimationHandlers:r,scrollToBottom:n})=>{const o=Vy(),a=i.useCallback(l=>{const u=(l.info.clientRole??l.info.role)!=="user"&&o.has(l.info.id)?im:am;return e.jsx(u,{message:l,onContentChange:s,animationHandlers:r(l.info.id),scrollToBottom:n},l.info.id)},[r,o,s,n]);return e.jsxs("section",{className:"relative w-full","data-turn-id":t.turnId,children:[e.jsxs("div",{className:"sticky top-0 z-20 relative bg-[var(--surface-background)] [overflow-anchor:none]",children:[e.jsx("div",{className:"relative z-10",children:a(t.userMessage)}),e.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 top-full z-0 h-8 bg-gradient-to-b from-[var(--surface-background)] to-transparent"})]}),e.jsx("div",{className:"relative z-0",children:t.assistantMessages.map(l=>a(l))})]})};Wy.displayName="TurnBlock";const W1=({turns:t,ungroupedMessages:s,onMessageContentChange:r,getAnimationHandlers:n,scrollToBottom:o})=>{const a=Vy(),l=i.useCallback(c=>{const m=(c.info.clientRole??c.info.role)!=="user"&&a.has(c.info.id)?im:am;return e.jsx(m,{message:c,onContentChange:r,animationHandlers:n(c.info.id),scrollToBottom:o},c.info.id)},[n,a,r,o]);return e.jsxs(e.Fragment,{children:[s.map(c=>l(c)),t.map(c=>e.jsx(Wy,{turn:c,onMessageContentChange:r,getAnimationHandlers:n,scrollToBottom:o},c.turnId))]})},G1=({messages:t,permissions:s,questions:r,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:l,onLoadOlder:c,hasRenderEarlier:d,onRenderEarlier:u,scrollToBottom:m})=>{i.useEffect(()=>{s.length===0&&r.length===0||n("permission")},[s,r,n]);const f=i.useMemo(()=>{const g=new Set;return t.filter(x=>{const y=x.info?.id;if(typeof y=="string"){if(g.has(y))return!1;g.add(y)}return!0}).map(x=>{const y=IA(x.parts);return y===x.parts?x:{...x,parts:y}})},[t]),{turns:p,ungroupedMessages:h}=i.useMemo(()=>{const g=zy(f),x=new Set;g.forEach(b=>{x.add(b.userMessage.info.id),b.assistantMessages.forEach(v=>{x.add(v.info.id)})});const y=f.filter(b=>!x.has(b.info.id));return{turns:g,ungroupedMessages:y}},[f]);return e.jsx(V1,{messages:f,children:e.jsxs("div",{children:[d&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("button",{type:"button",onClick:u,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Render earlier messages"})}),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(W1,{turns:p,ungroupedMessages:h,onMessageContentChange:n,getAnimationHandlers:o,scrollToBottom:m}),(r.length>0||s.length>0)&&e.jsxs("div",{children:[r.map(g=>e.jsx(L1,{question:g},g.id)),s.map(g=>e.jsx(F1,{permission:g},g.id))]}),e.jsx("div",{className:"flex-shrink-0",style:{height:"10vh"},"aria-hidden":"true"})]})})},K1=i.memo(G1);function q1(...t){return s=>{t.forEach(r=>{typeof r=="function"?r(s):r&&typeof r=="object"&&(r.current=s)})}}const Ti=i.forwardRef(({orientation:t="vertical",offset:s=72,size:r=48,isEnabled:n=!0,hideBottomShadow:o=!1,observeMutations:a=!0,onVisibilityChange:l,style:c,className:d,children:u,...m},f)=>{const p=i.useRef(null),h=i.useRef("none"),g=m["data-scroll-shadow"];delete m["data-scroll-shadow"];const x=i.useMemo(()=>{const j={...c};return j["--scroll-shadow-size"]=`${r}px`,j},[r,c]),y=i.useCallback((j,k,N,w,C)=>{const S=`${w}${C.charAt(0).toUpperCase()}${C.slice(1)}Scroll`;k&&N?(j.dataset[S]="true",j.removeAttribute(`data-${w}-scroll`),j.removeAttribute(`data-${C}-scroll`)):(j.dataset[`${w}Scroll`]=String(k),j.dataset[`${C}Scroll`]=String(N),j.removeAttribute(`data-${w}-${C}-scroll`))},[]),b=i.useCallback(j=>{["top","bottom","top-bottom","left","right","left-right"].forEach(k=>{j.removeAttribute(`data-${k}-scroll`)})},[]),v=i.useCallback(()=>{const j=p.current;if(!j)return;if(!n){b(j);return}const k=t==="vertical"?j.scrollTop>s:j.scrollLeft>s;let N=t==="vertical"?j.scrollTop+j.clientHeight+s<j.scrollHeight:j.scrollLeft+j.clientWidth+s<j.scrollWidth;o&&t==="vertical"&&(N=!1),y(j,k,N,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const w=k&&N?"both":k?t==="vertical"?"top":"left":N?t==="vertical"?"bottom":"right":"none";w!==h.current&&(h.current=w,l?.(w))},[b,o,n,s,l,t,y]);return i.useEffect(()=>{const j=p.current;if(!j)return;let k=null;const N=()=>{k===null&&(k=requestAnimationFrame(()=>{k=null,v()}))},w=()=>v(),C=typeof ResizeObserver<"u"?new ResizeObserver(N):null,S=a&&typeof MutationObserver<"u"?new MutationObserver(N):null;return v(),j.addEventListener("scroll",w,{passive:!0}),C?.observe(j),S?.observe(j,{childList:!0,subtree:!0}),()=>{k!==null&&cancelAnimationFrame(k),j.removeEventListener("scroll",w),C?.disconnect(),S?.disconnect()}},[v,a]),e.jsx("div",{...m,ref:q1(p,f),className:d,"data-orientation":t,"data-scroll-shadow":g??!0,style:x,children:u})});Ti.displayName="ScrollShadow";const Q1=160,Y1=({containerRef:t})=>{const[s,r]=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(k=>{const N=t.current;if(!N){m();return}l.current===null&&(l.current=k),u.current&&(d.current=N.scrollHeight-N.clientHeight);const w=Math.min(1,(k-l.current)/Q1),C=1-Math.pow(1-w,3),S=c.current,M=d.current,D=S+(M-S)*C;if(N.scrollTop=D,w<1){a.current=window.requestAnimationFrame(f);return}N.scrollTop=M,m(),n.current&&(n.current=!1,r(!1))},[m,t,r]),p=i.useCallback((k,N)=>{const w=t.current;if(!w)return;const C=Math.max(0,k),S=N?.instant??!1,M=N?.followBottom??!1;if(o.current=!1,typeof window>"u"||S){m(),w.scrollTop=C;const A=C<=1;n.current!==A&&(n.current=A,r(A));return}if(M&&u.current&&a.current!==null)return;if(m(),Math.abs(C-w.scrollTop)<=.5){w.scrollTop=C;const A=C<=1;n.current!==A&&(n.current=A,r(A));return}c.current=w.scrollTop,d.current=C,l.current=null,u.current=M,a.current=window.requestAnimationFrame(f)},[m,t,f,r]),h=i.useCallback(()=>{o.current=!0},[]),g=i.useCallback(()=>{o.current=!0},[]),x=i.useCallback(()=>o.current,[]),y=i.useCallback(()=>t.current?.scrollTop??0,[t]),b=i.useCallback(()=>t.current?.scrollHeight??0,[t]),v=i.useCallback(()=>t.current?.clientHeight??0,[t]),j=i.useCallback(()=>{const k=t.current;if(!k)return;o.current&&a.current!==null&&m();const N=k.scrollTop<=1;n.current!==N&&(n.current=N,r(N))},[m,t]);return i.useEffect(()=>{const k=t.current;if(k)return k.addEventListener("wheel",g,{passive:!0}),k.addEventListener("touchstart",g,{passive:!0}),()=>{k.removeEventListener("wheel",g),k.removeEventListener("touchstart",g)}},[t,g]),i.useEffect(()=>()=>{m()},[m]),i.useMemo(()=>({handleScroll:j,scrollToPosition:p,forceManualMode:h,isAtTop:s,isManualOverrideActive:x,getScrollTop:y,getScrollHeight:b,getClientHeight:v}),[j,p,h,s,x,y,b,v])},J1=typeof window<"u"?i.useLayoutEffect:i.useEffect,X1=.1,Z1=({currentSessionId:t,sessionMessages:s,updateViewportAnchor:r,isSyncing:n,isMobile:o})=>{const a=i.useRef(null),l=Y1({containerRef:a}),c=i.useCallback(()=>{const M=a.current;if(!M||M.clientHeight<=0)return 0;const D=M.clientHeight*X1;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(!0),g=i.useRef(0),x=i.useCallback(()=>{const M=a.current;return M?M.scrollHeight-M.scrollTop-M.clientHeight:0},[]),y=i.useCallback(M=>{h.current!==M&&(h.current=M,f(M))},[]),b=i.useCallback(M=>{const D=a.current;if(!D)return;const A=D.scrollHeight-D.clientHeight;l.scrollToPosition(Math.max(0,A),M)},[l]),v=i.useCallback(()=>{const M=a.current;if(!M){u(!1);return}if(!(M.scrollHeight>M.clientHeight)){u(!1);return}const A=x();u(A>c())},[x,c]),j=i.useCallback((M,D)=>{a.current&&l.scrollToPosition(Math.max(0,M),D)},[l]),k=i.useCallback(M=>{a.current&&(y(!0),b(M),u(!1))},[b,y]),N=i.useCallback(()=>{const M=a.current;if(!M||!t)return;l.handleScroll(),v();const D=M.scrollTop;D<g.current&&h.current&&y(!1),h.current||x()<=c()&&y(!0),g.current=D;const{scrollTop:P,scrollHeight:$,clientHeight:R}=M,O=(P+R/2)/Math.max($,1),T=Math.floor(O*s.length);r(t,T)},[t,x,c,l,s.length,y,v,r]);i.useEffect(()=>{const M=a.current;if(M)return M.addEventListener("scroll",N,{passive:!0}),()=>{M.removeEventListener("scroll",N)}},[N]),J1(()=>{if(!t||t===p.current)return;p.current=t,lo.getInstance().recordSessionStart(t),y(!0),u(!1),a.current&&b({instant:!0})},[t,b,y]),i.useEffect(()=>{if(!h.current||n||!a.current)return;x()>c()&&b({instant:!0})},[x,c,n,b,s]),i.useEffect(()=>{const M=a.current;if(!M||typeof ResizeObserver>"u")return;const D=new ResizeObserver(()=>{v(),h.current&&x()>c()&&b({instant:!0})});D.observe(M);const A=new MutationObserver(()=>{h.current&&x()>c()&&b({instant:!0})});return A.observe(M,{childList:!0,subtree:!0}),()=>{D.disconnect(),A.disconnect()}},[x,c,b,v]),i.useEffect(()=>{if(typeof window>"u"){v();return}const M=window.requestAnimationFrame(()=>{v()});return()=>{window.cancelAnimationFrame(M)}},[t,s.length,v]);const w=i.useRef(new Map),C=i.useCallback(()=>{v(),h.current&&x()>c()&&b({instant:!0})},[x,c,b,v]),S=i.useCallback(M=>{const D=w.current.get(M);if(D)return D;const A={onChunk:()=>{v(),h.current&&x()>c()&&b({instant:!0})},onComplete:()=>{v()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{v(),h.current&&x()>c()&&b({instant:!0})},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return w.current.set(M,A),A},[x,c,b,v]);return{scrollRef:a,handleMessageContentChange:C,getAnimationHandlers:S,showScrollButton:d,scrollToBottom:k,scrollToPosition:j,isPinned:m}};function eD(t){const r=Date.now()-t,n=Math.floor(r/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 tD=({open:t,onOpenChange:s,onScrollToMessage:r})=>{const n=Ae(x=>x.currentSessionId),o=rs(x=>n?x.messages.get(n)||[]:[]),a=Ae(x=>x.revertToMessage),l=Ae(x=>x.forkFromMessage),c=Ae(x=>x.loadSessions),[d,u]=i.useState(null),[m,f]=i.useState(""),p=i.useMemo(()=>o.filter(y=>y.info.role==="user").reverse(),[o]),h=i.useMemo(()=>{if(!m.trim())return p;const x=m.toLowerCase();return p.filter(y=>Rp(y.parts).toLowerCase().includes(x))},[p,m]),g=async x=>{if(n){u(x);try{await l(n,x),await c(),s(!1)}finally{u(null)}}};return n?e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(Ss,{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Is,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Bt,{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 y=Rp(x.parts),b=x.info.time.created,v=eD(b),j=p.length-p.indexOf(x);return e.jsxs("div",{className:"group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",onClick:()=>{r?.(x.info.id),s(!1)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:[j,"."]}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:[y||"[No text content]",y&&y.length>=80&&"…"]}),e.jsxs("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground whitespace-nowrap group-hover:hidden",children:v}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:async k=>{k.stopPropagation(),await a(n,x.info.id),s(!1)},children:e.jsx(Oo,{className:"h-4 w-4"})})}),e.jsx(ht,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",onClick:k=>{k.stopPropagation(),g(x.info.id)},disabled:d===x.info.id,children:d===x.info.id?e.jsx(Ot,{className:"h-4 w-4 animate-spin"}):e.jsx(Ms,{className:"h-4 w-4"})})}),e.jsx(ht,{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(Oo,{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(Ms,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function Rp(t){const s=t.find(r=>r.type==="text");return!s||typeof s.text!="string"?"":s.text.replace(/\n/g," ").slice(0,80)}const Fp=[],Lp=[],Op=[],_p={type:"idle"},Gy=()=>{const{currentSessionId:t,isLoading:s,loadMessages:r,loadMoreMessages:n,updateViewportAnchor:o,openNewSessionDraft:a,trimToViewportWindow:l,newSessionDraft:c}=Ae(oo(B=>({currentSessionId:B.currentSessionId,isLoading:B.isLoading,loadMessages:B.loadMessages,loadMoreMessages:B.loadMoreMessages,updateViewportAnchor:B.updateViewportAnchor,openNewSessionDraft:B.openNewSessionDraft,trimToViewportWindow:B.trimToViewportWindow,newSessionDraft:B.newSessionDraft}))),{isSyncing:d,messageStreamStates:u,sessionMemoryStateMap:m}=Ae(oo(B=>({isSyncing:B.isSyncing,messageStreamStates:B.messageStreamStates,sessionMemoryStateMap:B.sessionMemoryState}))),{isTimelineDialogOpen:f,setTimelineDialogOpen:p}=Te(),h=Ae(i.useCallback(B=>t?B.messages.get(t)??Fp:Fp,[t])),g=Ae(i.useCallback(B=>t?B.permissions.get(t)??Lp:Lp,[t])),x=Ae(i.useCallback(B=>t?B.questions.get(t)??Op:Op,[t])),y=Ae(i.useCallback(B=>t?B.sessionMemoryState.get(t)??null:null,[t])),b=Ae(i.useCallback(B=>t?B.streamingMessageIds.get(t)??null:null,[t])),v=Ae(i.useCallback(B=>t?B.sessionStatus?.get(t)??_p:_p,[t])),j=Ae(i.useCallback(B=>t?B.messages.has(t):!1,[t])),{isMobile:k}=ks(),N=!!c?.open;i.useEffect(()=>{!t&&!N&&a()},[t,N,a]);const[w,C]=i.useState(0),S=i.useRef(null),M=i.useRef(!1),D=20,A=20,P=i.useMemo(()=>{const B=[];for(let se=0;se<h.length;se+=1){const H=h[se];(H.info.clientRole??H.info.role)==="user"&&B.push(se)}return B},[h]),$=i.useCallback(()=>{const B=S.current;if(B!==null){if(S.current=null,M.current&&typeof window<"u"&&typeof window.cancelIdleCallback=="function"){window.cancelIdleCallback(B);return}typeof window<"u"&&window.clearTimeout(B)}},[]),R=i.useMemo(()=>{if(w<=0||P.length===0)return h;const B=P[w]??0;return h.slice(B)},[h,w,P]),O=i.useCallback(()=>{if(w<=0)return;const B=typeof document<"u"?document.querySelector('[data-scrollbar="chat"]'):null,se=B?.scrollTop??null,H=B?.scrollHeight??null;C(le=>le-A>0?le-A:0),B&&se!==null&&H!==null&&window.requestAnimationFrame(()=>{const le=B.scrollHeight-H;le!==0&&(B.scrollTop=se+le)})},[w]),T=i.useCallback(()=>{if(!(S.current!==null||w<=0)){if(typeof window<"u"&&typeof window.requestIdleCallback=="function"){M.current=!0,S.current=window.requestIdleCallback(()=>{S.current=null,O()});return}M.current=!1,S.current=window.setTimeout(()=>{S.current=null,O()},0)}},[O,w]);i.useMemo(()=>[...g,...x],[g,x]);const{scrollRef:_,handleMessageContentChange:F,getAnimationHandlers:I,showScrollButton:E,scrollToBottom:W,scrollToPosition:V,isPinned:ve}=Z1({currentSessionId:t,sessionMessages:R,updateViewportAnchor:o,isSyncing:d,isMobile:k});i.useEffect(()=>{if($(),!t){C(0);return}const B=P.length,se=B>D?B-D:0;C(se)},[$,t,P.length]),i.useEffect(()=>(T(),()=>{$()}),[$,T,w]);const oe=i.useMemo(()=>!y||y.historyComplete===!0?!1:y.hasMoreAbove||y.historyComplete===!1?!0:y.hasMoreAbove===void 0&&y.historyComplete===void 0?h.length>=Zd().HISTORICAL_MESSAGES:!1,[y,h.length]),[Z,ce]=i.useState(!1);i.useEffect(()=>{ce(!1)},[t]);const Q=i.useCallback(async()=>{if(!t||Z)return;$(),C(0);const B=_.current,se=B?.scrollHeight??null,H=B?.scrollTop??null;ce(!0);try{if(await n(t,"up"),B&&se!==null&&H!==null){const le=B.scrollHeight-se;V(H+le,{instant:!0})}}finally{ce(!1)}},[$,t,Z,n,_,V]),Y=i.useCallback(()=>{$(),C(0)},[$]),ie=i.useCallback(B=>{const se=_.current;if(!se)return;const H=se.querySelector(`[data-message-id="${B}"]`);if(H){const le=se.getBoundingClientRect(),J=H.getBoundingClientRect().top-le.top+se.scrollTop-50;se.scrollTo({top:J,behavior:"smooth"})}},[_]);return i.useEffect(()=>{if(!t||j)return;(async()=>{try{await r(t)}finally{const H=v.type??"idle";(H==="busy"||H==="retry")&&ve||(typeof window>"u"?W():window.requestAnimationFrame(()=>{W()}))}})()},[t,j,ve,r,W,h.length,v.type]),!t&&!N?e.jsx("div",{className:"flex flex-col h-full bg-background",style:k?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(ad,{})}):!t&&N?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:k?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(ad,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Xi,{scrollToBottom:W})})]}):t?s&&h.length===0&&!b&&!j?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:k?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-message-column space-y-4",children:[1,2,3].map(se=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(od,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(od,{className:"h-4 w-24"}),e.jsx(od,{className:"h-20 w-full"})]})]},se))})}),e.jsx(Xi,{scrollToBottom:W})]}):h.length===0&&!b?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:k?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(ad,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Xi,{scrollToBottom:W})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:k?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(Ti,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:_,observeMutations:!1,"data-scroll-shadow":"true","data-scrollbar":"chat",children:e.jsx("div",{className:"relative z-0 min-h-full",children:e.jsx(K1,{messages:R,permissions:g,questions:x,onMessageContentChange:F,getAnimationHandlers:I,hasMoreAbove:oe,isLoadingOlder:Z,onLoadOlder:Q,hasRenderEarlier:w>0,onRenderEarlier:Y,scrollToBottom:W})})}),e.jsx(pc,{containerRef:_})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[E&&h.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Me,{variant:"outline",size:"sm",onClick:()=>W({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-interactive-hover","aria-label":"Scroll to bottom",children:e.jsx(va,{className:"h-4 w-4"})})}),e.jsx(Xi,{scrollToBottom:W})]}),e.jsx(tD,{open:f,onOpenChange:p,onScrollToMessage:ie})]}):null};class Ky extends i.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,r){this.setState({error:s,errorInfo:r})}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(Ju,{className:"w-full max-w-md",children:[e.jsx(Zx,{className:"text-center",children:e.jsxs(ey,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(vw,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(ty,{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-interactive-hover/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(Me,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(jr,{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 oi=()=>{const t=Ae(s=>s.currentSessionId);return e.jsx(Ky,{sessionId:t||void 0,children:e.jsx(Gy,{})})},$p=new Da,Bp=new Da,zp=new Da,Up=new Da,Hp=new Da,Vp=new Da,Wp=t=>t,Gp=Iw,sD=Tw,rD=Ew;class nD extends Pw{constructor(s,r){super(),this.id=s,this.containerMap=r}toDOM(){let s=this.containerMap.get(this.id);return s||(s=document.createElement("div"),s.className="oc-block-widget",s.dataset.widgetId=this.id,this.containerMap.set(this.id,s)),s}eq(s){return s.id===this.id}destroy(){}}const Kp=(t,s)=>!t||t.length===0?[]:Dw.define({create(r){const n=new gg,o=[...t].sort((a,l)=>a.afterLine-l.afterLine);for(const a of o){const l=r.doc.lines;if(a.afterLine>l)continue;const c=r.doc.line(a.afterLine);n.add(c.to,c.to,xg.widget({widget:new nD(a.id,s),block:!0,side:1}))}return n.finish()},update(r,n){return r.map(n.changes)},provide:r=>kn.decorations.from(r)}),qp=t=>{if(!t)return[];const s=Math.max(1,t.start),r=Math.max(s,t.end);return Aw.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 gg;for(let a=s;a<=r&&a<=n.state.doc.lines;a+=1){const l=n.state.doc.line(a);o.add(l.from,l.from,xg.line({class:"oc-cm-selected-line"}))}return o.finish()}},{decorations:n=>n.decorations})};function fu({value:t,onChange:s,extensions:r,className:n,readOnly:o,lineNumbersConfig:a,highlightLines:l,onViewReady:c,onViewDestroy:d,blockWidgets:u,enableSearch:m,searchOpen:f}){const p=i.useRef(null),h=i.useRef(null),g=i.useRef(t),x=i.useRef(s),y=i.useRef(c),b=i.useRef(d),[,v]=i.useReducer(k=>k+1,0),j=i.useRef(new Map);return i.useEffect(()=>{g.current=t},[t]),i.useEffect(()=>{x.current=s},[s]),i.useEffect(()=>{y.current=c,b.current=d},[c,d]),i.useEffect(()=>{if(!p.current)return;const k=(()=>{if(typeof document>"u")return null;const w=document.querySelector('meta[name="csp-nonce"]')?.getAttribute("content");if(w)return w;const C=window.__IKANBAN_CSP_NONCE__;return typeof C=="string"&&C.length>0?C:null})(),N=ww.create({doc:g.current,extensions:[...k?[kn.cspNonce.of(k)]:[],jw({fixed:!0}),$p.of(bm(a)),Sw(),Nw.of(" "),Cc.of([kw,...Cw,...Mw]),kn.updateListener.of(w=>{if((w.docChanged||w.viewportChanged||w.geometryChanged)&&v(),!w.docChanged)return;const C=w.state.doc.toString();g.current=C,x.current(C)}),Bp.of(kn.editable.of(!o)),zp.of(r??[]),Up.of(qp(l)),Hp.of(Kp(u,j.current)),Vp.of(m?[vm({top:!0}),Cc.of(Wp(wm))]:[])]});return h.current=new kn({state:N,parent:p.current}),Gp(h.current,h.current.state.doc.length,200),h.current.requestMeasure(),h.current&&y.current?.(h.current),()=>{b.current?.(),h.current?.destroy(),h.current=null}},[]),i.useEffect(()=>{const k=h.current;k&&(k.dispatch({effects:[$p.reconfigure(bm(a)),Bp.reconfigure(kn.editable.of(!o)),zp.reconfigure(r??[]),Up.reconfigure(qp(l)),Hp.reconfigure(Kp(u,j.current)),Vp.reconfigure(m?[vm({top:!0}),Cc.of(Wp(wm))]:[])]}),Gp(k,k.state.doc.length,200),k.requestMeasure(),v())},[r,l,a,o,u,m]),i.useEffect(()=>{const k=h.current;!k||m===!1||(f?sD(k):rD(k))},[f,m]),i.useEffect(()=>{const k=h.current;if(!k)return;const N=k.state.doc.toString();N!==t&&k.dispatch({changes:{from:0,to:N.length,insert:t}})},[t]),e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:p,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","[&_.cm-lineNumbers]:text-[var(--tools-edit-line-number)]",n)}),u?.map(k=>{const N=j.current.get(k.id);return N?co.createPortal(k.content,N,k.id):null})]})}const pu=({currentMode:t,onToggle:s})=>{const r=t==="preview",n=r?"Switch to edit mode":"Switch to preview mode",o=r?"Edit":"Preview";return e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"ghost",size:"icon",onClick:s,"aria-label":n,className:"size-8",children:r?e.jsx(Rw,{className:"size-4","aria-hidden":"true"}):e.jsx(Fw,{className:"size-4","aria-hidden":"true"})})}),e.jsx(ht,{sideOffset:8,children:o})]})};function hu(t){const s=t.metadata.variant==="dark",r=t.config?.fonts?.mono||"monospace",n=t.colors.syntax.highlights||{},o=t.colors.syntax.tokens||{},a=kn.theme({"&":{backgroundColor:"var(--background)",color:t.colors.syntax.base.foreground,fontSize:"var(--text-code)",lineHeight:"1.5rem"},".cm-scroller":{fontFamily:r,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-operator":{color:t.colors.syntax.base.operator},".cm-punctuation":{color:o.punctuation||t.colors.syntax.base.comment},".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-panels":{backgroundColor:t.colors.surface.elevated,color:t.colors.surface.foreground},".cm-panels-top":{borderBottom:`1px solid ${t.colors.interactive.border}`,boxShadow:`0 1px 0 ${t.colors.surface.subtle}`},".cm-panel.cm-search":{padding:"0.625rem 0.75rem",backgroundColor:t.colors.surface.elevated},".cm-search":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"0.5rem",color:t.colors.surface.foreground,fontSize:"0.8125rem"},".cm-search .cm-textfield":{minHeight:"2rem",padding:"0.375rem 0.625rem",borderRadius:"0.5rem",border:`1px solid ${t.colors.interactive.border}`,backgroundColor:t.colors.surface.background,color:t.colors.surface.foreground,outline:"none",transition:"border-color 120ms ease, box-shadow 120ms ease"},".cm-search .cm-textfield:hover":{borderColor:t.colors.interactive.borderHover},".cm-search .cm-textfield:focus, .cm-search .cm-textfield:focus-visible":{borderColor:t.colors.interactive.borderFocus,boxShadow:`0 0 0 2px ${t.colors.interactive.focusRing}`},".cm-search .cm-button":{minHeight:"2rem",padding:"0.375rem 0.625rem",borderRadius:"0.5rem",border:`1px solid ${t.colors.interactive.border}`,backgroundColor:t.colors.surface.background,color:t.colors.surface.foreground,cursor:"pointer",transition:"background-color 120ms ease, border-color 120ms ease, color 120ms ease"},".cm-search .cm-button:hover":{backgroundColor:t.colors.interactive.hover,borderColor:t.colors.interactive.borderHover},".cm-search .cm-button:active":{backgroundColor:t.colors.interactive.active,borderColor:t.colors.interactive.borderFocus},".cm-search .cm-button:focus, .cm-search .cm-button:focus-visible":{outline:"none",boxShadow:`0 0 0 2px ${t.colors.interactive.focusRing}`},".cm-search .cm-button:disabled":{opacity:.55,cursor:"not-allowed",backgroundColor:t.colors.surface.muted,color:t.colors.surface.mutedForeground},".cm-searchMatch":{backgroundColor:t.colors.status.infoBackground,boxShadow:`inset 0 0 0 1px ${t.colors.status.infoBorder}`,borderRadius:"2px"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:t.colors.interactive.selection,color:t.colors.interactive.selectionForeground,boxShadow:`inset 0 0 0 1px ${t.colors.interactive.borderFocus}`},"&.cm-focused":{outline:"none"}},{dark:s}),l=yg.define([{tag:[wt.comment,wt.docComment,wt.meta,wt.documentMeta],class:"cm-comment"},{tag:[wt.keyword,wt.controlKeyword,wt.moduleKeyword,wt.definitionKeyword,wt.modifier],class:"cm-keyword"},{tag:[wt.operatorKeyword,wt.operator,wt.derefOperator,wt.updateOperator,wt.definitionOperator,wt.typeOperator,wt.controlOperator,wt.logicOperator,wt.bitwiseOperator,wt.arithmeticOperator,wt.compareOperator],class:"cm-operator"},{tag:[wt.punctuation,wt.separator,wt.bracket,wt.paren,wt.brace,wt.squareBracket,wt.angleBracket],class:"cm-punctuation"},{tag:[wt.string,wt.regexp,wt.attributeValue,wt.special(wt.string),wt.monospace],class:"cm-string"},{tag:wt.escape,class:"cm-string-2"},{tag:[wt.number,wt.bool,wt.atom,wt.null,wt.self],class:"cm-number"},{tag:[wt.function(wt.variableName),wt.function(wt.definition(wt.variableName)),wt.function(wt.propertyName),wt.standard(wt.variableName),wt.special(wt.variableName)],class:"cm-builtin"},{tag:wt.definition(wt.variableName),class:"cm-def"},{tag:[wt.variableName,wt.local(wt.variableName),wt.constant(wt.variableName),wt.literal],class:"cm-variable"},{tag:wt.propertyName,class:"cm-property"},{tag:wt.attributeName,class:"cm-attribute"},{tag:[wt.className,wt.typeName,wt.namespace],class:"cm-variable-3"},{tag:[wt.tagName,wt.labelName,wt.annotation,wt.macroName],class:"cm-tag"},{tag:wt.link,class:"cm-link"},{tag:[wt.heading,wt.heading1,wt.heading2,wt.heading3,wt.heading4,wt.heading5,wt.heading6],class:"cm-keyword"}]);return[a,ll(Lw,{fallback:!0}),ll(Ow),ll(l)]}const gu=Vo.define(_w),qy=Vo.define($w),oD=Vo.define(Bw),aD=Vo.define(zw),iD=Vo.define(Uw),lD=Vo.define(Hw),Qy=Vw(),cD=Qy.language,Yy=Vo.define(Ww);function dD(t){const s=t.trim().toLowerCase();switch(s){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return gu;case"toml":return qy;case"diff":case"patch":return oD;case"json":case"jsonc":case"json5":return kg().language;case"js":case"javascript":return oa().language;case"jsx":return oa({jsx:!0}).language;case"ts":case"typescript":return oa({typescript:!0}).language;case"tsx":return oa({typescript:!0,jsx:!0}).language;case"yaml":case"yml":return Sg().language;case"html":return Al().language;case"css":return Ng().language;case"xml":case"svg":return vg().language;case"py":case"python":return jg().language;case"sql":return wg().language;case"rs":case"rust":return bg().language;case"ex":case"exs":case"elixir":return cD;case"erl":case"hrl":case"erlang":return Yy;case"heex":case"eex":case"leex":return Al().language;default:return Kw.matchLanguageName(qw,s,!0)}}const uD=t=>t.split("/").pop()?.toLowerCase()??"",mD=()=>ll(yg.define([{tag:[wt.heading1,wt.heading2,wt.heading3,wt.heading4,wt.heading5,wt.heading6],fontWeight:"600"},{tag:wt.strong,fontWeight:"600"},{tag:wt.emphasis,fontStyle:"italic"},{tag:wt.strikethrough,textDecoration:"line-through"},{tag:[wt.link,wt.url],color:"var(--markdown-link, currentColor)",textDecoration:"underline"},{tag:wt.monospace,color:"var(--markdown-inline-code, currentColor)",backgroundColor:"var(--markdown-inline-code-bg, transparent)"},{tag:wt.quote,color:"var(--markdown-blockquote, currentColor)",fontStyle:"italic"},{tag:wt.list,color:"color-mix(in srgb, var(--muted-foreground) 40%, var(--foreground) 60%)"},{tag:wt.heading,color:"var(--markdown-heading1, currentColor)"}]));function Jy(t){const s=t.toLowerCase();switch(uD(s)){case"dockerfile":return aD;case"makefile":case"gnumakefile":return gu}const n=s.lastIndexOf("."),o=n>=0?s.slice(n+1):"";switch(o){case"ts":case"tsx":case"mts":case"cts":return oa({typescript:!0,jsx:o==="tsx"});case"js":case"jsx":case"mjs":case"cjs":return oa({typescript:!1,jsx:o==="jsx"});case"json":case"jsonc":case"json5":case"jsonl":case"ndjson":case"geojson":return kg();case"css":case"scss":case"sass":case"less":return Ng();case"html":case"htm":return Al();case"md":case"mdx":case"markdown":case"mdown":case"mkd":return[Gw({codeLanguages:dD}),mD()];case"yml":case"yaml":return Sg();case"toml":return qy;case"ini":case"cfg":case"conf":case"config":case"properties":return lD;case"sh":case"bash":case"zsh":case"fish":case"env":return gu;case"py":case"pyw":case"pyi":return jg();case"sql":case"psql":case"plsql":return wg();case"xml":case"xsl":case"xslt":case"xsd":case"dtd":case"plist":case"svg":return vg();case"rs":return bg();case"rb":case"erb":case"rake":case"gemspec":return iD;case"ex":case"exs":return Qy;case"erl":case"hrl":return Yy;case"eex":case"leex":case"heex":return Al();default:return null}}const ai=t=>{if(!t)return"";const s=t.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},md=(t,s)=>{const r=ai(t),n=s.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!r||r==="/"?`/${n}`:`${r}/${n}`},fD=(t,s,r)=>md(md(md(t,".opencode"),"plans"),`${s}-${r}.md`),pD=(t,s)=>`~/.opencode/plans/${t}-${s}.md`,hD=(t,s)=>{const r=t.trim();return r.startsWith("~")?r==="~"?s||r:(r.startsWith("~/")||r.startsWith("~\\"))&&s?`${s}${r.slice(1)}`:r:r},gD=(t,s)=>{const r=ai(s.currentDirectory),n=ai(s.homeDirectory),o=ai(t);return r&&o.startsWith(r+"/")?o.slice(r.length+1):n&&o===n?"~":n&&o.startsWith(n+"/")?`~${o.slice(n.length)}`:o},xD=()=>{const t=Ae(B=>B.currentSessionId),s=Ae(B=>B.sessions),r=Yt(B=>B.homeDirectory),n=Vr(),o=Ae(B=>B.newSessionDraft?.open);Te();const{isMobile:a}=ks(),{currentTheme:l}=rn();i.useMemo(()=>wc(l),[l]);const c=Br(B=>B.addDraft),d=Br(B=>B.updateDraft),u=Br(B=>B.removeDraft),m=Br(B=>B.drafts),f=i.useCallback(()=>t??(o?"draft":null),[t,o]),p=i.useMemo(()=>t?s.find(B=>B.id===t)??null:null,[t,s]),h=i.useMemo(()=>{const B=typeof p?.directory=="string"?p.directory:"";return ai(B||"")},[p?.directory]),[g,x]=i.useState(null),y=i.useMemo(()=>!g||!h||!r?g:gD(g,{currentDirectory:h,homeDirectory:r}),[g,h,r]),[b,v]=i.useState(""),[j,k]=i.useState(!1),[N,w]=i.useState(!1),[C,S]=i.useState(!1),[M,D]=i.useState("edit"),A=i.useRef(null),P=i.useRef(null),[$,R]=i.useState(null),[O,T]=i.useState(""),[_,F]=i.useState(null),I="ikanban:plan:md-viewer-mode";i.useEffect(()=>{try{const B=localStorage.getItem(I);if(!B)return;const se=JSON.parse(B);(se==="preview"||se==="edit")&&D(se)}catch{}},[]);const E=i.useCallback(B=>{D(B);try{localStorage.setItem(I,JSON.stringify(B))}catch{}},[]),W=i.useRef(!1),V=i.useRef(null),[ve,oe]=i.useState(!1);i.useEffect(()=>{const B=()=>{W.current=!1,V.current=null,oe(!1)};return document.addEventListener("mouseup",B),()=>document.removeEventListener("mouseup",B)},[]),i.useEffect(()=>{R(null),T(""),F(null)},[b]),i.useEffect(()=>{if(!$)return;const B=H=>{const le=H.target;le.closest('[data-comment-card="true"]')||le.closest('[data-comment-input="true"]')||le.closest(".oc-block-widget")||le.closest(".cm-gutterElement")||le.closest("[data-sonner-toast]")||le.closest("[data-sonner-toaster]")||(R(null),T(""),F(null))},se=window.setTimeout(()=>{document.addEventListener("click",B)},100);return()=>{window.clearTimeout(se),document.removeEventListener("click",B)}},[$,_,a]);const Z=i.useCallback((B,se)=>{const H=B.split(`
|
|
214
|
+
`),le=Math.max(1,se.start),ge=Math.min(H.length,se.end);return le>ge?"":H.slice(le-1,ge).join(`
|
|
215
|
+
`)},[]),ce=i.useCallback(()=>{T(""),R(null),F(null)},[]),Q=i.useCallback((B,se)=>{const H=se??$;if(!H||!B.trim())return;const le=f();if(!le){K.error("Select a session to save comment");return}const ge=Z(b,H),z=y&&y.split("/").pop()||"plan",J=g&&Jn(g)||"markdown";_?d(le,_,{fileLabel:z,startLine:H.start,endLine:H.end,code:ge,language:J,text:B.trim()}):c({sessionKey:le,source:"plan",fileLabel:z,startLine:H.start,endLine:H.end,code:ge,language:J,text:B.trim()}),T(""),R(null),F(null)},[$,b,y,g,c,d,f,Z,_]),Y=i.useMemo(()=>{const B=[hu(l)],se=Jy(g||"plan.md");return se&&B.push(se),B.push(kn.lineWrapping),B},[l,g]);i.useEffect(()=>{let B=!1;const se=async ge=>{if(n.files?.readFile)return(await n.files.readFile(ge))?.content??"";const z=await fetch(`/api/fs/read?path=${encodeURIComponent(ge)}`);if(!z.ok)throw new Error(`Failed to read plan file (${z.status})`);return z.text()},H=async ge=>{if(ge&&(x(null),v("")),!p?.slug||!p?.time?.created||!h){x(null),v("");return}ge&&k(!0);try{const z=fD(h,p.time.created,p.slug),J=hD(pD(p.time.created,p.slug),r||null);let je=null,X=null;try{X=await se(z),je=z}catch{}if(!je)try{X=await se(J),je=J}catch{}if(B)return;if(!je||X===null){x(null),v("");return}x(je),v(X)}catch{if(B)return;x(null),v("")}finally{!B&&ge&&k(!1)}};H(!0);const le=window.setInterval(()=>{H(!1)},3e3);return()=>{B=!0,window.clearInterval(le)}},[h,p?.slug,p?.time?.created,r,n.files]),i.useEffect(()=>()=>{A.current!==null&&window.clearTimeout(A.current),P.current!==null&&window.clearTimeout(P.current)},[]);const ie=i.useMemo(()=>{if(M==="preview")return[];const B=f();if(!B)return[];const se=m[B]??[],H=y&&y.split("/").pop()||"plan",le=se.filter(z=>z.source==="plan"&&z.fileLabel===H),ge=[];return le.forEach(z=>{z.id===_?ge.push({afterLine:z.endLine,id:`edit-${z.id}`,content:e.jsx(Sa,{fileLabel:H,lineRange:{start:z.startLine,end:z.endLine},initialText:O,onSave:Q,onCancel:ce,isEditing:!0})}):ge.push({afterLine:z.endLine,id:`draft-${z.id}`,content:e.jsx(qu,{draft:z,onEdit:()=>{R({start:z.startLine,end:z.endLine}),T(z.text),F(z.id)},onDelete:()=>u(z.sessionKey,z.id)})})}),$&&!_&&!ve&&ge.push({afterLine:$.end,id:"plan-new-comment-input",content:e.jsx(Sa,{fileLabel:H,lineRange:$,initialText:O,onSave:Q,onCancel:ce,isEditing:!1})}),ge},[M,f,m,y,_,$,O,Q,ce,u,ve]);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"}),g?e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:y??g,children:y??g}):null]}),g?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(pu,{currentMode:M,onToggle:()=>E(M==="preview"?"edit":"preview")}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(b),S(!0),P.current!==null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{S(!1)},1200)}catch{}},className:"h-5 w-5 p-0",title:"Copy plan contents","aria-label":"Copy plan contents",children:C?e.jsx(ss,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Cl,{className:"h-4 w-4"})}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(y??g),w(!0),A.current!==null&&window.clearTimeout(A.current),A.current=window.setTimeout(()=>{w(!1)},1200)}catch{}},className:"h-5 w-5 p-0",title:`Copy plan path (${y??g})`,"aria-label":`Copy plan path (${y??g})`,children:N?e.jsx(ss,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(zd,{className:"h-4 w-4"})})]}):null]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(Ut,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:j?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":"0px"},children:e.jsx("div",{className:"h-full oc-plan-editor",children:M==="preview"?e.jsx("div",{className:"h-full overflow-auto p-3",children:e.jsx(Gs,{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(zr,{content:b,className:"typography-markdown-body"})})}):e.jsx("div",{className:"relative h-full",children:e.jsx(fu,{value:b,onChange:()=>{},readOnly:!0,className:"h-full [&_.cm-scroller]:pb-[var(--oc-plan-comment-pad)] [&_.cm-scroller]:relative",extensions:Y,highlightLines:$?{start:Math.min($.start,$.end),end:Math.max($.start,$.end)}:void 0,blockWidgets:ie,lineNumbersConfig:{domEventHandlers:{mousedown:(B,se,H)=>{if(!(H instanceof MouseEvent)||H.button!==0)return!1;H.preventDefault();const le=B.state.doc.lineAt(se.from).number;if(a&&$&&!H.shiftKey){const ge=Math.min($.start,$.end,le),z=Math.max($.start,$.end,le);return R({start:ge,end:z}),W.current=!1,V.current=null,oe(!1),!0}if(W.current=!0,V.current=le,oe(!0),$&&H.shiftKey){const ge=Math.min($.start,le),z=Math.max($.end,le);R({start:ge,end:z})}else R({start:le,end:le});return!0},mouseover:(B,se,H)=>{if(!(H instanceof MouseEvent)||H.buttons!==1||!W.current||V.current===null)return!1;const le=B.state.doc.lineAt(se.from).number,ge=Math.min(V.current,le),z=Math.max(V.current,le);return R({start:ge,end:z}),oe(!0),!1},mouseup:()=>(W.current=!1,V.current=null,oe(!1),!1)}}})})})})})})})]})},Qp=12,yD=[{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"}],bD=({isActive:t,burstKey:s=0,className:r,durationMs:n=900,bursts:o=yD,onComplete:a})=>{const l=ne.useRef(!1);ne.useEffect(()=>{!t&&l.current&&a?.(),t&&(l.current=!0)},[t,a]);const c=ne.useMemo(()=>Array.from({length:Qp},(d,u)=>{const m=Math.PI*2*u/Qp;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return t?e.jsx("div",{className:L("fireworks-overlay pointer-events-none",r),"aria-hidden":"true","data-burst-key":s,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}-${s}`)})},`${d.id}-${s}`)})}):null},vD=({durationMs:t=3400}={})=>{const[s,r]=ne.useState({isActive:!1,cycle:0}),n=ne.useRef(null),o=ne.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=ne.useCallback(()=>{o(),r(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=ne.useCallback(()=>{o(),r(c=>({isActive:!0,cycle:c.cycle+1})),n.current=window.setTimeout(()=>{r(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},t)},[o,t]);return ne.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},Xy=i.createContext(void 0),Yp=({children:t})=>{const{isActive:s,burstKey:r,triggerFireworks:n,dismissFireworks:o}=vD(),a=i.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(Xy.Provider,{value:a,children:[t,e.jsx(bD,{isActive:s,burstKey:r})]})},wD=()=>{const t=i.useContext(Xy);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},ka=Ls()(Us(Ar((t,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:r=>{t({selectedProfileId:r})},loadProfiles:async()=>{t({isLoading:!0});const r=s().profiles;try{const n=await d0();return t({profiles:n,isLoading:!1}),!0}catch(n){return console.error("Failed to load git identity profiles:",n),t({profiles:r,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const r=await h0();if(r&&r.userName&&r.userEmail){const n={id:"global",name:"Global Identity",userName:r.userName,userEmail:r.userEmail,authType:r.sshCommand?"ssh":void 0,sshKey:r.sshCommand?r.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"house"};t({globalIdentity:n})}else t({globalIdentity:null});return!0}catch(r){return console.error("Failed to load global git identity:",r),t({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const r=await p0();return t({discoveredCredentials:r}),!0}catch(r){return console.error("Failed to discover git credentials:",r),t({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const r=n=>{if(typeof n!="string")return null;const o=n.trim();return o.length>0?o:null};try{let n=null;if(n===null){const o=Ur()?.settings;if(o)try{const l=(await o.load())?.settings||{};n=r(l.defaultGitIdentityId)}catch{}}if(n===null)try{const o=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);n=r(a?.defaultGitIdentityId)}}catch{}return t({defaultGitIdentityId:n}),!0}catch(n){return console.error("Failed to load default git identity setting:",n),!1}},setDefaultGitIdentityId:async r=>{try{const n=typeof r=="string"?r.trim():"",o=n.length>0?n:"";return await xs({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 r=>{try{const n={...r,id:r.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:r.color||"keyword",icon:r.icon||"branch"};return await u0(n),await s().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(r,n)=>{try{const o=s().profiles.find(l=>l.id===r);if(!o)throw new Error("Profile not found");const a={...o,...n};return await m0(r,a),await s().loadProfiles(),!0}catch(o){return console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async r=>{try{return await f0(r),s().selectedProfileId===r&&t({selectedProfileId:null}),await s().loadProfiles(),!0}catch(n){return console.error("Failed to delete git identity profile:",n),!1}},getProfileById:r=>{const{profiles:n,globalIdentity:o}=s();return r==="global"?o||void 0:n.find(a=>a.id===r)},getUnimportedCredentials:()=>{const{profiles:r,discoveredCredentials:n}=s();return n.filter(o=>!r.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Dr(()=>Ws()),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=ka);const Pr=t=>{const s=t.trim();return s?`'${s.replace(/'/g,"'\\''")}'`:"''"},Ca=t=>(t||"").split(/\r?\n/).map(s=>s.trim()).filter(Boolean),bi=t=>!!t.success,zo=t=>(t.stdout||"").trim(),Ma=t=>(t.stderr||"").trim();async function jD(t){const r=((await Ds("git worktree list --porcelain",t)).stdout||"").split(/\r?\n/),n=[];let o=null;for(const a of r){if(a.startsWith("worktree ")){o&&n.push(o),o={path:a.slice(9).trim(),branchRef:null};continue}o&&a.startsWith("branch ")&&(o.branchRef=a.slice(7).trim())}return o&&n.push(o),n.filter(a=>!!a.path)}async function SD(t){const s=`refs/heads/${t.targetBranch}`,r=new Set(t.excludePaths),o=(await jD(t.repoRoot)).filter(l=>l.branchRef===s).map(l=>l.path).filter(l=>l&&!r.has(l)),a=[];for(const l of o){const c=await Ds("git status --porcelain",l);zo(c)||a.push(l)}return a}async function Zy(t,s){for(const r of s)await Ds("git reset --hard",r).catch(()=>{})}async function ND(t,s){const r=s.trim();if(!r||r==="HEAD")return"HEAD";const n=await Ds(`git show-ref --verify --quiet ${Pr(`refs/heads/${r}`)} && echo ok || echo missing`,t);if(zo(n)==="ok")return r;if(r.startsWith("remotes/")){const l=r.slice(8).split("/"),c=l[0]||"origin",d=l.slice(1).join("/");if(d)return await Ds(`git branch --track ${Pr(d)} ${Pr(`${c}/${d}`)}`,t),d}const o=await Ds(`git show-ref --verify --quiet ${Pr(`refs/remotes/origin/${r}`)} && echo ok || echo missing`,t);return zo(o)==="ok"&&await Ds(`git branch --track ${Pr(r)} ${Pr(`origin/${r}`)}`,t),r}async function Ga(t){const s=t.repoRoot,r=t.sourceBranch.trim(),n=t.targetBranch.trim();if(!r||!n)return{repoRoot:s,sourceBranch:r,targetBranch:n,commits:[]};const o=await ND(s,n),a=await Ds(`git cherry ${Pr(o)} ${Pr(r)}`,s),l=Ca(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 Ds(`git rev-list --reverse ${Pr(`${o}..${r}`)}`,s),m=Ca(d.stdout).filter(f=>c.has(f));return{repoRoot:s,sourceBranch:r,targetBranch:o,commits:m}}async function kD(t,s){const r=await Ds('mkdir -p "$HOME/.config/ikanban/tmp" && mktemp -d "$HOME/.config/ikanban/tmp/oc-integrate-XXXXXX"',t),n=zo(r);if(!n)throw new Error(Ma(r)||"Failed to create temp directory");const o=await Ds(`git worktree add --force ${Pr(n)} ${Pr(s)}`,t);if(!bi(o))throw new Error(Ma(o)||"Failed to create temp worktree");return n}async function Jl(t,s){await Ds(`git worktree remove --force ${Pr(s)}`,t).catch(()=>{}),await Ds("git worktree prune",t).catch(()=>{})}async function CD(t){const s=await Ds("git rev-parse --abbrev-ref --symbolic-full-name @{u}",t),r=zo(s);if(!r)return;await Ds("git fetch",t);const n=await Ds(`git merge --ff-only ${Pr(r)}`,t);if(!bi(n))throw new Error(Ma(n)||"Fast-forward failed")}async function Xl(t){const s=await Ds("git status --porcelain",t),r=await Ds("git diff --name-only --diff-filter=U",t),n=await Ds("git diff",t),o=await Ds("git show --no-patch --pretty=fuller CHERRY_PICK_HEAD",t),a=await Ds("git show CHERRY_PICK_HEAD",t);return{statusPorcelain:s.stdout||"",unmergedFiles:Ca(r.stdout),diff:n.stdout||n.stderr||"",currentPatchMeta:o.stdout||o.stderr||"",currentPatch:a.stdout||a.stderr||""}}async function MD(t){return Xl(t)}async function AD(t){const s=await Ds("git rev-parse --verify --quiet CHERRY_PICK_HEAD && echo yes || echo no",t);return zo(s)==="yes"}async function DD(t){if(t.commits.length===0)return{kind:"noop",reason:"No commits to move"};const s=await kD(t.repoRoot,t.targetBranch);let r=[];try{await CD(s);const n=await Ds("git status --porcelain",s);if(zo(n))throw new Error("Target branch has local changes; abort integration and retry");const o=await SD({repoRoot:t.repoRoot,targetBranch:t.targetBranch,excludePaths:[s]}).catch(()=>[]);for(r=[...t.commits];r.length>0;){const a=r[0],l=await Ds(`git cherry-pick ${Pr(a)}`,s);if(bi(l)){r.shift();continue}const c=await Ds("git diff --name-only --diff-filter=U",s);if(Ca(c.stdout).length>0){const u=await Xl(s);return{kind:"conflict",state:{repoRoot:t.repoRoot,tempWorktreePath:s,sourceBranch:t.sourceBranch,targetBranch:t.targetBranch,cleanTargetWorktrees:o,remainingCommits:r,currentCommit:a},details:u}}throw new Error(Ma(l)||"Cherry-pick failed")}return await Jl(t.repoRoot,s),await Zy(t.repoRoot,o).catch(()=>{}),{kind:"success",moved:t.commits.length}}catch(n){throw await Jl(t.repoRoot,s).catch(()=>{}),n}}async function ID(t){await Ds("git cherry-pick --abort",t.tempWorktreePath).catch(()=>{}),await Jl(t.repoRoot,t.tempWorktreePath)}async function TD(t){const s=await Ds("git cherry-pick --continue",t.tempWorktreePath);if(!bi(s)){const a=await Ds("git diff --name-only --diff-filter=U",t.tempWorktreePath);if(Ca(a.stdout).length>0){const c=await Xl(t.tempWorktreePath);return{kind:"conflict",state:t,details:c}}throw new Error(Ma(s)||"Cherry-pick continue failed")}const r=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 Ds(`git cherry-pick ${Pr(a)}`,r);if(bi(l)){o.shift();continue}const c=await Ds("git diff --name-only --diff-filter=U",r);if(Ca(c.stdout).length>0){const u=await Xl(r);return{kind:"conflict",state:{repoRoot:t.repoRoot,tempWorktreePath:r,sourceBranch:t.sourceBranch,targetBranch:t.targetBranch,cleanTargetWorktrees:t.cleanTargetWorktrees,remainingCommits:o,currentCommit:a},details:u}}throw new Error(Ma(l)||"Cherry-pick failed")}return await Jl(t.repoRoot,t.tempWorktreePath),await Zy(t.repoRoot,t.cleanTargetWorktrees).catch(()=>{}),{kind:"success",moved:n.length}}const ED=({repoRoot:t,sourceBranch:s,worktreeMetadata:r,localBranches:n,defaultTargetBranch:o,refreshKey:a,onRefresh:l,variant:c="framed"})=>{const d=Ae(I=>I.currentSessionId),u=Te(I=>I.setActiveMainTab),[m,f]=ne.useState(!1),p=ne.useRef(null),[h,g]=ne.useState(o);ne.useEffect(()=>{g(o)},[o]),ne.useEffect(()=>{if(m){const I=setTimeout(()=>{p.current?.focus()},0);return()=>clearTimeout(I)}},[m]);const x=!!(t&&s&&h&&h!=="HEAD"&&s!==h),[y,b]=ne.useState({kind:"idle"}),[v,j]=ne.useState(!1),[k,N]=ne.useState([]),w=ne.useMemo(()=>d?`ikanban.integrate.conflict:${d}`:null,[d]);ne.useEffect(()=>{if(!w||typeof window>"u")return;const I=window.localStorage.getItem(w);if(I)try{const E=JSON.parse(I);if(!E?.tempWorktreePath||E.repoRoot!==t){window.localStorage.removeItem(w);return}(async()=>{if(!await AD(E.tempWorktreePath).catch(()=>!1)){window.localStorage.removeItem(w);return}const V=await MD(E.tempWorktreePath).catch(()=>null);V&&b({kind:"conflict",state:E,details:V})})()}catch{window.localStorage.removeItem(w)}},[w,t]),ne.useEffect(()=>{if(!x){b({kind:"idle"});return}let I=!1;return b({kind:"loading"}),(async()=>{try{const E=await Ga({repoRoot:t,sourceBranch:s,targetBranch:h});if(I)return;if(b({kind:"ready",plan:E}),E.commits.length>0){const ve=E.commits.slice(-50).reverse().map(Q=>JSON.stringify(Q)).join(" "),Z=((await Ds(`git show -s --format=%H%x09%h%x09%s ${ve}`,t)).stdout||"").split(/\r?\n/).filter(Boolean),ce=[];for(const Q of Z){const[Y,ie,B]=Q.split(" ");!Y||!ie||ce.push({sha:Y,short:ie,subject:B||""})}I||(N(ce),j(!1))}else I||(N([]),j(!1))}catch{I||b({kind:"idle"})}})(),()=>{I=!0}},[x,t,s,h,a]);const C=ne.useCallback(I=>{d&&Ae.getState().setWorktreeMetadata(d,{...r,createdFromBranch:I})},[d,r]),S=Ae(I=>I.openNewSessionDraft),M=ne.useCallback(I=>{const E=`Resolve cherry-pick conflicts, stage the resolved files, and continue the cherry-pick. Keep intent of commit ${I.state.currentCommit} onto branch ${I.state.targetBranch}.`,W=`Worktree commit integration (cherry-pick) is in progress with conflicts.
|
|
216
|
+
- Repo root: ${I.state.repoRoot}
|
|
217
|
+
- Temp target worktree: ${I.state.tempWorktreePath}
|
|
218
|
+
- Source branch: ${I.state.sourceBranch}
|
|
219
|
+
- Target branch: ${I.state.targetBranch}
|
|
220
|
+
- Current commit: ${I.state.currentCommit}
|
|
221
|
+
|
|
222
|
+
Required steps:
|
|
223
|
+
1. Read each conflicted file in the temp worktree to understand the conflict markers (<<<<<<< HEAD, =======, >>>>>>> ...)
|
|
224
|
+
2. Edit each file to resolve conflicts by choosing the correct code or merging both changes appropriately
|
|
225
|
+
3. Stage all resolved files with: git add <file>
|
|
226
|
+
4. Complete the cherry-pick with: git cherry-pick --continue
|
|
227
|
+
|
|
228
|
+
Important:
|
|
229
|
+
- Work inside the temp worktree directory: ${I.state.tempWorktreePath}
|
|
230
|
+
- Remove ALL conflict markers from files (<<<<<<< HEAD, =======, >>>>>>>)
|
|
231
|
+
- Preserve the intent of the commit being applied
|
|
232
|
+
- Make sure the final code is syntactically correct
|
|
233
|
+
- Do not leave any files with unresolved conflict markers
|
|
234
|
+
- After completing all steps, confirm the cherry-pick was successful
|
|
235
|
+
`,V=`Cherry-pick conflict context (JSON)
|
|
236
|
+
${JSON.stringify({repoRoot:I.state.repoRoot,tempWorktreePath:I.state.tempWorktreePath,sourceBranch:I.state.sourceBranch,targetBranch:I.state.targetBranch,currentCommit:I.state.currentCommit,remainingCommits:I.state.remainingCommits,statusPorcelain:I.details.statusPorcelain,unmergedFiles:I.details.unmergedFiles,currentPatchMeta:I.details.currentPatchMeta,currentPatch:I.details.currentPatch,diff:I.details.diff},null,2)}`;return{visibleText:E,instructionsText:W,payloadText:V}},[]),D=Ae(I=>I.setPendingInputText),A=Ae(I=>I.setPendingSyntheticParts),P=ne.useCallback((I,E)=>{const W=M(I);if(E){S({directoryOverride:I.state.tempWorktreePath,initialPrompt:W.visibleText,syntheticParts:[{text:W.instructionsText,synthetic:!0},{text:W.payloadText,synthetic:!0}]}),u("chat");return}if(!d){K.error("No active session",{description:"Open a chat session first or start a new session."});return}D(W.visibleText,"replace"),A([{text:W.instructionsText,synthetic:!0},{text:W.payloadText,synthetic:!0}]),u("chat")},[d,u,M,S,D,A]),$=ne.useCallback(async()=>{if(y.kind==="ready"){if(y.plan.commits.length===0){K.message("No commits to move");return}b({kind:"running",plan:y.plan});try{const I=await DD(y.plan);if(I.kind==="success"){K.success("Commits moved",{description:`${I.moved} commit${I.moved===1?"":"s"} into ${y.plan.targetBranch}`});const E=await Ga(y.plan);b({kind:"ready",plan:E}),l?.();return}I.kind==="conflict"&&(K.error("Cherry-pick conflict",{description:"Resolve conflicts, then continue."}),b({kind:"conflict",state:I.state,details:I.details}),w&&typeof window<"u"&&window.localStorage.setItem(w,JSON.stringify(I.state)))}catch(I){const E=I instanceof Error?I.message:String(I);K.error("Failed to move commits",{description:E});const W=await Ga({repoRoot:t,sourceBranch:s,targetBranch:h}).catch(()=>null);b(W?{kind:"ready",plan:W}:{kind:"idle"})}}},[y,l,t,s,h,w]),R=ne.useCallback(async()=>{if(y.kind==="conflict")try{await ID(y.state),K.message("Cherry-pick aborted"),w&&typeof window<"u"&&window.localStorage.removeItem(w)}finally{const I=await Ga({repoRoot:t,sourceBranch:s,targetBranch:h}).catch(()=>null);b(I?{kind:"ready",plan:I}:{kind:"idle"})}},[y,t,s,h,w]),O=ne.useCallback(async()=>{if(y.kind==="conflict")try{const I=await TD(y.state);if(I.kind==="success"){K.success("Cherry-pick finished");const E=await Ga({repoRoot:t,sourceBranch:s,targetBranch:h}).catch(()=>null);b(E?{kind:"ready",plan:E}:{kind:"idle"}),w&&typeof window<"u"&&window.localStorage.removeItem(w),l?.();return}I.kind==="conflict"&&(b({kind:"conflict",state:I.state,details:I.details}),w&&typeof window<"u"&&window.localStorage.setItem(w,JSON.stringify(I.state)))}catch(I){const E=I instanceof Error?I.message:String(I);K.error("Cherry-pick continue failed",{description:E})}},[y,t,s,h,l,w]);if(!t||!s)return null;const T=c==="framed"?"rounded-xl border border-border/60 bg-background/70 overflow-hidden":"border-0 bg-transparent rounded-none",_=c==="framed"?"px-3 py-2 border-b border-border/40 flex items-center justify-between gap-2":"px-0 py-3 border-b border-border/40 flex items-center justify-between gap-2",F=c==="framed"?"flex flex-col gap-3 p-3":"flex flex-col gap-3 py-3";return e.jsxs("section",{className:T,children:[e.jsxs("div",{className:_,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Cg,{className:"size-4 text-muted-foreground"}),e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:"Re-integrate commits"}),y.kind==="ready"&&y.plan.commits.length>0?e.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:[y.plan.commits.length," to move"]}):null]}),e.jsx("div",{className:"flex items-center gap-2",children:y.kind==="loading"||y.kind==="running"?e.jsx(Ot,{className:"size-4 animate-spin text-muted-foreground"}):null})]}),e.jsxs("div",{className:F,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:[s," → ",h]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(us,{open:m,onOpenChange:f,children:[e.jsx(ms,{asChild:!0,children:e.jsxs(Me,{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:h}),e.jsx(is,{className:"size-4 opacity-60"})]})}),e.jsx(fs,{align:"end",className:"w-72 p-0 max-h-(--radix-dropdown-menu-content-available-height) flex flex-col overflow-hidden",children:e.jsxs(Mi,{className:"h-full min-h-0",children:[e.jsx(Ea,{ref:p,placeholder:"Search branches..."}),e.jsxs(Ai,{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(hn,{heading:"Local branches",children:n.map(I=>e.jsx(Qs,{value:I,onSelect:()=>{g(I),C(I),f(!1)},children:I},I))})]})]})})]}),y.kind==="ready"?e.jsx(Me,{size:"sm",onClick:()=>{$()},disabled:!x||y.plan.commits.length===0,children:"Move"}):y.kind==="loading"?e.jsx(Me,{size:"sm",variant:"outline",disabled:!0,children:"Checking…"}):y.kind==="running"?e.jsx(Me,{size:"sm",variant:"outline",disabled:!0,children:"Moving…"}):null]}),y.kind==="ready"&&y.plan.commits.length===0&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:"No commits to move."}),y.kind==="ready"&&y.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:[" (",y.plan.commits.length,")"]})]}),k.length>0&&y.plan.commits.length>5&&e.jsx("button",{type:"button",onClick:()=>j(I=>!I),className:"typography-micro text-muted-foreground hover:text-foreground",children:v?"Show less":"Show all"})]}),e.jsxs("div",{className:"space-y-1",children:[(v?k:k.slice(0,5)).map(I=>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:I.short}),e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:I.subject||I.sha})]},I.sha)),k.length===0&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Preview unavailable."}),y.plan.commits.length>k.length&&e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["Showing first ",k.length," commits."]})]})]}),y.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 ",y.details.unmergedFiles.length," files"]}),e.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:["Current commit: ",e.jsx("span",{className:"font-mono",children:y.state.currentCommit.slice(0,7)})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.details.unmergedFiles.slice(0,6).map(I=>e.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:I},I)),y.details.unmergedFiles.length>6&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",y.details.unmergedFiles.length-6," more"]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(Me,{size:"sm",variant:"ghost",className:"h-7 px-2 py-0 typography-meta",onClick:()=>{R()},children:"Abort"}),e.jsxs(Me,{size:"sm",variant:"secondary",className:"h-7 px-2 py-0 typography-meta gap-1",disabled:!d,onClick:()=>{P({state:y.state,details:y.details},!1)},children:[e.jsx(Ud,{className:"size-3.5"}),"Current Session"]}),e.jsxs(Me,{size:"sm",variant:"secondary",className:"h-7 px-2 py-0 typography-meta gap-1",onClick:()=>{P({state:y.state,details:y.details},!0)},children:[e.jsx(Ud,{className:"size-3.5"}),"New Session"]}),e.jsx(Me,{size:"sm",className:"h-7 px-2 py-0 typography-meta",onClick:()=>{O()},children:"Continue"})]})]})]})]})},PD=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Jp=({currentBranch:t,localBranches:s,remoteBranches:r,branchInfo:n,onCheckout:o,onCreate:a,remotes:l=[],disabled:c=!1,tooltipDelayMs:d=1e3})=>{const[u,m]=i.useState(!1),[f,p]=i.useState(""),[h,g]=i.useState(!1),[x,y]=i.useState(!1),[b,v]=i.useState(""),[j,k]=i.useState(!1),N=i.useRef(null),w=l.length>1,C=i.useMemo(()=>PD(b),[b]),S=i.useMemo(()=>{const T=f.toLowerCase();return T?s.filter(_=>_.toLowerCase().includes(T)):s},[f,s]),M=i.useMemo(()=>{const T=f.toLowerCase();return T?r.filter(_=>_.toLowerCase().includes(T)):r},[f,r]),D=T=>{if(T===t){m(!1);return}o(T),m(!1),p("")},A=()=>{g(!0),setTimeout(()=>N.current?.focus(),50)},P=async()=>{if(!(!C||j)){if(w){y(!0);return}k(!0);try{await a(C,l[0]),v(""),g(!1),m(!1)}finally{k(!1)}}},$=async T=>{if(!(!C||j)){k(!0);try{await a(C,T),v(""),g(!1),y(!1),m(!1)}finally{k(!1)}}},R=()=>{y(!1)},O=()=>{v(""),g(!1),y(!1)};return i.useEffect(()=>{u||(p(""),g(!1),y(!1),v(""))},[u]),e.jsxs(us,{open:u,onOpenChange:m,children:[e.jsxs(gt,{delayDuration:d,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:e.jsxs(Me,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[e.jsx(Ms,{className:"size-4 text-primary"}),e.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:t||"Detached HEAD"}),e.jsx(is,{className:"size-4 opacity-60"})]})})}),e.jsx(ht,{sideOffset:8,children:"Current branch"})]}),e.jsx(fs,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Mi,{className:"h-full min-h-0",children:[e.jsx(Ea,{placeholder:"Search branches...",value:f,onValueChange:p}),e.jsxs(Ai,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Di,{children:"No branches found."}),e.jsx(hn,{children:x?e.jsxs("div",{className:"px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{type:"button",onClick:R,disabled:j,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Mu,{className:"size-4"})}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push ",e.jsx("span",{className:"text-foreground font-medium",children:C})," to:"]})]}),e.jsx("div",{className:"flex flex-col gap-1",children:l.map(T=>e.jsxs("button",{type:"button",onClick:()=>$(T),disabled:j,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[e.jsxs("span",{className:"typography-ui-label text-foreground",children:[j?e.jsx(Ot,{className:"inline size-3 mr-1.5 animate-spin"}):null,T.name]}),e.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:T.pushUrl})]},T.name))})]}):h?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:N,placeholder:"New branch name",value:b,onChange:T=>v(T.target.value),onKeyDown:T=>{T.key==="Enter"?(T.preventDefault(),P()):T.key==="Escape"&&(T.preventDefault(),O())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:P,disabled:!C||j,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:j?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(Fs,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:O,disabled:j,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(hs,{className:"size-4"})})]}):e.jsxs(Qs,{onSelect:A,children:[e.jsx(Fs,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(ya,{}),e.jsxs(hn,{heading:"Local branches",children:[S.map(T=>e.jsxs(Qs,{onSelect:()=>D(T),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:T}),(n?.[T]?.ahead||n?.[T]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[T].ahead||0," ahead ·"," ",n[T].behind||0," behind"]})]}),t===T&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${T}`)),S.length===0&&e.jsx(Qs,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(ya,{}),e.jsxs(hn,{heading:"Remote branches",children:[M.map(T=>e.jsx(Qs,{onSelect:()=>D(T),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:T})},`remote-${T}`)),M.length===0&&e.jsx(Qs,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},RD=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Xp=({currentBranch:t,onRename:s,showEditButton:r=!0})=>{const[n,o]=i.useState(!1),[a,l]=i.useState(t||""),[c,d]=i.useState(!1),u=i.useRef(null),m=()=>{!t||!s||(l(t),o(!0),setTimeout(()=>u.current?.focus(),0))},f=async()=>{if(!t||!s||!a.trim())return;const g=RD(a);if(g===t){o(!1);return}d(!0);try{await s(t,g),o(!1),l("")}finally{d(!1)}},p=()=>{o(!1),l("")},h=g=>{g.key==="Enter"?(g.preventDefault(),f()):g.key==="Escape"&&(g.preventDefault(),p())};return n?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:g=>{g.preventDefault(),f()},children:[e.jsx(Ms,{className:"size-4 text-primary"}),e.jsx("input",{ref:u,value:a,onChange:g=>l(g.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:h,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:c,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(ss,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:p,disabled:c,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(hs,{className:"size-4"})})]})}):e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[e.jsx(Ms,{className:"size-4 text-primary shrink-0"}),e.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:t||"Detached HEAD"}),r&&s&&t&&e.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:m,title:"Rename branch",children:e.jsx(go,{className:"size-4"})})]})]})},FD=({syncAction:t,remotes:s=[],onFetch:r,onPull:n,onPush:o,disabled:a,iconOnly:l=!1,tooltipDelayMs:c=1e3,aheadCount:d=0,behindCount:u=0})=>{const m=s.length===0,f=a||t!==null||m,p=s.length>1,h=()=>{const v=s[0];s.length===1&&v&&r(v)},g=()=>{const v=s[0];s.length===1&&v&&n(v)},x=()=>{s.length>=1&&o()},y=(v,j,k,N,w,C,S)=>{const M=e.jsxs(Me,{variant:"ghost",size:"sm",className:l?"relative h-8 w-8 px-0":"h-8 px-2",onClick:w,disabled:f,children:[t===v?k:j,!l&&e.jsx("span",{className:"git-header-label",children:N}),!l&&typeof S=="number"&&S>0?e.jsx("span",{className:"rounded-sm bg-interactive-selection/40 px-1 text-[10px] leading-4 text-foreground tabular-nums",children:S}):null,l&&typeof S=="number"&&S>0?e.jsx("span",{className:"absolute -right-1 -top-1 min-w-[1rem] rounded-full bg-interactive-selection px-1 text-[10px] leading-4 text-interactive-selection-foreground tabular-nums",children:S}):null]});return e.jsxs(gt,{delayDuration:c,children:[e.jsx(xt,{asChild:!0,children:M}),e.jsx(ht,{sideOffset:8,children:C})]})},b=(v,j,k,N,w,C,S)=>e.jsxs(us,{children:[e.jsxs(gt,{delayDuration:c,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:e.jsxs(Me,{variant:"ghost",size:"sm",className:l?"relative h-8 w-8 px-0":"h-8 px-2",disabled:f,children:[t===v?k:j,!l&&e.jsx("span",{className:"git-header-label",children:N}),!l&&typeof S=="number"&&S>0?e.jsx("span",{className:"rounded-sm bg-interactive-selection/40 px-1 text-[10px] leading-4 text-foreground tabular-nums",children:S}):null,l&&typeof S=="number"&&S>0?e.jsx("span",{className:"absolute -right-1 -top-1 min-w-[1rem] rounded-full bg-interactive-selection px-1 text-[10px] leading-4 text-interactive-selection-foreground tabular-nums",children:S}):null]})})}),e.jsx(ht,{sideOffset:8,children:C})]}),e.jsx(fs,{align:"start",className:"min-w-[200px]",children:s.map(M=>e.jsx(Et,{onSelect:()=>w(M),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:M.name}),e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:M.fetchUrl})]})},M.name))})]});return e.jsxs("div",{className:"flex items-center gap-0.5",children:[p?b("fetch",e.jsx(Mr,{className:"size-4"}),e.jsx(Ot,{className:"size-4 animate-spin"}),"Fetch",r,"Fetch from remote"):y("fetch",e.jsx(Mr,{className:"size-4"}),e.jsx(Ot,{className:"size-4 animate-spin"}),"Fetch",h,"Fetch from remote"),p?b("pull",e.jsx(va,{className:"size-4"}),e.jsx(Ot,{className:"size-4 animate-spin"}),"Pull",n,u>0?`Pull changes (${u} behind)`:"Pull changes",u):y("pull",e.jsx(va,{className:"size-4"}),e.jsx(Ot,{className:"size-4 animate-spin"}),"Pull",g,u>0?`Pull changes (${u} behind)`:"Pull changes",u),y("push",e.jsx(ii,{className:"size-4"}),e.jsx(Ot,{className:"size-4 animate-spin"}),"Push",x,d>0?`Push changes (${d} ahead)`:"Push changes",d)]})},LD={branch:Ms,briefcase:Iu,house:Du,graduation:Au,code:xn,heart:Ag,user:en},OD={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 eb(t){return t&&OD[t]||"var(--primary)"}const Zp=({icon:t,className:s,colorToken:r})=>{const n=LD[t??"branch"]??en;return e.jsx(n,{className:s,style:{color:eb(r)}})},_D=({activeProfile:t,identities:s,onSelect:r,isApplying:n,tooltipDelayMs:o=1e3,iconOnly:a=!1})=>{const l=n||s.length===0;return e.jsxs(us,{children:[e.jsxs(gt,{delayDuration:o,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ms,{asChild:!0,children:e.jsxs(Me,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:eb(t?.color)},disabled:l,children:[n?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(Zp,{icon:t?.icon,colorToken:t?.color,className:"size-4"}),!a&&e.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:t?.name||"No identity"}),e.jsx(is,{className:"size-4 opacity-60"})]})})}),e.jsx(ht,{sideOffset:8,children:"Git identity"})]}),e.jsx(fs,{align:"end",className:"w-64",children:s.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."})}):s.map(c=>{const d=t?.id===c.id;return e.jsx(Et,{onSelect:()=>r(c),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Zp,{icon:c.icon,colorToken:c.color,className:"size-4"}),e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:c.name}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:c.userEmail})]}),d?e.jsx(ss,{className:"ml-auto size-4 text-foreground"}):null]})},c.id)})})]})},$D=({status:t,localBranches:s,remoteBranches:r,branchInfo:n,syncAction:o,remotes:a,onFetch:l,onPull:c,onPush:d,onCheckoutBranch:u,onCreateBranch:m,onRenameBranch:f,activeIdentityProfile:p,availableIdentities:h,onSelectIdentity:g,isApplyingIdentity:x,isWorktreeMode:y,isSidebarMode:b=!1,onOpenHistory:v,onOpenBranchPicker:j})=>{const k=Te(M=>M.isMobile);if(!t)return null;const N=b||k,w=e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[j?e.jsxs(gt,{delayDuration:N?300:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsxs(Me,{variant:"ghost",size:"sm",className:b?"h-8 w-8 px-0":"gap-1.5 px-2 py-1 h-8 typography-ui-label",onClick:j,children:[e.jsx(Mg,{className:"size-4"}),!b&&e.jsx("span",{className:"git-header-label",children:"Manage branches"})]})}),e.jsx(ht,{sideOffset:8,children:"Manage branches"})]}):null,v?e.jsxs(gt,{delayDuration:N?300:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsxs(Me,{variant:"ghost",size:"sm",className:b?"h-8 w-8 px-0":"gap-1.5 px-2 py-1 h-8 typography-ui-label",onClick:v,children:[e.jsx(Qw,{className:"size-4"}),!b&&e.jsx("span",{className:"git-header-label",children:"History"})]})}),e.jsx(ht,{sideOffset:8,children:"History"})]}):null]}),C=e.jsx(FD,{syncAction:o,remotes:a,onFetch:l,onPull:c,onPush:d,disabled:!t,iconOnly:b,tooltipDelayMs:N?300:1e3,aheadCount:t.ahead,behindCount:t.behind}),S=e.jsx(_D,{activeProfile:p,identities:h,onSelect:g,isApplying:x,tooltipDelayMs:N?300:1e3,iconOnly:!1});return N?e.jsxs("header",{className:"@container/git-header border-b border-border/40 px-3 py-2 bg-background",children:[e.jsx("div",{className:"flex items-center justify-between gap-2 min-w-0",children:e.jsx("div",{className:"min-w-0 flex-1",children:y?e.jsx(Xp,{currentBranch:t.current,onRename:f}):e.jsx(Jp,{currentBranch:t.current,localBranches:s,remoteBranches:r,branchInfo:n,onCheckout:u,onCreate:m,remotes:a,tooltipDelayMs:N?300:1e3})})}),e.jsxs("div",{className:"mt-1.5 flex items-center justify-between gap-2 min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:[C,w]}),e.jsx("div",{className:"min-w-0 max-w-[45%]",children:S})]})]}):e.jsxs("header",{className:"@container/git-header flex items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[y?e.jsx(Xp,{currentBranch:t.current,onRename:f}):e.jsx(Jp,{currentBranch:t.current,localBranches:s,remoteBranches:r,branchInfo:n,onCheckout:u,onCreate:m,remotes:a}),e.jsx("div",{className:"shrink-0",children:C})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[w,S]})]})},tb={"?":{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"}},BD=tb.M;function zD(t){const s=t.index?.trim(),r=t.working_dir?.trim();return s&&s!=="?"?s.charAt(0):r?r.charAt(0):s?.charAt(0)||r?.charAt(0)||"M"}function UD(t){const s=zD(t);return tb[s]??BD}const HD=i.memo(function({file:s,checked:r,onToggle:n,onViewDiff:o,onRevert:a,isReverting:l,stats:c}){const d=ne.useMemo(()=>UD(s),[s]),u=d.description,m=c?.insertions??0,f=c?.deletions??0,p=ne.useCallback(x=>{x.key===" "?(x.preventDefault(),n()):x.key==="Enter"&&(x.preventDefault(),o())},[n,o]),h=ne.useCallback(x=>{x.preventDefault(),x.stopPropagation(),n()},[n]),g=ne.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":r,"aria-label":`Select ${s.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:r?e.jsx(Kn,{className:"size-4 text-primary"}):e.jsx(qn,{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:s.path,children:s.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(gt,{delayDuration:200,children:[e.jsx(xt,{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 ${s.path}`,children:l?e.jsx(Ot,{className:"size-3.5 animate-spin"}):e.jsx(Oo,{className:"size-3.5"})})}),e.jsx(ht,{sideOffset:8,children:"Revert changes"})]})]})})}),VD=({changeEntries:t,selectedPaths:s,diffStats:r,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:l,onViewDiff:c,onRevertFile:d,variant:u="framed",maxListHeightClassName:m})=>{const f=i.useRef(null),p=s.size,h=t.length,g=u==="framed"?"flex flex-col rounded-xl border border-border/60 bg-background/70":"flex flex-col flex-1 min-h-0",x=u==="framed"?"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40":"flex items-center justify-between gap-2 px-4 py-3 border-b border-border/40",y=u==="framed"?"flex-1 min-h-0 max-h-[30vh]":`flex-1 min-h-0 ${m??""}`.trim();return e.jsxs("section",{className:g,children:[e.jsxs("header",{className:x,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:[p,"/",h]}),h>0&&e.jsxs(e.Fragment,{children:[e.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:l,disabled:p===0,children:"None"})]})]})]}),e.jsxs("div",{className:L("relative flex flex-col min-h-0 w-full overflow-hidden",y),children:[e.jsx(Ti,{ref:f,className:"overlay-scrollbar-target overlay-scrollbar-container flex-1 min-h-0 w-full overflow-y-auto overflow-x-hidden",children:e.jsx("ul",{className:"divide-y divide-border/60",children:t.map(b=>e.jsx(HD,{file:b,checked:s.has(b.path),stats:r?.[b.path],onToggle:()=>o(b.path),onViewDiff:()=>c(b.path),onRevert:()=>d(b.path),isReverting:n.has(b.path)},b.path))})}),e.jsx(pc,{containerRef:f,disableHorizontal:!0})]})]})};function bn({className:t,variant:s,...r}){return e.jsx(Me,{variant:s,size:"sm",className:L("h-7 px-2 py-0",t),...r})}const fd=38,eh=200,WD=({value:t,onChange:s,placeholder:r="Commit message",disabled:n=!1,hasTouchInput:o=!1})=>{const a=i.useRef(null);return i.useEffect(()=>{const l=a.current;if(!l)return;l.style.height=`${fd}px`;const c=Math.min(Math.max(l.scrollHeight,fd),eh);l.style.height=`${c}px`},[t]),e.jsx(hr,{ref:a,value:t,onChange:l=>s(l.target.value),placeholder:r,rows:1,disabled:n,autoCorrect:o?"on":"off",autoCapitalize:o?"sentences":"off",spellCheck:!!o,className:L("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:fd,maxHeight:eh}})},GD=({highlights:t,onInsert:s,onClear:r})=>{if(t.length===0)return null;const n=()=>{s(),r()};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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(va,{className:"size-4"})})}),e.jsx(ht,{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))})]})},KD=({selectedCount:t,commitMessage:s,onCommitMessageChange:r,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:l,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f,gitmojiEnabled:p,onOpenGitmojiPicker:h,variant:g="framed"})=>{const x=t>0,y=s.trim()&&x&&m===null,{isMobile:b,hasTouchInput:v}=ks(),j=g==="framed"?"rounded-xl border border-border/60 bg-background/70 overflow-hidden":"border-0 bg-transparent rounded-none",k=g==="framed"?"flex w-full items-center justify-between px-3 py-2":"flex w-full items-center justify-between px-4 py-3 border-b border-border/40",N=g==="framed"?"flex flex-col gap-3 p-3 pt-0":"flex flex-col gap-3 px-4 py-3";return e.jsxs(tn,{open:g==="plain"?!0:x,className:j,"data-keyboard-avoid":"true",children:[e.jsxs("div",{className:k,children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:x?`${t} file${t===1?"":"s"} selected`:"No files selected"})]}),e.jsx(sn,{children:e.jsxs("div",{className:N,children:[x?null:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select files in Changes to enable commit."}),e.jsx(GD,{highlights:n,onInsert:o,onClear:a}),e.jsx(WD,{value:s,onChange:r,placeholder:"Commit message",disabled:m!==null,hasTouchInput:v}),p&&e.jsxs(Me,{variant:"outline",size:"sm",onClick:h,className:"w-fit",type:"button",children:[e.jsx(Yw,{className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"@container/commit-actions flex items-center gap-2 min-w-0",children:[e.jsxs(Me,{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(Ot,{className:"size-4 animate-spin"}):e.jsx(Ja,{className:"size-4 text-primary"}),e.jsx("span",{className:"commit-actions__label",children:"Generate"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(bn,{variant:"outline",onClick:d,disabled:!y||c,className:"commit-actions__btn whitespace-nowrap","aria-label":"Commit",children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"size-4 animate-spin"}),e.jsx("span",{className:"commit-actions__label",children:"Committing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(ec,{className:"size-4"}),e.jsx("span",{className:"commit-actions__label",children:"Commit"})]})}),b?e.jsxs(gt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"default",size:"sm",onClick:()=>u(),disabled:!y||c,className:"h-7 w-7 p-0","aria-label":"Commit & Push",children:m==="commitAndPush"?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(ii,{className:"size-4"})})}),e.jsx(ht,{side:"top",children:e.jsx("p",{children:"Commit & Push"})})]}):e.jsx(bn,{variant:"default",onClick:()=>u(),disabled:!y||c,className:"commit-actions__btn","aria-label":"Commit & Push",children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{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(ii,{className:"size-4"}),e.jsx("span",{className:"commit-actions__label commit-actions__label--long",children:"Commit & Push"})]})})]})]})})]})},qD=({behind:t,onPull:s,isPulling:r})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[e.jsx(ec,{className:"size-10 text-muted-foreground/70 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(Me,{variant:"outline",onClick:s,disabled:r,children:[r?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(va,{className:"size-4"}),"Pull ",t," commit",t===1?"":"s"]})]});function th(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function QD(t){switch(t){case"A":return"text-[var(--status-success)]";case"D":return"text-[var(--status-error)]";case"M":return"text-[var(--status-warning)]";case"R":return"text-[var(--status-info)]";default:return"text-muted-foreground"}}const YD=({entry:t,isExpanded:s,onToggle:r,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:r,className:L("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",s?"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:th(t.date),children:th(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(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:l=>{l.stopPropagation(),a(t.hash)},children:e.jsx(Hr,{className:"size-3"})})}),e.jsx(ht,{sideOffset:8,children:"Copy SHA"})]})]})]})]}),s&&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(Ot,{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",QD(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))})})]}),JD=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],XD=({log:t,isLogLoading:s,logMaxCount:r,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:l,loadingCommitHashes:c,onCopyHash:d,showHeader:u=!0})=>{const[m,f]=i.useState(!0);if(!t)return null;const p=e.jsx(Ut,{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(h=>e.jsx(YD,{entry:h,isExpanded:o.has(h.hash),onToggle:()=>a(h.hash),files:l.get(h.hash)??[],isLoadingFiles:c.has(h.hash),onCopyHash:d},h.hash))})});return u?e.jsxs(tn,{open:m,onOpenChange:f,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(On,{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:[m&&e.jsx("div",{onClick:h=>h.stopPropagation(),onPointerDown:h=>h.stopPropagation(),children:e.jsxs($s,{value:String(r),onValueChange:h=>n(Number(h)),disabled:s,children:[e.jsx(Bs,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:s,children:e.jsx(Sr,{placeholder:"Commits"})}),e.jsx(zs,{children:JD.map(h=>e.jsx(ns,{value:String(h.value),children:h.label},h.value))})]})}),m?e.jsx(vi,{className:"size-4 text-muted-foreground"}):e.jsx(is,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(sn,{children:p})]}):e.jsx("section",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:p})},ZD=9e4,eI=3e4,tI=5*6e4,sI=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"}},rI=t=>{const s=t?.pr;if(!s)return null;if(s.state==="merged")return"merged";if(s.state==="closed")return"closed";if(s.draft)return"draft";const r=t?.checks?.state==="failure",n=t?.canMerge===!1||s.mergeable===!1;return r||n?"blocked":"open"},sh=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,s=>s.toUpperCase()),to=t=>{let s=t.trim();return s?(s.startsWith("refs/heads/")&&(s=s.slice(11)),s.startsWith("heads/")&&(s=s.slice(6)),s.startsWith("remotes/")&&(s=s.slice(8)),s):""},nI=(t,s)=>{const r=to(t);if(!r||r.includes("->"))return"";if(s){const o=`${s}/`;return r.startsWith(o)?r.slice(o.length).trim():""}const n=r.indexOf("/");return n>0?r.slice(n+1).trim():r},oI=(t,s)=>`${t}::${s}`,pd=new Map,hd=new Map,gd=async t=>{if(typeof window>"u")return;const s=window.__TAURI__;if(s?.shell?.open)try{await s.shell.open(t);return}catch{}try{window.open(t,"_blank","noopener,noreferrer")}catch{}},aI=({directory:t,branch:s,baseBranch:r,remotes:n=[],remoteBranches:o=[],variant:a="framed",onGeneratedDescription:l})=>{const{github:c}=Vr(),d=$r(Ie=>Ie.status),u=$r(Ie=>Ie.hasChecked),m=Te(Ie=>Ie.setSettingsDialogOpen),f=Te(Ie=>Ie.setSidebarSection),p=Te(Ie=>Ie.setActiveMainTab),h=Ae(Ie=>Ie.currentSessionId),{isMobile:g,hasTouchInput:x}=ks(),y=i.useCallback(()=>{f("settings"),m(!0)},[m,f]),b=i.useMemo(()=>oI(t,s),[t,s]),v=i.useMemo(()=>pd.get(b)??null,[b]),j=i.useMemo(()=>hd.get(b)??null,[b]),[k,N]=i.useState(!1),[w,C]=i.useState(()=>j),[S,M]=i.useState(null),[D,A]=i.useState(()=>!!j),[P,$]=i.useState(()=>v?.title??sh(s)),[R,O]=i.useState(()=>v?.body??""),[T,_]=i.useState(()=>v?.draft??!1),[F,I]=i.useState(()=>v?.additionalContext??""),[E,W]=i.useState(()=>{const Ie=typeof v?.targetBaseBranch=="string"?to(v.targetBaseBranch):"";return Ie||to(r)}),[V,ve]=i.useState("squash"),[oe,Z]=i.useState(!1),[ce,Q]=i.useState(!1),[Y,ie]=i.useState(!1),[B,se]=i.useState(!1),[H,le]=i.useState(!1),[ge,z]=i.useState(!1),[J,je]=i.useState(null),[X,G]=i.useState(""),[ae,me]=i.useState(""),[Oe,Be]=i.useState(!1),[fe,q]=i.useState(!1),[ye,he]=i.useState(()=>n[0]??null),He=i.useMemo(()=>{const Ie=ye?.name?.trim()||null,Ge=new Set;for(const Kt of o){const It=nI(Kt,Ie);!It||It==="HEAD"||Ge.add(It)}const At=to(r);At&&At!=="HEAD"&&Ge.add(At);const it=to(E);return it&&it!=="HEAD"&&Ge.add(it),Array.from(Ge).sort((Kt,It)=>Kt.localeCompare(It))},[r,o,ye?.name,E]),ot=n.length>1;i.useEffect(()=>{n.length>0&&!ye&&he(n[0])},[n,ye]),i.useEffect(()=>{const Ie=to(r);if(!E&&Ie){W(Ie);return}if(He.length!==0&&!He.includes(E)){const Ge=He.includes(Ie)?Ie:He[0];Ge&&W(Ge)}},[He,r,E]);const[ue,Ve]=i.useState(!1),[De,we]=i.useState(null),[Fe,Pe]=i.useState(!1),[$e,Ze]=i.useState(new Set),[Ue,Ee]=i.useState(!1),[Re,Xe]=i.useState(null),[st,St]=i.useState(!1),mt=i.useRef(!1),Tt=i.useRef(0),qt=i.useRef(0),yt=i.useRef(null),os=i.useRef(new Set),cs=i.useRef(null),ds=!!(t&&s&&r&&s!==r),de=w?.pr??null,ke=de?`${t}#${de.number}`:null,We=!!(ke&&J===ke);i.useEffect(()=>{if(!c?.prContext||!de||typeof de.body=="string"&&de.body.length>0)return;const Ie=`${t}#${de.number}`;if(os.current.has(Ie))return;os.current.add(Ie),je(Ie);let Ge=!1;return c.prContext(t,de.number,{includeDiff:!1,includeCheckDetails:!1}).then(At=>{if(Ge)return;const it=At?.pr;it&&C(Kt=>!Kt?.pr||Kt.pr.number!==de.number?Kt:{...Kt,pr:{...Kt.pr,body:it.body||""}})}).catch(()=>{}).finally(()=>{Ge||je(At=>At===Ie?null:At)}),()=>{Ge=!0}},[t,c,de]),i.useEffect(()=>{if(!de){z(!1),G(""),me(""),cs.current=null;return}const Ie=cs.current!==null&&cs.current!==de.number;Ie&&z(!1),(!ge||Ie)&&(G(de.title||""),me(de.body||"")),cs.current=de.number},[ge,de]);const qe=i.useCallback(async()=>{if(!c?.prContext){K.error("GitHub runtime API unavailable");return}if(de){Ve(!0),Ze(new Set),Pe(!0);try{const Ie=await c.prContext(t,de.number,{includeDiff:!1,includeCheckDetails:!0});we(Ie)}catch(Ie){const Ge=Ie instanceof Error?Ie.message:String(Ie);K.error("Failed to load check details",{description:Ge})}finally{Pe(!1)}}},[t,c,de]),et=i.useCallback(async()=>{if(!c?.prContext){K.error("GitHub runtime API unavailable");return}if(de){Ee(!0),St(!0);try{const Ie=await c.prContext(t,de.number,{includeDiff:!1,includeCheckDetails:!1});Xe(Ie)}catch(Ie){const Ge=Ie instanceof Error?Ie.message:String(Ie);K.error("Failed to load comments",{description:Ge})}finally{St(!1)}}},[t,c,de]),ct=i.useCallback(Ie=>{if(!Ie)return"";const Ge=Date.parse(Ie);return Number.isFinite(Ge)?new Date(Ge).toLocaleString():Ie},[]),bt=i.useMemo(()=>{const Ie=d?.user?.login;return typeof Ie=="string"?Ie.trim():""},[d]),at=i.useMemo(()=>"[&_a[href*='oc-self-mention=1']]:!text-[var(--primary-base)] [&_a[href*='oc-self-mention=1']]:font-semibold [&_a[href*='oc-self-mention=1']]:!no-underline [&_a[href*='oc-self-mention=1']:hover]:!text-[var(--primary-hover)]",[]),_t=i.useCallback(Ie=>{const Ge=bt.toLowerCase(),At=/(^|[^\w`])@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,38}))/g;return Ie.replace(At,(it,Kt,It)=>{const Ps=`@${It}`,Hs=It.toLowerCase();return`${Kt}[${Ps}](https://github.com/${Hs}${Ge&&Hs===Ge?"?oc-self-mention=1":""})`})},[bt]),Nt=i.useMemo(()=>{const Ie=(Re?.issueComments??[]).map(it=>({id:`issue-${it.id}`,body:it.body||"",authorName:it.author?.name||it.author?.login||"Unknown author",authorLogin:it.author?.login||null,avatarUrl:it.author?.avatarUrl||null,createdAt:it.createdAt,context:"General comment",path:null,line:null})),Ge=(Re?.reviewComments??[]).map(it=>({id:`review-${it.id}`,body:it.body||"",authorName:it.author?.name||it.author?.login||"Unknown author",authorLogin:it.author?.login||null,avatarUrl:it.author?.avatarUrl||null,createdAt:it.createdAt,context:"Code review comment",path:it.path||null,line:it.line??null})),At=[...Ie,...Ge];return At.sort((it,Kt)=>{const It=it.createdAt?Date.parse(it.createdAt):0,Ps=Kt.createdAt?Date.parse(Kt.createdAt):0,Hs=Number.isFinite(It)?It:0,Es=Number.isFinite(Ps)?Ps:0;return Hs-Es}),At},[Re]),Gt=i.useCallback(()=>{if(!h)return K.error("No active session",{description:"Open a chat session first."}),null;const{currentProviderId:Ie,currentModelId:Ge,currentAgentName:At,currentVariant:it}=ut.getState(),Kt=rs.getState().lastUsedProvider,It=Ie||Kt?.providerID,Ps=Ge||Kt?.modelID;return!It||!Ps?(K.error("No model selected"),null):{sessionId:h,providerID:It,modelID:Ps,currentAgentName:At??null,currentVariant:it??null}},[h]),zt=i.useCallback((Ie,Ge,At,it)=>{rs.getState().sendMessage(Ge,Ie.providerID,Ie.modelID,Ie.currentAgentName??void 0,Ie.sessionId,void 0,null,[{text:At,synthetic:!0},{text:it,synthetic:!0}],Ie.currentVariant??void 0).catch(Kt=>{const It=Kt instanceof Error?Kt.message:String(Kt);K.error("Failed to send message",{description:It})})},[]),Ct=i.useCallback(Ie=>{const Ge=Ie.status||"unknown",At=Ie.conclusion??void 0,it=At?`${Ge} / ${At}`:Ge,Kt=Ie.app?.name||Ie.app?.slug;return e.jsxs("div",{className:"space-y-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:Ie.name}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:Kt?`${Kt} · ${it}`:it})]}),Ie.detailsUrl?e.jsx(Me,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:e.jsxs("a",{href:Ie.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"size-4"}),"Open"]})}):null]}),Ie.output?.title?e.jsx("div",{className:"typography-micro text-foreground",children:Ie.output.title}):null,Ie.output?.summary?e.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap",children:Ie.output.summary}):null,Ie.output?.text?e.jsx("div",{className:"rounded border border-border/40 bg-background/40 px-2 py-2 typography-micro text-muted-foreground whitespace-pre-wrap max-h-48 overflow-y-auto",children:Ie.output.text}):null,Array.isArray(Ie.annotations)&&Ie.annotations.length>0?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Failed annotations",Ie.annotations.length>20?` (showing 20/${Ie.annotations.length})`:""]}),e.jsx("div",{className:"space-y-1",children:Ie.annotations.slice(0,20).map((It,Ps)=>e.jsxs("div",{className:"rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)]/40 px-2 py-2",children:[e.jsxs("div",{className:"typography-micro text-[var(--status-error)]",children:[It.title||It.level||"Issue",It.path?` · ${It.path}`:"",typeof It.startLine=="number"?`:${It.startLine}`:"",typeof It.endLine=="number"&&It.endLine!==It.startLine?`-${It.endLine}`:""]}),e.jsx("div",{className:"typography-micro text-foreground whitespace-pre-wrap mt-1",children:It.message}),It.rawDetails?e.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap mt-1",children:It.rawDetails}):null]},`${It.path||"file"}:${It.startLine||Ps}:${Ps}`))})]}):null,Ie.job?.steps&&Ie.job.steps.length>0?e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Steps"}),e.jsx("div",{className:"space-y-1",children:Ie.job.steps.map((It,Ps)=>{const Hs=(It.conclusion||"").toLowerCase(),Es=Hs&&!["success","neutral","skipped"].includes(Hs),er=`${Ie.id??"run"}:${Ie.job?.jobId??"job"}:${It.number??Ps}:${It.name}`,Cs=$e.has(er);return Es?e.jsxs(tn,{open:Cs,children:[e.jsxs("button",{type:"button",onClick:()=>{Ze(ar=>{const ir=new Set(ar);return ir.has(er)?ir.delete(er):ir.add(er),ir})},className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-left "+(Es?"bg-destructive/10 text-destructive":"text-muted-foreground"),children:[Cs?e.jsx(is,{className:"size-4"}):e.jsx(dr,{className:"size-4"}),e.jsx("span",{className:"truncate",children:It.name}),It.conclusion?e.jsx("span",{className:"ml-auto flex-shrink-0",children:It.conclusion}):null]}),e.jsx(sn,{children:e.jsxs("div",{className:"ml-6 mt-1 rounded border border-border/40 bg-background/40 px-2 py-2 typography-micro text-muted-foreground space-y-1",children:[typeof It.number=="number"?e.jsxs("div",{children:["Step: ",It.number]}):null,It.status?e.jsxs("div",{children:["Status: ",It.status]}):null,It.conclusion?e.jsxs("div",{children:["Conclusion: ",It.conclusion]}):null,It.startedAt?e.jsxs("div",{children:["Started: ",ct(It.startedAt)]}):null,It.completedAt?e.jsxs("div",{children:["Completed: ",ct(It.completedAt)]}):null]})})]},er):e.jsxs("div",{className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-muted-foreground",children:[e.jsx("span",{className:"truncate",children:It.name}),It.conclusion?e.jsx("span",{className:"ml-auto flex-shrink-0",children:It.conclusion}):null]},er)})})]}):null]})},[$e,ct]),Qt=i.useCallback(async()=>{if(p("chat"),!c?.prContext){K.error("GitHub runtime API unavailable");return}if(!t||!de)return;const Ie=Gt();if(Ie)try{const Ge=await c.prContext(t,de.number,{includeDiff:!1,includeCheckDetails:!0}),it=(Ge.checkRuns??[]).filter(Es=>{const er=typeof Es.conclusion=="string"?Es.conclusion.toLowerCase():"";return er?!["success","neutral","skipped"].includes(er):!1});if(it.length===0){K.message("No failed checks");return}const Kt="Review these PR failed checks and propose likely fixes. Do not implement until I confirm.",It=`Use the attached checks payload.
|
|
237
|
+
- Summarize what is failing.
|
|
238
|
+
- Prioritize check annotations/errors over generic status text.
|
|
239
|
+
- Identify likely root cause(s).
|
|
240
|
+
- Propose a minimal fix plan and verification steps.
|
|
241
|
+
- No speculation: ask for missing info if needed.`,Ps=it.flatMap(Es=>(Array.isArray(Es.annotations)?Es.annotations:[]).map(Cs=>({run:Es.name,level:Cs.level,title:Cs.title,path:Cs.path,startLine:Cs.startLine,endLine:Cs.endLine,message:Cs.message,rawDetails:Cs.rawDetails}))),Hs=`GitHub PR failed checks (JSON)
|
|
242
|
+
${JSON.stringify({repo:Ge.repo??null,pr:Ge.pr??null,failedChecks:it,failedAnnotations:Ps},null,2)}`;zt(Ie,Kt,It,Hs)}catch(Ge){const At=Ge instanceof Error?Ge.message:String(Ge);K.error("Failed to load checks",{description:At})}},[t,zt,c,de,Gt,p]),Mt=i.useCallback(async()=>{if(p("chat"),!c?.prContext){K.error("GitHub runtime API unavailable");return}if(!t||!de)return;const Ie=Gt();if(Ie)try{const Ge=await c.prContext(t,de.number,{includeDiff:!1,includeCheckDetails:!1}),At=Ge.issueComments??[],it=Ge.reviewComments??[];if(At.length+it.length===0){K.message("No PR comments");return}const It="Review these PR comments and propose the required changes and next actions. Do not implement until I confirm.",Ps=`Use the attached comments payload.
|
|
243
|
+
- Identify required vs optional changes.
|
|
244
|
+
- Call out intent/implementation mismatch if present.
|
|
245
|
+
- Propose a minimal plan and verification steps.
|
|
246
|
+
- No speculation: ask for missing info if needed.`,Hs=`GitHub PR comments (JSON)
|
|
247
|
+
${JSON.stringify({repo:Ge.repo??null,pr:Ge.pr??null,issueComments:At,reviewComments:it},null,2)}`;zt(Ie,It,Ps,Hs)}catch(Ge){const At=Ge instanceof Error?Ge.message:String(Ge);K.error("Failed to load PR comments",{description:At})}},[t,zt,c,de,Gt,p]),Zt=i.useCallback(Ie=>{Ee(!1),p("chat");const Ge=Gt();if(!Ge)return;const At="Address this comment from PR and propose required changes. Do not implement until I confirm.",it=`Use the attached single-comment payload.
|
|
248
|
+
- Explain what the reviewer is asking for.
|
|
249
|
+
- Identify exact code areas likely impacted.
|
|
250
|
+
- Propose a minimal implementation plan and verification steps.
|
|
251
|
+
- Call out ambiguity and ask focused follow-up questions if needed.`,Kt=`GitHub PR comment (JSON)
|
|
252
|
+
${JSON.stringify({repo:Re?.repo??null,pr:Re?.pr??de??null,comment:Ie},null,2)}`;zt(Ge,At,it,Kt)},[Re,zt,de,Gt,p]);i.useEffect(()=>{yt.current=w},[w]);const jt=i.useCallback(async Ie=>{if(ds&&!(Ie?.onlyExistingPr&&!yt.current?.pr)&&!(!Ie?.force&&Date.now()-Tt.current<ZD)&&!mt.current){if(mt.current=!0,Tt.current=Date.now(),u&&d?.connected===!1){C({connected:!1}),M(null),Ie?.silent||N(!1),Ie?.markInitialResolved!==!1&&A(!0),mt.current=!1;return}if(!c?.prStatus){C(null),M("GitHub runtime API unavailable"),Ie?.markInitialResolved!==!1&&A(!0),mt.current=!1;return}Ie?.silent||N(!0),M(null);try{const Ge=await c.prStatus(t,s,ye?.name);C(At=>{const it=Ge.pr,Kt=At?.pr;if(!!!(it&&Kt&&it.number===Kt.number&&(!it.body||!it.body.trim())&&typeof Kt.body=="string"&&Kt.body.trim().length>0)||!it)return Ge;const Ps=Kt?.body;return Ps?{...Ge,pr:{...it,body:Ps}}:Ge}),Ge.connected===!1&&M(null)}catch(Ge){const At=Ge instanceof Error?Ge.message:String(Ge);M(At||"Failed to load PR status")}finally{Ie?.silent||N(!1),Ie?.markInitialResolved!==!1&&A(!0),mt.current=!1}}},[s,ds,t,c,u,d,ye?.name]),es=i.useCallback(Ie=>{he(Ie),C(null),M(null),Tt.current=0},[]);i.useEffect(()=>{const Ie=pd.get(b)??null,Ge=hd.get(b)??null;$(Ie?.title??sh(s)),O(Ie?.body??""),_(Ie?.draft??!1),W(Ie?.targetBaseBranch?to(Ie.targetBaseBranch):to(r)),C(Ge),M(null),A(!!Ge),jt({force:!0,markInitialResolved:!0})},[r,s,jt,b]),i.useEffect(()=>{ye&&jt({force:!0,markInitialResolved:!0})},[ye,jt]),i.useEffect(()=>{const Ie=()=>{jt({force:!0,silent:!0})},Ge=()=>{document.visibilityState==="visible"&&jt({force:!0,silent:!0})};return window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ge),()=>{window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ge)}},[jt]),i.useEffect(()=>{const Ie=window.setInterval(()=>{if(document.visibilityState!=="visible")return;if(!!!yt.current?.pr){const At=Date.now();if(!(At-qt.current>=tI))return;qt.current=At,jt({force:!0,silent:!0});return}jt({onlyExistingPr:!0,force:!0,silent:!0})},eI);return()=>{window.clearInterval(Ie)}},[jt]),i.useEffect(()=>{u&&d?.connected===!1&&(C({connected:!1}),M(null))},[u,d]),i.useEffect(()=>{!t||!s||pd.set(b,{title:P,body:R,draft:T,additionalContext:F,targetBaseBranch:E})},[b,P,R,T,F,E,t,s]),i.useEffect(()=>{w&&hd.set(b,w)},[b,w]);const Ye=i.useCallback(async()=>{if(!oe&&t){Z(!0);try{const Ie=ut.getState().settingsZenModel,Ge=await n0(t,{base:E,head:s,context:F,...Ie?{zenModel:Ie}:{}});Ge.title?.trim()&&$(Ge.title.trim()),Ge.body?.trim()&&O(Ge.body.trim()),l?.()}catch(Ie){const Ge=Ie instanceof Error?Ie.message:String(Ie);K.error("Failed to generate description",{description:Ge})}finally{Z(!1)}}},[s,t,oe,F,l,E]),ft=i.useCallback(async()=>{if(!c?.prCreate){K.error("GitHub runtime API unavailable");return}const Ie=P.trim();if(!Ie){K.error("Title is required");return}const Ge=E.trim();if(!Ge){K.error("Base branch is required");return}if(Ge===s){K.error("Base branch must differ from head branch");return}Q(!0);try{const At=await c.prCreate({directory:t,title:Ie,head:s,base:Ge,...R.trim()?{body:R}:{},draft:T,...ye?{remote:ye.name}:{}});K.success("PR created"),C(it=>it&&{...it,pr:At}),await jt({force:!0})}catch(At){const it=At instanceof Error?At.message:String(At);K.error("Failed to create PR",{description:it})}finally{Q(!1)}},[R,s,t,T,c,jt,ye,E,P]),vt=i.useCallback(async Ie=>{if(!c?.prMerge){K.error("GitHub runtime API unavailable");return}se(!0);try{const Ge=await c.prMerge({directory:t,number:Ie.number,method:V});Ge.merged?K.success("PR merged"):K.message("PR not merged",{description:Ge.message||"Not mergeable"}),await jt({force:!0})}catch(Ge){const At=Ge instanceof Error?Ge.message:String(Ge);K.error("Merge failed",{description:At}),Ie.url&&gd(Ie.url)}finally{se(!1)}},[t,c,V,jt]),pt=i.useCallback(async Ie=>{if(!c?.prReady){K.error("GitHub runtime API unavailable");return}le(!0);try{await c.prReady({directory:t,number:Ie.number}),K.success("Marked ready for review"),await jt({force:!0})}catch(Ge){const At=Ge instanceof Error?Ge.message:String(Ge);K.error("Failed to mark ready",{description:At}),Ie.url&&gd(Ie.url)}finally{le(!1)}},[t,c,jt]),Rt=i.useCallback(async Ie=>{if(!c?.prUpdate){K.error("GitHub runtime API unavailable");return}const Ge=X.trim();if(!Ge){K.error("Title is required");return}ie(!0);try{const At=await c.prUpdate({directory:t,number:Ie.number,title:Ge,body:ae});C(it=>it&&{...it,pr:{...it.pr??Ie,...At}}),z(!1),K.success("PR updated"),await jt({force:!0})}catch(At){const it=At instanceof Error?At.message:String(At);K.error("Failed to update PR",{description:it})}finally{ie(!1)}},[t,ae,X,c,jt]);if(!ds)return null;const Ft=w?.repo?.url||null,Pt=w?.checks??null,Jt=!!w?.canMerge,Ns=!!w?.connected,Ts=u&&w?.connected===!1,sr=rI(w),Xs=sr?`var(--pr-${sr})`:"var(--status-info)",_s=sr==="draft"?Jw:sr==="merged"?Io:sr==="closed"?Xw:no,mr=a==="framed"?"rounded-xl border border-border/60 bg-background/70 overflow-hidden":"border-0 bg-transparent rounded-none",Zs=a==="framed"?"px-3 py-2 border-b border-border/40 flex flex-col gap-1":"px-0 py-3 border-b border-border/40 flex flex-col gap-1",gr=a==="framed"?"flex flex-col gap-3 p-3":"flex flex-col gap-3 py-3";return e.jsxs("section",{className:mr,children:[e.jsxs("div",{className:Zs,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[de?e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex size-6 shrink-0 items-center justify-center rounded-md border border-border/60 bg-background/70 hover:bg-interactive-hover/60",onClick:()=>{gd(de.url)},"aria-label":"Open PR on GitHub",children:e.jsx(_s,{className:"size-4 shrink-0",style:{color:Xs}})})}),e.jsx(ht,{children:e.jsx("p",{children:"Open PR on GitHub"})})]}):e.jsx(_s,{className:"size-4 shrink-0",style:{color:"var(--surface-muted-foreground)"}}),e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:"Pull Request"}),de?e.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",de.number]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[k?e.jsx(Ot,{className:"size-4 animate-spin text-muted-foreground"}):null,Pt?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 ${sI(Pt.state)}`}),Pt.total>0?`${Pt.success}/${Pt.total} checks`:`${Pt.state} checks`]}):null,ot?e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsxs(Me,{variant:"ghost",size:"sm",className:"h-6 px-2 gap-1",children:[e.jsx("span",{className:"typography-micro",children:ye?.name}),e.jsx(is,{className:"size-3"})]})}),e.jsx(fs,{align:"end",className:"min-w-[200px]",children:n.map(Ie=>e.jsx(Et,{onSelect:()=>es(Ie),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("span",{className:"typography-ui-label text-foreground",children:[Ie.name,Ie.name===ye?.name&&e.jsx("span",{className:"ml-2 text-primary",children:"✓"})]}),e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:Ie.pushUrl})]})},Ie.name))})]}):null]})]}),de?e.jsxs("div",{className:"typography-micro text-muted-foreground",children:[e.jsxs("span",{style:{color:Xs},children:[de.state,de.draft?" (draft)":""]}),de.mergeable===!1?" · not mergeable":"",de.state==="open"&&typeof de.mergeableState=="string"&&de.mergeableState&&de.mergeableState!=="unknown"?` · ${de.mergeableState}`:""]}):null]}),e.jsxs("div",{className:gr,children:[Ts?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(Me,{variant:"outline",size:"sm",onClick:y,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}),Ft?e.jsx(Me,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:e.jsxs("a",{href:Ft,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"size-4"}),"Open Repo"]})}):null]}):null,!de&&!D&&!S&&!Ts?e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground",children:[e.jsx(Ot,{className:"size-4 animate-spin"}),"Checking PR status..."]}):de?e.jsx("div",{className:"flex flex-col gap-2",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[ge?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Bt,{value:X,onChange:Ie=>G(Ie.target.value),placeholder:"PR title",autoCorrect:x?"on":"off",autoCapitalize:x?"sentences":"off",spellCheck:x}),e.jsx(hr,{value:ae,onChange:Ie=>me(Ie.target.value),className:"min-h-[120px] bg-background/80",placeholder:"Describe this PR",autoCorrect:x?"on":"off",autoCapitalize:x?"sentences":"off",spellCheck:x})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-markdown text-xl font-semibold text-foreground break-words leading-snug",children:de.title}),de.body?.trim()?e.jsx(zr,{content:de.body,className:"typography-markdown-body text-muted-foreground break-words mt-1"}):e.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap break-words mt-1",children:We?"Loading description...":"No description provided."})]}),Jt&&de.draft?e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Draft PRs must be marked ready before merge."}):null,Jt?null:e.jsx("div",{className:"typography-micro text-muted-foreground",children:"No merge permission; use Open in GitHub."})]}),e.jsxs("div",{className:"order-first w-full flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[de.state==="open"?ge?e.jsxs(e.Fragment,{children:[e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"outline",size:"sm",className:"w-8 px-0",onClick:()=>{z(!1),G(de.title||""),me(de.body||"")},disabled:Y,"aria-label":"Cancel editing",children:e.jsx(hs,{className:"size-4"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Cancel editing"})})]}),e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{size:"sm",className:"w-8 px-0",onClick:()=>Rt(de),disabled:Y||!X.trim(),"aria-label":"Save PR title and description",children:Y?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(ss,{className:"size-4"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Save PR title and description"})})]})]}):e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"outline",size:"sm",className:"w-8 px-0",onClick:()=>z(!0),"aria-label":"Edit PR title and description",children:e.jsx(go,{className:"size-4"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Edit PR title and description"})})]}):null,Pt?e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"outline",size:"sm",className:"w-8 px-0",onClick:qe,disabled:Fe,"aria-label":"Open checks details",children:Fe?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(cr,{className:"size-4"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Open checks details"})})]}):null,Pt?.failure?e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"outline",size:"sm",className:"w-8 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:Qt,"aria-label":"Resolve failed checks with agent",children:e.jsx(kl,{className:"size-4"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Resolve failed checks with agent"})})]}):null,e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"outline",size:"sm",className:"w-8 px-0",onClick:et,"aria-label":"Open PR comments",children:e.jsx(og,{className:"size-4"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Open PR comments"})})]}),e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"outline",size:"sm",className:"w-8 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:Mt,"aria-label":"Share comments with agent",children:e.jsx(Ja,{className:"size-4"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Share comments with agent"})})]}),Jt&&de.draft&&de.state==="open"?e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{variant:"outline",size:"sm",className:"w-8 px-0",onClick:()=>pt(de),disabled:H||B||Y||ge,"aria-label":"Mark PR ready for review",children:H?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(al,{className:"size-4"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Mark PR ready for review"})})]}):null]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:Jt?e.jsxs(e.Fragment,{children:[e.jsxs($s,{value:V,onValueChange:Ie=>ve(Ie),disabled:B||de.state!=="open",children:[e.jsx(Bs,{size:"lg",className:"h-8 w-auto min-w-0",children:e.jsx(Sr,{})}),e.jsxs(zs,{children:[e.jsx(ns,{value:"squash",children:"Squash"}),e.jsx(ns,{value:"merge",children:"Merge"}),e.jsx(ns,{value:"rebase",children:"Rebase"})]})]}),e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{size:"sm",className:"w-8 px-0",onClick:()=>vt(de),disabled:B||H||de.state!=="open"||de.draft||Y||ge,"aria-label":"Merge pull request",children:B?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(Io,{className:"size-4"})})}),e.jsx(ht,{children:e.jsx("p",{children:"Merge pull request"})})]})]}):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:[s," → ",E]})]}),Ft?e.jsx(Me,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:Ft,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{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(Bt,{value:P,onChange:Ie=>$(Ie.target.value),placeholder:"PR title",autoCorrect:x?"on":"off",autoCapitalize:x?"sentences":"off",spellCheck:x})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Base branch"}),He.length>0?e.jsxs($s,{value:E,onValueChange:W,children:[e.jsx(Bs,{className:"h-9",children:e.jsx(Sr,{placeholder:"Select base branch"})}),e.jsx(zs,{children:He.map(Ie=>e.jsx(ns,{value:Ie,children:Ie},Ie))})]}):e.jsx(Bt,{value:E,onChange:Ie=>W(Ie.target.value),placeholder:"main"})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Description"}),e.jsx(hr,{value:R,onChange:Ie=>O(Ie.target.value),className:"min-h-[110px] bg-background/80",placeholder:"What changed and why",autoCorrect:x?"on":"off",autoCapitalize:x?"sentences":"off",spellCheck:x})]}),e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":T,onClick:()=>_(Ie=>!Ie),onKeyDown:Ie=>{(Ie.key===" "||Ie.key==="Enter")&&(Ie.preventDefault(),_(Ge=>!Ge))},children:[e.jsx("button",{type:"button",onClick:Ie=>{Ie.preventDefault(),Ie.stopPropagation(),_(Ge=>!Ge)},"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:T?e.jsx(Kn,{className:"size-4 text-primary"}):e.jsx(qn,{className:"size-4"})}),e.jsx("span",{className:"typography-ui-label text-foreground select-none",children:"Draft"})]}),g?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Additional context (optional)"}),e.jsx(Me,{variant:"outline",size:"sm",onClick:()=>q(!0),children:F.trim()?"Edit":"Add"})]}),F.trim()&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"inline-flex items-center rounded-full bg-[var(--interactive-selection)] px-2 py-0.5 text-xs text-[var(--interactive-selection-foreground)]",children:"Context added"})})]}):e.jsxs(tn,{open:Oe,onOpenChange:Be,children:[e.jsxs(On,{className:"flex w-full items-center justify-between rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-2 hover:bg-[var(--interactive-hover)]",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Additional context (optional)"}),e.jsx("span",{className:"typography-micro text-[var(--primary-base)]",children:Oe?"Hide":F.trim()?"Edit":"Add"})]}),e.jsx(sn,{children:e.jsxs("div",{className:"mt-2 space-y-2 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3",children:[e.jsx(hr,{value:F,onChange:Ie=>I(Ie.target.value),className:"min-h-[100px] bg-transparent",placeholder:`Explain why this change is needed...
|
|
253
|
+
Mention how to test (commands / steps)...
|
|
254
|
+
Call out risks / rollout plan...`}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"This text is only used to guide PR generation."})]})})]}),e.jsx(Cr,{open:fe,onClose:()=>q(!1),title:"Additional context",footer:e.jsx(Me,{size:"sm",onClick:()=>q(!1),className:"w-full",children:"Done"}),children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(hr,{value:F,onChange:Ie=>I(Ie.target.value),className:"min-h-[200px] bg-transparent",placeholder:`Explain why this change is needed...
|
|
255
|
+
Mention how to test (commands / steps)...
|
|
256
|
+
Call out risks / rollout plan...`,autoFocus:!0}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"This text is only used to guide PR generation."})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Me,{variant:"outline",size:"sm",onClick:Ye,disabled:oe||ce,children:[oe?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(Ja,{className:"size-4 text-primary"}),"Generate"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(Me,{size:"sm",className:"min-w-[7.5rem] justify-center gap-2",onClick:ft,disabled:ce||!Ns||!E.trim()||E.trim()===s,children:[e.jsx("span",{className:"inline-flex size-4 items-center justify-center",children:ce?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(no,{className:"size-4"})}),e.jsx("span",{children:"Create PR"})]})]})]})]}),e.jsx(bs,{open:ue,onOpenChange:Ve,children:e.jsxs(vs,{className:"max-w-2xl max-h-[70vh] flex flex-col min-h-0",children:[e.jsxs(js,{children:[e.jsxs(Ss,{className:"flex items-center gap-2",children:[e.jsx(no,{className:"h-5 w-5"}),"Check Details"]}),e.jsx(Is,{children:de?`PR #${de.number}`:"Pull request"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto mt-2",children:[Fe?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Ot,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):null,Fe?null:e.jsx("div",{className:"space-y-3",children:Array.isArray(De?.checkRuns)&&De?.checkRuns.length>0?De.checkRuns.map((Ie,Ge)=>{const At=`${Ie.id??"run"}:${Ie.job?.jobId??"job"}:${Ie.name}:${Ge}`;return e.jsx("div",{className:"p-1",children:Ct(Ie)},At)}):e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No check details available."})})]})]})}),e.jsx(bs,{open:Ue,onOpenChange:Ee,children:e.jsxs(vs,{className:"max-w-2xl max-h-[82vh] min-h-[38rem] flex flex-col gap-2",children:[e.jsx(js,{children:e.jsxs(Ss,{className:"flex items-center gap-2",children:[e.jsx(no,{className:"h-5 w-5"}),"PR Comments",de?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["PR #",de.number]}):null]})}),e.jsxs(Ti,{className:"mt-2 max-h-[66vh] overflow-y-auto overlay-scrollbar-target overlay-scrollbar-container",children:[st?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Ot,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):null,st?null:e.jsx("div",{className:"space-y-4",children:Nt.length>0?e.jsx("div",{className:"relative pl-3",children:e.jsx("div",{children:Nt.map((Ie,Ge)=>{const At=(Ie.authorName||"?").charAt(0).toUpperCase(),it=Ge===Nt.length-1;return e.jsxs("div",{className:"relative pl-10 pb-5 last:pb-0",children:[it?null:e.jsx("div",{className:"absolute left-4 top-[2.375rem] bottom-[0.375rem] w-px bg-border/60"}),e.jsx("div",{className:"absolute left-0 top-0 z-10 flex size-8 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-surface-elevated text-xs text-muted-foreground",children:Ie.avatarUrl?e.jsx("img",{src:Ie.avatarUrl,alt:Ie.authorName,className:"h-full w-full object-cover"}):e.jsx("span",{children:At})}),e.jsxs("div",{className:"rounded-lg bg-surface-elevated px-3 pt-0 pb-3 space-y-2",children:[e.jsxs("div",{className:"flex flex-col items-start gap-1 typography-micro text-muted-foreground sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-1 sm:gap-y-1",children:[e.jsxs("span",{className:"text-foreground whitespace-nowrap",children:[Ie.authorName,Ie.authorLogin&&Ie.authorLogin!==Ie.authorName?` · @${Ie.authorLogin}`:""]}),Ie.createdAt?e.jsx("span",{className:"whitespace-nowrap",children:ct(Ie.createdAt)}):null,e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsxs(Me,{variant:"ghost",size:"sm",className:"h-6 px-0 has-[>svg]:px-0 sm:px-2 sm:has-[>svg]:px-2.5 text-[var(--status-success)] hover:bg-[var(--status-success-background)] hover:text-[var(--status-success)] justify-start",onClick:()=>Zt(Ie),"aria-label":"Send this comment to agent",children:[e.jsx(Ja,{className:"size-3.5"}),"Send to agent"]})}),e.jsx(ht,{children:e.jsx("p",{children:"Send this comment to agent"})})]})]}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:[Ie.context,Ie.path?` · ${Ie.path}`:"",Ie.line?`:${Ie.line}`:""]}),e.jsx(zr,{content:_t(Ie.body),className:["typography-markdown-body text-foreground break-words [&_a]:no-underline [&_a:hover]:no-underline",at].filter(Boolean).join(" ")})]})]},Ie.id)})})}):e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No comments found."})})]})]})})]})},iI=({open:t,onOpenChange:s,conflictFiles:r=[],directory:n,operation:o,onAbort:a,onClearState:l})=>{const c=Ae(M=>M.openNewSessionDraft),d=Ae(M=>M.currentSessionId),u=Ae(M=>M.setPendingInputText),m=Ae(M=>M.setPendingSyntheticParts),f=Te(M=>M.setActiveMainTab),[p,h]=i.useState(!1),[g,x]=i.useState(null),[y,b]=i.useState(null);i.useEffect(()=>{!t||!n||(h(!0),b(null),x(null),x0(n).then(M=>{x(M)}).catch(M=>{const D=M instanceof Error?M.message:"Failed to load conflict details";b(D)}).finally(()=>{h(!1)}))},[t,n]);const v=i.useCallback(()=>{if(!g)return null;const M=o==="merge"?"merge":"rebase",D=g.headInfo||(o==="merge"?"MERGE_HEAD":"REBASE_HEAD"),A=o==="merge"?"git commit --no-edit":"git rebase --continue",P=`Resolve ${M} conflicts, stage the resolved files, and complete the ${M}. Preserve the intent of changes from ${D}.`,$=`Git ${M} operation is in progress with conflicts.
|
|
257
|
+
- Directory: ${n}
|
|
258
|
+
- Operation: ${o}
|
|
259
|
+
- Head Info: ${g.headInfo||"N/A"}
|
|
260
|
+
|
|
261
|
+
Required steps:
|
|
262
|
+
1. Read each conflicted file to understand the conflict markers (<<<<<<< HEAD, =======, >>>>>>> ...)
|
|
263
|
+
2. Edit each file to resolve conflicts by choosing the correct code or merging both changes appropriately
|
|
264
|
+
3. Stage all resolved files with: git add <file>
|
|
265
|
+
4. Complete the ${M} with: ${A}
|
|
266
|
+
|
|
267
|
+
Important:
|
|
268
|
+
- Remove ALL conflict markers from files (<<<<<<< HEAD, =======, >>>>>>>)
|
|
269
|
+
- Make sure the final code is syntactically correct and preserves intent from both sides
|
|
270
|
+
- Do not leave any files with unresolved conflict markers
|
|
271
|
+
- After completing all steps, confirm the ${M} was successful
|
|
272
|
+
`,R=`${M} conflict context (JSON)
|
|
273
|
+
${JSON.stringify({directory:n,operation:g.operation,headInfo:g.headInfo,statusPorcelain:g.statusPorcelain,unmergedFiles:g.unmergedFiles,diff:g.diff},null,2)}`;return{visibleText:P,instructionsText:$,payloadText:R}},[g,n,o]),j=()=>{a(),s(!1)},k=()=>{l?.(),s(!1)},N=()=>{const M=v();if(!M){K.error("No conflict details available");return}if(!d){K.error("No active session",{description:'Open a chat session first or use "New Session".'});return}u(M.visibleText,"replace"),m([{text:M.instructionsText,synthetic:!0},{text:M.payloadText,synthetic:!0}]),f("chat"),l?.(),s(!1)},w=()=>{const M=v();if(!M){K.error("No conflict details available");return}c({directoryOverride:n,initialPrompt:M.visibleText,syntheticParts:[{text:M.instructionsText,synthetic:!0},{text:M.payloadText,synthetic:!0}]}),f("chat"),l?.(),s(!1)},C=o==="merge"?"Merge":"Rebase",S=g?.unmergedFiles||r;return e.jsx(bs,{open:t,onOpenChange:s,children:e.jsx(vs,{className:"max-w-md w-[calc(100vw-2rem)]",children:e.jsxs("div",{className:"flex flex-col gap-4 overflow-hidden",children:[e.jsxs(js,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tc,{className:"size-5 shrink-0 text-[var(--status-warning)]"}),e.jsxs(Ss,{children:[C," Conflicts Detected"]})]}),e.jsxs(Is,{children:["The ",o," operation resulted in conflicts that need to be resolved."]})]}),p&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[e.jsx(Ot,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Loading conflict details..."})]}),y&&e.jsxs("div",{className:"rounded-lg bg-[var(--status-error-bg)] p-3 text-[var(--status-error)] typography-meta break-words",children:["Error loading details: ",y]}),S.length>0&&e.jsxs("div",{className:"space-y-2 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Conflicted files:"}),e.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-[var(--surface-elevated)] text-muted-foreground",children:S.length})]}),e.jsx("div",{className:"bg-[var(--surface-elevated)] rounded-lg p-3 max-h-40 overflow-y-auto overflow-x-hidden",children:e.jsx("ul",{className:"space-y-1",children:S.map((M,D)=>e.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:M,children:M},D))})})]}),g?.headInfo&&e.jsxs("div",{className:"space-y-1 overflow-hidden",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"HEAD information:"}),e.jsx("div",{className:"typography-micro text-foreground font-mono bg-[var(--surface-elevated)] rounded-lg p-3 max-h-24 overflow-y-auto break-words whitespace-pre-wrap",children:g.headInfo})]}),e.jsxs("div",{className:"flex flex-col gap-2 pt-2",children:[e.jsxs(Me,{variant:"default",onClick:w,disabled:p||!g,className:"w-full gap-2",children:[p?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(Fs,{className:"size-4"}),"Resolve in New Session"]}),e.jsxs(Me,{variant:"outline",onClick:()=>{N()},disabled:p||!g||!d,className:"w-full gap-2",children:[p?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(Zw,{className:"size-4"}),"Resolve in Current Session"]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(Me,{variant:"ghost",size:"sm",onClick:k,className:"flex-1",children:"Continue Later"}),e.jsxs(Me,{variant:"ghost",size:"sm",onClick:j,className:"flex-1 text-[var(--status-error)]",children:["Abort ",C]})]})]})]})})})},lI=({open:t,onOpenChange:s,operation:r,targetBranch:n,onConfirm:o})=>{const[a,l]=i.useState(!0),[c,d]=i.useState(!1),u=r==="merge"?"Merge":"Rebase",m=async()=>{d(!0);try{await o(a),s(!1)}catch(p){const h=p instanceof Error?p.message:`Failed to ${r}`;K.error(h)}finally{d(!1)}},f=()=>{c||s(!1)};return e.jsx(bs,{open:t,onOpenChange:c?void 0:s,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tc,{className:"size-5 text-[var(--status-warning)]"}),e.jsx(Ss,{children:"Uncommitted Changes"})]}),e.jsxs(Is,{children:["You have uncommitted changes that would be overwritten by this ",r,". Would you like to stash them temporarily?"]})]}),e.jsxs("div",{className:"py-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground mb-3",children:"This will:"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 typography-meta text-foreground",children:[e.jsx("li",{children:"Stash your uncommitted changes"}),e.jsxs("li",{children:[r==="merge"?"Merge":"Rebase"," ",r==="merge"?"with":"onto"," ",e.jsx("span",{className:"font-mono text-primary",children:n})]}),a&&e.jsx("li",{children:"Restore your stashed changes"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx(Xr,{checked:a,onChange:l,disabled:c,ariaLabel:"Restore changes after operation"}),e.jsxs("span",{className:"typography-ui-label text-foreground cursor-pointer select-none",onClick:()=>!c&&l(!a),children:["Restore changes after the ",r]})]}),e.jsxs(Js,{className:"gap-2",children:[e.jsx(Me,{variant:"ghost",size:"sm",onClick:f,disabled:c,children:"Cancel"}),e.jsx(Me,{variant:"default",size:"sm",onClick:m,disabled:c,className:"gap-1.5",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"size-4 animate-spin"}),"Processing..."]}):`Stash & ${u}`})]})]})})},cI=({mergeInProgress:t,rebaseInProgress:s,onContinue:r,onAbort:n,onResolveWithAI:o,hasUnresolvedConflicts:a=!1,isLoading:l=!1})=>{const[c,d]=i.useState(null),u=t&&t.head,m=s&&(s.headName||s.onto),f=u?"merge":m?"rebase":null;if(!f)return null;const p=async()=>{d("continue");try{await r()}finally{d(null)}},h=async()=>{d("abort");try{await n()}finally{d(null)}},g=c!==null,x=f==="merge"?"Merge":"Rebase",y=f==="merge"?Io:Ms;let b="";return t?b=t.message?`Merging: ${t.message}`:`Merge in progress (${t.head})`:s&&(b=s.headName?`Rebasing ${s.headName} onto ${s.onto}`:"Rebase in progress"),e.jsxs("div",{className:"bg-[var(--status-warning-bg)] border border-[var(--status-warning)] rounded-lg p-3 mx-3 mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(y,{className:"size-4 text-[var(--status-warning)] shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"typography-label text-[var(--status-warning)]",children:[x," in Progress"]}),b&&e.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:b})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a&&o&&e.jsxs(Me,{variant:"outline",size:"sm",onClick:o,disabled:g||l,className:"gap-1.5",children:[e.jsx(Ud,{className:"size-4"}),"Resolve with AI"]}),c!=="continue"&&e.jsxs(Me,{variant:"ghost",size:"sm",onClick:h,disabled:g||l,className:"gap-1.5",children:[c==="abort"?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(hs,{className:"size-4"}),"Abort"]}),!a&&e.jsxs(Me,{variant:"default",size:"sm",onClick:p,disabled:g||l,className:"gap-1.5",children:[c==="continue"?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(ss,{className:"size-4"}),"Continue"]})]})]}),a&&e.jsx("p",{className:"typography-micro text-[var(--status-warning)] mt-2",children:'Conflicts must be resolved before continuing. Use "Resolve with AI" or resolve manually, then stage changes and click Continue.'})]})},dI=({currentBranch:t,localBranches:s,remoteBranches:r,onMerge:n,onRebase:o,disabled:a=!1,isOperating:l=!1,operationLogs:c=[],onOperationComplete:d,mode:u="dialog"})=>{const[m,f]=i.useState(!1),[p,h]=i.useState("merge"),[g,x]=i.useState(null),[y,b]=i.useState(!1),[v,j]=i.useState(""),k=i.useRef(null),N=i.useRef(null),w=a||l,C=t||"current branch",S=c.length>0&&c.every(E=>E.status==="done"||E.status==="error"),M=c.some(E=>E.status==="error");i.useEffect(()=>{N.current&&(N.current.scrollTop=N.current.scrollHeight)},[c]);const D=i.useMemo(()=>{const E=v.toLowerCase(),W=s.filter(V=>V!==t);return E?W.filter(V=>V.toLowerCase().includes(E)):W},[v,s,t]),A=i.useMemo(()=>{const E=v.toLowerCase();return E?r.filter(W=>W.toLowerCase().includes(E)):r},[v,r]),P=()=>{f(!0),x(null),h("merge"),j("")},$=E=>{x(E),b(!1),j("")},R=()=>{g&&(p==="merge"?n(g):o(g))},O=()=>{l||(x(null),h("merge"),j(""),f(!1))},T=()=>{l&&!S||(S&&d?.(),x(null),h("merge"),j(""),f(!1))};i.useEffect(()=>{if(!y)j("");else{const E=setTimeout(()=>{k.current?.focus()},0);return()=>clearTimeout(E)}},[y]);const I=l?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{ref:N,className:"rounded-lg border border-border bg-muted/30 p-3 max-h-48 overflow-y-auto",children:e.jsx("div",{className:"space-y-2",children:c.map((E,W)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"mt-0.5 shrink-0",children:[E.status==="running"&&e.jsx(Ot,{className:"size-3.5 animate-spin text-primary"}),E.status==="done"&&e.jsx(ss,{className:"size-3.5 text-success"}),E.status==="error"&&e.jsx(hs,{className:"size-3.5 text-destructive"}),E.status==="pending"&&e.jsx("div",{className:"size-3.5 rounded-full border border-muted-foreground/30"})]}),e.jsx("span",{className:L("typography-micro",E.status==="error"&&"text-destructive",E.status==="done"&&"text-muted-foreground",E.status==="running"&&"text-foreground",E.status==="pending"&&"text-muted-foreground/60"),children:E.message})]},W))})}),S?u==="dialog"?e.jsx(Js,{children:e.jsx(Me,{variant:"default",size:"sm",onClick:T,children:M?"Close":"Done"})}):e.jsx("div",{className:"flex justify-end",children:e.jsx(Me,{variant:"default",size:"sm",onClick:T,children:M?"Close":"Done"})}):null]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Operation"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>h("merge"),className:L("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",p==="merge"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Io,{className:L("size-4",p==="merge"?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:L("typography-ui-label",p==="merge"?"text-foreground":"text-muted-foreground"),children:"Merge"})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Combines branches with a merge commit and preserves history."})]}),e.jsxs("button",{type:"button",onClick:()=>h("rebase"),className:L("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",p==="rebase"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ms,{className:L("size-4",p==="rebase"?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:L("typography-ui-label",p==="rebase"?"text-foreground":"text-muted-foreground"),children:"Rebase"})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Moves your commits to be on top of another branch. Creates linear history."})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:p==="merge"?`Branch to merge into ${C}`:"Branch to rebase onto"}),e.jsxs(us,{open:y,onOpenChange:b,children:[e.jsx(ms,{asChild:!0,children:e.jsxs(Me,{variant:"outline",className:"w-full justify-between h-10",children:[e.jsx("span",{className:L("truncate",!g&&"text-muted-foreground"),children:g||"Select a branch..."}),e.jsx(is,{className:"size-4 opacity-60 shrink-0"})]})}),e.jsx(fs,{align:"start",className:"w-[--radix-dropdown-menu-trigger-width] p-0 max-h-[300px]",children:e.jsxs(Mi,{children:[e.jsx(Ea,{ref:k,placeholder:"Search branches...",value:v,onValueChange:j}),e.jsxs(Ai,{children:[e.jsx(Di,{children:"No branches found."}),D.length>0&&e.jsx(hn,{heading:"Local branches",children:D.map(E=>e.jsx(Qs,{onSelect:()=>$(E),children:e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:E})},`local-${E}`))}),D.length>0&&A.length>0?e.jsx(ya,{}):null,A.length>0&&e.jsx(hn,{heading:"Remote branches",children:A.map(E=>e.jsx(Qs,{onSelect:()=>$(E),children:e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:E})},`remote-${E}`))})]})]})})]})]}),g?e.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:p==="merge"?e.jsxs(e.Fragment,{children:["This will merge ",e.jsx("span",{className:"font-mono text-foreground",children:g})," into"," ",e.jsx("span",{className:"font-mono text-foreground",children:C})]}):e.jsxs(e.Fragment,{children:["This will rebase ",e.jsx("span",{className:"font-mono text-foreground",children:C})," onto"," ",e.jsx("span",{className:"font-mono text-foreground",children:g})]})})}):null,u==="dialog"?e.jsxs(Js,{className:"gap-2",children:[e.jsx(Me,{variant:"ghost",size:"sm",onClick:O,children:"Cancel"}),e.jsx(Me,{variant:"default",size:"sm",onClick:R,disabled:!g,className:"gap-1.5",children:p==="merge"?e.jsxs(e.Fragment,{children:[e.jsx(Io,{className:"size-4"}),"Merge"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ms,{className:"size-4"}),"Rebase"]})})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{variant:"ghost",size:"sm",onClick:O,disabled:w,children:"Reset"}),e.jsx("div",{className:"flex-1"}),e.jsx(Me,{variant:"default",size:"sm",onClick:R,disabled:w||!g,children:p==="merge"?"Merge":"Rebase"})]})]});return u==="inline"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:"Update branch"}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Bring changes from another branch into"," ",e.jsx("span",{className:"font-mono text-foreground",children:C}),"."]})]}),I]}):e.jsxs(e.Fragment,{children:[e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsxs(Me,{variant:"outline",size:"sm",className:"h-8 px-2 gap-1.5",onClick:P,disabled:w,children:[l?e.jsx(Ot,{className:"size-4 animate-spin"}):e.jsx(Io,{className:"size-4"}),e.jsx("span",{children:"Merge/Rebase"})]})}),e.jsx(ht,{sideOffset:8,children:"Merge or rebase changes from another branch."})]}),e.jsx(bs,{open:m,onOpenChange:E=>{E?f(!0):T()},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Update Branch"}),e.jsx(Is,{children:l?S?M?"Operation failed":"Operation completed":`${p==="merge"?"Merging":"Rebasing"} in progress...`:e.jsxs(e.Fragment,{children:["Choose how to bring changes from another branch into"," ",e.jsx("span",{className:"font-mono text-foreground",children:C}),"."]})})]}),I]})})]})},uI=t=>t.label||t.normalizedPath.split("/").pop()||t.normalizedPath;function mI({open:t,onOpenChange:s,project:r}){const[n,o]=ne.useState(""),[a,l]=ne.useState(null),[c,d]=ne.useState([]),[u,m]=ne.useState(!1),[f,p]=ne.useState(null),[h,g]=ne.useState(null),[x,y]=ne.useState(null),[b,v]=ne.useState(null),[j,k]=ne.useState(null),[N,w]=ne.useState(""),[C,S]=ne.useState(null),M=ne.useCallback(async()=>{if(r){m(!0),p(null);try{const[E,W]=await Promise.all([_u(r.path),Si.worktree.list(r.path)]);l(E),d(W)}catch(E){p(E instanceof Error?E.message:"Failed to load"),l(null),d([])}finally{m(!1)}}},[r]);ne.useEffect(()=>{if(!t){o(""),y(null),v(null),k(null),w(""),S(null);return}M()},[t,M]);const D=(E,W)=>{if(!W.trim())return E;const V=W.toLowerCase();return E.filter(ve=>ve.toLowerCase().includes(V))},A=ne.useCallback(E=>{k(E),w(E)},[]),P=ne.useCallback(()=>{k(null),w(""),S(null)},[]),$=ne.useCallback(()=>{y(null),v(null)},[]),R=ne.useCallback(async E=>{if(!r)return;const W=N.trim();if(!W||W===E){P();return}S(E);try{if(!(await c0(r.path,E,W))?.success)throw new Error("Rename rejected");await M(),P(),K.success("Branch renamed",{description:`${E} -> ${W}`})}catch(V){K.error("Failed to rename branch",{description:V instanceof Error?V.message:"Rename failed"}),S(null)}},[r,N,M,P]),O=ne.useCallback(async E=>{if(r){g(E);try{const W=b===E;if(!(await s0(r.path,{branch:E,force:W}))?.success)throw new Error("Delete rejected");await M(),K.success("Branch deleted",{description:E}),y(null),v(null)}catch(W){const V=W instanceof Error?W.message:"Delete failed";/not fully merged/i.test(V)&&b!==E?(v(E),K.error("Branch not merged",{description:"Confirm again to force delete"})):K.error("Failed to delete branch",{description:V})}finally{g(null)}}},[r,M,b]),T=new Set(c.map(E=>E.branch).filter(Boolean)),_=a?.all||[],I=D(_,n).filter(E=>!E.startsWith("remotes/"));return e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-2xl max-h-[70vh] flex flex-col overflow-hidden gap-3",children:[e.jsxs(js,{className:"flex-shrink-0",children:[e.jsxs(Ss,{className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"h-5 w-5"}),"Manage Branches"]}),e.jsx(Is,{children:r?`Local branches for ${uI(r)}`:"Select a project"})]}),e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Bt,{placeholder:"Search branches...",value:n,onChange:E=>o(E.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:r?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}):I.length===0?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:n?"No matching branches":"No branches found"}):I.map(E=>{const W=a?.branches[E],V=!!W?.current,ve=h===E,oe=C===E,Z=T.has(E),ce=j===E,Q=x===E,Y=b===E,ie=!!(V||Z||ve||oe||ce),B=!!(Z||ve||oe||ce);return e.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5 hover:bg-interactive-hover/30 rounded-md overflow-hidden",children:[e.jsx(Ms,{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:[ce?e.jsx("form",{className:"flex w-full items-center min-w-0",onSubmit:se=>{se.preventDefault(),R(E)},children:e.jsx("input",{value:N,onChange:se=>w(se.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:se=>{se.key==="Escape"&&(se.preventDefault(),P()),se.key==="Enter"&&(se.preventDefault(),R(E))}})}):e.jsx("span",{className:L("text-sm truncate",V&&"font-medium text-primary"),children:E}),V&&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&&!ce&&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:[W?.commit?e.jsx("span",{className:"font-mono",children:W.commit.slice(0,7)}):null,typeof W?.ahead=="number"&&W.ahead>0?e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["↑",W.ahead]}):null,typeof W?.behind=="number"&&W.behind>0?e.jsxs("span",{className:"text-[color:var(--status-warning)]",children:["↓",W.behind]}):null]})]}),!ce&&!Q?e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsxs(gt,{delayDuration:700,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>A(E),disabled:B,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-interactive-hover/40 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50","aria-label":"Rename",children:e.jsx(wu,{className:"h-4 w-4"})})}),e.jsx(ht,{side:"left",children:Z?"Rename (remove worktree first)":"Rename"})]}),e.jsxs(gt,{delayDuration:700,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>y(E),disabled:ie,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:ve?e.jsx(Ot,{className:"h-4 w-4 animate-spin"}):e.jsx(Nr,{className:"h-4 w-4"})})}),e.jsx(ht,{side:"left",children:V?"Delete (current branch)":Z?"Delete (remove worktree first)":"Delete"})]})]}):null,ce?e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("button",{type:"button",onClick:()=>{R(E)},disabled:oe,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-interactive-hover/40 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50","aria-label":"Confirm rename",children:oe?e.jsx(Ot,{className:"h-4 w-4 animate-spin"}):e.jsx(ss,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:P,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-interactive-hover/40 text-muted-foreground hover:text-foreground transition-colors","aria-label":"Cancel rename",children:e.jsx(hs,{className:"h-4 w-4"})})]}):null,!ce&&Q?e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("span",{className:L("text-xs mr-1",Y?"text-destructive":"text-muted-foreground"),children:Y?"Force delete?":"Delete?"}),e.jsx("button",{type:"button",onClick:()=>{O(E)},disabled:ve,className:L("inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors disabled:opacity-50",Y?"bg-destructive/10 text-destructive hover:bg-destructive/15":"hover:bg-destructive/10 text-muted-foreground hover:text-destructive"),"aria-label":"Confirm delete",children:ve?e.jsx(Ot,{className:"h-4 w-4 animate-spin"}):e.jsx(ss,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:$,className:"inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-interactive-hover/40 text-muted-foreground hover:text-foreground transition-colors","aria-label":"Cancel delete",children:e.jsx(hs,{className:"h-4 w-4"})})]}):null]},E)}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No project selected"})})})]})})}const rh="oc.git.actionTab",fI=t=>t==="commit"||t==="branch"||t==="pr"||t==="worktree",sb="gitmojiCache",pI=1e3*60*60*24*7,rb="1",hI="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",nh={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:"},nb=t=>{if(!t||typeof t!="object")return!1;const s=t;return typeof s.emoji=="string"&&typeof s.code=="string"&&typeof s.description=="string"},gI=()=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(sb);if(!t)return null;const s=JSON.parse(t);return!s||s.version!==rb||typeof s.fetchedAt!="number"||!Array.isArray(s.gitmojis)?null:{gitmojis:s.gitmojis.filter(nb),fetchedAt:s.fetchedAt,version:s.version}}catch{return null}},xI=t=>{if(!(typeof window>"u"))try{const s={gitmojis:t,fetchedAt:Date.now(),version:rb};localStorage.setItem(sb,JSON.stringify(s))}catch{return}},yI=t=>Date.now()-t.fetchedAt<pI,bI=(t,s)=>{const r=t.toLowerCase(),n=/^([a-z]+)(?:\(.*\))?!?:/,o=r.match(n);if(o){const c=o[1],d=nh[c];if(d)return s.find(u=>u.code===d)||null}const a=r.split(" ")[0],l=nh[a];return l&&s.find(c=>c.code===l)||null},oh=new Map,xd=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),ah=({mode:t="full"})=>{const{git:s}=Vr(),r=Ci(),{currentSessionId:n,worktreeMetadata:o}=Ae(),a=n?o.get(n)??void 0:void 0,{profiles:l,globalIdentity:c,defaultGitIdentityId:d,loadProfiles:u,loadGlobalIdentity:m,loadDefaultGitIdentityId:f}=ka(),p=Fx(r??null),h=Wu(r??null),g=zN(r??null),x=UN(r??null),y=HN(r??null),b=or(be=>be.isLoadingStatus),v=or(be=>be.isLoadingLog),{setActiveDirectory:j,fetchAll:k,fetchStatus:N,fetchBranches:w,fetchLog:C,fetchIdentity:S,setLogMaxCount:M}=or(),D=i.useMemo(()=>r?oh.get(r)??null:null,[r]),A=ut(be=>be.settingsGitmojiEnabled),P=ps(be=>be.projects),[$,R]=i.useState(!1),[O,T]=i.useState(null);i.useEffect(()=>{const be=a?.projectDirectory;if(!be){T(null);return}let U=!1;return Wo(be).then(te=>{if(U)return;const Se=te.trim();T(Se&&Se!=="HEAD"?Se:null)}).catch(()=>{U||T(null)}),()=>{U=!0}},[a?.projectDirectory]);const _=i.useMemo(()=>{const be=xd(r),U=xd(a?.projectDirectory);return P.map(Se=>({id:Se.id,path:Se.path,label:Se.label,normalizedPath:xd(Se.path)})).sort((Se,Je)=>Je.normalizedPath.length-Se.normalizedPath.length).find(Se=>Se.normalizedPath?U&&Se.normalizedPath===U?!0:be===Se.normalizedPath||be.startsWith(`${Se.normalizedPath}/`):!1)??null},[r,P,a?.projectDirectory]),[F,I]=i.useState(D?.commitMessage??""),[E,W]=i.useState(!1),V=i.useRef(null),[ve,oe]=i.useState(null),[Z,ce]=i.useState(null),[Q,Y]=i.useState(25),[ie,B]=i.useState(!1),{triggerFireworks:se}=wD(),H=t==="sidebar",le=i.useRef(new Map),ge=i.useRef(0),z=i.useCallback(()=>{ge.current+=1,B(!0)},[]),J=i.useCallback(()=>{ge.current=Math.max(0,ge.current-1),ge.current===0&&B(!1)},[]),[je,X]=i.useState(()=>new Set(D?.selectedPaths??[])),[G,ae]=i.useState(!1),[me,Oe]=i.useState(new Set),[Be,fe]=i.useState(0),[q,ye]=i.useState(!1),[he,He]=i.useState(D?.generatedHighlights??[]),ot=i.useCallback(()=>{const be=V.current;be&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{be.scrollTo({top:be.scrollHeight,behavior:"smooth"})})})},[]),ue=a?.projectDirectory||null,Ve=h?.current||null,De=i.useMemo(()=>{const be=h?.tracking;return be?be.startsWith("origin/"):!0},[h?.tracking]),we=i.useMemo(()=>{const be=a?.createdFromBranch,U=typeof be=="string"?be.trim():"",te=typeof h?.current=="string"?h.current.trim():"",Se=typeof O=="string"?O.trim():"";return U?U===te&&U.startsWith("opencode/")&&Se.length>0&&Se!==U?Se:U:Se||te||"HEAD"},[a?.createdFromBranch,h,O]),Fe=i.useCallback(()=>{He([])},[]),[Pe,$e]=i.useState(new Set),[Ze,Ue]=i.useState(new Map),[Ee,Re]=i.useState(new Set),[Xe,st]=i.useState(null),[St,mt]=i.useState([]),[Tt,qt]=i.useState(""),[yt,os]=i.useState(!1),[cs,ds]=i.useState(()=>{if(typeof window>"u")return"commit";const be=window.localStorage.getItem(rh);return fI(be)?be:"commit"}),[de,ke]=i.useState([]),[We,qe]=i.useState(null),[et,ct]=i.useState([]),[bt,at]=i.useState(!1),[_t,Nt]=i.useState([]),[Gt,zt]=i.useState("merge"),Ct=i.useMemo(()=>n?`ikanban.conflict:${n}`:null,[n]),Qt=i.useCallback((be,U,te)=>{if(!Ct||typeof window>"u")return;const Se={directory:be,conflictFiles:U,operation:te};window.localStorage.setItem(Ct,JSON.stringify(Se))},[Ct]),Mt=i.useCallback(()=>{!Ct||typeof window>"u"||window.localStorage.removeItem(Ct)},[Ct]);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(rh,cs)},[cs]),i.useEffect(()=>{if(!Ct||typeof window>"u"||!r)return;const be=window.localStorage.getItem(Ct);if(be)try{const U=JSON.parse(be);if(U.directory!==r){window.localStorage.removeItem(Ct);return}Nt(U.conflictFiles??[]),zt(U.operation??"merge"),at(!0)}catch{window.localStorage.removeItem(Ct)}},[Ct,r]);const[Zt,jt]=i.useState(!1),[es,Ye]=i.useState("merge"),[ft,vt]=i.useState(""),pt=i.useCallback(be=>{navigator.clipboard.writeText(be).then(()=>{K.success("Commit hash copied")}).catch(()=>{K.error("Failed to copy")})},[]),Rt=i.useCallback(be=>{$e(U=>{const te=new Set(U);return te.has(be)?te.delete(be):te.add(be),te})},[]);i.useEffect(()=>{if(!r||!s)return;const be=Array.from(Pe).filter(U=>!Ze.has(U)&&!Ee.has(U));if(be.length!==0){Re(U=>{const te=new Set(U);for(const Se of be)te.add(Se);return te});for(const U of be)s.getCommitFiles(r,U).then(te=>{Ue(Se=>new Map(Se).set(U,te.files))}).catch(te=>{console.error("Failed to fetch commit files:",te),Ue(Se=>new Map(Se).set(U,[]))}).finally(()=>{Re(te=>{const Se=new Set(te);return Se.delete(U),Se})})}},[Pe,r,s,Ze,Ee]),i.useEffect(()=>{r&&oh.set(r,{directory:r,selectedPaths:Array.from(je),commitMessage:F,generatedHighlights:he})},[F,r,je,he]),i.useEffect(()=>{u(),m(),f()},[u,m,f]),i.useEffect(()=>{if(!r||!s?.getRemoteUrl){st(null);return}s.getRemoteUrl(r).then(st).catch(()=>st(null))},[r,s]),i.useEffect(()=>{if(!r||!s?.getRemotes){ke([]);return}s.getRemotes(r).then(ke).catch(()=>ke([]))},[r,s]),i.useEffect(()=>{if(!A){mt([]);return}let be=!1;const U=gI();return U&&(mt(U.gitmojis),yI(U))?()=>{be=!0}:((async()=>{try{const Se=await fetch(hI);if(!Se.ok)throw new Error(`Failed to load gitmojis: ${Se.statusText}`);const Je=await Se.json(),rt=Array.isArray(Je.gitmojis)?Je.gitmojis.filter(nb):[];be||(mt(rt),xI(rt))}catch(Se){be||console.warn("Failed to load gitmoji list:",Se)}})(),()=>{be=!0})},[A]),i.useEffect(()=>{r&&(j(r),or.getState().directories.get(r)?.status||k(r,s,{force:!0}))},[r,j,k,s]);const Ft=i.useCallback(async(be=!0)=>{if(r)try{await Promise.all([N(r,s),w(r,s)])}catch(U){if(be){const te=U instanceof Error?U.message:"Failed to refresh repository state";K.error(te)}}},[r,s,N,w]),Pt=i.useCallback(async()=>{r&&await C(r,s,Q)},[r,s,C,Q]),Jt=i.useCallback(async()=>{r&&await S(r,s)},[r,s,S]);i.useEffect(()=>{if(!r||!s?.hasLocalIdentity||p!==!0)return;const be=typeof d=="string"?d.trim():"";if(!be||be==="global"||le.current.get(r)===be)return;let te=!1;return(async()=>{try{const Je=await s.hasLocalIdentity?.(r);if(te||Je===!0)return;z(),await s.setGitIdentity(r,be),le.current.set(r,be),await Jt()}catch(Je){console.warn("Failed to auto-apply default git identity:",Je)}finally{te||J()}})(),()=>{te=!0}},[z,r,d,J,s,p,Jt]);const Ns=i.useMemo(()=>{if(!h)return[];const be=h.files??[],U=new Map;for(const te of be)U.set(te.path,te);return Array.from(U.values()).sort((te,Se)=>te.path.localeCompare(Se.path))},[h]);i.useEffect(()=>{if(!h||Ns.length===0){X(new Set),ae(!1);return}X(be=>{const U=new Set,te=be??new Set;for(const Se of Ns)te.has(Se.path)?U.add(Se.path):G||U.add(Se.path);return U})},[h,Ns,G]);const Ts=async(be,U)=>{if(r){oe(be);try{if(be==="fetch"){if(!U)throw new Error("No remote available for fetch");await s.gitFetch(r,{remote:U.name}),K.success(`Fetched from ${U.name}`)}else if(be==="pull"){if(!U)throw new Error("No remote available for pull");const te=await s.gitPull(r,{remote:U.name});K.success(`Pulled ${te.files.length} file${te.files.length===1?"":"s"} from ${U.name}`)}else be==="push"&&(await s.gitPush(r),K.success("Pushed to upstream"));await Ft(!1),await Pt()}catch(te){const Se=te instanceof Error?te.message:`Failed to ${be==="pull"?"pull":be}`;K.error(Se)}finally{oe(null)}}},sr=async(be={})=>{if(!r)return;if(!F.trim()){K.error("Please enter a commit message");return}const U=Array.from(je).sort();if(U.length===0){K.error("Select at least one file to commit");return}const te=be.pushAfter?"commitAndPush":"commit";ce(te);try{await s.createGitCommit(r,F.trim(),{files:U}),K.success("Commit created successfully"),I(""),X(new Set),ae(!1),Fe(),await Ft(),be.pushAfter?(await s.gitPush(r),K.success("Pushed to upstream"),se(),await Ft(!1)):await Ft(!1),await Pt(),fe(Se=>Se+1)}catch(Se){const Je=Se instanceof Error?Se.message:"Failed to create commit";K.error(Je)}finally{ce(null)}},Xs=i.useCallback(async()=>{if(r){if(je.size===0){K.error("Select at least one file to describe");return}ye(!0);try{const be=ut.getState().settingsZenModel,{message:U}=await s.generateCommitMessage(r,Array.from(je),be?{zenModel:be}:void 0),te=U.subject?.trim()??"",Se=Array.isArray(U.highlights)?U.highlights:[];if(te){let Je=te;if(A&&St.length>0){const rt=bI(te,St);if(rt){const{code:lt,emoji:Ke}=rt;!te.startsWith(lt)&&!te.startsWith(Ke)&&(Je=`${lt} ${te}`)}}I(Je)}He(Se),ot()}catch(be){const U=be instanceof Error?be.message:"Failed to generate commit message";K.error(U)}finally{ye(!1)}}},[r,je,s,A,St,ot]),_s=async(be,U)=>{if(!r||!h)return;const te=h.current??null,Se=U?.name??"origin";try{await s.createBranch(r,be,te??"HEAD"),K.success(`Created branch ${be}`),await s.checkoutBranch(r,be);let Je=!1;try{await s.gitPush(r,{remote:Se,branch:be,options:["--set-upstream"]}),Je=!0}catch(rt){const lt=rt instanceof Error?rt.message:`Unable to push new branch to ${Se}.`;K.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",lt]})})}await Ft(),await Pt(),Je&&K.success(`Upstream set for ${be} on ${Se}`)}catch(Je){const rt=Je instanceof Error?Je.message:"Failed to create branch";throw K.error(rt),Je}},mr=async(be,U)=>{if(r)try{await s.renameBranch(r,be,U),K.success(`Renamed branch ${be} to ${U}`),await Ft(),await Pt()}catch(te){const Se=te instanceof Error?te.message:`Failed to rename branch ${be} to ${U}`;K.error(Se)}},Zs=async be=>{if(!r)return;const U=be.replace(/^remotes\//,"");if(h?.current!==U)try{await s.checkoutBranch(r,U),K.success(`Checked out ${U}`),await Ft(),await Pt()}catch(te){const Se=te instanceof Error?te.message:`Failed to checkout ${U}`;K.error(Se)}},gr=async be=>{if(r){z();try{await s.setGitIdentity(r,be.id),K.success(`Applied "${be.name}" to repository`),await Jt()}catch(U){const te=U instanceof Error?U.message:"Failed to apply git identity";K.error(te)}finally{J()}}},Ie=i.useMemo(()=>g?.all?g.all.filter(be=>!be.startsWith("remotes/")).sort():[],[g]),Ge=i.useMemo(()=>g?.all?g.all.filter(be=>be.startsWith("remotes/")).map(be=>be.replace(/^remotes\//,"")).sort():[],[g]),At=i.useMemo(()=>{if(de.length>0)return de;const be=new Set,U=h?.tracking?.trim();U&&U.includes("/")&&be.add(U.split("/")[0]);for(const te of Ge){const Se=te.indexOf("/");Se>0&&be.add(te.slice(0,Se))}return be.size===0&&Xe&&be.add("origin"),Array.from(be).map(te=>({name:te,fetchUrl:Xe??"",pushUrl:Xe??""}))},[de,Ge,Xe,h?.tracking]),it=i.useMemo(()=>{const be=new Set(At.map(Je=>Je.name)),U=Je=>{if(!Je)return"";let rt=Je.trim();if(!rt||rt==="HEAD")return"";if(Ie.includes(rt))return rt;rt.startsWith("refs/heads/")&&(rt=rt.slice(11)),rt.startsWith("heads/")&&(rt=rt.slice(6)),rt.startsWith("remotes/")&&(rt=rt.slice(8));const lt=rt.indexOf("/");if(lt>0){const Ke=rt.slice(0,lt);if(be.has(Ke)){const Dt=rt.slice(lt+1).trim();Dt&&(rt=Dt)}}return rt},te=U(typeof a?.createdFromBranch=="string"?a.createdFromBranch:"");if(te)return te;const Se=U(typeof O=="string"?O:"");return Se||(Ie.includes("main")?"main":Ie.includes("master")?"master":Ie.includes("develop")?"develop":"main")},[At,Ie,O,a?.createdFromBranch]),Kt=i.useMemo(()=>{const be=new Map;c&&be.set(c.id,c);let U=null;if(Xe)try{let te=Xe.trim();te.startsWith("git@")&&(te=`https://${te.slice(4).replace(":","/")}`),te.endsWith(".git")&&(te=te.slice(0,-4));const Se=new URL(te);U=Se.hostname+Se.pathname}catch{}for(const te of l){if(te.authType!=="token"){be.set(te.id,te);continue}const Se=te.host;if(!Se){be.set(te.id,te);continue}if(!Se.includes("/")){be.set(te.id,te);continue}U&&U===Se&&be.set(te.id,te)}return Array.from(be.values())},[l,c,Xe]),It=i.useMemo(()=>{if(y?.userName&&y?.userEmail){const be=l.find(U=>U.userName===y.userName&&U.userEmail===y.userEmail);return be||(c&&c.userName===y.userName&&c.userEmail===y.userEmail?c:{id:"local-config",name:y.userName,userName:y.userName,userEmail:y.userEmail,sshKey:y.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return c??null},[y,l,c]),Ps=je.size,Hs=b||ve!==null||Z!==null,Es=!!(a&&ue&&Ve&&De),er=!!(r&&h?.current&&h?.tracking&&h.current!==it),Cs=!!h?.current,ar=Es&&ue&&Ve&&a?{repoRoot:ue,sourceBranch:Ve,worktreeMetadata:a}:null,ir=er&&r&&h?.current?{directory:r,branch:h.current}:null,qs=be=>{X(U=>{const te=new Set(U);return te.has(be)?te.delete(be):te.add(be),te}),ae(!0)},Ir=()=>{const be=new Set(Ns.map(U=>U.path));X(be),ae(!0)},fr=()=>{X(new Set),ae(!0)},xr=i.useCallback(async be=>{if(r){Oe(U=>{const te=new Set(U);return te.add(be),te});try{await s.revertGitFile(r,be),K.success(`Reverted ${be}`),await Ft(!1)}catch(U){const te=U instanceof Error?U.message:"Failed to revert changes";K.error(te)}finally{Oe(U=>{const te=new Set(U);return te.delete(be),te})}}},[r,Ft,s]),yr=i.useCallback(()=>{if(he.length===0)return;const be=he.map(U=>U.trim()).filter(Boolean);if(be.length===0){Fe();return}I(U=>{const te=U.trim(),Se=te.length>0?`
|
|
274
|
+
|
|
275
|
+
`:"";return`${te}${Se}${be.join(`
|
|
276
|
+
`)}`.trim()})},[he,Fe]),_r=i.useCallback((be,U)=>{const te=U||be;I(Se=>{const Je=Se.trimStart();return Je.startsWith(be)||U&&Je.startsWith(U)?Se:`${te.endsWith(" ")?te:`${te} `}${Se}`.trimStart()}),qt(""),W(!1)},[]),pe=i.useCallback(be=>{Y(be),r&&(M(r,be),C(r,s,be))},[r,M,C,s]),ee=i.useCallback(be=>{const U=be instanceof Error?be.message.toLowerCase():"";return U.includes("uncommitted changes")||U.includes("local changes")||U.includes("your local changes would be overwritten")||U.includes("please commit your changes or stash them")||U.includes("cannot rebase: you have unstaged changes")||U.includes("error: cannot pull with rebase")},[]),xe=i.useCallback((be,U)=>{ct(te=>[...te,{message:be,status:U,timestamp:Date.now()}])},[]),Ne=i.useCallback((be,U)=>{ct(te=>{if(te.length===0)return te;const Se=[...te];return Se[Se.length-1]={...Se[Se.length-1],status:be,...U?{message:U}:{}},Se})},[]),ze=i.useCallback(()=>{ct([])},[]),tt=i.useCallback(()=>{ct([]),qe(null)},[]),kt=i.useCallback(async be=>{if(!r)return;qe("merge"),ze();const U=h?.current;try{const te=be.indexOf("/");if(te>0){const Je=be.substring(0,te),rt=be.substring(te+1);xe(`Fetching ${Je}/${rt}...`,"running"),await s.gitFetch(r,{remote:Je,branch:rt}),Ne("done",`Fetched ${Je}/${rt}`)}xe(`Merging ${be} into ${U}...`,"running");const Se=await s.merge(r,{branch:be});Se.conflict?(Ne("error","Merge conflicts detected"),Nt(Se.conflictFiles??[]),zt("merge"),at(!0),Qt(r,Se.conflictFiles??[],"merge")):(Ne("done",`Merged ${be} into ${U}`),Mt(),xe("Refreshing repository status...","running"),await Ft(),await Pt(),Ne("done","Repository status updated"))}catch(te){if(ee(te))Ne("error","Uncommitted changes detected"),Ye("merge"),vt(be),jt(!0);else{const Se=te instanceof Error?te.message:`Failed to merge ${be}`;Ne("error",Se)}}},[r,s,h,Ft,Pt,ee,Qt,Mt,xe,Ne,ze]),re=i.useCallback(async be=>{if(!r)return;qe("rebase"),ze();const U=h?.current;try{const te=be.indexOf("/");if(te>0){const Je=be.substring(0,te),rt=be.substring(te+1);xe(`Fetching ${Je}/${rt}...`,"running"),await s.gitFetch(r,{remote:Je,branch:rt}),Ne("done",`Fetched ${Je}/${rt}`)}xe(`Rebasing ${U} onto ${be}...`,"running");const Se=await s.rebase(r,{onto:be});Se.conflict?(Ne("error","Rebase conflicts detected"),Nt(Se.conflictFiles??[]),zt("rebase"),at(!0),Qt(r,Se.conflictFiles??[],"rebase")):(Ne("done",`Rebased ${U} onto ${be}`),Mt(),xe("Refreshing repository status...","running"),await Ft(),await Pt(),Ne("done","Repository status updated"))}catch(te){if(ee(te))Ne("error","Uncommitted changes detected"),Ye("rebase"),vt(be),jt(!0);else{const Se=te instanceof Error?te.message:`Failed to rebase onto ${be}`;Ne("error",Se)}}},[r,s,h,Ft,Pt,ee,Qt,Mt,xe,Ne,ze]),Le=i.useCallback(async()=>{if(r)try{Gt==="merge"?(await s.abortMerge(r),K.success("Merge aborted")):(await s.abortRebase(r),K.success("Rebase aborted")),Mt(),await Ft(),await Pt()}catch(be){const U=be instanceof Error?be.message:`Failed to abort ${Gt}`;K.error(U)}},[r,s,Gt,Ft,Pt,Mt]),Ce=i.useMemo(()=>h?.files?h.files.some(be=>be.index==="U"||be.working_dir==="U"||be.index==="A"&&be.working_dir==="A"||be.index==="D"&&be.working_dir==="D"):!1,[h?.files]),_e=i.useCallback(async()=>{if(r)try{const be=!!h?.mergeInProgress?.head,U=!!(h?.rebaseInProgress?.headName||h?.rebaseInProgress?.onto);if(be){const te=await s.continueMerge(r);te.conflict?(Nt(te.conflictFiles??[]),zt("merge"),at(!0),Qt(r,te.conflictFiles??[],"merge"),K.error("Merge conflicts detected")):(Mt(),K.success("Merge completed"),await Ft(),await Pt())}else if(U){const te=await s.continueRebase(r);te.conflict?(Nt(te.conflictFiles??[]),zt("rebase"),at(!0),Qt(r,te.conflictFiles??[],"rebase"),K.error("Rebase conflicts detected")):(Mt(),K.success("Rebase step completed"),await Ft(),await Pt())}}catch(be){const U=be instanceof Error?be.message:"Failed to continue operation";K.error(U)}},[r,s,h,Ft,Pt,Qt,Mt]),Qe=i.useCallback(async()=>{if(r)try{!!h?.mergeInProgress?.head?(await s.abortMerge(r),K.success("Merge aborted")):(await s.abortRebase(r),K.success("Rebase aborted")),Mt(),await Ft(),await Pt()}catch(be){const U=be instanceof Error?be.message:"Failed to abort operation";K.error(U)}},[r,s,h,Ft,Pt,Mt]),dt=i.useCallback(()=>{if(!r)return;const U=!!h?.mergeInProgress?.head?"merge":"rebase",te=h?.files?.filter(Se=>Se.index==="U"||Se.working_dir==="U").map(Se=>Se.path)??[];te.length>0&&Nt(te),zt(U),at(!0)},[r,h]),$t=i.useCallback(async be=>{if(!r)return;const U=h?.current,te=es,Se=ft;try{await s.stash(r,{message:`Auto-stash before ${te} with ${Se}`,includeUntracked:!0})}catch(lt){const Ke=lt instanceof Error?lt.message:"Failed to stash changes";K.error(Ke);return}let Je=!1,rt=!1;try{if(te==="merge"){const lt=await s.merge(r,{branch:Se});lt.conflict?(rt=!0,Nt(lt.conflictFiles??[]),zt("merge"),at(!0)):(Je=!0,K.success(`Merged ${Se} into ${U}`))}else{const lt=await s.rebase(r,{onto:Se});lt.conflict?(rt=!0,Nt(lt.conflictFiles??[]),zt("rebase"),at(!0)):(Je=!0,K.success(`Rebased ${U} onto ${Se}`))}if(be&&Je)try{await s.stashPop(r),K.success("Stashed changes restored")}catch(lt){const Ke=lt instanceof Error?lt.message:"Failed to restore stashed changes";K.error(Ke)}else be&&rt&&K.info("Stashed changes will need to be restored manually after resolving conflicts");await Ft(),await Pt()}catch(lt){if(be)try{await s.stashPop(r)}catch{}throw lt}},[r,s,h,es,ft,Ft,Pt]);return r?b&&p===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(Ot,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):p===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Ms,{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($D,{status:h,localBranches:Ie,remoteBranches:Ge,branchInfo:g?.branches,syncAction:ve,remotes:At,onFetch:be=>Ts("fetch",be),onPull:be=>Ts("pull",be),onPush:()=>Ts("push"),onCheckoutBranch:Zs,onCreateBranch:_s,onRenameBranch:mr,activeIdentityProfile:It,availableIdentities:Kt,onSelectIdentity:gr,isApplyingIdentity:ie,isWorktreeMode:!!a,isSidebarMode:H,onOpenHistory:()=>os(!0),onOpenBranchPicker:_?()=>R(!0):void 0}),r&&(h?.mergeInProgress?.head||h?.rebaseInProgress?.headName||h?.rebaseInProgress?.onto)&&e.jsx(cI,{mergeInProgress:h?.mergeInProgress,rebaseInProgress:h?.rebaseInProgress,onContinue:_e,onAbort:Qe,onResolveWithAI:dt,hasUnresolvedConflicts:Ce,isLoading:b}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.jsx("div",{className:"h-full min-h-0 flex flex-col",children:e.jsxs("div",{className:L("min-w-0 min-h-0 h-full bg-muted/10 flex flex-col",H&&"border-t border-border/40"),children:[e.jsx("div",{className:"px-3 py-3",children:e.jsx(di,{value:cs,onValueChange:ds,collapseLabelsOnSmall:!0,collapseLabelsOnNarrow:H,tabs:[{value:"commit",label:"Commit",icon:ec},{value:"branch",label:"Update",icon:Io},{value:"pr",label:"PR",icon:no},{value:"worktree",label:"Worktree",icon:Cg}]})}),e.jsx("div",{className:"h-px bg-border/40"}),e.jsxs(Ut,{as:Ti,ref:V,outerClassName:"flex-1 min-h-0",className:"px-4 py-4",disableHorizontal:!0,preventOverscroll:!0,children:[cs==="commit"?e.jsx("div",{className:"space-y-4",children:(Ns?.length??0)>0?e.jsxs(e.Fragment,{children:[e.jsx(VD,{variant:"plain",maxListHeightClassName:"max-h-[40vh]",changeEntries:Ns,selectedPaths:je,diffStats:h?.diffStats,revertingPaths:me,onToggleFile:qs,onSelectAll:Ir,onClearSelection:fr,onViewDiff:be=>Te.getState().navigateToDiff(be),onRevertFile:xr}),e.jsx(KD,{variant:"plain",selectedCount:Ps,commitMessage:F,onCommitMessageChange:I,generatedHighlights:he,onInsertHighlights:yr,onClearHighlights:Fe,onGenerateMessage:Xs,isGeneratingMessage:q,onCommit:()=>sr({pushAfter:!1}),onCommitAndPush:()=>sr({pushAfter:!0}),commitAction:Z,isBusy:Hs,gitmojiEnabled:A,onOpenGitmojiPicker:()=>W(!0)})]}):e.jsx(qD,{behind:At.length>0?h?.behind??0:0,isPulling:ve==="pull",onPull:()=>{const be=At[0];be&&Ts("pull",be)}})}):null,cs==="branch"?e.jsx("div",{className:"space-y-4",children:Cs?e.jsx(dI,{mode:"inline",currentBranch:h?.current,localBranches:Ie,remoteBranches:Ge,onMerge:kt,onRebase:re,disabled:Hs,isOperating:We!==null,operationLogs:et,onOperationComplete:tt}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Branch actions unavailable."})}):null,cs==="worktree"?ar?e.jsx(ED,{variant:"plain",repoRoot:ar.repoRoot,sourceBranch:ar.sourceBranch,worktreeMetadata:ar.worktreeMetadata,localBranches:Ie,defaultTargetBranch:we,refreshKey:Be,onRefresh:()=>{r&&(N(r,s),w(r,s),C(r,s,Q))}}):e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:"Re-integrate commits"}),e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Available in worktree mode."})]}):null,cs==="pr"?ir?e.jsx(aI,{variant:"plain",directory:ir.directory,branch:ir.branch,baseBranch:it,remotes:de,remoteBranches:Ge,onGeneratedDescription:ot}):e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:"Pull Request"}),e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Push a non-base branch (with upstream) to create a PR."})]}):null]})]})})}),e.jsx(bs,{open:yt,onOpenChange:os,children:e.jsxs(vs,{className:"max-w-5xl max-h-[80vh] flex flex-col overflow-hidden",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"History"}),e.jsx(Is,{children:"Browse recent commits and inspect file-level changes."})]}),e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(XD,{log:x,isLogLoading:v,logMaxCount:Q,onLogMaxCountChange:pe,expandedCommitHashes:Pe,onToggleCommit:Rt,commitFilesMap:Ze,loadingCommitHashes:Ee,onCopyHash:pt,showHeader:!1})})]})}),e.jsx(bs,{open:E,onOpenChange:W,children:e.jsxs(vs,{className:"max-w-md p-0 overflow-hidden",children:[e.jsx(js,{className:"px-4 pt-4",children:e.jsx(Ss,{children:"Pick a gitmoji"})}),e.jsxs(Mi,{className:"h-[420px]",children:[e.jsx(Ea,{placeholder:"Search gitmojis...",value:Tt,onValueChange:qt}),e.jsxs(Ai,{children:[e.jsx(Di,{children:"No gitmojis found."}),e.jsx(hn,{children:(St.length===0?[]:St.filter(be=>{const U=Tt.trim().toLowerCase();return U?be.emoji.includes(U)||be.code.toLowerCase().includes(U)||be.description.toLowerCase().includes(U):!0})).map(be=>e.jsxs(Qs,{onSelect:()=>_r(be.emoji,be.code),children:[e.jsx("span",{className:"text-lg",children:be.emoji}),e.jsx("span",{className:"typography-ui-label text-foreground",children:be.code}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:be.description})]},be.code))})]})]})]})}),r&&e.jsx(iI,{open:bt,onOpenChange:at,conflictFiles:_t,directory:r,operation:Gt,onAbort:Le,onClearState:Mt}),e.jsx(lI,{open:Zt,onOpenChange:jt,operation:es,targetBranch:ft,onConfirm:$t}),e.jsx(mI,{open:$,onOpenChange:R,project:_})]}):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."})})},vI=1e6,wI="terminal-store";let ih=!1;const yd=t=>typeof t=="object"&&t!==null,jI=t=>{const s=/^tab-(\d+)$/.exec(t);if(!s)return null;const r=Number(s[1]);return Number.isFinite(r)?r:null};function an(t){let s=t.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const bd=(t,s)=>({id:t,terminalSessionId:null,label:s,bufferChunks:[],bufferLength:0,isConnecting:!1,createdAt:Date.now()}),vd=t=>({tabs:[t],activeTabId:t.id}),ea=(t,s)=>t.tabs.findIndex(r=>r.id===s),Ao=Ls()(Us(Ar((t,s)=>({sessions:new Map,nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:r=>{const n=an(r);n&&t(o=>{if(o.sessions.has(n))return o;const a=new Map(o.sessions),l=`tab-${o.nextTabId}`,c=bd(l,"Terminal");return a.set(n,vd(c)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:r=>{const n=an(r);return s().sessions.get(n)},getActiveTab:r=>{const n=an(r),o=s().sessions.get(n);if(!o)return;const a=o.activeTabId;return a?o.tabs.find(l=>l.id===a)??o.tabs[0]:o.tabs[0]},createTab:r=>{const n=an(r);if(!n)return"tab-invalid";const o=`tab-${s().nextTabId}`;return t(a=>{const l=new Map(a.sessions),c=l.get(n),d=a.nextTabId+1,m=`Terminal ${(c?.tabs.length??0)+1}`,f=bd(o,m);return c?l.set(n,{...c,tabs:[...c.tabs,f]}):l.set(n,vd(f)),{sessions:l,nextTabId:d}}),o},setActiveTab:(r,n)=>{const o=an(r);t(a=>{const l=new Map(a.sessions),c=l.get(o);return!c||c.activeTabId===n||ea(c,n)<0?a:(l.set(o,{...c,activeTabId:n}),{sessions:l})})},closeTab:async(r,n)=>{const o=an(r),c=s().sessions.get(o)?.tabs.find(d=>d.id===n)?.terminalSessionId??null;if(c)try{await Oj(c)}catch{}t(d=>{const u=new Map(d.sessions),m=u.get(o);if(!m)return d;const f=ea(m,n);if(f<0)return d;const p=m.tabs.filter(g=>g.id!==n);if(p.length===0){const g=`tab-${d.nextTabId}`,x=bd(g,"Terminal");return u.set(o,vd(x)),{sessions:u,nextTabId:d.nextTabId+1}}let h=m.activeTabId;return m.activeTabId===n&&(h=p[Math.min(f,p.length-1)]?.id??p[0]?.id??null),u.set(o,{...m,tabs:p,activeTabId:h}),{sessions:u}})},setTabSessionId:(r,n,o)=>{const a=an(r);t(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ea(d,n);if(u<0)return l;const m=d.tabs[u],f=m.terminalSessionId!==o,p={...m,terminalSessionId:o,isConnecting:!1,...f?{bufferChunks:[],bufferLength:0}:{}},h=[...d.tabs];return h[u]=p,c.set(a,{...d,tabs:h}),{sessions:c}})},setConnecting:(r,n,o)=>{const a=an(r);t(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ea(d,n);if(u<0)return l;const m=[...d.tabs];return m[u]={...m[u],isConnecting:o},c.set(a,{...d,tabs:m}),{sessions:c}})},appendToBuffer:(r,n,o)=>{if(!o)return;const a=an(r);t(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ea(d,n);if(u<0)return l;const m=d.tabs[u],f=l.nextChunkId,p={id:f,data:o},h=[...m.bufferChunks,p];let g=m.bufferLength+o.length;for(;g>vI&&h.length>1;){const y=h.shift();if(!y)break;g-=y.data.length}const x=[...d.tabs];return x[u]={...m,bufferChunks:h,bufferLength:g},c.set(a,{...d,tabs:x}),{sessions:c,nextChunkId:f+1}})},clearBuffer:(r,n)=>{const o=an(r);t(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const d=ea(c,n);if(d<0)return a;const u=[...c.tabs];return u[d]={...u[d],bufferChunks:[],bufferLength:0},l.set(o,{...c,tabs:u}),{sessions:l}})},removeDirectory:r=>{const n=an(r);t(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAll:()=>{t({sessions:new Map,nextChunkId:1,nextTabId:1})}}),{name:wI,storage:Dr(()=>Uj()),partialize:t=>({sessions:Array.from(t.sessions.entries()).map(([s,r])=>[s,{activeTabId:r.activeTabId,tabs:r.tabs.map(n=>({id:n.id,label:n.label,terminalSessionId:n.terminalSessionId,createdAt:n.createdAt}))}]),nextTabId:t.nextTabId}),merge:(t,s)=>{if(!yd(t))return s;const r=Array.isArray(t.sessions)?t.sessions:[],n=new Map;let o=0;for(const c of r){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!yd(u))continue;const m=Array.isArray(u.tabs)?u.tabs:[],f=[];for(const g of m){if(!yd(g))continue;const x=typeof g.id=="string"?g.id:null;if(!x)continue;const y=jI(x);y!==null&&(o=Math.max(o,y)),f.push({id:x,label:typeof g.label=="string"?g.label:"Terminal",terminalSessionId:typeof g.terminalSessionId=="string"||g.terminalSessionId===null?g.terminalSessionId:null,createdAt:typeof g.createdAt=="number"?g.createdAt:Date.now(),bufferChunks:[],bufferLength:0,isConnecting:!1})}if(f.length===0)continue;const p=typeof u.activeTabId=="string"?u.activeTabId:null,h=p?f.some(g=>g.id===p):!1;n.set(d,{tabs:f,activeTabId:h?p:f[0].id})}const a=typeof t.nextTabId=="number"&&Number.isFinite(t.nextTabId)?t.nextTabId:1,l=Math.max(s.nextTabId,a,o+1);return{...s,sessions:n,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!ih){ih=!0;const t=Ao.persist,s=()=>{Ao.getState().hasHydrated||Ao.setState({hasHydrated:!0})};t?.hasHydrated?.()?s():t?.onFinishHydration?t.onFinishHydration(s):s()}const ob=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),SI=[{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'}],NI=[{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'}],ab=t=>Object.fromEntries(t.map(s=>[s.id,s])),lh=ab(SI),ko=ab(NI),kI="ibm-plex-sans",Sl="ibm-plex-mono";function CI(t){const{colors:s}=t,r=s.syntax.base;return{background:s.surface.background,foreground:r.foreground,cursor:s.interactive.cursor,cursorAccent:s.surface.background,selectionBackground:s.interactive.selection,selectionForeground:s.interactive.selectionForeground,selectionInactiveBackground:s.interactive.selection+"50",black:s.surface.muted,red:s.status.error,green:s.status.success,yellow:s.status.warning,blue:r.function,magenta:r.keyword,cyan:r.type,white:r.foreground,brightBlack:r.comment,brightRed:s.status.error,brightGreen:s.status.success,brightYellow:s.status.warning,brightBlue:r.function,brightMagenta:r.keyword,brightCyan:r.type,brightWhite:s.surface.elevatedForeground}}function MI(t,s,r,n,o=!1){const l=`${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:!1,cursorStyle:"bar",fontSize:s,lineHeight:1.15,fontFamily:l,allowTransparency:!1,theme:{background:r.background,foreground:r.foreground,cursor:r.cursor,cursorAccent:r.cursorAccent,selectionBackground:r.selectionBackground,selectionForeground:r.selectionForeground,black:r.black,red:r.red,green:r.green,yellow:r.yellow,blue:r.blue,magenta:r.magenta,cyan:r.cyan,white:r.white,brightBlack:r.brightBlack,brightRed:r.brightRed,brightGreen:r.brightGreen,brightYellow:r.brightYellow,brightBlue:r.brightBlue,brightMagenta:r.brightMagenta,brightCyan:r.brightCyan,brightWhite:r.brightWhite},scrollback:1e4,ghostty:n,disableStdin:o}}let wd=null;function AI(){return wd||(wd=sj.load()),wd}function DI(t){if(typeof window>"u")return null;const s=[t,...Array.from(t.querySelectorAll("*"))];let r=null;for(const n of s){const a=window.getComputedStyle(n).overflowY;if(!(a!=="auto"&&a!=="scroll")){if(n.scrollHeight-n.clientHeight>2)return n;r||(r=n)}}return r}const xu=i.forwardRef(({sessionKey:t,chunks:s,onInput:r,onResize:n,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d,autoFocus:u=!0,keyboardAvoidTargetId:m},f)=>{const p=i.useRef(null),h=i.useRef(null),g=i.useRef(null),x=i.useRef(null),y=i.useRef(r),b=i.useRef(n),v=i.useRef(null),j=i.useRef(""),k=i.useRef(null),N=i.useRef(!1),w=i.useRef(null),C=i.useRef(null),S=i.useRef(null),M=i.useRef(0),D=i.useRef(null),A=i.useRef(null),P=i.useRef(!1),$=i.useRef(!1),R=i.useRef(null),O=i.useRef(null),T=i.useRef(null),_=i.useRef(null),F=i.useRef(""),I=i.useRef(null),[,E]=i.useReducer(ue=>ue+1,0),[W,V]=i.useReducer(ue=>ue+1,0);y.current=r,b.current=n;const ve=typeof navigator<"u"&&/Android/i.test(navigator.userAgent),oe=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches&&window.matchMedia("(hover: none)").matches,Z=!!d&&(ve||IN()||oe),ce=i.useCallback(()=>{const ue=p.current,Ve=D.current;if(!ue)return;Array.from(ue.querySelectorAll('[contenteditable="true"]')).forEach(Fe=>{Fe.style.setProperty("caret-color","transparent"),Fe.style.outline="none"}),Array.from(ue.querySelectorAll("textarea")).forEach(Fe=>{Fe.style.setProperty("caret-color","transparent"),Fe.style.color="transparent",Fe.style.setProperty("-webkit-text-fill-color","transparent"),Fe.style.background="transparent",Fe.style.border="0",Fe.style.outline="none",Fe.style.boxShadow="none",Fe.style.textShadow="none",Fe.style.fontSize="0",Fe.style.lineHeight="0",Z&&Fe!==Ve&&Fe.getAttribute("data-terminal-disabled-input")!=="true"&&(Fe.setAttribute("data-terminal-disabled-input","true"),Fe.setAttribute("aria-hidden","true"),Fe.tabIndex=-1,Fe.disabled=!0,Fe.style.position="absolute",Fe.style.opacity="0",Fe.style.width="0px",Fe.style.height="0px",Fe.style.pointerEvents="none",Fe.style.zIndex="-1")})},[Z]),Q=i.useCallback(ue=>{if(I.current===ue)return;const Ve=g.current;if(Ve)try{if(typeof Ve.setOption=="function"){Ve.setOption("cursorBlink",ue),I.current=ue;return}Ve.options&&(Ve.options.cursorBlink=ue,I.current=ue)}catch{}},[]),Y=Z&&ve,ie=i.useCallback((ue,Ve)=>{const De=Y?A.current:D.current,we=p.current;if(!De||!we)return;const Fe=we.getBoundingClientRect(),Pe=typeof window<"u"?window.innerWidth:Fe.width,$e=typeof window<"u"?window.innerHeight:Fe.height,Ze=Fe.left+Fe.width/2,Ue=Fe.top+Fe.height-12,Ee=typeof ue=="number"?ue:Ze,Re=typeof Ve=="number"?Ve:Ue,Xe=8,st=Math.max(Xe,Math.min(Pe-Xe,Ee)),St=Math.max(Xe,Math.min($e-Xe,Re));De.style.left=`${st}px`,De.style.top=`${St}px`,De.style.bottom="",(De instanceof HTMLTextAreaElement||De instanceof HTMLInputElement)&&(De.disabled=!1,De.readOnly=!1,De.removeAttribute("disabled"),De.removeAttribute("readonly"));try{De.focus({preventScroll:!0})}catch{try{De.focus()}catch{}}},[Y]),B=i.useCallback(()=>{if(Z){ie(),Q(!0);return}g.current?.focus(),Q(!0)},[ie,Q,Z]),se=i.useCallback(ue=>ue instanceof HTMLTextAreaElement||ue instanceof HTMLInputElement?ue.value:ue.textContent??"",[]),H=i.useCallback(ue=>{if(ue instanceof HTMLTextAreaElement||ue instanceof HTMLInputElement){ue.value="";return}ue.textContent=""},[]),le=i.useCallback(ue=>{if(typeof window>"u"||Y)return;_.current!==null&&(window.clearTimeout(_.current),_.current=null);let Ve=0;const De=3,we=()=>{_.current=window.setTimeout(()=>{_.current=null;const Fe=se(ue);if(!Fe){if(Ve+=1,Ve<De){we();return}return}const Pe=F.current;F.current=Fe;const $e=Fe.startsWith(Pe)?Fe.slice(Pe.length):Fe;$e&&y.current($e.replace(/\r\n|\r|\n/g,"\r")),H(ue),F.current=""},Ve===0?0:24)};we()},[H,se,Y]);i.useEffect(()=>{const ue=p.current;if(!Z||!ue)return;const Ve=De=>{const we=De.target;if(we&&we.getAttribute("data-terminal-hidden-input")!=="true"&&ue.contains(we)){try{we.blur()}catch{}ie()}};return ue.addEventListener("focusin",Ve,!0),()=>{ue.removeEventListener("focusin",Ve,!0)}},[Z,ie]);const ge=i.useCallback(async()=>{if(typeof window>"u"||typeof document>"u")return;const ue=window.getSelection();if(!ue)return;const Ve=ue.toString();if(!Ve.trim())return;const De=p.current;if(!De)return;const we=ue.anchorNode,Fe=ue.focusNode;if(!(we&&!De.contains(we))&&!(Fe&&!De.contains(Fe))&&!(navigator.clipboard?.writeText&&await navigator.clipboard.writeText(Ve).then(()=>!0).catch(()=>!1)))try{const Pe=document.createElement("textarea");Pe.value=Ve,Pe.style.position="fixed",Pe.style.opacity="0",document.body.appendChild(Pe),Pe.focus(),Pe.select(),document.execCommand("copy"),document.body.removeChild(Pe)}catch{return}},[]),z=i.useCallback(()=>{if(typeof window>"u")return!1;const ue=window.getSelection();if(!ue||!ue.toString().trim())return!1;const De=p.current;if(!De)return!1;const we=ue.anchorNode,Fe=ue.focusNode;return!(we&&!De.contains(we)||Fe&&!De.contains(Fe))},[]),J=i.useCallback(()=>{j.current="",k.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(k.current),k.current=null,N.current=!1,w.current=null},[]),je=i.useCallback(()=>{const ue=x.current,Ve=g.current,De=p.current;if(!ue||!Ve||!De)return;const we=De.getBoundingClientRect();if(!(we.width<24||we.height<24))try{ue.fit();const Fe={cols:Ve.cols,rows:Ve.rows},Pe=v.current;(!Pe||Pe.cols!==Fe.cols||Pe.rows!==Fe.rows)&&(v.current=Fe,b.current(Fe.cols,Fe.rows))}catch{}},[]),X=i.useCallback(()=>{if(N.current)return;const ue=g.current;if(!ue){J();return}if(!j.current)return;const Ve=j.current;j.current="",N.current=!0,ue.write(Ve,()=>{N.current=!1,j.current&&(typeof window<"u"?k.current=window.requestAnimationFrame(()=>{k.current=null,X()}):X())})},[J]),G=i.useCallback(()=>{k.current===null&&(typeof window<"u"?k.current=window.requestAnimationFrame(()=>{k.current=null,X()}):X())},[X]),ae=i.useCallback(ue=>{ue&&(j.current+=ue,G())},[G]),me=i.useCallback(()=>{if(C.current?.(),C.current=null,S.current!==null&&typeof window<"u"&&(window.clearTimeout(S.current),S.current=null),!d){M.current=0;return}const ue=p.current;if(!ue)return;const Ve=g.current;if(!Ve)return;M.current=0;const De=2.2,we=2.8,Fe=25,Pe=.25,$e=8,Ze=.05,Ue=.015,Ee={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},Re=()=>typeof performance<"u"?performance.now():Date.now(),Xe=Math.max(12,Math.round(l*1.35));let st=0;const St=ke=>{if(!ke)return!1;const We=Ve.getViewportY(),qe=st+ke,et=Math.trunc(qe/Xe);return st=qe-et*Xe,et!==0&&Ve.scrollLines(et),Ve.getViewportY()!==We},mt=()=>{Ee.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(Ee.rafId),Ee.rafId=null},Tt={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const ke=Object.assign(Ee,{pointerId:null,startX:null,startY:null,moved:!1}),We=6,qe=at=>{if(at.pointerType==="touch"){mt(),ke.pointerId=at.pointerId,ke.startX=at.clientX,ke.startY=at.clientY,ke.moved=!1,ke.lastY=at.clientY,ke.lastTime=Re(),ke.velocity=0;try{ue.setPointerCapture(at.pointerId)}catch{}}},et=at=>{if(at.pointerType!=="touch"||ke.pointerId!==at.pointerId)return;if(ke.startX!==null&&ke.startY!==null&&!ke.moved){const jt=at.clientX-ke.startX,es=at.clientY-ke.startY;Math.hypot(jt,es)>=We&&(ke.moved=!0)}if(ke.lastY===null){ke.lastY=at.clientY,ke.lastTime=Re();return}const _t=ke.lastY,Nt=ke.lastTime??Re(),Gt=Re();ke.lastY=at.clientY,ke.lastTime=Gt;const zt=_t-at.clientY;if(Math.abs(zt)<1)return;const Ct=Math.max(Gt-Nt,8),Qt=De+Math.min(we,Math.abs(zt)/Fe),Mt=zt*Qt,Zt=Mt/Ct;ke.velocity=ke.velocity*(1-Pe)+Zt*Pe,ke.velocity>$e?ke.velocity=$e:ke.velocity<-$e&&(ke.velocity=-$e),ke.moved&&(at.cancelable&&at.preventDefault(),at.stopPropagation()),St(Mt)},ct=at=>{if(at.pointerType!=="touch"||ke.pointerId!==at.pointerId)return;const _t=!ke.moved;ke.pointerId=null,ke.startX=null,ke.startY=null,ke.moved=!1,ke.lastY=null,ke.lastTime=null;try{ue.releasePointerCapture(at.pointerId)}catch{}if(_t){Z?ie(at.clientX,at.clientY):g.current?.focus();return}if(typeof window>"u")return;if(Math.abs(ke.velocity)<Ze){ke.velocity=0;return}let Nt=Re();const Gt=()=>{const zt=Re(),Ct=Math.max(zt-Nt,8);Nt=zt;const Qt=St(ke.velocity*Ct)??!1,Mt=Math.sign(ke.velocity),Zt=Math.max(0,Math.abs(ke.velocity)-Ue*Ct);if(ke.velocity=Zt*Mt,!Qt||Zt<=Ze){mt(),ke.velocity=0;return}ke.rafId=window.requestAnimationFrame(Gt)};ke.rafId=window.requestAnimationFrame(Gt)};ue.addEventListener("pointerdown",qe,Tt),ue.addEventListener("pointermove",et,Tt),ue.addEventListener("pointerup",ct,Tt),ue.addEventListener("pointercancel",ct,Tt);const bt=ue.style.touchAction;ue.style.touchAction="manipulation",C.current=()=>{mt(),S.current!==null&&typeof window<"u"&&(window.clearTimeout(S.current),S.current=null),M.current=0,ue.removeEventListener("pointerdown",qe,Tt),ue.removeEventListener("pointermove",et,Tt),ue.removeEventListener("pointerup",ct,Tt),ue.removeEventListener("pointercancel",ct,Tt),ue.style.touchAction=bt};return}const yt=6,os=ke=>{ke.touches.length===1&&(mt(),Ee.lastY=ke.touches[0].clientY,Ee.lastTime=Re(),Ee.velocity=0,Ee.startX=ke.touches[0].clientX,Ee.startY=ke.touches[0].clientY,Ee.didMove=!1)},cs=ke=>{if(ke.touches.length!==1){Ee.lastY=null,Ee.lastTime=null,Ee.velocity=0,Ee.startX=null,Ee.startY=null,Ee.didMove=!1,mt();return}const We=ke.touches[0].clientX,qe=ke.touches[0].clientY;if(Ee.startX!==null&&Ee.startY!==null&&!Ee.didMove){const Ct=We-Ee.startX,Qt=qe-Ee.startY;Math.hypot(Ct,Qt)>=yt&&(Ee.didMove=!0)}if(Ee.lastY===null){Ee.lastY=qe,Ee.lastTime=Re();return}const et=Ee.lastY,ct=Ee.lastTime??Re(),bt=Re();Ee.lastY=qe,Ee.lastTime=bt;const at=et-qe;if(Math.abs(at)<1)return;const _t=Math.max(bt-ct,8),Nt=De+Math.min(we,Math.abs(at)/Fe),Gt=at*Nt,zt=Gt/_t;Ee.velocity=Ee.velocity*(1-Pe)+zt*Pe,Ee.velocity>$e?Ee.velocity=$e:Ee.velocity<-$e&&(Ee.velocity=-$e),Ee.didMove&&(ke.preventDefault(),ke.stopPropagation()),St(Gt)},ds=ke=>{const We=!Ee.didMove;Ee.lastY=null,Ee.lastTime=null;const qe=Ee.velocity;if(Ee.startX=null,Ee.startY=null,Ee.didMove=!1,We){const bt=ke.changedTouches?.[0];Z?ie(bt?.clientX,bt?.clientY):g.current?.focus();return}if(typeof window>"u")return;if(Math.abs(qe)<Ze){Ee.velocity=0;return}let et=Re();const ct=()=>{const bt=Re(),at=Math.max(bt-et,8);et=bt;const _t=St(Ee.velocity*at)??!1,Nt=Math.sign(Ee.velocity),Gt=Math.max(0,Math.abs(Ee.velocity)-Ue*at);if(Ee.velocity=Gt*Nt,!_t||Gt<=Ze){mt(),Ee.velocity=0;return}Ee.rafId=window.requestAnimationFrame(ct)};Ee.rafId=window.requestAnimationFrame(ct)};ue.addEventListener("touchstart",os,Tt),ue.addEventListener("touchmove",cs,Tt),ue.addEventListener("touchend",ds,Tt),ue.addEventListener("touchcancel",ds,Tt);const de=ue.style.touchAction;ue.style.touchAction="manipulation",C.current=()=>{mt(),S.current!==null&&typeof window<"u"&&(window.clearTimeout(S.current),S.current=null),M.current=0,ue.removeEventListener("touchstart",os,Tt),ue.removeEventListener("touchmove",cs,Tt),ue.removeEventListener("touchend",ds,Tt),ue.removeEventListener("touchcancel",ds,Tt),ue.style.touchAction=de}},[d,Z,ie,l]);i.useEffect(()=>{let ue=!1,Ve=null,De=null,we=null,Fe=[];const Pe=p.current;if(!Pe)return;Pe.tabIndex=Z?-1:0;const $e=()=>{Q(!0)},Ze=()=>{Q(!1)},Ue=st=>{const St=st.target;if(St&&Pe.contains(St)){Q(!0);return}Q(!1)},Ee=()=>{Q(!1)};let Re=null;return(async()=>{try{const st=await AI();if(ue)return;const St=MI(a,l,o,st,Z),mt=new ej(St),Tt=new tj;Ve=mt,g.current=mt,x.current=Tt,mt.loadAddon(Tt),mt.open(Pe),V(),I.current=!1,Re=mt.textarea??Pe.querySelector("textarea"),Re&&(Re.addEventListener("focus",$e),Re.addEventListener("blur",Ze)),ce(),typeof MutationObserver<"u"&&(we=new MutationObserver(()=>{ce()}),we.observe(Pe,{childList:!0,subtree:!0}));const qt=DI(Pe);qt?(qt.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),h.current=qt,E()):h.current=null,je(),me(),Fe=[mt.onData(yt=>{y.current(yt)})],De=new ResizeObserver(()=>{je()}),De.observe(Pe),typeof window<"u"&&window.setTimeout(()=>{je()},0)}catch{}})(),document.addEventListener("focusin",Ue,!0),window.addEventListener("blur",Ee),()=>{ue=!0,C.current?.(),C.current=null,document.removeEventListener("focusin",Ue,!0),window.removeEventListener("blur",Ee),Fe.forEach(st=>st.dispose()),Re&&(Re.removeEventListener("focus",$e),Re.removeEventListener("blur",Ze)),De?.disconnect(),we?.disconnect(),Ve?.dispose(),g.current=null,x.current=null,h.current=null,v.current=null,I.current=null,J()}},[ce,je,a,l,me,o,J,Q,Z]),i.useEffect(()=>{const ue=g.current;ue&&(ue.reset(),J(),v.current=null,je())},[t,W,je,J]),i.useEffect(()=>{!u||!g.current||B()},[u,B,t,W]),i.useEffect(()=>(me(),()=>{C.current?.(),C.current=null}),[me,t]),i.useEffect(()=>{const ue=g.current;if(!ue)return;if(s.length===0){w.current!==null&&(ue.reset(),J(),je());return}const Ve=w.current;let De;if(Ve===null)De=s;else{const we=s.findIndex(Fe=>Fe.id===Ve);De=we>=0?s.slice(we+1):s}De.length>0&&ae(De.map(we=>we.data).join("")),w.current=s[s.length-1].id},[s,W,ae,je,J]),i.useImperativeHandle(f,()=>({focus:()=>{B()},clear:()=>{const ue=g.current;ue&&(ue.reset(),J(),je())},fit:()=>{je()}}),[B,je,J]);const Oe=i.useCallback(ue=>{if(!Z)return;const Ve=ue.relatedTarget,De=Ve?.tagName,we=De==="INPUT"||De==="TEXTAREA"||Ve?.isContentEditable,Fe=Ve?.getAttribute("data-terminal-hidden-input")==="true";we&&!Fe&&(T.current!==null&&typeof window<"u"&&window.clearTimeout(T.current),typeof window<"u"&&(T.current=window.setTimeout(()=>{T.current=null,ie()},0)))},[Z,ie]),Be=i.useCallback(ue=>{const Ve=ue.nativeEvent,De=Ve?.inputType??"",we=typeof Ve?.data=="string"?Ve.data:"";if(O.current=typeof performance<"u"?performance.now():Date.now(),De==="insertCompositionText"){P.current=!0;return}if(!De&&we){if(P.current)return;ue.preventDefault(),y.current(we),R.current={type:"insertText",at:typeof performance<"u"?performance.now():Date.now()},$.current=!0;return}if(De==="insertText"&&we){if(P.current)return;ue.preventDefault(),y.current(we),R.current={type:De,at:typeof performance<"u"?performance.now():Date.now()},$.current=!0;return}if(De==="insertLineBreak"){if(P.current)return;ue.preventDefault(),y.current("\r"),R.current={type:De,at:typeof performance<"u"?performance.now():Date.now()},$.current=!0;return}if(De==="deleteContentBackward"){if(P.current)return;ue.preventDefault(),y.current(""),R.current={type:De,at:typeof performance<"u"?performance.now():Date.now()},$.current=!0}},[]),fe=i.useCallback(ue=>{const Ve=ue.currentTarget;if(O.current=typeof performance<"u"?performance.now():Date.now(),P.current)return;if($.current){const Fe=R.current,Pe=typeof performance<"u"?performance.now():Date.now();if(Fe&&Pe-Fe.at<50){$.current=!1,H(Ve);return}$.current=!1}const De=se(Ve);if(!De)return;F.current=De;const we=De.replace(/\r\n|\r|\n/g,"\r");y.current(we),H(Ve),F.current=""},[H,se]),q=i.useCallback(ue=>{ue.stopPropagation();const Ve=ue.key.toLowerCase(),De=ue.metaKey&&!ue.ctrlKey&&!ue.altKey&&Ve==="c",we=ue.ctrlKey&&ue.shiftKey&&!ue.metaKey&&!ue.altKey&&Ve==="c";if((De||we)&&z()){ue.preventDefault(),ge();return}const Fe=ue.currentTarget;if(ue.nativeEvent?.isComposing)return;const $e=R.current,Ze=typeof performance<"u"?performance.now():Date.now(),Ue=!!($e&&Ze-$e.at<50);if(ue.key==="Enter"){if(Ue&&$e?.type==="insertLineBreak")return;ue.preventDefault(),y.current("\r"),H(Fe);return}if(ue.key==="Backspace"){if(ue.preventDefault(),Ue&&$e?.type==="deleteContentBackward")return;se(Fe)||y.current("")}if(ue.key.length===1&&!ue.ctrlKey&&!ue.metaKey&&!ue.altKey){const Ee=O.current;Ee&&Ze-Ee<50||(ue.preventDefault(),y.current(ue.key),$.current=!0,R.current={type:"keydown-text",at:Ze})}le(Fe)},[H,ge,z,se,le]),ye=i.useCallback(ue=>{ue.stopPropagation();const Ve=ue.currentTarget;ue.nativeEvent?.isComposing||le(Ve)},[le]),he=i.useCallback(ue=>{const Ve=ue.currentTarget;P.current=!1;const De=ue.data||se(Ve);if(O.current=typeof performance<"u"?performance.now():Date.now(),!De)return;const we=De.replace(/\r\n|\r|\n/g,"\r");y.current(we),H(Ve),R.current={type:"compositionend",at:typeof performance<"u"?performance.now():Date.now()},$.current=!0},[H,se]),He=i.useCallback(ue=>{ue.stopPropagation();const Ve=ue.clipboardData?.getData("text")??"";if(!Ve)return;ue.preventDefault();const we=g.current?.hasBracketedPaste?.()?`\x1B[200~${Ve}\x1B[201~`:Ve;y.current(we)},[]),ot={position:"fixed",left:0,top:0,width:1,height:1,opacity:0,zIndex:-1,background:"transparent",color:"transparent",WebkitTextFillColor:"transparent",caretColor:"transparent",textShadow:"none",WebkitAppearance:"none",appearance:"none",resize:"none",overflow:"hidden",whiteSpace:"nowrap",border:"0",padding:0,margin:0,outline:"none",outlineOffset:0,fontSize:16,fontWeight:400,pointerEvents:"none",WebkitUserSelect:"none",userSelect:"none"};return e.jsxs("div",{ref:p,className:L("relative h-full w-full terminal-viewport-container",c),style:{backgroundColor:o.background},onTouchStart:ue=>{if(Z){const Ve=ue.touches?.[0];ie(Ve?.clientX,Ve?.clientY)}},onClick:ue=>{Z?ie(ue.clientX,ue.clientY):g.current?.focus()},onMouseUp:()=>{d||ge()},onTouchEnd:()=>{d||ge()},children:[Z&&typeof document<"u"?co.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:A,type:"text",inputMode:"text",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,enterKeyHint:"send","data-terminal-hidden-input":"true","data-keyboard-avoid-target-id":m,"aria-label":"Terminal input","aria-hidden":"true",style:{...ot,display:Y?"block":"none"},onBlur:Oe,onBeforeInput:Be,onCompositionStart:()=>{P.current=!0},onInput:fe,onKeyDown:q,onKeyUp:ye,onCompositionEnd:he,onPaste:He}),e.jsx("textarea",{ref:D,inputMode:"text",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,enterKeyHint:"send","data-terminal-hidden-input":"true","data-keyboard-avoid-target-id":m,"aria-label":"Terminal input","aria-hidden":"true",style:{...ot,display:Y?"none":"block"},onBlur:Oe,onBeforeInput:Be,onCompositionStart:()=>{P.current=!0},onInput:fe,onKeyDown:q,onKeyUp:ye,onCompositionEnd:he,onPaste:He})]}),document.body):null,h.current&&!d?e.jsx(pc,{containerRef:h,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});xu.displayName="TerminalViewport";const II={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},el={ctrl:"5",cmd:"3"},ch={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},TI={retry:{maxRetries:0,initialDelayMs:200,maxDelayMs:500},connectionTimeoutMs:1500},EI=(t,s)=>{if(s)switch(t){case"arrow-up":return`\x1B[1;${el[s]}A`;case"arrow-down":return`\x1B[1;${el[s]}B`;case"arrow-right":return`\x1B[1;${el[s]}C`;case"arrow-left":return`\x1B[1;${el[s]}D`}return II[t]??null},dh=()=>{const{terminal:t,runtime:s}=Vr(),{currentTheme:r}=rn(),{monoFont:n}=ob(),o=Te(Ue=>Ue.terminalFontSize),{isMobile:a,hasTouchInput:l}=ks(),c=!a&&s.platform!=="vscode",d=Te(Ue=>Ue.showTerminalQuickKeysOnDesktop),u=a||d,{currentSessionId:m,newSessionDraft:f}=Ae(),p=m!==null||f?.open===!0,h=Ci()??null,g=Ao(),x=g.sessions,y=g.hasHydrated,b=g.ensureDirectory,v=g.createTab,j=g.setActiveTab,k=g.closeTab,N=g.setTabSessionId,w=g.setConnecting,C=g.appendToBuffer,S=i.useMemo(()=>{if(h)return x.get(h)},[x,h]),M=i.useMemo(()=>S?c?S.activeTabId??S.tabs[0]?.id??null:S.tabs[0]?.id??null:null,[S,c]),D=i.useMemo(()=>{if(S)return M?S.tabs.find(Ue=>Ue.id===M)??S.tabs[0]:S.tabs[0]},[S,M]),A=D?.terminalSessionId??null,P=D?.bufferChunks??[],$=D?.isConnecting??!1,[R,O]=i.useState(null),[T,_]=i.useState(!1),[F,I]=i.useState(null),[E,W]=i.useState(!1),V=i.useId(),ve=i.useRef(null),oe=i.useRef(null),Z=i.useRef(M),ce=i.useRef(A),Q=i.useRef(h),Y=i.useRef(null),ie=i.useRef(null),B=i.useRef(!1),se=i.useRef(null),H=i.useRef(new Set),le=i.useRef(!1);i.useEffect(()=>{if(!y||le.current)return;le.current=!0;const Ue=new Set;for(const[,Ee]of Ao.getState().sessions.entries())for(const Re of Ee.tabs)Re.terminalSessionId&&Ue.add(Re.terminalSessionId);H.current=Ue},[y]);const ge=Te(Ue=>Ue.activeMainTab),z=Te(Ue=>Ue.isBottomTerminalOpen),je=ge==="terminal"||z,[X,G]=i.useState(je);i.useEffect(()=>{!je||s.platform==="vscode"||_j()},[je,s.platform]),i.useEffect(()=>{je&&G(!0)},[je]),i.useEffect(()=>{B.current=je},[je]),i.useEffect(()=>{ce.current=A},[A]),i.useEffect(()=>{Z.current=M},[M]),i.useEffect(()=>{Q.current=h},[h]),i.useEffect(()=>{!u&&F!==null&&I(null)},[u,F,I]),i.useEffect(()=>{!A&&F!==null&&I(null)},[A,F,I]);const ae=i.useCallback(()=>{ve.current?.(),ve.current=null,oe.current=null},[]);i.useEffect(()=>()=>{ae(),ce.current=null},[ae]);const me=i.useCallback((Ue,Ee,Re,Xe=ch)=>{if(oe.current===Re)return;ae(),oe.current=Re;const st=t.connect(Re,{onEvent:St=>{if(oe.current===Re)switch(St.type){case"connected":{w(Ue,Ee,!1),O(null),_(!1),Y.current?.focus(),se.current===Re&&(se.current=null,t.sendInput(Re,"\r").catch(()=>{}));break}case"reconnecting":{const mt=St.attempt??0,Tt=St.maxAttempts??3;O(`Reconnecting (${mt}/${Tt})...`),_(!1);break}case"data":{St.data&&C(Ue,Ee,St.data);break}case"exit":{const mt=typeof St.exitCode=="number"?St.exitCode:null,Tt=typeof St.signal=="number"?St.signal:null;C(Ue,Ee,`\r
|
|
277
|
+
[Process exited${mt!==null?` with code ${mt}`:""}${Tt!==null?` (signal ${Tt})`:""}]\r
|
|
278
|
+
`),N(Ue,Ee,null),w(Ue,Ee,!1),O("Terminal session ended"),_(!1),ae();break}}},onError:(St,mt)=>{if(oe.current!==Re)return;const Tt=mt?`Connection failed: ${St.message}`:St.message||"Terminal stream connection error";O(Tt),_(!!mt),mt&&(w(Ue,Ee,!1),N(Ue,Ee,null),ae())}},Xe);ve.current=()=>{st.close(),oe.current=null}},[C,ae,w,N,t]);i.useEffect(()=>{let Ue=!1;if(!y||!X)return;if(!h){O(p?"No working directory available for terminal.":"Select a session to open the terminal."),ae();return}return(async()=>{const Re=h;if(!Q.current||Q.current!==Re)return;b(Re);const Xe=Ao.getState().getDirectoryState(Re);if(!Xe||Xe.tabs.length===0)return;const st=c?Xe.activeTabId??Xe.tabs[0]?.id??null:Xe.tabs[0]?.id??null;if(!st)return;const St=Xe.tabs.find(yt=>yt.id===st)??Xe.tabs[0];let mt=St?.terminalSessionId??null;const Tt=!!mt&&H.current.has(mt)&&(St?.bufferLength??0)===0&&(St?.bufferChunks?.length??0)===0,qt=!!mt&&H.current.has(mt);if(!mt){O(null),_(!1),w(Re,st,!0);try{const yt=ie.current,os=await t.createSession({cwd:Re,cols:yt?.cols,rows:yt?.rows});if(!(!Ue&&Q.current===Re&&Z.current===st)){try{await t.close(os.sessionId)}catch{}return}N(Re,st,os.sessionId),mt=os.sessionId}catch(yt){Ue||(O(yt instanceof Error?yt.message:"Failed to start terminal session"),_(!0),w(Re,st,!1));return}}!mt||Ue||(ce.current=mt,qt&&H.current.delete(mt),Tt&&(se.current=mt),me(Re,st,mt,qt?TI:ch))})(),()=>{Ue=!0,ce.current=null,ae()}},[p,h,A,M,X,c,y,b,w,N,me,ae,t]),i.useEffect(()=>{if(!je)return;if(typeof window>"u"){Y.current?.focus();return}const Ue=window.requestAnimationFrame(()=>{Y.current?.focus()});return()=>{window.cancelAnimationFrame(Ue)}},[M,je]);const Oe=i.useCallback(async()=>{if(!h||E)return;const Ue=Ao.getState().getDirectoryState(h),Ee=a?Ue?.tabs[0]?.id??null:M??Ue?.activeTabId??Ue?.tabs[0]?.id??null;if(Ee){W(!0),O(null),_(!1),ae();try{await k(h,Ee)}catch(Re){O(Re instanceof Error?Re.message:"Failed to restart terminal"),_(!0)}finally{W(!1)}}},[M,k,ae,h,a,E]),Be=i.useCallback(async()=>{await Oe()},[Oe]),fe=i.useCallback(()=>{if(!h)return;const Ue=v(h);j(h,Ue),O(null),_(!1),ae()},[v,ae,h,j]),q=i.useCallback(Ue=>{h&&(j(h,Ue),O(null),_(!1),ae())},[ae,h,j]),ye=i.useCallback(Ue=>{h&&(Ue===M&&ae(),O(null),_(!1),k(h,Ue))},[M,k,ae,h]),he=i.useCallback(Ue=>{if(!Ue)return;let Ee=Ue,Re=!1;if(F&&Ue.length>0){const st=Ue[0];if(st.length===1&&/[a-zA-Z]/.test(st)){const St=st.toUpperCase();(F==="ctrl"||F==="cmd")&&(Ee=String.fromCharCode(St.charCodeAt(0)&31),Re=!0)}Re||(Re=!0)}const Xe=ce.current;Xe&&(t.sendInput(Xe,Ee).catch(st=>{O(st instanceof Error?st.message:"Failed to send input")}),Re&&(I(null),Y.current?.focus()))},[F,I,t]),He=i.useCallback((Ue,Ee)=>{if(ie.current={cols:Ue,rows:Ee},!B.current)return;const Re=ce.current;Re&&t.resize({sessionId:Re,cols:Ue,rows:Ee}).catch(()=>{})},[t]),ot=i.useCallback(Ue=>{I(Ee=>Ee===Ue?null:Ue),Y.current?.focus()},[I]),ue=i.useCallback(Ue=>{const Ee=EI(Ue,F);Ee&&(he(Ee),I(null),Y.current?.focus())},[F,he,I]);i.useEffect(()=>{if(!u||!F||!A)return;const Ue=Ee=>{if(Ee.repeat)return;const Re=Ee.key;if(!Re||Re==="Control"||Re==="Meta"||Re==="Alt"||Re==="Shift")return;const Xe=Re.length===1?Re.toLowerCase():Re,st=Ee.code??"",St=st.startsWith("Key")&&st.length===4?st.slice(3).toUpperCase():null,mt=Re.length===1&&/[a-zA-Z]/.test(Re)?Re.toUpperCase():St,Tt={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(Xe in Tt){Ee.preventDefault(),Ee.stopPropagation(),ue(Tt[Xe]);return}if(F==="ctrl"&&mt&&mt.length===1&&mt>="A"&&mt<="Z"){const qt=String.fromCharCode(mt.charCodeAt(0)&31);Ee.preventDefault(),Ee.stopPropagation(),he(qt),I(null),Y.current?.focus()}};return window.addEventListener("keydown",Ue),()=>{window.removeEventListener("keydown",Ue)}},[F,ue,he,u,I,A]);const Ve=i.useMemo(()=>{const Ue=ko[Sl].stack;if(typeof window>"u")return(ko[n]??ko[Sl]).stack;const Re=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return Re&&Re.trim().length>0?Re.trim():(ko[n]??ko[Sl]).stack??Ue},[n]),De=i.useMemo(()=>CI(r),[r]),we=i.useMemo(()=>{const Ue=h??"no-dir",Ee=M??"no-tab",Re=A??`pending-${Ee}`;return`${Ue}::${Ee}::${Re}`},[h,M,A]),Fe=A??we;if(i.useEffect(()=>{if(!je)return;const Ue=Y.current;if(!Ue)return;const Ee=()=>{Ue.fit()};if(typeof window<"u"){const Re=window.requestAnimationFrame(()=>{Ee(),Ue.focus()}),Xe=[220,400].map(st=>window.setTimeout(Ee,st));return()=>{window.cancelAnimationFrame(Re),Xe.forEach(st=>window.clearTimeout(st))}}Ee()},[je,we,A]),!p)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(!h)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:Oe,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Pe=!A||$||E,$e=a?je:X,Ze=e.jsxs(e.Fragment,{children:[e.jsx(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>ue("esc"),disabled:Pe,children:"Esc"}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ue("tab"),disabled:Pe,children:[e.jsx(jm,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:F==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ot("ctrl"),disabled:Pe,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:F==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ot("cmd"),disabled:Pe,children:[e.jsx(xo,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ue("arrow-up"),disabled:Pe,children:[e.jsx(ii,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ue("arrow-left"),disabled:Pe,children:[e.jsx(Mu,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ue("arrow-down"),disabled:Pe,children:[e.jsx(va,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ue("arrow-right"),disabled:Pe,children:[e.jsx(jm,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ue("enter"),disabled:Pe,children:[e.jsx(Oo,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[e.jsxs("div",{className:"sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] px-5 py-2 text-xs",children:[c&&S?e.jsxs("div",{className:"mt-2 pl-1 pr-1 flex items-center gap-2",children:[e.jsx("div",{className:"min-w-0 flex-1 overflow-x-auto pb-1",children:e.jsxs("div",{className:"flex w-max items-center gap-1 pr-1",children:[S.tabs.map(Ue=>{const Ee=Ue.id===M;return e.jsxs("div",{className:L("group flex items-center gap-1 rounded-md border px-2 py-1 text-xs whitespace-nowrap",Ee?"bg-[var(--interactive-selection)] border-[var(--primary-muted)] text-[var(--interactive-selection-foreground)]":"bg-transparent border-[var(--interactive-border)] text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]"),children:[e.jsx("button",{type:"button",onClick:()=>q(Ue.id),className:"max-w-[10rem] truncate text-left",title:Ue.label,children:Ue.label}),e.jsx("button",{type:"button",className:L("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!Ee&&"opacity-0 group-hover:opacity-100"),onClick:Re=>{Re.stopPropagation(),ye(Ue.id)},title:"Close tab",children:e.jsx(hs,{size:14})})]},Ue.id)}),e.jsx("button",{type:"button",onClick:fe,className:"ml-1 flex h-7 w-7 items-center justify-center rounded-md border border-[var(--interactive-border)] bg-transparent text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]",title:"New tab",children:e.jsx(Fs,{size:16})})]})}),!a&&u?e.jsx("div",{className:"flex shrink-0 items-center gap-1 overflow-x-auto pb-1",children:Ze}):null]}):null,u&&(a||!c||!S)?e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Ze}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:De.background},id:V,"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border pl-7 pr-5 pt-3 pb-4",children:$e?a?e.jsx(xu,{ref:Ue=>{Y.current=Ue},sessionKey:Fe,chunks:P,onInput:he,onResize:He,theme:De,fontFamily:Ve,fontSize:o,enableTouchScroll:l,autoFocus:je,keyboardAvoidTargetId:V},Fe):e.jsx(Ut,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(xu,{ref:Ue=>{Y.current=Ue},sessionKey:Fe,chunks:P,onInput:he,onResize:He,theme:De,fontFamily:Ve,fontSize:o,enableTouchScroll:l,autoFocus:je,keyboardAvoidTargetId:V},Fe)}):null}),R&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2",children:[e.jsx("span",{children:R}),T&&a&&e.jsx(Me,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Be,disabled:E,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},rr=t=>{if(!t)return"";const s=t.replace(/\\/g,"/"),r=s.startsWith("//");let n=s.replace(/\/+/g,"/");r&&!n.startsWith("//")&&(n=`/${n}`);const o=n==="/",a=/^[A-Za-z]:\/$/.test(n);return!o&&!a&&(n=n.replace(/\/+$/,"")),n},uh=t=>/^[A-Za-z]:\//.test(t)?t.toLowerCase():t,jd=(t,s)=>{const r=rr(s),n=rr(t);if(!r||!n)return!1;const o=uh(r),a=uh(n);return a===o||a.startsWith(`${o}/`)},PI=t=>{if(!t||typeof t!="object")return{};const s=t,r={};for(const[n,o]of Object.entries(s)){const a=rr(n);if(!a||!o||typeof o!="object")continue;const l=o,c=Array.isArray(l.openPaths)?Array.from(new Set(l.openPaths.filter(h=>typeof h=="string").map(h=>rr(h)).filter(h=>jd(h,a)))):[],d=Array.isArray(l.expandedPaths)?Array.from(new Set(l.expandedPaths.filter(h=>typeof h=="string").map(h=>rr(h)).filter(h=>jd(h,a)))):[],u=typeof l.selectedPath=="string"?rr(l.selectedPath):null,m=u&&jd(u,a)?u:c[0]??null,f=typeof l.touchedAt=="number"&&Number.isFinite(l.touchedAt)?l.touchedAt:Date.now(),p=r[a];if(p){const h=Array.from(new Set([...p.openPaths,...c])),g=Array.from(new Set([...p.expandedPaths,...d])),x=p.selectedPath??m??h[0]??null;r[a]={openPaths:h,selectedPath:x,expandedPaths:g,touchedAt:Math.max(p.touchedAt,f)};continue}r[a]={openPaths:c,selectedPath:m,expandedPaths:d,touchedAt:f}}return r},No=(t,s)=>{const r=Object.entries(t);if(r.length<=s)return t;r.sort((o,a)=>(a[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const n={};for(const[o,a]of r.slice(0,s))n[o]=a;return n},Ka=t=>t?{...t,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},Bn=Ls()(Us(Ar((t,s)=>({byRoot:{},addOpenPath:(r,n)=>{const o=rr((r||"").trim()),a=rr((n||"").trim());!o||!a||t(l=>{const c=l.byRoot[o],d=Ka(c),u=d.openPaths.includes(a),m=u?d.openPaths:[...d.openPaths,a],f=d.selectedPath??a;if(c&&u&&c.selectedPath===f)return l;const p={...l.byRoot,[o]:{...d,openPaths:m,selectedPath:f}};return{byRoot:No(p,20)}})},removeOpenPath:(r,n)=>{const o=rr((r||"").trim()),a=rr((n||"").trim());!o||!a||t(l=>{const c=l.byRoot[o];if(!c||!c.openPaths.includes(a)&&c.selectedPath!==a)return l;const d=c.openPaths.filter(f=>f!==a),u=c.selectedPath===a?d[0]??null:c.selectedPath,m={...l.byRoot,[o]:{...c,openPaths:d,selectedPath:u,touchedAt:Date.now()}};return{byRoot:No(m,20)}})},removeOpenPathsByPrefix:(r,n)=>{const o=rr((r||"").trim()),a=rr((n||"").trim());!o||!a||t(l=>{const c=l.byRoot[o];if(!c)return l;const d=a.endsWith("/")?a:`${a}/`,u=c.openPaths.filter(p=>p!==a&&!p.startsWith(d));if(u.length===c.openPaths.length)return l;const m=c.selectedPath&&(c.selectedPath===a||c.selectedPath.startsWith(d))?u[0]??null:c.selectedPath,f={...l.byRoot,[o]:{...c,openPaths:u,selectedPath:m,touchedAt:Date.now()}};return{byRoot:No(f,20)}})},setSelectedPath:(r,n)=>{const o=rr((r||"").trim()),a=n?rr(n.trim()):null;o&&t(l=>{const c=l.byRoot[o],d=Ka(c),u=a&&!d.openPaths.includes(a)?[...d.openPaths,a]:d.openPaths;if(c&&c.selectedPath===a&&u===c.openPaths)return l;const m={...l.byRoot,[o]:{...d,openPaths:u,selectedPath:a}};return{byRoot:No(m,20)}})},ensureSelectedPath:r=>{const n=rr((r||"").trim());if(!n)return;const o=s().byRoot[n];if(!o||o.selectedPath)return;const a=o.openPaths[0]??null;a&&s().setSelectedPath(n,a)},toggleExpandedPath:(r,n)=>{const o=rr((r||"").trim()),a=rr((n||"").trim());!o||!a||t(l=>{const c=l.byRoot[o],d=Ka(c),m=d.expandedPaths.includes(a)?d.expandedPaths.filter(p=>p!==a):[...d.expandedPaths,a];if(c&&c.expandedPaths===m&&c.selectedPath===d.selectedPath&&c.openPaths===d.openPaths)return l;const f={...l.byRoot,[o]:{...d,expandedPaths:m}};return{byRoot:No(f,20)}})},expandPath:(r,n)=>{const o=rr((r||"").trim()),a=rr((n||"").trim());!o||!a||t(l=>{const c=l.byRoot[o],d=Ka(c);if(d.expandedPaths.includes(a)&&c)return l;const m={...l.byRoot,[o]:{...d,expandedPaths:[...d.expandedPaths,a]}};return{byRoot:No(m,20)}})},expandPaths:(r,n)=>{const o=rr((r||"").trim());if(!o||!n||n.length===0)return;const a=n.map(l=>rr((l||"").trim())).filter(Boolean);t(l=>{const c=l.byRoot[o],d=Ka(c),u=new Set(d.expandedPaths),m=a.filter(p=>!u.has(p));if(m.length===0)return l;const f={...l.byRoot,[o]:{...d,expandedPaths:[...d.expandedPaths,...m]}};return{byRoot:No(f,20)}})}}),{name:"files-view-tabs-store",version:2,storage:Dr(()=>Ws()),migrate:t=>{if(!t||typeof t!="object")return{byRoot:{}};const s=t.byRoot;return{byRoot:PI(s)}},partialize:t=>({byRoot:t.byRoot})}),{name:"files-view-tabs-store"})),RI=t=>t.slice().sort((s,r)=>s.type!==r.type?s.type==="directory"?-1:1:s.name.localeCompare(r.name)),wr=t=>{if(!t)return"";const s=t.replace(/\\/g,"/"),r=s.startsWith("//");let n=s.replace(/\/+/g,"/");r&&!n.startsWith("//")&&(n=`/${n}`);const o=n==="/",a=/^[A-Za-z]:\/$/.test(n);return!o&&!a&&(n=n.replace(/\/+$/,"")),n},FI=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),mh=t=>/^[A-Za-z]:\//.test(t)?t.toLowerCase():t,ib=(t,s)=>{const r=wr(s),n=wr(t);if(!r||!n)return!1;const o=mh(r),a=mh(n);return a===o||a.startsWith(`${o}/`)},fh=(t,s)=>{const r=wr(s),n=wr(t);if(!ib(n,r))return[];const a=n.slice(r.length).replace(/^\//,"").split("/"),l=[];let c=r;for(let d=0;d<a.length-1;d++)c=c?`${c}/${a[d]}`:a[d],l.push(c);return l},LI=(t,s)=>{const r=t.split("/"),n=[];let o=s;for(const a of r)a&&(o=o?`${o}/${a}`:a,n.push({label:a,path:o}));return n},OI=({path:t,root:s,onNavigate:r})=>{const n=i.useMemo(()=>LI(t,s),[t,s]);return e.jsx("div",{className:"flex items-center gap-1 overflow-x-auto whitespace-nowrap min-w-0 flex-1 hide-scrollbar",children:n.map((o,a)=>e.jsxs(i.Fragment,{children:[a>0&&e.jsx(dr,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("button",{type:"button",onClick:()=>a<n.length-1&&r(o.path),className:L("typography-meta transition-colors",a===n.length-1?"text-foreground font-medium cursor-default":"text-muted-foreground hover:text-foreground hover:underline cursor-pointer"),disabled:a===n.length-1,children:o.label})]},o.path))})},_I=new Set(["node_modules"]),$I=({status:t})=>{const s={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"}[t];return e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:s}})},BI=t=>_I.has(t),zI=t=>{const s=wr(t);return s==="node_modules"||s.endsWith("/node_modules")||s.includes("/node_modules/")},UI=t=>{const r=(t instanceof Error?t.message:String(t??"")).toLowerCase();return r.includes("is a directory")||r.includes("eisdir")},qa=2e5,HI=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"]),VI=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"]),WI=new Set(["png","jpg","jpeg","gif","svg","webp","ico","icns","bmp","tiff","tif","psd","ai","eps","raw","cr2","nef","heic","heif","avif","jxl"]),GI=new Set(["md","mdx","markdown","mdown","mkd","txt","text","rtf","doc","docx","odt","pdf","rst","adoc","asciidoc","org","tex","latex","bib"]),lb=t=>{const s=t?.toLowerCase();return s&&HI.has(s)?e.jsx(xn,{className:"h-4 w-4 flex-shrink-0 text-[var(--status-info)]"}):s&&VI.has(s)?e.jsx(xn,{className:"h-4 w-4 flex-shrink-0 text-[var(--status-warning)]"}):s&&WI.has(s)?e.jsx(Ln,{className:"h-4 w-4 flex-shrink-0 text-[var(--status-success)]"}):s&&GI.has(s)?e.jsx(Eo,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(Eo,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})},ta=t=>{if(!t)return!1;const s=t.toLowerCase().split(".").pop();return s==="md"||s==="markdown"},KI=({node:t,isExpanded:s,isActive:r,isLoading:n,isMobile:o,status:a,badge:l,permissions:c,contextMenuPath:d,setContextMenuPath:u,onSelect:m,onToggle:f,onOpenDialog:p})=>{const h=t.type==="directory",{canRename:g,canCreateFile:x,canCreateFolder:y,canDelete:b}=c,v=i.useCallback(N=>{!g&&!x&&!y&&!b||(N?.preventDefault(),u(t.path))},[g,x,y,b,t.path,u]),j=i.useCallback(()=>{h?f(t.path):m(t)},[h,t,m,f]),k=i.useCallback(N=>{N.stopPropagation(),u(t.path)},[t.path,u]);return e.jsxs("div",{className:"group relative flex items-center",onContextMenu:o?void 0:v,children:[e.jsxs("button",{type:"button",onClick:j,onContextMenu:o?void 0:v,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",r?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[h?n?e.jsx(Ot,{className:"h-4 w-4 flex-shrink-0 animate-spin"}):s?e.jsx(rj,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):e.jsx(nj,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):lb(t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!h&&a&&e.jsx($I,{status:a}),h&&l&&e.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[l.modified>0&&e.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",l.modified]}),l.added>0&&e.jsxs("span",{className:"text-[var(--status-success)]",children:["+",l.added]})]})]}),(g||x||y||b)&&e.jsx("div",{className:L("absolute right-1 top-1/2 -translate-y-1/2",!o&&"opacity-0 focus-within:opacity-100 group-hover:opacity-100",o&&"opacity-100"),children:e.jsxs(us,{open:d===t.path,onOpenChange:N=>u(N?t.path:null),children:[e.jsx(ms,{asChild:!0,children:e.jsx(Me,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:k,children:e.jsx(oj,{className:"h-4 w-4"})})}),e.jsxs(fs,{align:"end",side:"bottom",onCloseAutoFocus:()=>u(null),children:[g&&e.jsxs(Et,{onClick:N=>{N.stopPropagation(),p("rename",t)},children:[e.jsx(go,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(Et,{onClick:N=>{N.stopPropagation(),navigator.clipboard.writeText(t.path),K.success("Path copied")},children:[e.jsx(Hr,{className:"mr-2 h-4 w-4"})," Copy Path"]}),h&&(x||y)&&e.jsxs(e.Fragment,{children:[e.jsx(lr,{}),x&&e.jsxs(Et,{onClick:N=>{N.stopPropagation(),p("createFile",t)},children:[e.jsx(Dg,{className:"mr-2 h-4 w-4"})," New File"]}),y&&e.jsxs(Et,{onClick:N=>{N.stopPropagation(),p("createFolder",t)},children:[e.jsx(Cu,{className:"mr-2 h-4 w-4"})," New Folder"]})]}),b&&e.jsxs(e.Fragment,{children:[e.jsx(lr,{}),e.jsxs(Et,{onClick:N=>{N.stopPropagation(),p("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(Nr,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]})})]})},qI=()=>{const{files:t,runtime:s}=Vr(),{currentTheme:r}=rn();i.useMemo(()=>wc(r),[r]);const{isMobile:n,screenWidth:o}=ks(),a=wi(),l=lc(),c=Ci()??"",d=wr(c.trim()),u=cc(re=>re.searchFiles),m=Wu(c),[f,p]=i.useState(""),h=bc(f,200),g=i.useRef(null),[x,y]=i.useState(!1),[b,v]=i.useState(n),[j,k]=i.useState(!1),[N,w]=i.useState(!1),C=i.useMemo(()=>[],[]),S=Bn(re=>d?re.byRoot[d]?.openPaths??C:C),M=Bn(re=>d?re.byRoot[d]?.selectedPath??null:null),D=Bn(re=>d?re.byRoot[d]?.expandedPaths??C:C),A=Bn(re=>re.addOpenPath),P=Bn(re=>re.removeOpenPath),$=Bn(re=>re.removeOpenPathsByPrefix),R=Bn(re=>re.setSelectedPath),O=Bn(re=>re.toggleExpandedPath),T=Bn(re=>re.expandPaths),_=i.useCallback(re=>{const Le=wr(re),Ce=Le.split("/"),_e=Ce[Ce.length-1]||Le,Qe=_e.includes(".")?_e.split(".").pop()?.toLowerCase():void 0;return{name:_e,path:Le,type:"file",extension:Qe}},[]),F=i.useMemo(()=>S.map(_),[S,_]),I=i.useMemo(()=>M??S[0]??null,[S,M]),E=i.useMemo(()=>I?_(I):null,[I,_]),[W,V]=i.useState({}),ve=i.useRef(new Set),oe=i.useRef(new Set),[Z,ce]=i.useState([]),[Q,Y]=i.useState(!1),[ie,B]=i.useState(""),[se,H]=i.useState(!1),[le,ge]=i.useState(null),[z,J]=i.useState(""),[je,X]=i.useState(null),[G,ae]=i.useState(""),[me,Oe]=i.useState(!1),[Be,fe]=i.useState(!1),q=i.useRef(null),ye=i.useRef(null),he=i.useRef(null),He=i.useRef(!1),ot=i.useRef(null),ue=i.useRef(null),Ve=i.useRef(null),[De,we]=i.useState(null),[Fe,Pe]=i.useState(null),[$e,Ze]=i.useState(""),[Ue,Ee]=i.useState(!1),[Re,Xe]=i.useState(null),[st,St]=i.useState(!1),[mt,Tt]=i.useState(!1),[qt,yt]=i.useState("edit"),os=!!t.writeFile,cs=!!t.createDirectory,ds=!!t.rename,de=!!t.delete,ke=i.useCallback((re,Le)=>{we(re),Pe(Le),Ze(re==="rename"&&Le.name||""),Ee(!1)},[]),[We,qe]=i.useState(null),et=i.useRef(!1),ct=i.useRef(null),[bt,at]=i.useState(!1),_t=Ae(re=>re.currentSessionId),Nt=Te(re=>re.setMainTabGuard),Gt=Br(re=>re.addDraft),zt=Br(re=>re.updateDraft),Ct=Br(re=>re.removeDraft),Qt=Br(re=>re.drafts),[Mt,Zt]=i.useState(null);i.useEffect(()=>{const re=()=>{et.current=!1,ct.current=null,at(!1)};return document.addEventListener("mouseup",re),()=>document.removeEventListener("mouseup",re)},[]),i.useEffect(()=>{qe(null),Nt(null),ae(""),Oe(!1)},[E?.path,Nt]),i.useEffect(()=>()=>{ot.current!==null&&window.clearTimeout(ot.current),ue.current!==null&&window.clearTimeout(ue.current)},[]),i.useEffect(()=>{if(!We&&!Mt)return;const re=Ce=>{const _e=Ce.target;_e.closest('[data-comment-input="true"]')||_e.closest('[data-comment-card="true"]')||_e.closest(".cm-gutterElement")||_e.closest("[data-sonner-toast]")||_e.closest("[data-sonner-toaster]")||(qe(null),Zt(null))},Le=setTimeout(()=>{document.addEventListener("click",re)},100);return()=>{clearTimeout(Le),document.removeEventListener("click",re)}},[We,Mt]);const jt=i.useCallback((re,Le)=>{const Ce=re.split(`
|
|
279
|
+
`),_e=Math.max(1,Le.start),Qe=Math.min(Ce.length,Le.end);return _e>Qe?"":Ce.slice(_e-1,Qe).join(`
|
|
280
|
+
`)},[]),es=i.useCallback((re,Le)=>{if(!E)return;const Ce=_t??"draft",_e=Le||We;if(!_e)return;const Qe=jt(ie,{start:_e.start,end:_e.end});Mt?zt(Ce,Mt,{text:re.trim(),code:Qe,startLine:_e.start,endLine:_e.end}):Gt({sessionKey:Ce,source:"file",fileLabel:E.path,startLine:_e.start,endLine:_e.end,code:Qe,language:Jn(E.path)||"text",text:re.trim()}),qe(null),Zt(null)},[E,_t,We,ie,jt,Mt,zt,Gt]),Ye=i.useCallback((re,Le)=>{const Ce=Le.filter(_e=>_e&&typeof _e.name=="string"&&_e.name.length>0).filter(_e=>a||!_e.name.startsWith(".")).filter(_e=>l||!BI(_e.name)).map(_e=>{const Qe=_e.name,dt=wr(_e.path||""),$t=dt?FI(dt)?dt:wr(`${re}/${dt}`):wr(`${re}/${Qe}`),be=_e.isDirectory?"directory":"file",U=be==="file"&&Qe.includes(".")?Qe.split(".").pop()?.toLowerCase():void 0;return{name:Qe,path:$t,type:be,extension:U}});return RI(Ce)},[l,a]),ft=i.useCallback(async re=>{const Le=wr(re.trim());if(Le&&!(ve.current.has(Le)||oe.current.has(Le))){oe.current=new Set(oe.current),oe.current.add(Le);try{const Ce=!l;let _e;s.isDesktop?_e=(await t.listDirectory(Le,{respectGitignore:Ce})).entries.map($t=>({name:$t.name,path:$t.path,isDirectory:$t.isDirectory})):_e=(await nt.listLocalDirectory(Le,{respectGitignore:Ce})).map($t=>({name:$t.name,path:$t.path,isDirectory:$t.isDirectory}));const Qe=Ye(Le,_e);ve.current=new Set(ve.current),ve.current.add(Le),V(dt=>({...dt,[Le]:Qe}))}catch{V(Ce=>({...Ce,[Le]:Ce[Le]??[]}))}finally{oe.current=new Set(oe.current),oe.current.delete(Le)}}},[t,Ye,s.isDesktop,l]),vt=i.useCallback(async()=>{d&&(ve.current=new Set,oe.current=new Set,V(re=>Object.keys(re).length===0?re:{}),await ft(d))},[ft,d]),pt=i.useRef(""),Rt=i.useRef("");i.useEffect(()=>{if(!d)return;const re=`${d}|h${a?"1":"0"}|g${l?"1":"0"}`,Le=pt.current!==d,Ce=Rt.current!==re;!Le&&!Ce||(Le&&(pt.current=d,B(""),ge(null),J(""),X(null),y(!1)),Ce&&(Rt.current=re,ve.current=new Set,oe.current=new Set,V(_e=>Object.keys(_e).length===0?_e:{}),ft(d)))},[ft,d,l,a]);const Ft="ikanban:files:md-viewer-mode";i.useEffect(()=>{try{const re=localStorage.getItem(Ft);if(re){const Le=JSON.parse(re);(Le==="preview"||Le==="edit")&&yt(Le)}}catch{}},[]);const Pt=i.useCallback(re=>{yt(re);try{localStorage.setItem(Ft,JSON.stringify(re))}catch{}},[]),Jt=i.useCallback(()=>qt,[qt]),Ns=i.useCallback(async re=>{if(re?.preventDefault(),!(!Fe||!De)){Ee(!0);try{if(De==="createFile"){if(!$e.trim())throw new Error("Filename is required");const Le=Fe.path,Ce=Le?`${Le}/`:"",_e=wr(`${Ce}${$e.trim()}`);if(!t.writeFile)throw new Error("Write not supported");(await t.writeFile(_e,"")).success&&(K.success("File created"),await vt())}else if(De==="createFolder"){if(!$e.trim())throw new Error("Folder name is required");const Le=Fe.path,Ce=Le?`${Le}/`:"",_e=wr(`${Ce}${$e.trim()}`);(await t.createDirectory(_e)).success&&(K.success("Folder created"),await vt())}else if(De==="rename"){if(!$e.trim())throw new Error("Name is required");const Le=Fe.path,Ce=Le.split("/").slice(0,-1).join("/"),_e=Ce?`${Ce}/`:"",Qe=wr(`${_e}${$e.trim()}`);t.rename?(await t.rename(Le,Qe)).success&&(K.success("Renamed successfully"),await vt(),d&&$(d,Le),(E?.path===Le||E?.path.startsWith(`${Le}/`))&&(d&&R(d,null),B(""),ge(null),J(""),X(null),n&&y(!1))):K.error("Rename not supported")}else De==="delete"&&(t.delete?(await t.delete(Fe.path)).success&&(K.success("Deleted successfully"),await vt(),d&&$(d,Fe.path),(E?.path===Fe.path||E?.path.startsWith(Fe.path+"/"))&&(d&&R(d,null),B(""),ge(null),J(""),X(null),n&&y(!1))):K.error("Delete not supported"));we(null)}catch(Le){K.error(Le instanceof Error?Le.message:"Operation failed")}finally{Ee(!1)}}},[De,Fe,$e,t,vt,n,$,d,E?.path,R]),Ts=i.useCallback((re,Le)=>{const Ce=re.trim().toLowerCase();if(!Ce)return 0;const _e=Le.toLowerCase();let Qe=0,dt=-1,$t=0;for(let be=0;be<Ce.length;be+=1){const U=Ce[be];if(!U||U===" ")continue;const te=_e.indexOf(U,dt+1);if(te===-1)return null;const Se=te-dt-1;if(Se===0?$t+=1:$t=0,Qe+=10,Qe+=Math.max(0,18-te),Qe-=Math.max(0,Se),te===0)Qe+=12;else{const Je=_e[te-1];(Je==="/"||Je==="_"||Je==="-"||Je==="."||Je===" ")&&(Qe+=10)}Qe+=$t>0?12:0,dt=te}return Qe+=Math.max(0,24-Math.round(_e.length/3)),Qe},[]);i.useEffect(()=>{if(!c){ce([]),Y(!1);return}const re=h.trim();if(!re){ce([]),Y(!1);return}const Le=re.toLowerCase();let Ce=!1;return Y(!0),u(c,re,150,{includeHidden:a,respectGitignore:!l}).then(_e=>{if(Ce)return;const dt=_e.filter(be=>l||!zI(be.path)).map(be=>{const U=be.relativePath||be.name||be.path,te=Ts(Le,U);return te===null?null:{hit:be,score:te,labelLength:U.length}}).filter(Boolean);dt.sort((be,U)=>U.score-be.score||be.labelLength-U.labelLength||be.hit.path.localeCompare(U.hit.path));const $t=dt.map(({hit:be})=>({name:be.name,path:wr(be.path),type:"file",extension:be.extension,relativePath:be.relativePath}));ce($t)}).catch(()=>{Ce||ce([])}).finally(()=>{Ce||Y(!1)}),()=>{Ce=!0}},[c,h,Ts,u,a,l]);const sr=i.useCallback(async re=>{if(t.readFile)return(await t.readFile(re)).content??"";const Le=await fetch(`/api/fs/read?path=${encodeURIComponent(re)}`);if(!Le.ok){const Ce=await Le.json().catch(()=>({error:Le.statusText}));throw new Error(Ce.error||"Failed to read file")}return Le.text()},[t]),Xs=i.useMemo(()=>ie.length>qa?`${ie.slice(0,qa)}
|
|
281
|
+
|
|
282
|
+
… truncated …`:ie,[ie]),_s=i.useMemo(()=>G!==Xs,[G,Xs]),mr=i.useCallback(async()=>{if(!E||!t.writeFile){K.error("Saving not supported");return}if(_s){Oe(!0);try{if(!(await t.writeFile(E.path,G))?.success)throw new Error("Failed to write file");B(G)}catch(re){K.error(re instanceof Error?re.message:"Save failed")}finally{Oe(!1)}}},[G,t,_s,E]);i.useEffect(()=>{if(!_s){Nt(null);return}const re=Le=>He.current?(He.current=!1,!0):(fe(!0),ye.current=Le,!1);return Nt(re),()=>{Te.getState().mainTabGuard===re&&Nt(null)}},[_s,Nt]),i.useEffect(()=>{const re=Le=>{kr(Le)&&(Le.key.toLowerCase()==="s"?(Le.preventDefault(),me||mr()):Le.key.toLowerCase()==="f"&&(Le.preventDefault(),w(!0)))};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[me,mr]);const Zs=i.useCallback(async re=>{ge(null),J(""),X(re.path);const Le=xi(re.path),Ce=re.path.toLowerCase().endsWith(".svg");if(n&&y(!0),s.isDesktop&&Le&&!Ce){B(""),ae(""),H(!0);return}if(!s.isDesktop&&Le&&!Ce){B(""),ae(""),H(!1);return}H(!0);try{const _e=await sr(re.path);B(_e),ae(_e.length>qa?`${_e.slice(0,qa)}
|
|
283
|
+
|
|
284
|
+
… truncated …`:_e)}catch(_e){if(UI(_e)){if(d&&R(d,null),ge(null),B(""),ae(""),X(null),f.trim().length>0&&p(""),n&&y(!1),d){const dt=[...fh(re.path,d),re.path];dt.length>0&&T(d,dt);for(const $t of dt)ve.current.has($t)||ft($t)}return}B(""),ae(""),ge(_e instanceof Error?_e.message:"Failed to read file")}finally{H(!1)}},[T,n,ft,sr,d,s.isDesktop,f,R]),gr=i.useCallback(async(re,Le)=>{if(!d)return;const Ce=fh(re,d),_e=Le?[...Ce,re]:Ce;_e.length>0&&T(d,_e);for(const Qe of _e)ve.current.has(Qe)||await ft(Qe)},[T,ft,d]),Ie=i.useCallback((re,Le)=>{const Ce=Le.findIndex(_e=>_e.path===re);return Ce===-1||Le.length<=1?null:Le[Ce+1]??Le[Ce-1]??null},[]),Ge=i.useCallback(async re=>{if(He.current)He.current=!1;else if(_s){fe(!0),q.current=re;return}d&&(R(d,re.path),A(d,re.path),gr(re.path,!1)),ge(null),J(""),B(""),ae(""),X(null),n&&y(!0)},[A,gr,_s,n,d,R]);i.useEffect(()=>{E?.path&&gr(E.path,!1)},[gr,E?.path]),i.useEffect(()=>{E&&je!==E.path&&Zs(E)},[Zs,je,E]);const At=i.useCallback(()=>{const re=q.current,Le=ye.current,Ce=he.current;if(q.current=null,ye.current=null,he.current=null,He.current=!0,fe(!1),ae(Xs),Ce){d&&P(d,Ce),E?.path===Ce&&(re?Ge(re):(d&&R(d,null),B(""),ge(null),J(""),X(null),n&&y(!1)));return}if(re){Ge(re);return}Le&&(Nt(null),Te.getState().setActiveMainTab(Le))},[Xs,Ge,n,P,d,E?.path,Nt,R]),it=i.useCallback(async()=>{const re=q.current,Le=ye.current,Ce=he.current;if(q.current=null,ye.current=null,he.current=null,He.current=!0,fe(!1),await mr(),Ce){d&&P(d,Ce),E?.path===Ce&&(re?await Ge(re):(d&&R(d,null),B(""),ge(null),J(""),X(null),n&&y(!1)));return}if(re){await Ge(re);return}Le&&(Nt(null),Te.getState().setActiveMainTab(Le))},[Ge,n,P,d,mr,E?.path,Nt,R]),Kt=i.useCallback(re=>{const Le=E?.path===re,Ce=Ie(re,F);if(Le&&_s){fe(!0),q.current=Ce,he.current=re;return}if(d&&P(d,re),!!Le){if(Ce){Ge(Ce);return}d&&R(d,null),B(""),ge(null),J(""),X(null),n&&y(!1)}},[Ie,Ge,_s,n,F,P,d,E?.path,R]),It=i.useCallback(re=>{if(S.includes(re))return"open";if(m?.files){const Le=re.startsWith(d+"/")?re.slice(d.length+1):re,Ce=m.files.find(_e=>_e.path===Le);if(Ce){if(Ce.index==="A"||Ce.working_dir==="?")return"git-added";if(Ce.index==="D")return"git-deleted";if(Ce.index==="M"||Ce.working_dir==="M")return"git-modified"}}return null},[S,m,d]),Ps=i.useCallback(re=>{if(!m?.files)return null;const Le=re.startsWith(d+"/")?re.slice(d.length+1):re,Ce=Le?`${Le}/`:"";let _e=0,Qe=0;for(const dt of m.files)dt.path.startsWith(Ce)&&((dt.index==="M"||dt.working_dir==="M")&&_e++,(dt.index==="A"||dt.working_dir==="?")&&Qe++);return _e+Qe>0?{modified:_e,added:Qe}:null},[m,d]),Hs=i.useCallback(async re=>{const Le=wr(re);d&&(O(d,Le),ve.current.has(Le)||await ft(Le))},[ft,d,O]),Es=i.useCallback(re=>{d&&(f.trim().length>0&&p(""),n&&y(!1),gr(re,!0))},[gr,n,d,f]),er=i.useCallback((re,Le)=>{const Ce=W[re]??[];return Ce.map((_e,Qe)=>{const dt=_e.type==="directory",$t=dt&&D.includes(_e.path),be=E?.path===_e.path,U=dt&&oe.current.has(_e.path),te=Qe===Ce.length-1;return e.jsxs("li",{className:"relative",children:[Le>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),te&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),e.jsx(KI,{node:_e,isExpanded:$t,isActive:be,isLoading:U,isMobile:n,status:dt?void 0:It(_e.path),badge:dt?Ps(_e.path):void 0,permissions:{canRename:ds,canCreateFile:os,canCreateFolder:cs,canDelete:de},contextMenuPath:Re,setContextMenuPath:Xe,onSelect:Ge,onToggle:Hs,onOpenDialog:ke}),dt&&$t&&e.jsx("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:er(_e.path,Le+1)})]},_e.path)})},[W,D,Ge,E?.path,Hs,ke,os,cs,ds,de,Re,Xe,n,It,Ps]),Cs=!!(E?.path&&xi(E.path)),ar=!!(E?.path&&E.path.toLowerCase().endsWith(".svg")),ir=i.useCallback(re=>{if(!re)return"";const Le=wr(re);if(d&&ib(Le,d)){const Ce=Le.slice(d.length);return Ce.startsWith("/")?Ce.slice(1):Ce}return Le},[d]),qs=i.useMemo(()=>E?.path?ir(E.path):"",[ir,E?.path]),Ir=!!(E&&(!Cs||ar)&&ie.length>0),fr=!!(E&&qs.length>0),xr=!!(E&&!Cs&&t.writeFile&&ie.length<=qa),yr=i.useCallback(re=>{if(!n||!re||!re.hasFocus||typeof window>"u")return;const Le=window.visualViewport;if(!Le)return;const Ce=getComputedStyle(document.documentElement),_e=Number.parseFloat(Ce.getPropertyValue("--oc-keyboard-inset"))||0,Qe=Number.parseFloat(Ce.getPropertyValue("--oc-keyboard-home-indicator"))||0;if(_e+Qe<=0)return;const $t=re.state.selection.main.head,be=re.coordsAtPos($t);if(!be)return;const U=Math.round(Le.offsetTop+Le.height),Se=be.bottom+20-U;Se<=0||(re.scrollDOM.scrollTop+=Se)},[n]);i.useEffect(()=>{if(!n||typeof window>"u")return;const re=()=>{window.requestAnimationFrame(()=>{yr(Ve.current)})},Le=window.visualViewport;return Le?.addEventListener("resize",re),Le?.addEventListener("scroll",re),document.addEventListener("selectionchange",re),()=>{Le?.removeEventListener("resize",re),Le?.removeEventListener("scroll",re),document.removeEventListener("selectionchange",re)}},[n,yr]);const _r=i.useMemo(()=>{if(!E?.path)return[hu(r)];const re=[hu(r)],Le=Jy(E.path);return Le&&re.push(Le),b&&re.push(kn.lineWrapping),n&&re.push(kn.updateListener.of(Ce=>{Ce.view.hasFocus&&(Ce.selectionSet||Ce.focusChanged||Ce.viewportChanged||Ce.geometryChanged)&&window.requestAnimationFrame(()=>{yr(Ce.view)})})),re},[r,E?.path,b,n,yr]),pe=E?.path&&Cs?s.isDesktop?ar?`data:${su(E.path)};utf8,${encodeURIComponent(ie)}`:z:ar?`data:${su(E.path)};utf8,${encodeURIComponent(ie)}`:`/api/fs/raw?path=${encodeURIComponent(E.path)}`:"";i.useEffect(()=>{let re=!1;return(async()=>{if(!s.isDesktop||!E?.path||!Cs||ar){J("");return}ge(null);try{if(t.readFileBinary){const dt=await t.readFileBinary(E.path);re||J(dt.dataUrl);return}const _e=(await Ks(()=>import("@tauri-apps/api/core"),[])).convertFileSrc;if(!_e)return;const Qe=_e(E.path,"asset");re||J(Qe)}catch(Ce){re||(J(""),ge(Ce instanceof Error?Ce.message:"Failed to read file"))}finally{re||H(!1)}})(),()=>{re=!0}},[t,Cs,ar,s.isDesktop,E?.path]);const ee=()=>e.jsx(bs,{open:!!De,onOpenChange:re=>!re&&we(null),children:e.jsxs(vs,{children:[e.jsxs(js,{children:[e.jsxs(Ss,{children:[De==="createFile"&&"Create File",De==="createFolder"&&"Create Folder",De==="rename"&&"Rename",De==="delete"&&"Delete"]}),e.jsxs(Is,{children:[De==="createFile"&&`Create a new file in ${Fe?.path??"root"}`,De==="createFolder"&&`Create a new folder in ${Fe?.path??"root"}`,De==="rename"&&`Rename ${Fe?.name}`,De==="delete"&&`Are you sure you want to delete ${Fe?.name}? This action cannot be undone.`]})]}),De!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(Bt,{value:$e,onChange:re=>Ze(re.target.value),placeholder:De==="rename"?"New name":"Name",onKeyDown:re=>{re.key==="Enter"&&Ns()},autoFocus:!0})}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"outline",onClick:()=>we(null),disabled:Ue,children:"Cancel"}),e.jsx(Me,{variant:De==="delete"?"destructive":"default",onClick:()=>{Ns()},disabled:Ue||De!=="delete"&&!$e.trim(),children:Ue?e.jsx(Ot,{className:"animate-spin"}):De==="delete"?"Delete":"Confirm"})]})]})}),xe=i.useMemo(()=>{if(!E)return[];const re=_t??"draft",Ce=(Qt[re]??[]).filter(Qe=>Qe.source==="file"&&Qe.fileLabel===E.path),_e=[];return Ce.forEach(Qe=>{Mt===Qe.id?_e.push({afterLine:Qe.endLine,id:`edit-${Qe.id}`,content:e.jsx(Sa,{initialText:Qe.text,lineRange:{start:Qe.startLine,end:Qe.endLine},onSave:$t=>es($t,{start:Qe.startLine,end:Qe.endLine}),onCancel:()=>Zt(null),isEditing:!0})}):_e.push({afterLine:Qe.endLine,id:`card-${Qe.id}`,content:e.jsx(qu,{draft:Qe,onEdit:()=>{Zt(Qe.id),qe(null)},onDelete:()=>Ct(re,Qe.id)})})}),We&&!Mt&&!bt&&_e.push({afterLine:We.end,id:"files-new-comment-input",content:e.jsx(Sa,{lineRange:We,onSave:Qe=>es(Qe),onCancel:()=>qe(null)})}),_e},[E,_t,Qt,Mt,We,es,Ct,bt]),Ne=e.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[e.jsx(bs,{open:Be,onOpenChange:re=>{re||fe(!0)},children:e.jsxs(vs,{showCloseButton:!1,className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Unsaved changes"}),e.jsx(Is,{children:"Save your edits before continuing?"})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"outline",onClick:()=>{it()},disabled:me,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(Me,{variant:"destructive",onClick:At,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&&x&&e.jsx("button",{type:"button",onClick:()=>y(!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(ju,{className:"h-5 w-5"})}),e.jsx("div",{className:"min-w-0 flex-1",children:n?E?e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsxs("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-center gap-1 text-left typography-ui-label font-medium","aria-label":"Open files",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate",children:E.name}),e.jsx(is,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(fs,{align:"start",className:"min-w-[16rem]",children:F.map(re=>{const Le=E?.path===re.path;return e.jsxs(Et,{onSelect:Ce=>{if(Ce.target.closest("[data-close-open-file]")){Ce.preventDefault();return}Le||Ge(re)},className:L("flex items-center justify-between gap-2",Le&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate",children:re.name}),e.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:Ce=>{Ce.preventDefault(),Ce.stopPropagation()},onClick:Ce=>{Ce.preventDefault(),Ce.stopPropagation(),Kt(re.path)},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]","aria-label":`Close ${re.name}`,children:e.jsx(hs,{className:"h-3.5 w-3.5"})})]},re.path)})})]}):e.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"}):F.length>0?e.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-1 overflow-x-auto",children:F.map(re=>{const Le=E?.path===re.path;return e.jsxs("div",{title:ir(re.path),className:L("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",Le?"bg-[var(--interactive-selection)] border-[var(--primary-muted)] text-[var(--interactive-selection-foreground)]":"bg-transparent border-[var(--interactive-border)] text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]"),children:[e.jsx("button",{type:"button",onClick:()=>{Le||Ge(re)},className:"max-w-[12rem] truncate text-left",children:re.name}),e.jsx("button",{type:"button",onClick:Ce=>{Ce.stopPropagation(),Kt(re.path)},className:L("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!Le&&"opacity-0 group-hover:opacity-100"),"aria-label":`Close ${re.name}`,children:e.jsx(hs,{size:14})})]},re.path)})}),E&&e.jsx(OI,{path:qs,root:d,onNavigate:Es})]}):e.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[xr&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>{mr()},disabled:!_s||me,className:"h-5 w-5 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Ys()}+S)`,"aria-label":`Save (${Ys()}+S)`,children:me?e.jsx(Ot,{className:"h-4 w-4 animate-spin"}):e.jsx(Sm,{className:"h-4 w-4"})}),xr&&E&&!Cs&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),E&&!Cs&&e.jsxs(e.Fragment,{children:[e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>v(!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(Rd,{className:"size-4"})}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>w(!N),className:L("h-5 w-5 p-0 transition-opacity",N?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:"Find in file",children:e.jsx(Rr,{className:"size-4"})})]}),(Ir||fr||E&&ta(E.path))&&(xr||E&&!Cs)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),E&&ta(E.path)&&e.jsx(pu,{currentMode:Jt(),onToggle:()=>Pt(Jt()==="preview"?"edit":"preview")}),Ir&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(ie),St(!0),ot.current!==null&&window.clearTimeout(ot.current),ot.current=window.setTimeout(()=>{St(!1)},1200)}catch{K.error("Copy failed")}},className:"h-5 w-5 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:st?e.jsx(ss,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Cl,{className:"h-4 w-4"})}),fr&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(qs),Tt(!0),ue.current!==null&&window.clearTimeout(ue.current),ue.current=window.setTimeout(()=>{Tt(!1)},1200)}catch{K.error("Copy failed")}},className:"h-5 w-5 p-0",title:`Copy file path (${qs})`,"aria-label":`Copy file path (${qs})`,children:mt?e.jsx(ss,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(zd,{className:"h-4 w-4"})}),E&&!n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>k(!j),className:"h-5 w-5 p-0",title:j?"Exit fullscreen":"Fullscreen","aria-label":j?"Exit fullscreen":"Fullscreen",children:j?e.jsx(Ld,{className:"h-4 w-4"}):e.jsx(ig,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(Ut,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:E?se?e.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Ot,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):le?e.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:le}):Cs?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("img",{src:pe,alt:E?.name??"Image",className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"})}):E&&ta(E.path)&&Jt()==="preview"?e.jsxs("div",{className:"h-full overflow-auto p-3",children:[ie.length>500*1024&&e.jsxs("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:["⚠️ This file is large (",Math.round(ie.length/1024),"KB). Preview may be limited."]}),e.jsx(Gs,{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(zr,{content:ie,className:"typography-markdown-body"})})]}):e.jsx("div",{className:"h-full","data-keyboard-avoid":"none",style:n?{height:"calc(100% - var(--oc-keyboard-inset, 0px))"}:void 0,children:e.jsx(fu,{value:G,onChange:ae,extensions:_r,className:"h-full",onViewReady:re=>{Ve.current=re,window.requestAnimationFrame(()=>{yr(re)})},onViewDestroy:()=>{Ve.current&&(Ve.current=null)},enableSearch:!0,searchOpen:N,onSearchOpenChange:w,blockWidgets:xe,highlightLines:We?{start:Math.min(We.start,We.end),end:Math.max(We.start,We.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(re,Le,Ce)=>{if(!(Ce instanceof MouseEvent)||Ce.button!==0)return!1;Ce.preventDefault();const _e=re.state.doc.lineAt(Le.from).number;if(n&&We&&!Ce.shiftKey){const Qe=Math.min(We.start,We.end,_e),dt=Math.max(We.start,We.end,_e);return qe({start:Qe,end:dt}),et.current=!1,ct.current=null,at(!1),!0}if(et.current=!0,ct.current=_e,at(!0),We&&Ce.shiftKey){const Qe=Math.min(We.start,_e),dt=Math.max(We.end,_e);qe({start:Qe,end:dt})}else qe({start:_e,end:_e});return!0},mouseover:(re,Le,Ce)=>{if(!(Ce instanceof MouseEvent)||Ce.buttons!==1||!et.current||ct.current===null)return!1;const _e=re.state.doc.lineAt(Le.from).number,Qe=Math.min(ct.current,_e),dt=Math.max(ct.current,_e);return qe({start:Qe,end:dt}),at(!0),!1},mouseup:()=>(et.current=!1,ct.current=null,at(!1),!1)}}})}):e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})})]}),ze=!!(d&&W[d]),tt=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(Rr,{className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(Bt,{ref:g,value:f,onChange:re=>p(re.target.value),placeholder:"Search files…",className:"h-8 pl-8 pr-8 typography-meta"}),f.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:()=>{p(""),g.current?.focus()},children:e.jsx(hs,{className:"h-4 w-4"})})]}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>ke("createFile",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File",children:e.jsx(Dg,{className:"h-4 w-4"})}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>ke("createFolder",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder",children:e.jsx(Cu,{className:"h-4 w-4"})}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>{vt()},className:"h-8 w-8 p-0 flex-shrink-0",children:e.jsx(Mr,{className:"h-4 w-4"})})]})}),e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:L("py-2",n?"px-3":"px-2"),children:e.jsx("ul",{className:"flex flex-col",children:Q?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(Ot,{className:"h-4 w-4 animate-spin"}),"Searching…"]}):Z.length>0?Z.map(re=>{const Le=E?.path===re.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{Ge(re)},className:L("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",Le?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[lb(re.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:re.path,children:re.relativePath??re.path})]})},re.path)}):ze?er(d,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading…"})})})]}),kt=j&&E&&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:E.name}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:qs,children:qs})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[xr&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>{mr()},disabled:!_s||me,className:"h-6 w-6 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Ys()}+S)`,"aria-label":`Save (${Ys()}+S)`,children:me?e.jsx(Ot,{className:"h-4 w-4 animate-spin"}):e.jsx(Sm,{className:"h-4 w-4"})}),xr&&!Cs&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),!Cs&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>v(!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(Rd,{className:"size-4"})}),(Ir||fr||ta(E.path))&&(xr||!Cs)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),ta(E.path)&&e.jsx(pu,{currentMode:Jt(),onToggle:()=>Pt(Jt()==="preview"?"edit":"preview")}),Ir&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(ie),St(!0),ot.current!==null&&window.clearTimeout(ot.current),ot.current=window.setTimeout(()=>{St(!1)},1200)}catch{K.error("Copy failed")}},className:"h-6 w-6 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:st?e.jsx(ss,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(Cl,{className:"h-4 w-4"})}),fr&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(qs),Tt(!0),ue.current!==null&&window.clearTimeout(ue.current),ue.current=window.setTimeout(()=>{Tt(!1)},1200)}catch{K.error("Copy failed")}},className:"h-6 w-6 p-0",title:`Copy file path (${qs})`,"aria-label":`Copy file path (${qs})`,children:mt?e.jsx(ss,{className:"h-4 w-4 text-[color:var(--status-success)]"}):e.jsx(zd,{className:"h-4 w-4"})}),e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>k(!1),className:"h-6 w-6 p-0",title:"Exit fullscreen","aria-label":"Exit fullscreen",children:e.jsx(Ld,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(Ut,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:se?e.jsxs("div",{className:"p-4 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Ot,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):le?e.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:le}):Cs?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("img",{src:pe,alt:E.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"})}):ta(E.path)&&Jt()==="preview"?e.jsxs("div",{className:"h-full overflow-auto p-4",children:[ie.length>500*1024&&e.jsxs("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:["This file is large (",Math.round(ie.length/1024),"KB). Preview may be limited."]}),e.jsx(Gs,{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(zr,{content:ie,className:"typography-markdown-body"})})]}):e.jsx("div",{className:"h-full",children:e.jsx(fu,{value:G,onChange:ae,extensions:_r,className:"h-full",onViewReady:re=>{Ve.current=re,window.requestAnimationFrame(()=>{yr(re)})},onViewDestroy:()=>{Ve.current&&(Ve.current=null)}})})})})]});return e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[ee(),kt,n?x?Ne:tt:e.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[o>=700&&e.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:tt}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:Ne})]})]})},cb=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Nu},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Rn},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:xo},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:hg},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:Ro},{id:"usage",label:"Usage",description:"Monitor API quota and usage across providers.",icon:aj},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Ms},{id:"settings",label:"IKanban",description:"IKanban app settings: themes, fonts, and preferences.",icon:Po}],QI={},YI={},JI={};cb.forEach(t=>{QI[t.id]=t.label,YI[t.id]=t.description,JI[t.id]=t});const XI=t=>{if(!Array.isArray(t))return[];const s=[];for(const r of t){if(!r||typeof r!="object")continue;const n=r;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||s.push({permission:n.permission,pattern:n.pattern,action:n.action})}return s},ZI=t=>{const s=new Map;for(const r of t)!r.permission||r.permission==="invalid"||r.pattern&&s.set(`${r.permission}::${r.pattern}`,r);return Array.from(s.values())},ph=t=>{const s=ZI(XI(t));if(s.length===0)return;const r={};for(const o of s)o.permission&&((r[o.permission]||={})[o.pattern]=o.action);const n={};for(const[o,a]of Object.entries(r)){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},eT=({onItemSelect:t})=>{const[s,r]=i.useState(null),[n,o]=i.useState(""),[a,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(!1),{selectedAgentName:f,agents:p,setSelectedAgent:h,setAgentDraft:g,createAgent:x,deleteAgent:y,loadAgents:b}=bo(),{setSidebarOpen:v}=Te(),{isMobile:j}=ks(),k=i.useMemo(()=>gs(),[]);i.useEffect(()=>{b()},[b]);const N=k?"bg-background":"bg-sidebar",w=()=>{const F="new-agent";let I=F,E=1;for(;p.some(W=>W.name===I);)I=`${F}-${E}`,E++;g({name:I,scope:"user"}),h(I),t?.(),j&&v(!1)},C=async F=>{if(Mo(F)){K.error("Built-in agents cannot be deleted");return}l(F),d("delete")},S=async F=>{Mo(F)&&(l(F),d("reset"))},M=()=>{l(null),d(null)},D=async()=>{if(!a||!c)return;m(!0),await y(a.name)?(c==="delete"?K.success(`Agent "${a.name}" deleted successfully`):K.success(`Agent "${a.name}" reset to default`),M()):c==="delete"?K.error("Failed to delete agent"):K.error("Failed to reset agent"),m(!1)},A=F=>{const I=F.name;let E=1,W=`${I}-copy`;for(;p.some(Z=>Z.name===W);)E++,W=`${I}-copy-${E}`;const V=F,ve=F.model?.providerID&&F.model?.modelID?`${F.model.providerID}/${F.model.modelID}`:null,oe=F;g({name:W,scope:V.scope||"user",description:F.description,model:ve,temperature:F.temperature,top_p:F.topP,prompt:F.prompt,mode:F.mode,permission:ph(F.permission),disable:oe.disable}),h(W),j&&v(!1)},P=F=>{o(F.name),r(F)},$=async()=>{if(!s)return;const F=n.trim().replace(/\s+/g,"-");if(!F){K.error("Agent name is required");return}if(F===s.name){r(null);return}if(p.some(V=>V.name===F)){K.error("An agent with this name already exists");return}const I=s.model?.providerID&&s.model?.modelID?`${s.model.providerID}/${s.model.modelID}`:null,E=s;await x({name:F,description:s.description,model:I,temperature:s.temperature,top_p:s.topP,prompt:s.prompt,mode:s.mode,permission:ph(s.permission),disable:E.disable,scope:E.scope})?await y(s.name)?(K.success(`Agent renamed to "${F}"`),h(F)):K.error("Failed to remove old agent after rename"):K.error("Failed to rename agent"),r(null)},R=F=>{switch(F){case"primary":return e.jsx(Lo,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Tg,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(Ig,{className:"h-3 w-3 text-primary"});default:return null}},O=p.filter(F=>!nx(F)),T=O.filter(Mo),_=O.filter(F=>!Mo(F));return e.jsxs("div",{className:L("flex h-full flex-col",N),children:[e.jsx("div",{className:L("border-b px-3",j?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",O.length]}),e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(Fs,{className:"size-4"})})]})}),e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:O.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(ci,{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:[T.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"}),T.map(F=>e.jsx(hh,{agent:F,isSelected:f===F.name,onSelect:()=>{h(F.name),t?.(),j&&v(!1)},onReset:()=>S(F),onDuplicate:()=>A(F),getAgentModeIcon:R},F.name))]}),_.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"}),_.map(F=>e.jsx(hh,{agent:F,isSelected:f===F.name,onSelect:()=>{h(F.name),t?.(),j&&v(!1)},onRename:()=>P(F),onDelete:()=>C(F),onDuplicate:()=>A(F),getAgentModeIcon:R},F.name))]})]})}),e.jsx(bs,{open:a!==null&&c!==null,onOpenChange:F=>{!F&&!u&&M()},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:c==="delete"?"Delete Agent":"Reset Agent"}),e.jsx(Is,{children:c==="delete"?`Are you sure you want to delete agent "${a?.name}"?`:`Are you sure you want to reset agent "${a?.name}" to its default configuration?`})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:M,disabled:u,className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(bn,{onClick:D,disabled:u,children:c==="delete"?"Delete":"Reset"})]})]})}),e.jsx(bs,{open:s!==null,onOpenChange:F=>!F&&r(null),children:e.jsxs(vs,{children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Rename Agent"}),e.jsxs(Is,{children:['Enter a new name for the agent "@',s?.name,'"']})]}),e.jsx(Bt,{value:n,onChange:F=>o(F.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:F=>{F.key==="Enter"&&$()}}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>r(null),className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(bn,{onClick:$,children:"Rename"})]})]})})]})},hh=({agent:t,isSelected:s,onSelect:r,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",s?"bg-interactive-selection":"hover:bg-interactive-hover"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:r,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||Mo(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:Mo(t)?"system":d.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(Me,{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(Qn,{className:"h-3.5 w-3.5"})})}),e.jsxs(fs,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Et,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(go,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Et,{onClick:u=>{u.stopPropagation(),l()},children:[e.jsx(Hr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Et,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(jr,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Et,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Nr,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function pr({className:t,variant:s,...r}){return e.jsx(Me,{variant:s,size:"sm",className:L("h-6 px-2 text-xs",t),...r})}const tT=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),sT=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const s=tT.format(t);return s.endsWith(".0")?s.slice(0,-2):s},lm=({providerId:t,modelId:s,onChange:r,className:n,allowedProviderIds:o,placeholder:a})=>{const{providers:l,modelsMetadata:c}=ut(),d=Te(Z=>Z.isMobile),{toggleFavoriteModel:u,isFavoriteModel:m,addRecentModel:f}=Te(),{favoriteModelsList:p,recentModelsList:h}=vc(),{isMobile:g}=ks(),x=d||g,[y,b]=i.useState(!1),[v,j]=i.useState(new Set),[k,N]=i.useState(!1),[w,C]=i.useState(""),[S,M]=i.useState(0),D=i.useRef([]),A=i.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),P=i.useMemo(()=>A?l.filter(Z=>A.has(String(Z.id))):l,[l,A]),$=()=>b(!1),R=Z=>{j(ce=>{const Q=new Set(ce);return Q.has(Z)?Q.delete(Z):Q.add(Z),Q})};i.useEffect(()=>{k||(C(""),M(0))},[k]),i.useEffect(()=>{M(0)},[w]);const O=Z=>{const ce=Z?.name||Z?.id||"",Q=String(ce);return Q.length>40?Q.substring(0,37)+"...":Q},T=(Z,ce)=>{const Q=`${Z}/${ce}`;return c.get(Q)},_=(Z,ce)=>{r(Z,ce),Z&&ce&&f(Z,ce),N(!1)},F=(Z,ce)=>{if(!w.trim())return!0;const Q=w.toLowerCase();return Z.toLowerCase().includes(Q)||ce.toLowerCase().includes(Q)},I=(Z,ce,Q,Y,ie,B)=>{const se=T(ce,Q),H=sT(se?.limit?.context),le=t===ce&&s===Q,ge=m(ce,Q),z=Y==="fav"||Y==="recent";return e.jsxs("div",{ref:J=>{D.current[ie]=J},className:L("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",B?"bg-interactive-selection":"hover:bg-interactive-hover/50"),onClick:()=>_(ce,Q),onMouseEnter:()=>M(ie),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[z&&e.jsx(Os,{providerId:ce,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:O(Z)}),H?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:H}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[le&&e.jsx(ss,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:J=>{J.preventDefault(),J.stopPropagation(),u(ce,Q)},className:L("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-primary/80",ge?"text-primary":"text-muted-foreground"),"aria-label":ge?"Unfavorite":"Favorite",title:ge?"Remove from favorites":"Add to favorites",children:ge?e.jsx(Mn,{className:"h-3.5 w-3.5"}):e.jsx(Do,{className:"h-3.5 w-3.5"})})]})]},`${Y}-${ce}-${Q}`)},E=p.filter(({model:Z,providerID:ce})=>{if(A&&!A.has(ce))return!1;const Y=l.find(B=>B.id===ce)?.name||ce,ie=O(Z);return F(ie,Y)}),W=h.filter(({model:Z,providerID:ce})=>{if(A&&!A.has(ce))return!1;const Y=l.find(B=>B.id===ce)?.name||ce,ie=O(Z);return F(ie,Y)}),V=P.map(Z=>{const Q=(Array.isArray(Z.models)?Z.models:[]).filter(Y=>{const ie=O(Y);return F(ie,Z.name||Z.id||"")});return{...Z,models:Q}}).filter(Z=>Z.models.length>0),ve=E.length>0||W.length>0||V.length>0,oe=()=>x?e.jsx(Cr,{open:y,onClose:$,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[p.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] 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:p.map(({model:Z,providerID:ce,modelID:Q})=>{const Y=ce===t&&Q===s;return e.jsxs("div",{className:L("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",Y?"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:()=>{_(ce,Q),$()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{providerId:ce,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:O(Z)})]})}),e.jsx("button",{onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),u(ce,Q)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-primary hover:text-primary/80 active:scale-95 touch-manipulation","aria-label":"Unfavorite",children:e.jsx(Mn,{className:"h-4 w-4"})})]},`fav-mobile-${ce}-${Q}`)})})]}),h.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] 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:h.map(({model:Z,providerID:ce,modelID:Q})=>{const Y=ce===t&&Q===s;return e.jsxs("div",{className:L("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",Y?"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:()=>{_(ce,Q),$()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{providerId:ce,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:O(Z)})]})}),e.jsx("button",{onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),u(ce,Q)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-primary/80 active:scale-95 touch-manipulation","aria-label":"Favorite",children:e.jsx(Do,{className:"h-4 w-4"})})]},`recent-mobile-${ce}-${Q}`)})})]}),P.map(Z=>{const ce=Array.isArray(Z.models)?Z.models:[];if(ce.length===0)return null;const Q=Z.id===t,Y=v.has(Z.id);return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)]",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:()=>R(Z.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{providerId:Z.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Z.name}),Q&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Y?e.jsx(is,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(dr,{className:"h-3 w-3 text-muted-foreground"})]}),Y&&e.jsx("div",{className:"border-t border-border/20",children:ce.map(ie=>{const B=Z.id===t&&ie.id===s;return e.jsxs("div",{className:L("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",B?"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:()=>{_(Z.id,ie.id),$()},children:e.jsx("span",{className:"font-medium truncate",children:O(ie)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:se=>{se.preventDefault(),se.stopPropagation(),u(Z.id,ie.id)},className:L("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation hover:text-primary/80",m(Z.id,ie.id)?"text-primary":"text-muted-foreground/50"),"aria-label":m(Z.id,ie.id)?"Unfavorite":"Favorite",children:m(Z.id,ie.id)?e.jsx(Mn,{className:"h-4 w-4"}):e.jsx(Do,{className:"h-4 w-4"})}),B&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},ie.id)})})]},Z.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-[var(--surface-elevated)] px-2 py-1.5 text-left",onClick:()=>{_("",""),$()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:a||"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[x?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-[var(--surface-elevated)] px-2 py-1.5 text-left",n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[t?e.jsx(Os,{providerId:t,className:"h-3.5 w-3.5"}):e.jsx(fn,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:t&&s?`${t}/${s}`:a||"Select model..."})]}),e.jsx(is,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(us,{open:k,onOpenChange:N,children:[e.jsx(ms,{asChild:!0,children:e.jsxs("div",{className:L("flex items-center gap-2 px-2 rounded-lg bg-interactive-selection/20 border border-border/20 cursor-pointer hover:bg-interactive-hover/30 h-6 w-fit",n),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(Os,{providerId:t,className:"h-3 w-3 flex-shrink-0"}),e.jsx(fn,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(fn,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:t&&s?`${t}/${s}`:a||"Not selected"}),e.jsx(is,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(fs,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const Z=[];E.forEach(({model:ie,providerID:B,modelID:se})=>{Z.push({model:ie,providerID:B,modelID:se,section:"fav"})}),W.forEach(({model:ie,providerID:B,modelID:se})=>{Z.push({model:ie,providerID:B,modelID:se,section:"recent"})}),V.forEach(ie=>{ie.models.forEach(B=>{Z.push({model:B,providerID:ie.id,modelID:B.id,section:"provider"})})});const ce=Z.length,Q=ie=>{if(ie.stopPropagation(),ie.key==="ArrowDown"){ie.preventDefault();const B=(S+1)%Math.max(1,ce);M(B),setTimeout(()=>{D.current[B]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(ie.key==="ArrowUp"){ie.preventDefault();const B=(S-1+Math.max(1,ce))%Math.max(1,ce);M(B),setTimeout(()=>{D.current[B]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(ie.key==="Enter"){ie.preventDefault();const B=Z[S];B&&_(B.providerID,B.modelID)}else ie.key==="Escape"&&(ie.preventDefault(),N(!1))};let Y=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(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Bt,{type:"text",placeholder:"Search models",value:w,onChange:ie=>C(ie.target.value),onKeyDown:Q,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(Ut,{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-interactive-hover/50"),onClick:()=>_("",""),children:[e.jsx(hs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:a||"Not selected"}),!t&&!s&&e.jsx(ss,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(lr,{}),!ve&&w&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),E.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Wr,{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[e.jsx(Mn,{className:"h-4 w-4 text-primary"}),"Favorites"]}),E.map(({model:ie,providerID:B,modelID:se})=>{const H=Y++;return I(ie,B,se,"fav",H,S===H)})]}),W.length>0&&e.jsxs(e.Fragment,{children:[E.length>0&&e.jsx(lr,{}),e.jsxs(Wr,{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[e.jsx(Pn,{className:"h-4 w-4"}),"Recent"]}),W.map(({model:ie,providerID:B,modelID:se})=>{const H=Y++;return I(ie,B,se,"recent",H,S===H)})]}),(E.length>0||W.length>0)&&V.length>0&&e.jsx(lr,{}),V.map((ie,B)=>e.jsxs(i.Fragment,{children:[B>0&&e.jsx(lr,{}),e.jsxs(Wr,{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[e.jsx(Os,{providerId:ie.id,className:"h-4 w-4 flex-shrink-0"}),ie.name]}),ie.models.map(se=>{const H=Y++;return I(se,ie.id,se.id,"provider",H,S===H)})]},ie.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"})]})})()})]}),oe()]})},gh=["*","read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop","question","plan_enter","plan_exit"],Nl=t=>t==="allow"||t==="ask"||t==="deny",Co=(t,s)=>`${t}::${s}`,Uo=t=>{const s=new Map;for(const r of t)!r.permission||r.permission==="invalid"||r.pattern&&Nl(r.action)&&s.set(Co(r.permission,r.pattern),{permission:r.permission,pattern:r.pattern,action:r.action});return Array.from(s.values())},tl=t=>{const s=new Map;for(const r of Uo(t))s.set(Co(r.permission,r.pattern),r);return s},xh=t=>[...t].sort((s,r)=>{const n=s.permission.localeCompare(r.permission);return n!==0?n:s.pattern.localeCompare(r.pattern)}),rT=(t,s)=>{const r=xh(Uo(t)),n=xh(Uo(s));return r.length!==n.length?!1:r.every((o,a)=>{const l=n[a];return o.permission===l.permission&&o.pattern===l.pattern&&o.action===l.action})},nT=t=>t.find(r=>r.permission==="*"&&r.pattern==="*")?.action??"allow",oT=(t,s)=>Uo(t).filter(r=>!(r.permission==="*"&&r.pattern==="*")).filter(r=>r.pattern!=="*"||r.action!==s),aT=t=>{if(Nl(t))return[{permission:"*",pattern:"*",action:t}];if(!t||typeof t!="object"||Array.isArray(t))return[];const s=[];for(const[r,n]of Object.entries(t))if(r!=="__originalKeys"){if(Nl(n)){s.push({permission:r,pattern:"*",action:n});continue}if(n&&typeof n=="object"&&!Array.isArray(n))for(const[o,a]of Object.entries(n))Nl(a)&&s.push({permission:r,pattern:o,action:a})}return s},iT=(t,s)=>{const r=Uo(s),n={};for(const a of r)(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},lT=()=>{const{selectedAgentName:t,getAgentByName:s,createAgent:r,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:l}=bo();ut();const c=t?s(t):null,d=!!(a&&a.name===t&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,g]=i.useState(""),[x,y]=i.useState("subagent"),[b,v]=i.useState(""),[j,k]=i.useState(void 0),[N,w]=i.useState(void 0),[C,S]=i.useState(""),[M,D]=i.useState("allow"),[A,P]=i.useState([]),[$,R]=i.useState([]),[O,T]=i.useState(""),[_,F]=i.useState("*"),[I,E]=i.useState(!1),[W,V]=i.useState(!1),ve=i.useRef(null),oe=Yt(q=>q.currentDirectory??null),[Z,ce]=i.useState([]),Q=gi(q=>q.permissions);i.useEffect(()=>{let q=!1;return(async()=>{const he=await nt.listToolIds({directory:oe});if(q)return;const He=new Set(["write","patch","multiedit"]),ot=he.map(ue=>typeof ue=="string"?ue.trim():"").filter(Boolean).filter(ue=>ue!=="*").filter(ue=>ue!=="invalid").filter(ue=>!He.has(ue));ce(Array.from(new Set(ot)).sort((ue,Ve)=>ue.localeCompare(Ve)))})(),()=>{q=!0}},[oe]);const Y=i.useMemo(()=>{const q=new Set;for(const ye of o){const he=Uo(Array.isArray(ye.permission)?ye.permission:[]);for(const He of he)He.permission&&He.permission!=="*"&&He.permission!=="invalid"&&q.add(He.permission)}for(const ye of Q.values())for(const he of ye){const He=he.permission?.trim();He&&He!=="invalid"&&q.add(He)}for(const ye of Z)q.add(ye);return Array.from(q).sort((ye,he)=>ye.localeCompare(he))},[o,Q,Z]),ie=i.useMemo(()=>tl(A),[A]),B=i.useMemo(()=>tl($),[$]),se=i.useCallback(q=>B.get(Co(q,"*"))?.action,[B]),H=i.useCallback(q=>$.filter(ye=>ye.permission===q&&ye.pattern!=="*").sort((ye,he)=>ye.pattern.localeCompare(he.pattern)),[$]),le=i.useMemo(()=>{const q=new Set;for(const ye of gh)q.add(ye);for(const ye of Y)q.add(ye);return Array.from(q).sort((ye,he)=>ye.localeCompare(he))},[Y]),ge=i.useCallback(q=>{const ye=q==="*"?M:se(q)??M,he=H(q),He=!1,ot=he.reduce((Ve,De)=>(Ve[De.action]=(Ve[De.action]??0)+1,Ve),{allow:0,ask:0,deny:0}),ue=["allow","ask","deny"].filter(Ve=>ot[Ve]>0).map(Ve=>`${ot[Ve]} ${Ve}`).join(", ");return{defaultAction:ye,patternRulesCount:he.length,patternSummary:ue,hasDefaultHint:He}},[H,se,M]),z=i.useMemo(()=>{const q=new Set;for(const ye of gh)q.add(ye);for(const ye of Y)q.add(ye);return Array.from(q).sort((ye,he)=>ye.localeCompare(he))},[Y]),J=i.useCallback((q,ye,he)=>{R(He=>{const ot=tl(He);return ot.set(Co(q,ye),{permission:q,pattern:ye,action:he}),Array.from(ot.values())})},[]),je=i.useCallback((q,ye)=>{R(he=>{const He=tl(he);return He.delete(Co(q,ye)),Array.from(He.values())})},[]),X=i.useCallback((q,ye)=>{const he=ie.get(Co(q,ye));if(he){J(q,ye,he.action);return}je(q,ye)},[ie,je,J]),G=i.useCallback((q,ye,he)=>{J(q,ye,he)},[J]),ae=i.useCallback(q=>{D(q),R(ye=>ye.filter(he=>!(he.pattern==="*"&&he.action===q)))},[]),me=i.useCallback(q=>{const ye=O.trim();if(!ye){K.error("Permission name is required");return}const he=_.trim()||"*";if(ye==="*"&&he==="*"){ae(q),T(""),F("*");return}he==="*"&&ye!=="*"&&q===M?je(ye,"*"):J(ye,he,q),T(""),F("*")},[M,O,_,je,ae,J]),Oe=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(ye=>ye.charAt(0).toUpperCase()+ye.slice(1)).join(" "),[]);i.useEffect(()=>{T(""),F("*");const q=ye=>{const he=Uo(ye),He=nT(he),ot=oT(he,He);return D(He),P(ot),R(ot),{global:He,rules:ot}};if(d&&a){const ye=a.name||"",he=a.scope||"user",He=a.description||"",ot=a.mode||"subagent",ue=a.model||"",Ve=a.temperature,De=a.top_p,we=a.prompt||"";m(ye),p(he),g(He),y(ot),v(ue),k(Ve),w(De),S(we);const Fe=aT(a.permission),Pe=q(Fe);ve.current={draftName:ye,draftScope:he,description:He,mode:ot,model:ue,temperature:Ve,topP:De,prompt:we,globalPermission:Pe.global,permissionRules:Pe.rules};return}if(c&&t===c.name){const ye=c.description||"",he=c.mode||"subagent",He=c.model?.providerID&&c.model?.modelID?`${c.model.providerID}/${c.model.modelID}`:"",ot=c.temperature,ue=c.topP,Ve=c.prompt||"";g(ye),y(he),v(He),k(ot),w(ue),S(Ve);const De=q(Array.isArray(c.permission)?c.permission:[]);ve.current={draftName:"",draftScope:"user",description:ye,mode:he,model:He,temperature:ot,topP:ue,prompt:Ve,globalPermission:De.global,permissionRules:De.rules}}},[a,d,c,t]);const Be=i.useMemo(()=>{const q=ve.current;return q?!!(d&&(u!==q.draftName||f!==q.draftScope)||h!==q.description||x!==q.mode||b!==q.model||j!==q.temperature||N!==q.topP||C!==q.prompt||M!==q.globalPermission||!rT($,q.permissionRules)):!1},[h,u,f,M,d,x,b,$,C,j,N]),fe=async()=>{const q=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!q){K.error("Agent name is required");return}if(d&&o.some(ye=>ye.name===q)){K.error("An agent with this name already exists");return}V(!0);try{const ye=b.trim(),he=iT(M,$),He={name:q,description:h.trim()||void 0,mode:x,model:ye===""?null:ye,temperature:j,top_p:N,prompt:C.trim()||void 0,permission:he,scope:d?f:void 0};let ot;d?(ot=await r(He),ot&&l(null)):ot=await n(q,He),ot?K.success(d?"Agent created successfully":"Agent updated successfully"):K.error(d?"Failed to create agent":"Failed to update agent")}catch(ye){console.error("Error saving agent:",ye);const he=ye instanceof Error&&ye.message?ye.message:"An error occurred while saving";K.error(he)}finally{V(!1)}};return t?e.jsx(Ut,{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(Bt,{value:u,onChange:q=>m(q.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs($s,{value:f,onValueChange:q=>p(q),children:[e.jsxs(Bs,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(en,{className:"h-4 w-4"}):e.jsx(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(zs,{align:"end",children:[e.jsx(ns,{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(en,{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(ns,{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(Fn,{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(hr,{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(pr,{variant:x==="primary"?"default":"outline",onClick:()=>y("primary"),className:L("gap-2",x==="primary"?void 0:"text-foreground"),children:[e.jsx(Lo,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(pr,{variant:x==="subagent"?"default":"outline",onClick:()=>y("subagent"),className:L("gap-2",x==="subagent"?void 0:"text-foreground"),children:[e.jsx(Ig,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(pr,{variant:x==="all"?"default":"outline",onClick:()=>y("all"),className:L("gap-2",x==="all"?void 0:"text-foreground"),children:[e.jsx(Tg,{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(lm,{providerId:b?b.split("/")[0]:"",modelId:b?b.split("/")[1]:"",onChange:(q,ye)=>{v(q&&ye?`${q}/${ye}`:"")}})]}),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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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 ye=Math.max(0,(j!==void 0?j:.7)-.1);k(parseFloat(ye.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-interactive-hover text-muted-foreground hover:text-foreground",children:e.jsx(Fa,{className:"h-3.5 w-3.5"})}),e.jsx(Bt,{type:"text",inputMode:"decimal",value:j!==void 0?j:"",onChange:q=>{const ye=q.target.value;if(ye===""){k(void 0);return}const he=parseFloat(ye);!isNaN(he)&&he>=0&&he<=2&&k(he)},onBlur:q=>{const ye=q.target.value;if(ye!==""){const he=parseFloat(ye);if(!isNaN(he)){const He=Math.max(0,Math.min(2,he));k(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 ye=Math.min(2,(j!==void 0?j:.7)+.1);k(parseFloat(ye.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-interactive-hover text-muted-foreground hover:text-foreground",children:e.jsx(Fs,{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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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 ye=Math.max(0,(N!==void 0?N:.9)-.1);w(parseFloat(ye.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-interactive-hover text-muted-foreground hover:text-foreground",children:e.jsx(Fa,{className:"h-3.5 w-3.5"})}),e.jsx(Bt,{type:"text",inputMode:"decimal",value:N!==void 0?N:"",onChange:q=>{const ye=q.target.value;if(ye===""){w(void 0);return}const he=parseFloat(ye);!isNaN(he)&&he>=0&&he<=1&&w(he)},onBlur:q=>{const ye=q.target.value;if(ye!==""){const he=parseFloat(ye);if(!isNaN(he)){const He=Math.max(0,Math.min(1,he));w(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 ye=Math.min(1,(N!==void 0?N:.9)+.1);w(parseFloat(ye.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-interactive-hover text-muted-foreground hover:text-foreground",children:e.jsx(Fs,{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(hr,{value:C,onChange:q=>S(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(Me,{size:"sm",variant:"outline",onClick:()=>E(q=>!q),className:"h-8",children:I?"Hide":"Edit"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I?"Set a global default; tools only saved when different from global.":"Summary shows default actions; edit to manage granular rules."})]}),I?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($s,{value:M,onValueChange:q=>ae(q),children:[e.jsx(Bs,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:M})}),e.jsxs(zs,{children:[e.jsx(ns,{value:"allow",className:"pr-2 [&>span:first-child]:hidden",children:"Allow"}),e.jsx(ns,{value:"ask",className:"pr-2 [&>span:first-child]:hidden",children:"Ask"}),e.jsx(ns,{value:"deny",className:"pr-2 [&>span:first-child]:hidden",children:"Deny"})]})]})]})}),e.jsx("div",{className:"space-y-6",children:le.filter(q=>q!=="*").map(q=>{const ye=Oe(q),{defaultAction:he,patternRulesCount:He,patternSummary:ot}=ge(q),ue=se(q),Ve=ue??"global",De=H(q),we=["allow","ask","deny"].filter(Fe=>Fe!==M);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:ye}),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: ",he]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:he}),He>0?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:["Patterns: ",ot]}):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:"*"}),ue?e.jsxs(Me,{size:"sm",variant:"outline",onClick:()=>X(q,"*"),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(Fa,{className:"h-3 w-3"}),"Revert"]}):null]}),e.jsxs($s,{value:Ve,onValueChange:Fe=>{if(Fe==="global"){je(q,"*");return}J(q,"*",Fe)},children:[e.jsx(Bs,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:Ve==="global"?"Global":Ve})}),e.jsxs(zs,{children:[e.jsx(ns,{value:"global",className:"pr-2 [&>span:first-child]:hidden",children:"Global"}),we.map(Fe=>e.jsx(ns,{value:Fe,className:"pr-2 [&>span:first-child]:hidden",children:Fe.charAt(0).toUpperCase()+Fe.slice(1)},Fe))]})]})]}),De.map(Fe=>{const Pe=Co(Fe.permission,Fe.pattern),$e=ie.get(Pe),Ze=!$e,Ue=!!($e&&$e.action!==Fe.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:Fe.pattern}),Ze?e.jsx("span",{className:"typography-micro text-emerald-500",children:"New"}):null,Ue?e.jsx("span",{className:"typography-micro text-amber-500",children:"Modified"}):null,Ze?e.jsxs(Me,{size:"sm",variant:"outline",onClick:()=>je(Fe.permission,Fe.pattern),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(Fa,{className:"h-3 w-3"}),"Remove"]}):Ue?e.jsxs(Me,{size:"sm",variant:"outline",onClick:()=>X(Fe.permission,Fe.pattern),className:"h-5 px-2 text-[11px] gap-1",children:[e.jsx(Fa,{className:"h-3 w-3"}),"Revert"]}):null]}),e.jsxs($s,{value:Fe.action,onValueChange:Ee=>G(Fe.permission,Fe.pattern,Ee),children:[e.jsx(Bs,{className:"h-6 w-24 text-xs",children:e.jsx("span",{className:"capitalize",children:Fe.action})}),e.jsxs(zs,{children:[e.jsx(ns,{value:"allow",className:"pr-2 [&>span:first-child]:hidden",children:"Allow"}),e.jsx(ns,{value:"ask",className:"pr-2 [&>span:first-child]:hidden",children:"Ask"}),e.jsx(ns,{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($s,{value:O,onValueChange:T,children:[e.jsx(Bs,{className:"h-8 min-h-8 w-full sm:w-64",children:O?e.jsx("span",{className:"truncate",children:Oe(O)}):e.jsx("span",{className:"text-muted-foreground",children:"Permission…"})}),e.jsx(zs,{children:z.map(q=>e.jsx(ns,{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:Oe(q)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:q})]})},q))})]}),e.jsx(Bt,{value:_,onChange:q=>F(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(Me,{size:"sm",variant:"outline",onClick:()=>me("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>me("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(Me,{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:le.map(q=>{const{defaultAction:ye,patternRulesCount:he,patternSummary:He,hasDefaultHint:ot}=ge(q),ue=Oe(q),Ve=ot?`${ye} (env blocked)`:ye;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:ue}),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: ",Ve]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:Ve}),he>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(Me,{size:"sm",variant:"default",onClick:fe,disabled:W||!Be,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(nc,{className:"h-3 w-3"}),W?"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(ci,{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"})]})})},cT=({onItemSelect:t})=>{const[s,r]=i.useState(null),[n,o]=i.useState(""),[a,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(!1),{selectedCommandName:f,commands:p,setSelectedCommand:h,setCommandDraft:g,createCommand:x,deleteCommand:y,loadCommands:b}=yo(),{setSidebarOpen:v}=Te(),{isMobile:j}=ks(),k=i.useMemo(()=>gs(),[]);i.useEffect(()=>{b()},[b]);const N=k?"bg-background":"bg-sidebar",w=()=>{const T="new-command";let _=T,F=1;for(;p.some(I=>I.name===_);)_=`${T}-${F}`,F++;g({name:_,scope:"user"}),h(_),t?.(),j&&v(!1)},C=async T=>{if(aa(T)){K.error("Built-in commands cannot be deleted");return}l(T),d("delete")},S=async T=>{aa(T)&&(l(T),d("reset"))},M=()=>{l(null),d(null)},D=async()=>{if(!a||!c)return;m(!0),await y(a.name)?(c==="delete"?K.success(`Command "${a.name}" deleted successfully`):K.success(`Command "${a.name}" reset to default`),M()):c==="delete"?K.error("Failed to delete command"):K.error("Failed to reset command"),m(!1)},A=T=>{const _=T.name;let F=1,I=`${_}-copy`;for(;p.some(E=>E.name===I);)F++,I=`${_}-copy-${F}`;g({name:I,scope:T.scope||"user",description:T.description,template:T.template,agent:T.agent,model:T.model,subtask:T.subtask}),h(I),j&&v(!1)},P=T=>{o(T.name),r(T)},$=async()=>{if(!s)return;const T=n.trim().replace(/\s+/g,"-");if(!T){K.error("Command name is required");return}if(T===s.name){r(null);return}if(p.some(F=>F.name===T)){K.error("A command with this name already exists");return}await x({name:T,description:s.description,template:s.template,agent:s.agent,model:s.model,subtask:s.subtask})?await y(s.name)?(K.success(`Command renamed to "${T}"`),h(T)):K.error("Failed to remove old command after rename"):K.error("Failed to rename command"),r(null)},R=p.filter(aa),O=p.filter(T=>!aa(T));return e.jsxs("div",{className:L("flex h-full flex-col",N),children:[e.jsx("div",{className:L("border-b px-3",j?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",p.length]}),e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(Fs,{className:"size-4"})})]})}),e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:p.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(fo,{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:[R.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"}),[...R].sort((T,_)=>T.name.localeCompare(_.name)).map(T=>e.jsx(yh,{command:T,isSelected:f===T.name,onSelect:()=>{h(T.name),t?.(),j&&v(!1)},onReset:()=>S(T),onDuplicate:()=>A(T)},T.name))]}),O.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"}),[...O].sort((T,_)=>T.name.localeCompare(_.name)).map(T=>e.jsx(yh,{command:T,isSelected:f===T.name,onSelect:()=>{h(T.name),t?.(),j&&v(!1)},onRename:()=>P(T),onDelete:()=>C(T),onDuplicate:()=>A(T)},T.name))]})]})}),e.jsx(bs,{open:a!==null&&c!==null,onOpenChange:T=>{!T&&!u&&M()},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:c==="delete"?"Delete Command":"Reset Command"}),e.jsx(Is,{children:c==="delete"?`Are you sure you want to delete command "${a?.name}"?`:`Are you sure you want to reset command "${a?.name}" to its default configuration?`})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:M,disabled:u,className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(bn,{onClick:D,disabled:u,children:c==="delete"?"Delete":"Reset"})]})]})}),e.jsx(bs,{open:s!==null,onOpenChange:T=>!T&&r(null),children:e.jsxs(vs,{children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Rename Command"}),e.jsxs(Is,{children:['Enter a new name for the command "/',s?.name,'"']})]}),e.jsx(Bt,{value:n,onChange:T=>o(T.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:T=>{T.key==="Enter"&&$()}}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>r(null),className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(bn,{onClick:$,children:"Rename"})]})]})})]})},yh=({command:t,isSelected:s,onSelect:r,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",s?"bg-interactive-selection":"hover:bg-interactive-hover"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:r,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||aa(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:aa(t)?"system":t.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(Me,{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(Qn,{className:"h-3.5 w-3.5"})})}),e.jsxs(fs,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Et,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(go,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Et,{onClick:c=>{c.stopPropagation(),l()},children:[e.jsx(Hr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Et,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(jr,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Et,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Nr,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),db=({agentName:t,onChange:s,className:r})=>{const{loadAgents:n,getVisibleAgents:o}=bo(),a=o(),l=Te(g=>g.isMobile),{isMobile:c}=ks(),d=l||c,[u,m]=i.useState(!1);i.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=g=>{s(g)},h=()=>d?e.jsx(Cr,{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",r),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ci,{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(is,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsxs("div",{className:L("flex items-center gap-2 px-2 rounded-lg bg-interactive-selection/20 border border-border/20 cursor-pointer hover:bg-interactive-hover/30 h-6 w-fit",r),children:[e.jsx(ci,{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(is,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(fs,{className:"max-w-[300px]",children:[a.map(g=>e.jsx(Et,{className:"typography-meta",onSelect:()=>p(g.name),children:e.jsx("span",{className:"font-medium",children:g.name})},g.name)),e.jsx(Et,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},dT=()=>{const{selectedCommandName:t,getCommandByName:s,createCommand:r,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:l}=yo(),c=t?s(t):null,d=!!(a&&a.name===t&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,g]=i.useState(""),[x,y]=i.useState(""),[b,v]=i.useState(""),[j,k]=i.useState(""),[N,w]=i.useState(!1),[C,S]=i.useState(!1),M=i.useRef(null);i.useEffect(()=>{if(d&&a){const P=a.name||"",$=a.scope||"user",R=a.description||"",O=a.agent||"",T=a.model||"",_=a.template||"",F=a.subtask||!1;m(P),p($),g(R),y(O),v(T),k(_),w(F),M.current={draftName:P,draftScope:$,description:R,agent:O,model:T,template:_,subtask:F}}else if(c){const P=c.description||"",$=c.agent||"",R=c.model||"",O=c.template||"",T=c.subtask||!1;g(P),y($),v(R),k(O),w(T),M.current={draftName:"",draftScope:"user",description:P,agent:$,model:R,template:O,subtask:T}}},[c,d,t,o,a]);const D=i.useMemo(()=>{const P=M.current;return P?!!(d&&(u!==P.draftName||f!==P.draftScope)||h!==P.description||x!==P.agent||b!==P.model||j!==P.template||N!==P.subtask):!1},[x,h,u,f,d,b,N,j]),A=async()=>{const P=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!P){K.error("Command name is required");return}if(!j.trim()){K.error("Command template is required");return}if(d&&o.some($=>$.name===P)){K.error("A command with this name already exists");return}S(!0);try{const $=x.trim(),R=b.trim(),O=j.trim(),T={name:P,description:h.trim()||void 0,agent:$===""?null:$,model:R===""?null:R,template:O,subtask:N,scope:d?f:void 0};let _;d?(_=await r(T),_&&l(null)):_=await n(P,T),_?K.success(d?"Command created successfully":"Command updated successfully"):K.error(d?"Failed to create command":"Failed to update command")}catch($){console.error("Error saving command:",$),K.error("An error occurred while saving")}finally{S(!1)}};return t?e.jsx(Ut,{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(Bt,{value:u,onChange:P=>m(P.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs($s,{value:f,onValueChange:P=>p(P),children:[e.jsxs(Bs,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(en,{className:"h-4 w-4"}):e.jsx(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(zs,{align:"end",children:[e.jsx(ns,{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(en,{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(ns,{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(Fn,{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(hr,{value:h,onChange:P=>g(P.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(db,{agentName:x,onChange:P=>y(P)}),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(lm,{providerId:b?b.split("/")[0]:"",modelId:b?b.split("/")[1]:"",onChange:(P,$)=>{v(P&&$?`${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.jsx(Xr,{checked:N,onChange:P=>w(P)}),"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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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(hr,{value:j,onChange:P=>k(P.target.value),placeholder:`Your command template here...
|
|
285
|
+
|
|
286
|
+
Use $ARGUMENTS to reference user input.
|
|
287
|
+
Use !\`shell command\` to inject shell output.
|
|
288
|
+
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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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(Me,{size:"sm",variant:"default",onClick:A,disabled:C||!D,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(nc,{className:"h-3 w-3"}),C?"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(fo,{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"})]})})},uT=({onItemSelect:t})=>{const[s,r]=i.useState(null),[n,o]=i.useState(""),[a,l]=i.useState(null),[c,d]=i.useState(!1),{selectedSkillName:u,skills:m,setSelectedSkill:f,setSkillDraft:p,createSkill:h,deleteSkill:g,loadSkills:x,getSkillDetail:y}=pn(),{setSidebarOpen:b}=Te(),{isMobile:v}=ks(),j=i.useMemo(()=>gs(),[]);i.useEffect(()=>{x()},[x]);const k=j?"bg-background":"bg-sidebar",N=()=>{const $="new-skill";let R=$,O=1;for(;m.some(T=>T.name===R);)R=`${$}-${O}`,O++;p({name:R,scope:"user",description:""}),f(R),t?.(),v&&b(!1)},w=async $=>{l($)},C=async()=>{if(!a)return;d(!0),await g(a.name)?(K.success(`Skill "${a.name}" deleted successfully`),l(null)):K.error("Failed to delete skill"),d(!1)},S=async $=>{const R=$.name;let O=1,T=`${R}-copy`;for(;m.some(F=>F.name===T);)O++,T=`${R}-copy-${O}`;const _=await y($.name);if(!_){K.error("Failed to load skill details for duplication");return}p({name:T,scope:$.scope||"user",description:(_.sources.md.fields.includes("description"),""),instructions:""}),f(T),v&&b(!1)},M=$=>{o($.name),r($)},D=async()=>{if(!s)return;const $=n.trim().replace(/\s+/g,"-").toLowerCase();if(!$){K.error("Skill name is required");return}if($===s.name){r(null);return}if(m.some(T=>T.name===$)){K.error("A skill with this name already exists");return}if(!await y(s.name)){K.error("Failed to load skill details"),r(null);return}await h({name:$,description:"Renamed skill",scope:s.scope})?await g(s.name)?(K.success(`Skill renamed to "${$}"`),f($)):K.error("Failed to remove old skill after rename"):K.error("Failed to rename skill"),r(null)},A=m.filter($=>$.scope==="project"),P=m.filter($=>$.scope==="user");return e.jsxs("div",{className:L("flex h-full flex-col",k),children:[e.jsx("div",{className:L("border-b px-3",v?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",m.length]}),e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:N,children:e.jsx(Fs,{className:"size-4"})})]})}),e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:m.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Eg,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No skills configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[A.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Project Skills"}),A.map($=>e.jsx(bh,{skill:$,isSelected:u===$.name,onSelect:()=>{f($.name),t?.(),v&&b(!1)},onRename:()=>M($),onDelete:()=>w($),onDuplicate:()=>S($)},$.name))]}),P.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"}),P.map($=>e.jsx(bh,{skill:$,isSelected:u===$.name,onSelect:()=>{f($.name),t?.(),v&&b(!1)},onRename:()=>M($),onDelete:()=>w($),onDuplicate:()=>S($)},$.name))]})]})}),e.jsx(bs,{open:a!==null,onOpenChange:$=>{!$&&!c&&l(null)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Delete Skill"}),e.jsxs(Is,{children:['Are you sure you want to delete skill "',a?.name,'"?']})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>l(null),disabled:c,className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(bn,{onClick:C,disabled:c,children:"Delete"})]})]})}),e.jsx(bs,{open:s!==null,onOpenChange:$=>!$&&r(null),children:e.jsxs(vs,{children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Rename Skill"}),e.jsxs(Is,{children:['Enter a new name for the skill "',s?.name,'"']})]}),e.jsx(Bt,{value:n,onChange:$=>o($.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:$=>{$.key==="Enter"&&D()}}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>r(null),className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(bn,{onClick:D,children:"Rename"})]})]})})]})},bh=({skill:t,isSelected:s,onSelect:r,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",s?"bg-interactive-selection":"hover:bg-interactive-hover"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsx("button",{onClick:r,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(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(Me,{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(Qn,{className:"h-3.5 w-3.5"})})}),e.jsxs(fs,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(Et,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(go,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Et,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(Hr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(Et,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Nr,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),mT=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,fT=t=>{const s=t.trim(),r=s.match(/^git@github\.com:([^/\s]+)\/([^\s#]+)$/i);if(r)return`${r[1]}/${r[2].replace(/\.git$/i,"")}`;const n=s.match(/^https?:\/\/github\.com\/([^/\s]+)\/([^\s#]+)$/i);if(n)return`${n[1]}/${n[2].replace(/\.git$/i,"")}`;const o=s.match(/^([^/\s]+)\/([^/\s]+)(?:\/.+)?$/);return o?`${o[1]}/${o[2].replace(/\.git$/i,"")}`:s},pT=async()=>{try{const t=Ur()?.settings;if(t)return(await t.load())?.settings||{};const s=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return s.ok?await s.json().catch(()=>null):null}catch{return null}},hT=({open:t,onOpenChange:s})=>{const{scanRepo:r,loadCatalog:n,isScanning:o}=ji(),a=ka(D=>D.defaultGitIdentityId),l=ka(D=>D.loadDefaultGitIdentityId),[c,d]=i.useState(""),[u,m]=i.useState(""),[f,p]=i.useState(""),[h,g]=i.useState([]),[x,y]=i.useState(null),[b,v]=i.useState(!1),[j,k]=i.useState([]),[N,w]=i.useState(null);i.useEffect(()=>{t&&(d(""),m(""),p(""),y(null),v(!1),k([]),w(null),l(),(async()=>{const D=await pT(),A=Array.isArray(D?.skillCatalogs)?D?.skillCatalogs:[];g(A||[])})())},[t,l]);const C=i.useMemo(()=>{const D=u.trim(),A=f.trim();return h.some(P=>{const $=(P.source||"").trim(),R=(P.subpath||"").trim();return $===D&&R===A})},[h,u,f]),S=async()=>{const D=u.trim();if(!D){K.error("Repository source is required");return}c.trim()||d(fT(D)),v(!1),y(null);const A=await r({source:D,subpath:f.trim()||void 0,gitIdentityId:N||void 0});if(!A.ok){if(A.error?.kind==="authRequired"){if(gs()){K.error("Private repositories are not supported in VS Code yet");return}const $=A.error.identities||[];if(k($),!N&&$.length>0){const R=a&&a!=="global"&&$.some(O=>O.id===a)?a:$[0].id;w(R)}K.error("Authentication required. Select a Git identity and scan again.");return}K.error(A.error?.message||"Failed to scan repository");return}const P=A.items?.length||0;if(y(P),P===0){K.error("No skills found in this repository"),v(!1);return}k([]),v(!0),K.success(`Found ${P} skill(s)`)},M=async()=>{const D=c.trim(),A=u.trim(),P=f.trim();if(!D){K.error("Catalog name is required");return}if(!A){K.error("Repository source is required");return}if(!b){K.error("Scan the repository before adding this catalog");return}if(C){K.error("This catalog already exists");return}const $={id:mT(),label:D,source:A,...P?{subpath:P}:{},...N?{gitIdentityId:N}:{}},R=[...h,$];try{await xs({skillCatalogs:R}),g(R),K.success("Catalog added"),await n({refresh:!0}),s(!1)}catch(O){K.error(O instanceof Error?O.message:"Failed to save catalog")}};return e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Add skills catalog"}),e.jsxs(Is,{children:["Add a Git repository as a new catalog source. IKanban 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(Bt,{value:c,onChange:D=>d(D.target.value),placeholder:"e.g. Team Skills"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Repository"}),e.jsx(Bt,{value:u,onChange:D=>{m(D.target.value),v(!1),y(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(Bt,{value:f,onChange:D=>{p(D.target.value),v(!1),y(null)},placeholder:"e.g. skills"})]}),j.length>0&&!gs()?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($s,{value:N||"",onValueChange:D=>w(D),children:[e.jsx(Bs,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:j.find(D=>D.id===N)?.name||"Choose identity"})}),e.jsx(zs,{align:"start",children:j.map(D=>e.jsx(ns,{value:D.id,className:"pr-2 [&>span:first-child]:hidden",children:D.name},D.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,x!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",x," skill(s) found"]}):null,C?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>s(!1),children:"Cancel"}),e.jsxs(Me,{variant:"outline",onClick:()=>{S()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(Mg,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Me,{variant:"default",onClick:()=>{M()},disabled:!b||C||!c.trim()||!u.trim(),children:"Add catalog"})]})]})})},gT=({open:t,onOpenChange:s,conflicts:r,onConfirm:n})=>{const[o,a]=i.useState({});i.useEffect(()=>{if(!t)return;const d={};for(const u of r)d[u.skillName]="skip";a(d)},[t,r]);const l=d=>{const u={};for(const m of r)u[m.skillName]=d;a(u)},c=r.length>0&&r.every(d=>o[d.skillName]);return e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Skills already exist"}),e.jsx(Is,{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:[r.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{variant:"outline",size:"sm",onClick:()=>l("skip"),children:"Skip all"}),e.jsx(Me,{variant:"outline",size:"sm",onClick:()=>l("overwrite"),children:"Overwrite all"})]})]}),e.jsx("div",{className:"space-y-2",children:r.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($s,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Bs,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(zs,{align:"end",children:[e.jsx(ns,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(ns,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>s(!1),children:"Cancel"}),e.jsx(bn,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},xT=({open:t,onOpenChange:s,item:r})=>{const{installSkills:n,isInstalling:o}=ji(),[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};r?.clawdhub&&(x.clawdhub={slug:r.clawdhub.slug,version:r.clawdhub.version});const y=await n({source:g.source,subpath:g.subpath,gitIdentityId:r?.gitIdentityId,scope:g.scope,selections:[x],conflictPolicy:"prompt",conflictDecisions:g.conflictDecisions});if(y.ok){K.success("Skill installed successfully"),s(!1);return}if(y.error?.kind==="conflicts"){p({source:g.source,subpath:g.subpath,scope:g.scope,skillDir:g.skillDir}),m(y.error.conflicts),d(!0);return}if(y.error?.kind==="authRequired"){K.error(y.error.message||"Authentication required");return}K.error(y.error?.message||"Failed to install skill")};return r?e.jsxs(e.Fragment,{children:[e.jsx(bs,{open:t,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Install skill"}),e.jsxs(Is,{children:["Install ",e.jsx("span",{className:"font-semibold text-foreground",children:r.skillName})," into user or project scope."]})]}),e.jsx("div",{className:"space-y-3",children:r.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:r.warnings.map(g=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:g},g))})]}):null}),e.jsxs(Js,{className:"flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-center",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs($s,{value:a,onValueChange:g=>l(g),children:[e.jsx(Bs,{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(en,{className:"h-4 w-4"}):e.jsx(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(zs,{align:"start",children:[e.jsx(ns,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(en,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(ns,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fn,{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(Me,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>s(!1),children:"Cancel"}),e.jsx(Me,{className:"w-full sm:w-auto",variant:"default",disabled:o||!r.installable,onClick:()=>{h({source:r.repoSource,subpath:r.repoSubpath,scope:a,skillDir:r.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(gT,{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},yT=async()=>{try{const t=Ur()?.settings;if(t)return(await t.load())?.settings||{};const s=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return s.ok?await s.json().catch(()=>null):null}catch{return null}},bT=({mode:t,onModeChange:s})=>{const{sources:r,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:l,loadSource:c,loadMoreClawdHub:d,isLoadingCatalog:u,isLoadingSource:m,isLoadingMore:f,loadedSourceIds:p,clawdhubHasMoreBySource:h,lastCatalogError:g}=ji(),[x,y]=i.useState(""),[b,v]=i.useState(!1),[j,k]=i.useState(!1),[N,w]=i.useState(null),[C,S]=i.useState(!1),[M,D]=i.useState(!1);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{o&&(p[o]||c(o))},[o,p,c]);const A=i.useMemo(()=>o?n[o]||[]:[],[n,o]),P=i.useMemo(()=>{const F=x.trim().toLowerCase();return F?A.filter(I=>{const E=I.skillName.toLowerCase(),W=(I.description||"").toLowerCase(),V=(I.frontmatterName||"").toLowerCase();return E.includes(F)||W.includes(F)||V.includes(F)}):A},[A,x]),$=i.useMemo(()=>r.find(F=>F.id===o)||null,[r,o]),R=!!(o&&o.startsWith("custom:")),O=$?.source==="clawdhub:registry"||$?.sourceType==="clawdhub",T=!!(o&&(h[o]??!0)),_=async()=>{if(!(!o||!R)){S(!0);try{const F=await yT(),E=(Array.isArray(F?.skillCatalogs)?F?.skillCatalogs:[]).filter(W=>W.id!==o);await xs({skillCatalogs:E}),await l({refresh:!0}),D(!1)}finally{S(!1)}}};return e.jsx(Ut,{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(di,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:t,onValueChange:s,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($s,{value:o||"",onValueChange:F=>a(F),children:[e.jsx(Bs,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:$?.label||"Select source"})}),e.jsx(zs,{align:"start",children:r.map(F=>e.jsx(ns,{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(Me,{type:"button",variant:"outline",onClick:()=>{o?c(o,{refresh:!0}):l({refresh:!0})},disabled:u||m,className:"gap-2",children:[e.jsx(Mr,{className:"h-4 w-4"}),"Refresh"]}),R?e.jsxs(Me,{type:"button",variant:"outline",onClick:()=>D(!0),disabled:C,className:"gap-2",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Me,{type:"button",variant:"default",onClick:()=>v(!0),className:"gap-2",children:[e.jsx(Fs,{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(Bt,{value:x,onChange:F=>y(F.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:u?"Loading…":`${P.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:P.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:[P.map(F=>{const I=F.installed?.isInstalled,E=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}),I?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 (",E||"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(po,{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(Do,{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(Me,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!F.installable,onClick:()=>{w(F),k(!0)},children:"Install"})]})},`${F.sourceId}:${F.skillDir}`)}),O&&T?e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(Me,{type:"button",variant:"outline",onClick:()=>{d()},disabled:f||m,children:f?"Loading…":"Load more"})}):null]})}),e.jsx(hT,{open:b,onOpenChange:v}),e.jsx(xT,{open:j,onOpenChange:k,item:N}),e.jsx(bs,{open:M,onOpenChange:F=>{C||D(F)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Remove Catalog"}),e.jsx(Is,{children:"Are you sure you want to remove this catalog?"})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>D(!1),disabled:C,children:"Cancel"}),e.jsx(Me,{variant:"destructive",onClick:()=>{_()},disabled:C,children:"Remove"})]})]})})]})})},vT=()=>{const{selectedSkillName:t,getSkillByName:s,getSkillDetail:r,createSkill:n,updateSkill:o,skills:a,skillDraft:l,setSkillDraft:c,setSelectedSkill:d}=pn(),u=t?s(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(di,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[x,y]=i.useState(""),[b,v]=i.useState("user"),[j,k]=i.useState(""),[N,w]=i.useState(""),[C,S]=i.useState([]),[M,D]=i.useState([]),[A,P]=i.useState(!1),[$,R]=i.useState(!1),[O,T]=i.useState(""),[_,F]=i.useState(""),[I,E]=i.useState(!1),[W,V]=i.useState(""),[ve,oe]=i.useState(""),[Z,ce]=i.useState(null),[Q,Y]=i.useState(!1),[ie,B]=i.useState(""),[se,H]=i.useState(null),[le,ge]=i.useState(!1),z=m?x.trim()!==""||j.trim()!==""||N.trim()!==""||M.length>0:j!==O||N!==_,J=Z?ve!==ie:W.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&l)y(l.name||""),v(l.scope||"user"),k(l.description||""),w(l.instructions||""),T(""),F(""),S([]),D(l.pendingFiles||[]);else if(t&&u){R(!0);try{const fe=await r(t);if(fe){const q=fe.sources.md;k(q.description||""),w(q.instructions||""),T(q.description||""),F(q.instructions||""),S(q.supportingFiles||[])}}catch(fe){console.error("Failed to load skill details:",fe)}finally{R(!1)}}})()},[u,m,t,a,l,r,p]);const je=async()=>{const Be=m?x.trim().replace(/\s+/g,"-").toLowerCase():t?.trim();if(!Be){K.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(Be)||Be.length>64){K.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!j.trim()){K.error("Description is required");return}if(m&&a.some(fe=>fe.name===Be)){K.error("A skill with this name already exists");return}P(!0);try{const fe={name:Be,description:j.trim(),instructions:N.trim()||void 0,scope:m?b:void 0,supportingFiles:m&&M.length>0?M:void 0};let q;m?(q=await n(fe),q&&(c(null),D([]),d(Be))):(q=await o(Be,fe),q&&(T(j.trim()),F(N.trim()))),q?K.success(m?"Skill created successfully":"Skill updated successfully"):K.error(m?"Failed to create skill":"Failed to update skill")}catch(fe){console.error("Error saving skill:",fe),K.error("An error occurred while saving")}finally{P(!1)}},X=()=>{ce(null),V(""),oe(""),B(""),E(!0)},G=async Be=>{if(ce(Be),V(Be),m){const q=M.find(ye=>ye.path===Be)?.content||"";oe(q),B(q),E(!0);return}if(t){Y(!0),E(!0);try{const{readSupportingFile:fe}=pn.getState(),q=await fe(t,Be);oe(q||""),B(q||"")}catch{K.error("Failed to load file content"),oe(""),B("")}finally{Y(!1)}}},ae=async()=>{if(!W.trim()){K.error("File name is required");return}const Be=W.trim(),fe=Z!==null;if(m){if(fe)D(he=>he.map(He=>He.path===Z?{path:Be,content:ve}:He)),K.success(`File "${Be}" updated`);else{if(M.some(he=>he.path===Be)){K.error("A file with this name already exists");return}D(he=>[...he,{path:Be,content:ve}]),K.success(`File "${Be}" added`)}E(!1),ce(null);return}if(!t){K.error("No skill selected");return}const{writeSupportingFile:q}=pn.getState();if(await q(t,Be,ve)){K.success(fe?`File "${Be}" updated`:`File "${Be}" created`),E(!1),ce(null);const he=await r(t);he&&S(he.sources.md.supportingFiles||[])}else K.error(fe?"Failed to update file":"Failed to create file")},me=Be=>{if(m){D(fe=>fe.filter(q=>q.path!==Be)),K.success(`File "${Be}" removed`);return}t&&H(Be)},Oe=async()=>{if(!se||!t)return;ge(!0);const{deleteSupportingFile:Be}=pn.getState();if(await Be(t,se)){K.success(`File "${se}" deleted`);const q=await r(t);q&&S(q.sources.md.supportingFiles||[]),H(null)}else K.error("Failed to delete file");ge(!1)};return m&&p==="external"?e.jsx(bT,{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(Eg,{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"})]})}):$?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(Ut,{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(Bt,{value:x,onChange:Be=>y(Be.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs($s,{value:b,onValueChange:Be=>v(Be),children:[e.jsxs(Bs,{className:"!h-9 w-auto gap-1.5",children:[b==="user"?e.jsx(en,{className:"h-4 w-4"}):e.jsx(Fn,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:b})]}),e.jsxs(zs,{align:"end",children:[e.jsx(ns,{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(en,{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(ns,{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(Fn,{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(hr,{value:j,onChange:Be=>k(Be.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(hr,{value:N,onChange:Be=>w(Be.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(Me,{variant:"outline",size:"sm",onClick:X,className:"gap-1.5",children:[e.jsx(Fs,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const Be=m?M:C;return Be.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:Be.map(fe=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg border bg-muted/30 hover:bg-interactive-hover cursor-pointer transition-colors",onClick:()=>G(fe.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(In,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:fe.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(Me,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:q=>{q.stopPropagation(),me(fe.path)},children:e.jsx(Nr,{className:"h-3.5 w-3.5"})})]},fe.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Me,{size:"sm",variant:"default",onClick:je,disabled:A||!z,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(nc,{className:"h-3 w-3"}),A?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(bs,{open:se!==null,onOpenChange:Be=>{!Be&&!le&&H(null)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Delete Supporting File"}),e.jsxs(Is,{children:['Are you sure you want to delete "',se,'"?']})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>H(null),disabled:le,className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(bn,{onClick:Oe,disabled:le,children:"Delete"})]})]})}),e.jsx(bs,{open:I,onOpenChange:Be=>{E(Be),Be||ce(null)},children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(js,{className:"flex-shrink-0",children:[e.jsx(Ss,{children:Z?"Edit Supporting File":"Add Supporting File"}),e.jsx(Is,{children:Z?"Modify the file content":"Create a new file in the skill directory"})]}),Q?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(Bt,{value:W,onChange:Be=>V(Be.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:Z!==null}),!Z&&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(hr,{value:ve,onChange:Be=>oe(Be.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>{E(!1),ce(null)},className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(bn,{onClick:ae,disabled:Q||!J,children:Z?"Save Changes":"Create File"})]})]})})]})})},wT="__add_provider__",jT=({onItemSelect:t})=>{const s=ut(c=>c.providers),r=ut(c=>c.selectedProviderId),n=ut(c=>c.setSelectedProvider),{isMobile:o}=ks(),l=i.useMemo(()=>gs(),[])?"bg-background":"bg-sidebar";return e.jsxs("div",{className:L("flex h-full flex-col",l),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 ",s.length]}),e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(wT),t?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(Fs,{className:"size-4"})})]})}),e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:s.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ro,{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"})]}):s.map(c=>{const d=Array.isArray(c.models)?c.models.length:0,u=c.id===r;return e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",u?"bg-interactive-selection":"hover:bg-interactive-hover"),children:e.jsxs("button",{type:"button",onClick:()=>{n(c.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(Os,{providerId:c.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:c.name||c.id}),e.jsx("span",{className:"typography-micro text-muted-foreground/60 flex-shrink-0",children:d})]})},c.id)})})]})},ST=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),vh=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const s=ST.format(t);return s.endsWith(".0")?s.slice(0,-2):s},sa="__add_provider__",Aa=t=>typeof t=="object"&&t!==null,wh=t=>{const s=typeof t.type=="string"?t.type:"",r=`${t.name??""} ${t.label??""}`.toLowerCase(),n=`${s} ${r}`.toLowerCase();return n.includes("oauth")?"oauth":n.includes("api")?"api":s.toLowerCase()},NT=t=>{if(!Aa(t))return{};const s={};for(const[r,n]of Object.entries(t))Array.isArray(n)&&(s[r]=n.filter(o=>Aa(o)));return s},kT=t=>{if(typeof t=="string")return{id:t};if(!Aa(t))return null;const s=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(!s)return null;const r=typeof t.name=="string"?t.name:void 0;return{id:s,name:r}},CT=t=>{let s=[];Array.isArray(t)?s=t:Aa(t)&&(Array.isArray(t.all)?s=t.all:Array.isArray(t.providers)&&(s=t.providers));const r=s.map(o=>kT(o)).filter(o=>!!o),n=new Set;return r.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},MT=()=>{const t=ut(z=>z.providers),s=ut(z=>z.selectedProviderId),r=ut(z=>z.setSelectedProvider),n=ut(z=>z.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),[y,b]=i.useState({}),[v,j]=i.useState({}),[k,N]=i.useState([]),[w,C]=i.useState(!1),[S,M]=i.useState(null),[D,A]=i.useState(""),[P,$]=i.useState(""),[R,O]=i.useState(!1),[T,_]=i.useState({}),[F,I]=i.useState(!1);i.useEffect(()=>{!s&&t.length>0&&r(t[0].id)},[t,s,r]),i.useEffect(()=>{let z=!0;return(async()=>{c(!0);try{const je=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!je.ok)throw new Error(`Auth methods request failed (${je.status})`);const X=await je.json().catch(()=>({}));if(!z)return;a(NT(X))}catch(je){if(!z)return;console.error("Failed to load provider auth methods:",je),K.error("Failed to load provider authentication methods")}finally{z&&c(!1)}})(),()=>{z=!1}},[]),i.useEffect(()=>{let z=!0;return(async()=>{C(!0),M(null);try{const je=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!je.ok)throw new Error(`Provider list request failed (${je.status})`);const X=await je.json().catch(()=>({}));if(!z)return;N(CT(X))}catch(je){if(!z)return;console.error("Failed to load available providers:",je),M("Unable to load provider list")}finally{z&&C(!1)}})(),()=>{z=!1}},[]);const E=i.useMemo(()=>new Set(t.map(z=>z.id)),[t]),W=i.useMemo(()=>k.filter(z=>!E.has(z.id)),[k,E]);i.useEffect(()=>{if(s===sa){if(!D&&W.length>0){A(W[0].id);return}D&&!W.some(z=>z.id===D)&&A(W[0]?.id??"")}},[s,D,W]),i.useEffect(()=>{if(s===sa){I(!0);return}I(!1)},[s]),i.useEffect(()=>{if(!s||s===sa)return;let z=!1;return(async()=>{try{const je=await fetch(`/api/provider/${encodeURIComponent(s)}/source`,{method:"GET",headers:{Accept:"application/json"}}),X=await je.json().catch(()=>null);if(!je.ok)throw new Error(X?.error||"Failed to load provider sources");const G=X?.sources??X?.data?.sources;!z&&G&&_(ae=>({...ae,[s]:G}))}catch(je){z||console.error("Failed to load provider sources:",je)}})(),()=>{z=!0}},[s]);const V=t.find(z=>z.id===s),ve=s?T[s]:void 0,oe=async z=>{const J=d[z]?.trim()??"";if(!J){K.error("API key is required");return}const je=`api:${z}`;f(je);try{const X=await fetch(`/api/auth/${encodeURIComponent(z)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:J})}),G=await X.json().catch(()=>null);if(!X.ok){const ae=G?.error||"Failed to save API key";throw new Error(ae)}K.success("API key saved"),u(ae=>({...ae,[z]:""})),await ei({scopes:["providers"],mode:"active"}),r(z)}catch(X){console.error("Failed to save API key:",X),K.error("Failed to save API key")}finally{f(null)}},Z=async(z,J)=>{const je=`oauth:${z}:${J}`;f(je);try{const X=await fetch(`/api/provider/${encodeURIComponent(z)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:J})}),G=await X.json().catch(()=>null);if(!X.ok){const ye=G?.error||"Failed to start OAuth flow";throw new Error(ye)}const ae=Aa(G)?G:{},me=Aa(ae.data)?ae.data:ae,Oe=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,Be=typeof me.instructions=="string"&&me.instructions||typeof me.message=="string"&&me.message||void 0,fe=typeof me.user_code=="string"&&me.user_code||typeof me.code=="string"&&me.code||typeof me.userCode=="string"&&me.userCode||void 0;if(!Oe&&!Be&&!fe)throw new Error("No OAuth details returned");const q=`${z}:${J}`;j(ye=>({...ye,[q]:{url:Oe,instructions:Be,userCode:fe}})),Oe&&window.open(Oe,"_blank","noopener,noreferrer"),x({providerId:z,methodIndex:J}),K.message("Complete the OAuth flow in your browser")}catch(X){console.error("Failed to start OAuth flow:",X),K.error("Failed to start OAuth flow")}finally{f(null)}},ce=async(z,J)=>{const je=`${z}:${J}`,X=y[je]?.trim(),G=`oauth-complete:${z}:${J}`;f(G);try{const ae={method:J};X&&(ae.code=X);const me=await fetch(`/api/provider/${encodeURIComponent(z)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ae)}),Oe=await me.json().catch(()=>null);if(!me.ok){const Be=Oe?.error||"Failed to complete OAuth flow";throw new Error(Be)}K.success("OAuth connection completed"),b(Be=>({...Be,[je]:""})),x(null),await ei({scopes:["providers"],mode:"active"}),r(z)}catch(ae){console.error("Failed to complete OAuth flow:",ae),K.error("Failed to complete OAuth flow")}finally{f(null)}},Q=async z=>{try{await navigator.clipboard.writeText(z),K.success("OAuth link copied")}catch(J){console.error("Failed to copy OAuth link:",J),K.error("Failed to copy OAuth link")}},Y=async z=>{try{await navigator.clipboard.writeText(z),K.success("Device code copied")}catch(J){console.error("Failed to copy device code:",J),K.error("Failed to copy device code")}},ie=async z=>{const J=`disconnect:${z}`;f(J);try{const je=await fetch(`/api/provider/${encodeURIComponent(z)}/auth?scope=all`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),X=await je.json().catch(()=>null);if(!je.ok){const G=X?.error||"Failed to disconnect provider";throw new Error(G)}K.success("Provider disconnected"),await ei({scopes:["providers"],mode:"active"})}catch(je){console.error("Failed to disconnect provider:",je),K.error("Failed to disconnect provider")}finally{f(null)}},B=s===sa;if(!B&&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(Ro,{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(B)return e.jsx(Ut,{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."})]}),w?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):S?e.jsx("p",{className:"typography-meta text-muted-foreground",children:S}):W.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(us,{open:R,onOpenChange:z=>{O(z),z||$("")},children:[e.jsx(ms,{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-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[e.jsx("span",{className:D?"text-foreground":"text-muted-foreground",children:D?W.find(z=>z.id===D)?.name||D:"Select provider"}),e.jsx(is,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(fs,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:z=>z.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:z=>z.stopPropagation(),children:[e.jsx(Rr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:P,onChange:z=>$(z.target.value),onKeyDown:z=>z.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(Ut,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const z=W.filter(J=>{const je=P.toLowerCase();return(J.name||J.id).toLowerCase().includes(je)||J.id.toLowerCase().includes(je)});return z.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):z.map(J=>e.jsxs(Et,{onSelect:()=>{A(J.id),O(!1),$("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:J.name||J.id}),D===J.id&&e.jsx(ss,{className:"h-4 w-4 text-primary"})]},J.id))})()})]})]})]}),D&&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(Bt,{type:"password",value:d[D]??"",onChange:z=>u(J=>({...J,[D]:z.target.value})),placeholder:"sk-..."}),e.jsx(Me,{size:"sm",onClick:()=>oe(D),disabled:m===`api:${D}`,className:"h-8",children:m===`api:${D}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by IKanban."})]}),(()=>{const J=(o[D]??[]).filter(je=>wh(je)==="oauth");return J.length===0?null:e.jsx("div",{className:"space-y-3",children:J.map((je,X)=>{const G=je.label||je.name||`OAuth method ${X+1}`,ae=`${D}:${X}`,me=g?.providerId===D&&g?.methodIndex===X;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:G}),(je.description||je.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(je.description||je.help)})]}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>Z(D,X),disabled:m===`oauth:${D}:${X}`,className:"h-8",children:"Connect"})]}),v[ae]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[ae]?.instructions}),v[ae]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Bt,{value:v[ae]?.userCode,readOnly:!0}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>Y(v[ae]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[ae]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Bt,{value:v[ae]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Me,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[ae]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>Q(v[ae]?.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(Bt,{value:y[ae]??"",onChange:Oe=>b(Be=>({...Be,[ae]:Oe.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Me,{size:"sm",onClick:()=>ce(D,X),disabled:m===`oauth-complete:${D}:${X}`,className:"h-8",children:m===`oauth-complete:${D}:${X}`?"Saving…":"Complete"})]})]},`${D}-${G}`)})})})()]})]})]})});if(!V)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(Ro,{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 se=Array.isArray(V.models)?V.models:[],le=(o[V.id]??[]).filter(z=>wh(z)==="oauth"),ge=se.filter(z=>{const J=typeof z?.name=="string"?z.name:"",je=typeof z?.id=="string"?z.id:"",X=p.trim().toLowerCase();return X?J.toLowerCase().includes(X)||je.toLowerCase().includes(X):!0});return e.jsx(Ut,{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(Os,{providerId:V.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:V.name||V.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",V.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"}),s!==sa&&e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>I(z=>!z),className:"h-8",children:F?"Hide":"Reconnect"})]}),!F&&s!==sa?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(Bt,{type:"password",value:d[V.id]??"",onChange:z=>u(J=>({...J,[V.id]:z.target.value})),placeholder:"sk-..."}),e.jsx(Me,{size:"sm",onClick:()=>oe(V.id),disabled:m===`api:${V.id}`,className:"h-8",children:m===`api:${V.id}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by IKanban."})]}),le.length>0&&e.jsx("div",{className:"space-y-3",children:le.map((z,J)=>{const je=z.label||z.name||`OAuth method ${J+1}`,X=`${V.id}:${J}`,G=g?.providerId===V.id&&g?.methodIndex===J;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:je}),(z.description||z.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(z.description||z.help)})]}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>Z(V.id,J),disabled:m===`oauth:${V.id}:${J}`,className:"h-8",children:"Connect"})]}),v[X]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[X]?.instructions}),v[X]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Bt,{value:v[X]?.userCode,readOnly:!0}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>Y(v[X]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[X]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Bt,{value:v[X]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Me,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[X]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>Q(v[X]?.url??""),className:"h-8",children:"Copy link"})]})]}),G&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Bt,{value:y[X]??"",onChange:ae=>b(me=>({...me,[X]:ae.target.value})),placeholder:"Paste authorization code"}),e.jsx(Me,{size:"sm",onClick:()=>ce(V.id,J),disabled:m===`oauth-complete:${V.id}:${J}`,className:"h-8",children:m===`oauth-complete:${V.id}:${J}`?"Saving…":"Complete"})]})]},`${V.id}-${je}`)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Connection"}),ve&&(ve.auth.exists||ve.user.exists||ve.project.exists||ve.custom?.exists)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Configured in: ",[ve.auth.exists?"auth credentials":null,ve.user.exists?"user config":null,ve.project.exists?"project config":null,ve.custom?.exists?"custom config":null].filter(Boolean).join(", ")]}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>ie(V.id),disabled:m===`disconnect:${V.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${V.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(Bt,{value:p,onChange:z=>h(z.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:ge.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):ge.map(z=>{const J=typeof z?.id=="string"?z.id:"",je=typeof z?.name=="string"?z.name:J,X=J?n(V.id,J):void 0,G=vh(X?.limit?.context),ae=vh(X?.limit?.output),me=[];return X?.tool_call&&me.push({key:"tools",icon:rc,label:"Tool calling"}),X?.reasoning&&me.push({key:"reasoning",icon:Rn,label:"Reasoning"}),X?.attachment&&me.push({key:"image",icon:Ln,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:je}),(G||ae)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[G?`${G} ctx`:"",G&&ae?" · ":"",ae?`${ae} out`:""]}),me.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:me.map(({key:Oe,icon:Be,label:fe})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:fe,"aria-label":fe,children:e.jsx(Be,{className:"h-3 w-3"})},Oe))})]},J)})})]})]})})},AT=t=>{const s=t?.windows??{},r=Object.values(s).map(n=>n.usedPercent).filter(n=>typeof n=="number");return r.length===0?null:Math.max(...r)},DT=({onItemSelect:t})=>{const s=ts(k=>k.results),r=ts(k=>k.selectedProviderId),n=ts(k=>k.setSelectedProvider),o=ts(k=>k.fetchAllQuotas),a=ts(k=>k.isLoading),l=ts(k=>k.autoRefresh),c=ts(k=>k.refreshIntervalMs),d=ts(k=>k.displayMode),u=ts(k=>k.setAutoRefresh),m=ts(k=>k.setRefreshInterval),f=ts(k=>k.setDisplayMode),p=ts(k=>k.loadSettings),{isMobile:h}=ks(),g=i.useMemo(()=>gs(),[]);i.useEffect(()=>{p()},[p]);const x=i.useCallback(async k=>{try{await xs(k)}catch(N){console.warn("Failed to save usage settings:",N)}},[]),y=i.useCallback(k=>{u(k),x({usageAutoRefresh:k})},[x,u]),b=i.useCallback(k=>{const N=Number(k);Number.isFinite(N)&&(m(N),x({usageRefreshIntervalMs:N}))},[x,m]),v=i.useCallback(k=>{k!=="usage"&&k!=="remaining"||(f(k),x({usageDisplayMode:k}))},[x,f]),j=g?"bg-background":"bg-sidebar";return e.jsxs("div",{className:L("flex h-full flex-col",j),children:[e.jsxs("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 ",yn.length]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(gt,{delayDuration:700,children:[e.jsx(xt,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(nr,{checked:l,onCheckedChange:y,"aria-label":"Toggle auto refresh",className:"data-[state=checked]:bg-[var(--status-info)]"})})}),e.jsx(ht,{side:"bottom",children:"Auto-refresh usage data at set interval"})]}),e.jsxs($s,{value:String(c),onValueChange:b,disabled:!l,children:[e.jsx(Bs,{size:"sm",className:"min-w-[72px]",children:e.jsx(Sr,{placeholder:"Interval"})}),e.jsxs(zs,{children:[e.jsx(ns,{value:"30000",className:"pr-2 [&>span:first-child]:hidden",children:"30s"}),e.jsx(ns,{value:"60000",className:"pr-2 [&>span:first-child]:hidden",children:"1m"}),e.jsx(ns,{value:"300000",className:"pr-2 [&>span:first-child]:hidden",children:"5m"})]})]}),e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground overflow-hidden",onClick:()=>o(),"aria-label":"Refresh usage",title:"Refresh usage",disabled:a,children:e.jsx(Mr,{className:L("size-4",a&&"animate-spin")})})]})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Display"}),e.jsxs($s,{value:d,onValueChange:v,children:[e.jsx(Bs,{size:"sm",className:"min-w-[140px]",children:e.jsx(Sr,{placeholder:"Display mode"})}),e.jsxs(zs,{children:[e.jsx(ns,{value:"usage",className:"pr-2 [&>span:first-child]:hidden",children:"Usage"}),e.jsx(ns,{value:"remaining",className:"pr-2 [&>span:first-child]:hidden",children:"Quota remaining"})]})]})]})]}),e.jsx(Ut,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:yn.map(k=>{const N=s.find(A=>A.providerId===k.id),w=AT(N?.usage),C=Mx(w),S=k.id===r,M=N?.configured??!1,D=M?C==="critical"?{backgroundColor:"var(--status-error)"}:C==="warn"?{backgroundColor:"var(--status-warning)"}:{backgroundColor:"var(--status-success)"}:{backgroundColor:"var(--surface-muted-foreground)",opacity:.4};return e.jsx("div",{className:L("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",S?"bg-interactive-selection":"hover:bg-interactive-hover"),children:e.jsxs("button",{type:"button",onClick:()=>{n(k.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",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full flex-shrink-0",style:D}),e.jsx(Os,{providerId:k.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:k.name}),!M&&e.jsx("span",{className:"typography-micro text-muted-foreground/60 flex-shrink-0",children:"Not set"})]})},k.id)})})]})},Sd=({title:t,window:s,subtitle:r,showToggle:n=!1,toggleEnabled:o=!1,onToggle:a})=>{const l=ts(g=>g.displayMode),c=l==="remaining"?s.remainingPercent:s.usedPercent,d=l==="remaining"?"remaining":"used",u=s.valueLabel??Sn(c),m=s.resetAfterFormatted??s.resetAtFormatted??"",f=Hl(t),p=i.useMemo(()=>ca(s.usedPercent,s.resetAt,s.windowSeconds,t),[s.usedPercent,s.resetAt,s.windowSeconds,t]),h=i.useMemo(()=>{if(!p||p.dailyAllocationPercent===null)return null;const g=ln(p.elapsedRatio);return l==="remaining"?100-g:g},[p,l]);return e.jsxs("div",{className:"rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)]/60 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label text-foreground truncate",children:f}),r&&e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:r})]}),n?e.jsx(nr,{checked:o,onCheckedChange:a,"aria-label":"Show in dropdown"}):e.jsx("div",{className:"typography-ui-label text-foreground tabular-nums",children:u==="-"?"":u})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(da,{percent:c,tonePercent:s.usedPercent,expectedMarkerPercent:h}),e.jsx("div",{className:"mt-1 text-right typography-micro text-muted-foreground text-[10px]",children:d})]}),p&&e.jsx("div",{className:"mt-2",children:e.jsx(ua,{paceInfo:p})}),e.jsxs("div",{className:"mt-3 flex items-center justify-between text-muted-foreground",children:[e.jsx("span",{className:"typography-micro",children:"Resets"}),e.jsx("span",{className:"typography-micro tabular-nums",children:m})]})]})},IT=t=>{if(!t)return"-";try{return new Date(t).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}catch{return"-"}},TT=()=>{const t=ts(A=>A.results),s=ts(A=>A.selectedProviderId),r=ts(A=>A.setSelectedProvider),n=ts(A=>A.loadSettings),o=ts(A=>A.fetchAllQuotas),a=ts(A=>A.isLoading),l=ts(A=>A.lastUpdated),c=ts(A=>A.error),d=ts(A=>A.dropdownProviderIds),u=ts(A=>A.setDropdownProviderIds),m=ts(A=>A.selectedModels),f=ts(A=>A.toggleModelSelected),p=ts(A=>A.applyDefaultSelections);Hu(),i.useEffect(()=>{n(),o()},[n,o]),i.useEffect(()=>{if(s||t.length===0)return;const A=t.find(P=>P.configured)?.providerId;r(A??yn[0]?.id??null)},[t,s,r]);const h=t.find(A=>A.providerId===s)??null,x=yn.find(A=>A.id===s)?.name??s??"Usage",y=h?.usage,b=s?d.includes(s):!1,v=i.useCallback(A=>{if(!s)return;const P=A?Array.from(new Set([...d,s])):d.filter($=>$!==s);u(P),xs({usageDropdownProviders:P})},[d,s,u]),j=i.useMemo(()=>y?.models?Object.entries(y.models).map(([A,P])=>({name:A,windows:P})).filter(A=>Object.keys(A.windows.windows).length>0):[],[y?.models]);i.useEffect(()=>{s&&j.length>0&&p(s,j.map(A=>A.name))},[s,j,p]);const k=i.useMemo(()=>!s||j.length===0?new Map:NN(j,A=>A.name,s),[j,s]),N=i.useMemo(()=>{if(!s)return[];const A=Ix(s);return Tx(A)},[s]),[w,C]=i.useState(()=>({})),S=i.useCallback(A=>{C(P=>({...P,[A]:!P[A]}))},[]),M=i.useCallback(A=>{if(!s)return;f(s,A);const P=m[s]??[],R=P.includes(A)?P.filter(T=>T!==A):[...P,A],O={...m,[s]:R};xs({usageSelectedModels:O})},[s,m,f]),D=s?m[s]??[]:[];return s?e.jsx(Ut,{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-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{providerId:s,className:"h-5 w-5"}),e.jsxs("h1",{className:"typography-ui-header font-semibold text-lg",children:[x," Usage"]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:a?"Refreshing usage...":`Last updated ${IT(l)}`})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Show in dropdown"}),e.jsx(nr,{checked:b,onCheckedChange:v,"aria-label":`Show ${x} in usage dropdown`,className:"data-[state=checked]:bg-[var(--status-info)]"})]})]}),!h&&e.jsx("div",{className:"rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)]/60 p-4 text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"No usage data available yet."})}),c&&e.jsxs("div",{className:"rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)]/60 p-4 text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"Failed to refresh usage data."}),e.jsx("p",{className:"typography-meta mt-1",children:c})]}),h&&!h.configured&&e.jsxs("div",{className:"rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)]/60 p-4 text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"Provider is not configured yet."}),e.jsx("p",{className:"typography-meta mt-1",children:"Add credentials in the Providers tab to enable usage tracking."})]}),y?.windows&&Object.keys(y.windows).length>0&&e.jsx("div",{className:"space-y-3",children:Object.entries(y.windows).map(([A,P])=>e.jsx(Sd,{title:A,window:P},A))}),j.length>0&&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",children:"Toggle on to show in header dropdown"})]}),N.map(A=>{const P=k.get(A.id)??[];if(P.length===0)return null;const $=w[A.id]??!1;return e.jsxs(tn,{open:!$,onOpenChange:()=>S(A.id),children:[e.jsxs(On,{className:"flex w-full items-center justify-between py-2 text-left group",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:A.label}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:[P.length," model",P.length!==1?"s":""]})]}),$?e.jsx(dr,{className:"h-5 w-5 text-muted-foreground group-hover:text-foreground transition-colors"}):e.jsx(is,{className:"h-5 w-5 text-muted-foreground group-hover:text-foreground transition-colors"})]}),e.jsx(sn,{className:"pt-2 space-y-3",children:P.map(R=>{const O=Object.entries(R.windows.windows);if(O.length===0)return null;const[T,_]=O[0],F=D.includes(R.name);return e.jsx(Sd,{title:T,subtitle:Vl(R.name),window:_,showToggle:!0,toggleEnabled:F,onToggle:()=>M(R.name)},R.name)})})]},A.id)}),(()=>{const A=k.get(null)??[];if(A.length===0)return null;const P=w.other??!1;return e.jsxs(tn,{open:!P,onOpenChange:()=>S("other"),children:[e.jsxs(On,{className:"flex w-full items-center justify-between py-2 text-left group",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Other"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:[A.length," model",A.length!==1?"s":""]})]}),P?e.jsx(dr,{className:"h-5 w-5 text-muted-foreground group-hover:text-foreground transition-colors"}):e.jsx(is,{className:"h-5 w-5 text-muted-foreground group-hover:text-foreground transition-colors"})]}),e.jsx(sn,{className:"pt-2 space-y-3",children:A.map($=>{const R=Object.entries($.windows.windows);if(R.length===0)return null;const[O,T]=R[0],_=D.includes($.name);return e.jsx(Sd,{title:O,subtitle:Vl($.name),window:T,showToggle:!0,toggleEnabled:_,onToggle:()=>M($.name)},$.name)})})]})})()]}),h?.configured&&y&&Object.keys(y.windows??{}).length===0&&j.length===0&&e.jsx("div",{className:"rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)]/60 p-4 text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"No quota windows reported for this provider."})})]})}):e.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Select a provider to view usage details."})})},ET={branch:Ms,briefcase:Iu,house:Du,graduation:Au,code:xn,heart:Ag},PT={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},RT=({onItemSelect:t})=>{const[s,r]=i.useState(null),[n,o]=i.useState(!1),{selectedProfileId:a,defaultGitIdentityId:l,profiles:c,globalIdentity:d,setSelectedProfile:u,deleteProfile:m,loadProfiles:f,loadGlobalIdentity:p,loadDiscoveredCredentials:h,loadDefaultGitIdentityId:g,setDefaultGitIdentityId:x,getUnimportedCredentials:y}=ka(),{setSidebarOpen:b}=Te(),{isMobile:v}=ks(),j=i.useMemo(()=>gs(),[]),k=y();i.useEffect(()=>{f(),p(),h(),g()},[f,p,h,g]);const N=A=>{u(`import:${A.host}:${A.username}`),t?.(),v&&b(!1)},w=j?"bg-background":"bg-sidebar",C=()=>{u("new"),t?.(),v&&b(!1)},S=async A=>{r(A)},M=async()=>{if(!s)return;o(!0),await m(s.id)?(K.success(`Profile "${s.name}" deleted successfully`),r(null)):K.error("Failed to delete profile"),o(!1)},D=async A=>{const P=l===A?null:A;if(!await x(P)){K.error("Failed to update default identity");return}K.success(P?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:L("flex h-full flex-col",w),children:[e.jsx("div",{className:L("border-b px-3",v?"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(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:C,"aria-label":"Create new profile",children:e.jsx(Fs,{className:"size-4"})})]})}),e.jsxs(Ut,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[d&&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(jh,{profile:d,isSelected:a==="global",isDefault:l==="global",onSelect:()=>{u("global"),t?.(),v&&b(!1)},onToggleDefault:()=>D("global"),onDelete:void 0,isReadOnly:!0})]}),c.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"}),c.length===0&&!d&&k.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ms,{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:c.map(A=>e.jsx(jh,{profile:A,isSelected:a===A.id,isDefault:l===A.id,onSelect:()=>{u(A.id),t?.(),v&&b(!1)},onToggleDefault:()=>D(A.id),onDelete:()=>S(A)},A.id))}),k.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"}),k.map(A=>e.jsx(LT,{credential:A,onImport:()=>N(A)},`${A.host}-${A.username}`))]})]}),e.jsx(bs,{open:s!==null,onOpenChange:A=>{!A&&!n&&r(null)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Delete Profile"}),e.jsxs(Is,{children:['Are you sure you want to delete profile "',s?.name,'"?']})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>r(null),disabled:n,children:"Cancel"}),e.jsx(Me,{variant:"destructive",onClick:()=>{M()},disabled:n,children:"Delete"})]})]})})]})},jh=({profile:t,isSelected:s,isDefault:r=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:l=!1})=>{const c=ET[t.icon||"branch"]||Ms,d=PT[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",s?"bg-interactive-selection":"hover:bg-interactive-hover"),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}),r&&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(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(Me,{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(Qn,{className:"h-3.5 w-3.5"})})}),e.jsxs(fs,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(Et,{onClick:m=>{m.stopPropagation(),o()},children:r?"Unset default":"Set as default"}),!l&&a&&e.jsxs(Et,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(Nr,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},FT=t=>{const s=t.split("/");return s.length>=3?s[s.length-1]:t},LT=({credential:t,onImport:s})=>{const r=FT(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:bg-interactive-hover",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:r})}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n?t.host:t.username})]}),e.jsxs(Me,{size:"sm",variant:"ghost",onClick:s,className:"h-6 px-2 text-xs gap-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:[e.jsx(po,{className:"h-3 w-3"}),"Import"]})]})})},Sh=[{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)"}],OT=[{key:"branch",Icon:Ms,label:"Branch"},{key:"briefcase",Icon:Iu,label:"Work"},{key:"house",Icon:Du,label:"Personal"},{key:"graduation",Icon:Au,label:"School"},{key:"code",Icon:xn,label:"Code"}],_T=()=>{const{selectedProfileId:t,getProfileById:s,createProfile:r,updateProfile:n,deleteProfile:o}=ka(),a=i.useMemo(()=>{if(t?.startsWith("import:")){const[,I,E]=t.split(":");return{host:I,username:E}}return null},[t]),l=i.useMemo(()=>t&&t!=="new"&&!a?s(t):null,[t,s,a]),c=t==="new"||a!==null,d=t==="global",[u,m]=i.useState(""),[f,p]=i.useState(""),[h,g]=i.useState(""),[x,y]=i.useState("ssh"),[b,v]=i.useState(""),[j,k]=i.useState(""),[N,w]=i.useState("keyword"),[C,S]=i.useState("branch"),[M,D]=i.useState(!1),[A,P]=i.useState(!1),[$,R]=i.useState(!1);i.useEffect(()=>{if(a){const I=a.host.split("/"),E=I.length>=3?I[I.length-1]:a.host;m(E),p(a.username),g(""),y("token"),v(""),k(a.host),w("string"),S("code")}else c?(m(""),p(""),g(""),y("ssh"),v(""),k(""),w("keyword"),S("branch")):l&&(m(l.name),p(l.userName),g(l.userEmail),y(l.authType||"ssh"),v(l.sshKey||""),k(l.host||""),w(l.color||"keyword"),S(l.icon||"branch"))},[l,c,t,a]);const O=async()=>{if(!f.trim()||!h.trim()){K.error("User name and email are required");return}if(x==="token"&&!j.trim()){K.error("Host is required for token-based authentication");return}D(!0);try{const I={name:u.trim()||f.trim(),userName:f.trim(),userEmail:h.trim(),authType:x,sshKey:x==="ssh"&&b.trim()||null,host:x==="token"&&j.trim()||null,color:N,icon:C};let E;if(c)E=await r(I);else if(t)E=await n(t,I);else return;E?K.success(c?"Profile created successfully":"Profile updated successfully"):K.error(c?"Failed to create profile":"Failed to update profile")}catch(I){console.error("Error saving profile:",I),K.error("An error occurred while saving")}finally{D(!1)}},T=()=>{!t||c||P(!0)},_=async()=>{if(!(!t||c)){R(!0);try{await o(t)?(K.success("Profile deleted successfully"),P(!1)):K.error("Failed to delete profile")}catch(I){console.error("Error deleting profile:",I),K.error("An error occurred while deleting")}finally{R(!1)}}},F=i.useMemo(()=>Sh.find(E=>E.key===N)?.cssVar||"var(--syntax-keyword)",[N]);return t?e.jsx(Ut,{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(Bt,{value:u,onChange:I=>m(I.target.value),placeholder:"Work Profile, Personal, etc."}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Friendly name to identify this profile (optional, defaults to user name)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Color"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Sh.map(I=>e.jsx("button",{onClick:()=>w(I.key),className:L("w-8 h-8 rounded-lg border-2 transition-all",N===I.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:I.cssVar},title:I.label},I.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Icon"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:OT.map(I=>{const E=I.Icon;return e.jsx("button",{onClick:()=>S(I.key),className:L("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",C===I.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:I.label,children:e.jsx(E,{className:"w-4 h-4",style:{color:F}})},I.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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(Bt,{value:f,onChange:I=>p(I.target.value),placeholder:"John Doe",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.name configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Email ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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(Bt,{type:"email",value:h,onChange:I=>g(I.target.value),placeholder:"john@example.com",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Authentication Type",e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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:()=>y("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(ij,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>y("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(Pg,{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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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(Bt,{value:b,onChange:I=>v(I.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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(Bt,{value:j,onChange:I=>k(I.target.value),placeholder:"github.com",required:!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git host for token authentication (from ~/.git-credentials)"})]}),!d&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!c&&e.jsxs(Me,{size:"sm",variant:"destructive",onClick:T,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Nr,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:L("flex gap-2",c&&"ml-auto"),children:e.jsxs(Me,{size:"sm",variant:"default",onClick:O,disabled:M,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(nc,{className:"h-3 w-3"}),M?"Saving...":"Save Profile"]})})]})]}),e.jsx(bs,{open:A,onOpenChange:I=>{$||P(I)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Delete Profile"}),e.jsxs(Is,{children:['Are you sure you want to delete profile "',l?.name||u||"this profile",'"?']})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>P(!1),disabled:$,children:"Cancel"}),e.jsx(Me,{variant:"destructive",onClick:()=>{_()},disabled:$,children:"Delete"})]})]})})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(en,{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 Nd(t,s,r){return Math.min(r,Math.max(s,t))}const ro=ne.forwardRef(({value:t,onValueChange:s,min:r=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:l,onBlur:c,onKeyDown:d,disabled:u,...m},f)=>{const p=ne.useRef(null);ne.useImperativeHandle(f,()=>p.current);const[h,g]=ne.useState(()=>String(t));ne.useEffect(()=>{document.activeElement!==p.current&&g(String(t))},[t]);const x=ne.useCallback(()=>{p.current?.focus()},[]),y=ne.useCallback(D=>{const A=Nd(D,r,n);s(A),g(String(A))},[n,r,s]),b=ne.useCallback(()=>{const D=Number(h);return Number.isFinite(D)?D:t},[h,t]),v=ne.useCallback(()=>{y(b()+o),x()},[y,b,x,o]),j=ne.useCallback(()=>{y(b()-o),x()},[y,b,x,o]),k=D=>{const A=D.target.value;g(A);const P=Number(A);Number.isFinite(P)&&s(Nd(P,r,n))},N=D=>{const A=Number(h);if(!Number.isFinite(A))g(String(t));else{const P=Nd(A,r,n);P!==A&&s(P),g(String(P))}c?.(D)},w=D=>{if(D.key==="ArrowUp"){D.preventDefault(),v();return}if(D.key==="ArrowDown"){D.preventDefault(),j();return}d?.(D)},C=b(),S=u||C<=r,M=u||C>=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(r)?r:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:h,onChange:k,onBlur:N,onKeyDown:w,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:M,onClick:v,className:L("flex flex-1 items-center justify-center","text-muted-foreground hover:bg-interactive-hover hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(vi,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:S,onClick:j,className:L("flex flex-1 items-center justify-center border-t border-border","text-muted-foreground hover:bg-interactive-hover hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(is,{className:"h-3.5 w-3.5"})})]})]})});ro.displayName="NumberInput";const $T=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Nh=[{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"}],kh=[{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."}],Ch=[{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."}],cm=({visibleSettings:t})=>{const{isMobile:s}=ks(),r=wi(),n=Te(B=>B.showReasoningTraces),o=Te(B=>B.setShowReasoningTraces),a=Te(B=>B.showTextJustificationActivity),l=Te(B=>B.setShowTextJustificationActivity),c=Te(B=>B.toolCallExpansion),d=Te(B=>B.setToolCallExpansion),u=Te(B=>B.fontSize),m=Te(B=>B.setFontSize),f=Te(B=>B.terminalFontSize),p=Te(B=>B.setTerminalFontSize),h=Te(B=>B.padding),g=Te(B=>B.setPadding),x=Te(B=>B.cornerRadius),y=Te(B=>B.setCornerRadius),b=Te(B=>B.inputBarOffset),v=Te(B=>B.setInputBarOffset),j=Te(B=>B.diffLayoutPreference),k=Te(B=>B.setDiffLayoutPreference),N=Te(B=>B.diffViewMode),w=Te(B=>B.setDiffViewMode),C=Te(B=>B.showTerminalQuickKeysOnDesktop),S=Te(B=>B.setShowTerminalQuickKeysOnDesktop),M=Dn(B=>B.queueModeEnabled),D=Dn(B=>B.setQueueMode),A=Te(B=>B.persistChatDraft),P=Te(B=>B.setPersistChatDraft),{themeMode:$,setThemeMode:R,availableThemes:O,customThemesLoading:T,reloadCustomThemes:_,lightThemeId:F,darkThemeId:I,setLightThemePreference:E,setDarkThemePreference:W}=rn(),[V,ve]=i.useState(!1),oe=i.useMemo(()=>O.filter(B=>B.metadata.variant==="light").sort((B,se)=>B.metadata.name.localeCompare(se.metadata.name)),[O]),Z=i.useMemo(()=>O.filter(B=>B.metadata.variant==="dark").sort((B,se)=>B.metadata.name.localeCompare(se.metadata.name)),[O]),ce=i.useMemo(()=>oe.find(B=>B.metadata.id===F)??oe[0],[oe,F]),Q=i.useMemo(()=>Z.find(B=>B.metadata.id===I)??Z[0],[Z,I]),Y=i.useCallback((B,se)=>{const H=se==="dark"?" Dark":" Light";return B.endsWith(H)?B.slice(0,-H.length):B},[]),ie=B=>t?t.includes(B):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[ie("theme")&&!gs()&&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:$T.map(B=>e.jsx(pr,{variant:$===B.value?"default":"outline",className:L($===B.value?void 0:"text-foreground"),onClick:()=>R(B.value),children:B.label},B.value))}),e.jsxs("div",{className:"flex gap-10",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("h4",{className:"typography-ui-label font-medium text-foreground",children:"Light Theme"}),e.jsxs($s,{value:ce?.metadata.id??"",onValueChange:E,children:[e.jsx(Bs,{"aria-label":"Select light theme",className:"min-w-32",children:e.jsx(Sr,{placeholder:"Select theme"})}),e.jsx(zs,{className:"max-h-64 min-w-40",children:oe.map(B=>e.jsx(ns,{value:B.metadata.id,children:Y(B.metadata.name,"light")},B.metadata.id))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("h4",{className:"typography-ui-label font-medium text-foreground",children:"Dark Theme"}),e.jsxs($s,{value:Q?.metadata.id??"",onValueChange:W,children:[e.jsx(Bs,{"aria-label":"Select dark theme",className:"min-w-32",children:e.jsx(Sr,{placeholder:"Select theme"})}),e.jsx(zs,{className:"max-h-64 min-w-40",children:Z.map(B=>e.jsx(ns,{value:B.metadata.id,children:Y(B.metadata.name,"dark")},B.metadata.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("button",{type:"button",disabled:T||V,onClick:async()=>{ve(!0);try{await _()}finally{ve(!1)}},className:"typography-ui-label text-muted-foreground hover:text-foreground hover:underline underline-offset-2 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5",children:[e.jsx(jr,{className:L("h-3.5 w-3.5",V&&"animate-spin")}),"Reload custom themes"]}),e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Import themes from ~/.config/ikanban/themes/"})]})]}),ie("fontSize")&&!s&&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:B=>m(Number(B.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(ro,{value:u,onValueChange:m,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>m(100),disabled:u===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-interactive-hover disabled:opacity-100 disabled:bg-background","aria-label":"Reset font size",title:"Reset",children:e.jsx(jr,{className:"h-3.5 w-3.5"})})]})]}),ie("terminalFontSize")&&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:"Terminal Font Size"})}),s?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"9",max:"52",step:"1",value:f,onChange:B=>p(Number(B.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":"Terminal font size"}),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:[f,"px"]}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>p(13),disabled:f===13,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-interactive-hover disabled:opacity-100 disabled:bg-background","aria-label":"Reset terminal font size",title:"Reset",children:e.jsx(jr,{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:"9",max:"52",step:"1",value:f,onChange:B=>p(Number(B.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(ro,{value:f,onValueChange:p,min:9,max:52,step:1,"aria-label":"Terminal font size"}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>p(13),disabled:f===13,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-interactive-hover disabled:opacity-100 disabled:bg-background","aria-label":"Reset terminal font size",title:"Reset",children:e.jsx(jr,{className:"h-3.5 w-3.5"})})]})]}),ie("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"})}),s?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:h,onChange:B=>g(Number(B.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:h}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>g(100),disabled:h===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-interactive-hover disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(jr,{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:h,onChange:B=>g(Number(B.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(ro,{value:h,onValueChange:g,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>g(100),disabled:h===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-interactive-hover disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(jr,{className:"h-3.5 w-3.5"})})]})]}),ie("terminalQuickKeys")&&!s&&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:"Show terminal optional key bar"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Esc, Ctrl, arrows, Enter."})]}),e.jsx(nr,{checked:C,onCheckedChange:S,className:"data-[state=checked]:bg-status-info"})]}),ie("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"})}),s?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"32",step:"1",value:x,onChange:B=>y(Number(B.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:[x,"px"]}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>y(12),disabled:x===12,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-interactive-hover disabled:opacity-100 disabled:bg-background","aria-label":"Reset corner radius",title:"Reset",children:e.jsx(jr,{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:x,onChange:B=>y(Number(B.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(ro,{value:x,onValueChange:y,min:0,max:32,step:1,"aria-label":"Corner radius in pixels"}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>y(12),disabled:x===12,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-interactive-hover disabled:opacity-100 disabled:bg-background","aria-label":"Reset corner radius",title:"Reset",children:e.jsx(jr,{className:"h-3.5 w-3.5"})})]})]}),ie("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."})]}),s?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"100",step:"5",value:b,onChange:B=>v(Number(B.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:[b,"px"]}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>v(0),disabled:b===0,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-interactive-hover disabled:opacity-100 disabled:bg-background","aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(jr,{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:b,onChange:B=>v(Number(B.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(ro,{value:b,onValueChange:v,min:0,max:100,step:5,"aria-label":"Input bar offset in pixels"}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>v(0),disabled:b===0,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-interactive-hover disabled:opacity-100 disabled:bg-background","aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(jr,{className:"h-3.5 w-3.5"})})]})]}),ie("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:Nh.find(B=>B.value===c)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Nh.map(B=>e.jsx(pr,{variant:c===B.value?"default":"outline",className:L(c===B.value?void 0:"text-foreground"),onClick:()=>d(B.value),children:B.label},B.value))})]}),ie("diffLayout")&&!s&&!gs()&&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:kh.map(B=>e.jsx(pr,{variant:j===B.id?"default":"outline",className:L(j===B.id?void 0:"text-foreground"),onClick:()=>k(B.id),children:B.label},B.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:kh.find(B=>B.id===j)?.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:Ch.map(B=>e.jsx(pr,{variant:N===B.id?"default":"outline",className:L(N===B.id?void 0:"text-foreground"),onClick:()=>w(B.id),children:B.label},B.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Ch.find(B=>B.id===N)?.description})]})]}),ie("dotfiles")&&!gs()&&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(B=>e.jsx(pr,{variant:r===B.value?"default":"outline",className:L(r===B.value?void 0:"text-foreground"),onClick:()=>Pu(B.value),children:B.label},B.id))})})]}),ie("reasoning")&&e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Xr,{checked:n,onChange:o}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),ie("textJustificationActivity")&&e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Xr,{checked:a,onChange:l}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show text justification in activity"})]}),ie("queueMode")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Xr,{checked:M,onChange:D}),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:M?`Enter queues messages, ${Ys()}+Enter sends immediately.`:`Enter sends immediately, ${Ys()}+Enter queues messages.`})]}),ie("persistDraft")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Xr,{checked:A,onChange:P}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Persist chat input draft"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5",children:"Save your typed message across page reloads and session switches."})]})]})},Mh="https://github.com/btriapitsyn/ikanban",BT=800,ub=()=>{const[t,s]=i.useState(!1),[r,n]=i.useState(!1),o=ac(),{isMobile:a}=ks(),l=o.info?.currentVersion||"unknown",c=i.useRef(!1);i.useEffect(()=>{if(o.checking)n(!0),c.current=!0;else if(r){const u=setTimeout(()=>{n(!1),c.current&&!o.available&&!o.error&&(K.success("You are on the latest version"),c.current=!1)},BT);return()=>clearTimeout(u)}},[o.checking,r,o.available,o.error]);const d=o.checking||r;return a?e.jsxs("div",{className:"w-full space-y-2",children:[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:()=>s(!0),className:"flex items-center gap-1 typography-meta text-primary hover:underline",children:[e.jsx(po,{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:Mh,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(uo,{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(Rg,{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(Hd,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(au,{open:t,onOpenChange:s,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 IKanban"})}),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(ol,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Checking..."})]}),!o.checking&&o.available&&e.jsxs("button",{onClick:()=>s(!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(po,{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:Mh,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(uo,{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(Hd,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(au,{open:t,onOpenChange:s,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]})},zT=1440*60*1e3,mb=5,Ah=1440*60*1e3,kd=t=>t.time?.updated??t.time?.created??0,Dh=({sessions:t,currentSessionId:s,cutoffDays:r,keepRecent:n=mb,now:o=Date.now()})=>{if(!Array.isArray(t)||r<=0)return[];const a=o-r*zT,l=[...t].sort((d,u)=>kd(u)-kd(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===s||d.share)return!1;const u=kd(d);return u?u<a:!1}).map(d=>d.id)},fb=t=>{const s=t?.autoRun!==!1,r=Ae(x=>x.sessions),n=Ae(x=>x.currentSessionId),o=Ae(x=>x.isLoading),a=Ae(x=>x.deleteSessions),l=Te(x=>x.autoDeleteEnabled),c=Te(x=>x.autoDeleteAfterDays),d=Te(x=>x.autoDeleteLastRunAt),u=Te(x=>x.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),h=i.useMemo(()=>c<=0?[]:Dh({sessions:r,currentSessionId:n,cutoffDays:c}),[c,n,r]),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 y=Date.now();if(!x&&d&&y-d<Ah)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(r.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const b=Dh({sessions:r,currentSessionId:n,cutoffDays:c,now:y});if(b.length===0)return u(y),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(b,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[c,l,d,n,a,o,r,u]);return i.useEffect(()=>{if(!s||!l||c<=0||o||r.length===0)return;const x=Date.now();d&&x-d<Ah||g()},[c,l,d,s,o,r.length,g]),{candidates:h,isRunning:m,runCleanup:g,keepRecentCount:mb}},Cd=1,Md=365,pb=()=>{const{isMobile:t}=ks(),s=Te(p=>p.autoDeleteEnabled),r=Te(p=>p.autoDeleteAfterDays),n=Te(p=>p.setAutoDeleteEnabled),o=Te(p=>p.setAutoDeleteAfterDays),[a,l]=i.useState(String(r));i.useEffect(()=>{l(String(r))},[r]);const{candidates:c,isRunning:d,runCleanup:u}=fb({autoRun:!1}),m=c.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){K.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&K.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&K.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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{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(Xr,{checked:s,onChange:n}),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(Md,Math.max(Cd,Math.round(g)));o(x)},onBlur:()=>{if(a.trim()===""){l(String(r));return}const p=Number(a);if(!Number.isFinite(p)){l(String(r));return}const h=Math.min(Md,Math.max(Cd,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(ro,{value:r,onValueChange:o,min:Cd,max:Md,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(pr,{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]})]})},Ih=10,Th=500,UT=()=>{const{isMobile:t}=ks(),s=Te(c=>c.messageLimit),r=Te(c=>c.setMessageLimit),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let d=null;if(!d){const u=Ur()?.settings;if(u)try{const f=(await u.load())?.settings;f&&(d={messageLimit:typeof f.messageLimit=="number"?f.messageLimit:void 0})}catch{}}if(!d){const u=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});u.ok&&(d=await u.json())}d&&typeof d.messageLimit=="number"&&r(d.messageLimit)}catch(d){console.warn("Failed to load memory limits settings:",d)}finally{o(!1)}})()},[r]);const a=i.useCallback(c=>{r(c),xs({messageLimit:c}).catch(d=>{console.warn("Failed to save messageLimit:",d)})},[r]);if(n)return null;const l=s===ha;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:"Message Memory"}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ht,{sideOffset:8,className:"max-w-xs",children:["How many messages to keep in view per session.",e.jsx("br",{}),'Older messages are available via "Load more". Background sessions are trimmed automatically.']})]})]})}),e.jsx("div",{className:"space-y-3",children: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:"Message limit"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Messages loaded per session"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!l&&e.jsxs("span",{className:"typography-meta text-muted-foreground/60",children:["(default: ",ha,")"]}),t?e.jsx(HT,{value:s,min:Ih,max:Th,onChange:a}):e.jsx(ro,{value:s,onValueChange:a,min:Ih,max:Th,step:10,"aria-label":"Message limit"})]})]})})})]})},HT=({value:t,min:s,max:r,onChange:n})=>{const[o,a]=i.useState(String(t));i.useEffect(()=>{a(String(t))},[t]);const l=i.useCallback(d=>{const u=d.target.value;if(a(u),u.trim()==="")return;const m=Number(u);Number.isFinite(m)&&n(Math.min(r,Math.max(s,Math.round(m))))},[s,r,n]),c=i.useCallback(()=>{if(o.trim()===""){a(String(t));return}const d=Number(o);if(!Number.isFinite(d)){a(String(t));return}const u=Math.min(r,Math.max(s,Math.round(d)));n(u),a(String(u))},[o,t,s,r,n]);return e.jsx("input",{type:"number",inputMode:"numeric",value:o,onChange:l,onBlur:c,"aria-label":"Message limit",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"})},Eh="opencode",Ph="big-pickle",VT=(t,s)=>{if(t){const o=t.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(s.find(o=>o.id===Eh)?.models.some(o=>o.id===Ph))return{providerId:Eh,modelId:Ph};const n=s[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},hb=()=>{const t=ut(I=>I.setProvider),s=ut(I=>I.setModel),r=ut(I=>I.setAgent),n=ut(I=>I.setCurrentVariant),o=ut(I=>I.setSettingsDefaultModel),a=ut(I=>I.setSettingsDefaultVariant),l=ut(I=>I.setSettingsDefaultAgent),c=ut(I=>I.settingsAutoCreateWorktree),d=ut(I=>I.setSettingsAutoCreateWorktree),u=ut(I=>I.settingsZenModel),m=ut(I=>I.setSettingsZenModel),f=ut(I=>I.providers),[p,h]=i.useState(),[g,x]=i.useState(),[y,b]=i.useState(),[v,j]=i.useState(!0),[k,N]=i.useState([]),[w,C]=i.useState(!0),S=i.useMemo(()=>VT(p,f),[p,f]),M=i.useMemo(()=>gs(),[]);i.useEffect(()=>{(async()=>{try{const E=await fetch("/api/zen/models",{method:"GET",headers:{Accept:"application/json"}});if(E.ok){const W=await E.json();Array.isArray(W?.models)&&N(W.models)}}catch(E){console.warn("Failed to load zen models:",E)}finally{C(!1)}})()},[]);const D=i.useMemo(()=>u&&k.some(I=>I.id===u)?u:k[0]?.id??"",[u,k]);i.useEffect(()=>{(async()=>{try{let E=null;if(!E){const W=Ur()?.settings;if(W)try{const ve=(await W.load())?.settings;ve&&(E={defaultModel:typeof ve.defaultModel=="string"?ve.defaultModel:void 0,defaultVariant:typeof ve.defaultVariant=="string"?ve.defaultVariant:void 0,defaultAgent:typeof ve.defaultAgent=="string"?ve.defaultAgent:void 0,zenModel:typeof ve.zenModel=="string"?ve.zenModel:void 0})}catch{}}if(!E){const W=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});W.ok&&(E=await W.json())}if(E){const W=typeof E.defaultModel=="string"&&E.defaultModel.trim().length>0?E.defaultModel.trim():void 0,V=typeof E.defaultVariant=="string"&&E.defaultVariant.trim().length>0?E.defaultVariant.trim():void 0,ve=typeof E.defaultAgent=="string"&&E.defaultAgent.trim().length>0?E.defaultAgent.trim():void 0,oe=typeof E.zenModel=="string"&&E.zenModel.trim().length>0?E.zenModel.trim():void 0;W!==void 0&&h(W),V!==void 0&&x(V),ve!==void 0&&b(ve),oe!==void 0&&m(oe)}}catch(E){console.warn("Failed to load defaults settings:",E)}finally{j(!1)}})()},[m]);const A=i.useCallback(async(I,E)=>{const W=I&&E?`${I}/${E}`:void 0;h(W),x(void 0),a(void 0),n(void 0),o(W),I&&E&&f.find(ve=>ve.id===I)&&(t(I),s(E));try{await xs({defaultModel:W??"",defaultVariant:""});{const V=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:W})});V.ok||console.warn("Failed to save default model to server:",V.status,V.statusText)}}catch(V){console.warn("Failed to save default model:",V)}},[f,n,t,s,o,a]),P="__default__",$=i.useCallback(async I=>{const E=I===P?void 0:I||void 0;x(E),a(E),n(E);try{await xs({defaultVariant:E??""})}catch(W){console.warn("Failed to save default variant:",W)}},[n,a]),R=i.useCallback(async I=>{const E=I||void 0;b(E),l(E),I&&r(I);try{await xs({defaultAgent:E??""})}catch(W){console.warn("Failed to save default agent:",W)}},[r,l]),O=i.useMemo(()=>{if(!S.providerId||!S.modelId)return[];const W=f.find(V=>V.id===S.providerId)?.models.find(V=>V.id===S.modelId)?.variants;return W?Object.keys(W):[]},[S.modelId,S.providerId,f]),T=O.length>0;i.useEffect(()=>{!T&&g&&(x(void 0),a(void 0),n(void 0),xs({defaultVariant:""}).catch(()=>{}))},[g,n,a,T]);const _=i.useCallback(async I=>{const E=I.target.checked;d(E);try{await xs({autoCreateWorktree:E})}catch(W){console.warn("Failed to save auto create worktree setting:",W)}},[d]),F=i.useCallback(async I=>{m(I);try{await xs({zenModel:I})}catch(E){console.warn("Failed to save zen model setting:",E)}},[m]);return v?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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ht,{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(lm,{providerId:S.providerId,modelId:S.modelId,onChange:A})]}),T&&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($s,{value:g??P,onValueChange:$,children:[e.jsx(Bs,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Sr,{placeholder:"Thinking"})}),e.jsxs(zs,{children:[e.jsx(ns,{value:P,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),O.map(I=>e.jsx(ns,{value:I,className:"pr-2 [&>span:first-child]:hidden",children:I},I))]})]})]}),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(db,{agentName:y||"",onChange:R})]})]}),(S.providerId||y)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",S.providerId&&e.jsxs("span",{className:"text-foreground",children:[S.providerId,"/",S.modelId,T?` (${g??"default"})`:""]}),S.providerId&&y&&" / ",y&&e.jsx("span",{className:"text-foreground",children:y})]}),!M&&e.jsxs("div",{className:"pt-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Xr,{checked:c,onChange:I=>_({target:{checked:I}})}),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 mt-1",children:c?`New session (Worktree): ${Ys()} + N • New session (Standard): Shift + ${Ys()} + N`:`New session (Standard): ${Ys()} + N • New session (Worktree): Shift + ${Ys()} + N`})]}),e.jsxs("div",{className:"border-t border-border/40 pt-4 mt-4 space-y-3",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:"Zen Model"}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ht,{sideOffset:8,className:"max-w-xs",children:"The free model used for lightweight internal tasks like commit message generation, PR descriptions, notification summarization, and TTS text summarization."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Used for commit messages, PR descriptions, and text summarization."})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Model"}),w?e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Loading models..."}):k.length>0?e.jsxs($s,{value:D,onValueChange:F,children:[e.jsx(Bs,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Sr,{placeholder:"Select model"})}),e.jsx(zs,{children:k.map(I=>e.jsx(ns,{value:I.id,className:"pr-2 [&>span:first-child]:hidden",children:I.id},I.id))})]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No free models available"})]})]})]})},WT=()=>{const t=ut(l=>l.settingsGitmojiEnabled),s=ut(l=>l.setSettingsGitmojiEnabled),r=lc(),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let c=null;if(!c){const d=Ur()?.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 d=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});d.ok&&(c=await d.json())}c&&typeof c.gitmojiEnabled=="boolean"&&s(c.gitmojiEnabled)}catch(c){console.warn("Failed to load git settings:",c)}finally{o(!1)}})()},[s]);const a=i.useCallback(async l=>{const c=l.target.checked;s(c);try{await xs({gitmojiEnabled:c})}catch(d){console.warn("Failed to save gitmoji setting:",d)}},[s]);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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ht,{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(Xr,{checked:t,onChange:l=>a({target:{checked:l}})}),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(Xr,{checked:r,onChange:Kg}),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."})]})})]})},GT=()=>{const t=ps(S=>S.getActiveProject()),s=t?.path??null,{sessions:r,getWorktreeMetadata:n}=Ae(),o=Yt(S=>S.homeDirectory),[a,l]=i.useState([]),[c,d]=i.useState(!1),[u,m]=i.useState(null),[f,p]=i.useState([]),[h,g]=i.useState(!1),x=i.useMemo(()=>!t?.id||!s?null:{id:t.id,path:s},[t?.id,s]),y=i.useCallback(async()=>{if(!(!x||u===!1))try{const S=await $o(x);p(S)}catch{}},[x,u]);i.useEffect(()=>{if(!s)return;let S=!1;return m(null),(async()=>{try{const M=await Yn(s);if(S)return;m(M)}catch{}})(),()=>{S=!0}},[s]),i.useEffect(()=>{if(!x){p([]),g(!1);return}if(u===!1){p([]),g(!1);return}let S=!1;return g(!0),p([]),(async()=>{try{const M=await $o(x);if(S)return;p(M)}catch{}finally{S||g(!1)}})(),()=>{S=!0}},[x,u]),i.useEffect(()=>{if(!x)return;let S=!1;return d(!0),(async()=>{try{const M=await Ia(x);S||l(M.length>0?M:[""])}catch{S||l([""])}finally{S||d(!1)}})(),()=>{S=!0}},[x]);const b=i.useCallback((S,M)=>{l(D=>{const A=[...D];return A[S]=M,A})},[]),v=i.useCallback(()=>{l(S=>[...S,""])},[]),j=i.useCallback(async S=>{if(!x)return;const M=S.filter(D=>D.trim().length>0);await xx(x,M)},[x]),k=i.useCallback(S=>{l(M=>{const D=M.filter((A,P)=>P!==S);return j(D),D.length>0?D:[""]})},[j]),N=i.useCallback(()=>{j(a)},[j,a]),w=i.useCallback(S=>{const M=_=>_.replace(/\\/g,"/").replace(/\/+$/,""),D=M(S.path),A=r.filter(_=>{const F=n(_.id);if(F?.path&&M(F.path)===D)return!0;const I=_.directory;return!!(I&&M(I)===D)}),P=new Set(A.map(_=>_.id)),$=_=>{const F=r.filter(E=>{const W=E.parentID;return W&&_.has(W)});if(F.length===0)return[];const I=new Set(F.map(E=>E.id));return[...F,...$(I)]},R=$(P),O=new Set,T=[...A,...R].filter(_=>O.has(_.id)?!1:(O.add(_.id),!0));Na.requestDelete({sessions:T,mode:"worktree",worktree:S})},[r,n]),C=i.useMemo(()=>r.map(S=>S.id).join(","),[r]);return i.useEffect(()=>{u&&s&&y()},[C,u,s,y]),s?u===!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.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."]})]}),c?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[a.map((S,M)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Bt,{value:S,onChange:D=>b(M,D.target.value),onBlur:N,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{k(M)},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(hs,{className:"h-4 w-4"})})]},M)),e.jsxs("button",{type:"button",onClick:v,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Fs,{className:"h-3.5 w-3.5"}),"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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ht,{sideOffset:8,className:"max-w-xs",children:"Worktrees live outside the repo (OpenCode-managed). Deleting a worktree also removes linked sessions."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Manage worktrees for this project"})]}),h?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):f.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:f.map(S=>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:S.label||S.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:"OpenCode"})]}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:An(S.path,o)})]}),e.jsx("button",{type:"button",onClick:()=>w(S),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 ${S.branch||S.label}`,children:e.jsx(Nr,{className:"h-4 w-4"})})]},S.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to manage worktrees."})},Rh={completion:{title:"{agent_name} is ready",message:"{model_name} completed the task"},error:{title:"Tool error",message:"{last_message}"},question:{title:"Input needed",message:"{last_message}"},subtask:{title:"{agent_name} is ready",message:"{model_name} completed the task"}},KT=()=>{const t=i.useMemo(()=>Lr(),[]),s=i.useMemo(()=>gs(),[]),r=!t&&!s,n=Te(Y=>Y.nativeNotificationsEnabled),o=Te(Y=>Y.setNativeNotificationsEnabled),a=Te(Y=>Y.notificationMode),l=Te(Y=>Y.setNotificationMode),c=Te(Y=>Y.notifyOnSubtasks),d=Te(Y=>Y.setNotifyOnSubtasks),u=Te(Y=>Y.notifyOnCompletion),m=Te(Y=>Y.setNotifyOnCompletion),f=Te(Y=>Y.notifyOnError),p=Te(Y=>Y.setNotifyOnError),h=Te(Y=>Y.notifyOnQuestion),g=Te(Y=>Y.setNotifyOnQuestion),x=Te(Y=>Y.notificationTemplates),y=Te(Y=>Y.setNotificationTemplates),b=Te(Y=>Y.summarizeLastMessage),v=Te(Y=>Y.setSummarizeLastMessage),j=Te(Y=>Y.summaryThreshold),k=Te(Y=>Y.setSummaryThreshold),N=Te(Y=>Y.summaryLength),w=Te(Y=>Y.setSummaryLength),C=Te(Y=>Y.maxLastMessageLength),S=Te(Y=>Y.setMaxLastMessageLength),[M,D]=i.useState("default"),[A,P]=i.useState(!1),[$,R]=i.useState(!1),[O,T]=i.useState(!1);i.useEffect(()=>{if(!r){P(!1),R(!1);return}typeof Notification<"u"&&D(Notification.permission);const Y=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;P(Y),(async()=>{if(!Y){R(!1);return}try{const B=await navigator.serviceWorker.getRegistration();if(!B){R(!1);return}const se=await B.pushManager.getSubscription();R(!!se)}catch{R(!1)}})()},[r]);const _=async Y=>{if(t){o(Y);return}if(!r){o(Y);return}if(Y&&typeof Notification<"u"&&Notification.permission==="default")try{const ie=await Notification.requestPermission();D(ie),ie==="granted"?o(!0):K.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(ie){console.error("Failed to request notification permission:",ie),K.error("Failed to request notification permission")}else o(!!(Y&&M==="granted"))},F=t||r&&typeof Notification<"u"&&Notification.permission==="granted",I=(Y,ie,B)=>{y({...x,[Y]:{...x[Y],[ie]:B}})},E=Y=>{const ie="=".repeat((4-Y.length%4)%4),B=(Y+ie).replace(/-/g,"+").replace(/_/g,"/"),se=atob(B),H=new Uint8Array(se.length);for(let le=0;le<se.length;le+=1)H[le]=se.charCodeAt(le);return H},W=async(Y,ie,B)=>{let se=null;const H=new Promise((le,ge)=>{se=setTimeout(()=>{ge(new Error(B))},ie)});try{return await Promise.race([Y,H])}finally{se&&clearTimeout(se)}},V=async Y=>{if(Y.active)return;const ie=Y.installing||Y.waiting;ie&&ie.state!=="activated"&&await W(new Promise(B=>{const se=()=>{ie.state==="activated"&&(ie.removeEventListener("statechange",se),B())};ie.addEventListener("statechange",se),se()}),15e3,"Service worker activation timed out")},ve=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const Y=[{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 ie=null;for(const B of Y)try{const se=B.opts?navigator.serviceWorker.register("/sw.js",B.opts):navigator.serviceWorker.register("/sw.js");return await W(se,1e4,`Service worker registration timed out (${B.label})`)}catch(se){ie=se}throw ie instanceof Error?ie:new Error("Service worker registration failed")},oe=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const Y=await navigator.serviceWorker.getRegistration();if(Y)return Y;const ie=await ve();try{await ie.update()}catch{}return await V(ie),ie},Z=Y=>{const ie=Y,B=[`type=${typeof Y}`,`toString=${String(Y)}`,`name=${String(ie?.name??"")}`,`message=${String(ie?.message??"")}`];let se="";try{se=JSON.stringify(Y)}catch{}return{summary:B.filter(Boolean).join(" | "),json:se,stack:typeof ie?.stack=="string"?ie.stack:""}},ce=async()=>{if(!A){K.error("Push notifications not supported");return}const Y=Ur();if(!Y?.push){K.error("Push API not available");return}T(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const J=await Notification.requestPermission();if(D(J),J!=="granted"){K.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){K.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}const ie=await Y.push.getVapidPublicKey();if(!ie?.publicKey){K.error("Failed to load push key");return}const B=await oe();await V(B);const se=await B.pushManager.getSubscription();if(!("pushManager"in B)||!B.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const le=(se??await W(B.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:E(ie.publicKey)}),15e3,"Push subscription timed out")).toJSON(),ge=le.keys;if(!le.endpoint||!ge?.p256dh||!ge.auth)throw new Error("Push subscription missing keys");if(!(await W(Y.push.subscribe({endpoint:le.endpoint,keys:{p256dh:ge.p256dh,auth:ge.auth},origin:typeof window<"u"?window.location.origin:void 0}),15e3,"Push subscribe request timed out"))?.ok){K.error("Failed to enable background notifications");return}R(!0),K.success("Background notifications enabled")}catch(ie){console.error("[Push] Enable failed:",ie);const B=Z(ie);K.error("Failed to enable background notifications",{description:B.summary})}finally{T(!1)}},Q=async()=>{if(!A){R(!1);return}const Y=Ur();if(!Y?.push){K.error("Push API not available");return}T(!0);try{const B=await(await oe()).pushManager.getSubscription();if(!B){R(!1);return}const se=B.endpoint;await B.unsubscribe(),await Y.push.unsubscribe({endpoint:se}),R(!1),K.success("Background notifications disabled")}finally{T(!1)}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1 pt-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"When to notify"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Customize when notifications show up."})]}),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:"Enable notifications"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Turns notifications on or off."})]}),e.jsx(nr,{checked:n&&F,onCheckedChange:_,className:"data-[state=checked]:bg-status-info"})]}),r&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Your browser may ask for permission the first time."}),n&&F&&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 while app is focused"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"When off, only notify when you are not looking at IKanban."})]}),e.jsx(nr,{checked:a==="always",onCheckedChange:Y=>l(Y?"always":"hidden-only"),className:"data-[state=checked]:bg-status-info"})]}),n&&F&&e.jsxs("div",{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"typography-ui text-foreground font-medium",children:"Events"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Choose which events trigger notifications."})]}),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:"Completion"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Agent finished its task."})]}),e.jsx(nr,{checked:u,onCheckedChange:m,className:"data-[state=checked]:bg-status-info"})]}),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:"Errors"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"A tool call failed."})]}),e.jsx(nr,{checked:f,onCheckedChange:p,className:"data-[state=checked]:bg-status-info"})]}),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:"Questions"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Agent is asking for input or permission."})]}),e.jsx(nr,{checked:h,onCheckedChange:g,className:"data-[state=checked]:bg-status-info"})]}),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:"Subagents"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Also notify for child sessions started by the main one."})]}),e.jsx(nr,{checked:c,onCheckedChange:Y=>d(Y),className:"data-[state=checked]:bg-status-info"})]})]}),n&&F&&e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Customize content"}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Use template variables: ",e.jsx("code",{className:"text-accent-foreground",children:"{project_name}"})," ",e.jsx("code",{className:"text-accent-foreground",children:"{worktree}"})," ",e.jsx("code",{className:"text-accent-foreground",children:"{branch}"})," ",e.jsx("code",{className:"text-accent-foreground",children:"{session_name}"})," ",e.jsx("code",{className:"text-accent-foreground",children:"{agent_name}"})," ",e.jsx("code",{className:"text-accent-foreground",children:"{last_message}"})]})]}),["completion","error","question","subtask"].map(Y=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"typography-ui text-foreground font-medium capitalize",children:Y}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"typography-micro text-muted-foreground block mb-1",children:"Title"}),e.jsx("input",{type:"text",value:x[Y].title,onChange:ie=>I(Y,"title",ie.target.value),className:"w-full rounded-md border border-border bg-background px-3 py-1.5 typography-ui text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-accent",placeholder:Rh[Y].title})]}),e.jsxs("div",{children:[e.jsx("label",{className:"typography-micro text-muted-foreground block mb-1",children:"Message"}),e.jsx("input",{type:"text",value:x[Y].message,onChange:ie=>I(Y,"message",ie.target.value),className:"w-full rounded-md border border-border bg-background px-3 py-1.5 typography-ui text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-accent",placeholder:Rh[Y].message})]})]})]},Y))]}),n&&F&&e.jsxs("div",{className:"space-y-3 pt-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Summarization"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Summarize long messages in notifications using AI."})]}),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:"Summarize last message"}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Uses AI to shorten the ","{last_message}"," variable."]})]}),e.jsx(nr,{checked:b,onCheckedChange:v,className:"data-[state=checked]:bg-status-info"})]}),b?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"typography-ui text-foreground",children:"Summary threshold"}),e.jsxs("span",{className:"typography-micro text-muted-foreground tabular-nums",children:[j," chars"]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Messages longer than this will be summarized."}),e.jsx("input",{type:"range",min:50,max:2e3,step:50,value:j,onChange:Y=>k(Number(Y.target.value)),className:"w-full 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.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"typography-ui text-foreground",children:"Summary length"}),e.jsxs("span",{className:"typography-micro text-muted-foreground tabular-nums",children:[N," chars"]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Target length of the summary."}),e.jsx("input",{type:"range",min:20,max:500,step:10,value:N,onChange:Y=>w(Number(Y.target.value)),className:"w-full 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.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"typography-ui text-foreground",children:"Max last message length"}),e.jsxs("span",{className:"typography-micro text-muted-foreground tabular-nums",children:[C," chars"]})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Truncate ","{last_message}"," to this many characters."]}),e.jsx("input",{type:"range",min:50,max:1e3,step:10,value:C,onChange:Y=>S(Number(Y.target.value)),className:"w-full 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"})]})]}),r&&e.jsxs(e.Fragment,{children:[M==="denied"&&e.jsx("p",{className:"typography-micro text-destructive",children:"Notification permission denied. Enable it in your browser settings."}),M==="granted"&&!n&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Permission granted, but notifications are disabled."}),e.jsxs("div",{className:"space-y-1 pt-4",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Background (Push)"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Get notified even if this page is closed."})]}),A?e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Desktop Chrome/Edge and Android support push. iOS requires an installed PWA."}):e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Push not supported in this browser."}),A&&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 push notifications"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Clicking a notification opens the relevant session."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[O&&e.jsx("div",{className:"text-muted-foreground",children:e.jsx(ly,{size:"sm"})}),e.jsx(nr,{checked:$,disabled:O,onCheckedChange:Y=>{Y?ce():Q()},className:"data-[state=checked]:bg-status-info"})]})]})]}),s&&e.jsxs("div",{className:"space-y-1 pt-4",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Delivery"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"VS Code runtime handles notifications separately."})]})]})},qT=()=>{const t=Ur()?.github,s=$r(w=>w.status),r=$r(w=>w.isLoading),n=$r(w=>w.hasChecked),o=$r(w=>w.refreshStatus),a=$r(w=>w.setStatus),l=i.useCallback(async w=>{if(typeof window>"u")return;const C=window.__TAURI__;if(C?.shell?.open)try{await C.shell.open(w);return}catch{}try{window.open(w,"_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(w){console.warn("Failed to load GitHub auth status:",w)}})(),()=>{g()}),[n,o,t,g]);const x=i.useCallback(async()=>{d(!0);try{const w=t?await t.authStart():await(async()=>{const S=await fetch("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),M=await S.json().catch(()=>null);if(!S.ok||!M||!("deviceCode"in M))throw new Error(M?.error||S.statusText);return M})();m(w),p(Math.max(1,w.interval)*1e3);const C=w.verificationUriComplete||w.verificationUri;l(C)}catch(w){console.error("Failed to start GitHub connect:",w),K.error("Failed to start GitHub connect")}finally{d(!1)}},[l,t]),y=i.useCallback(async w=>{if(t)return t.authComplete(w);const C=await fetch("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:w})}),S=await C.json().catch(()=>null);if(!C.ok||!S)throw new Error(S?.error||C.statusText);return S},[t]);i.useEffect(()=>{if(!(!u?.deviceCode||!f)&&h.current==null)return h.current=window.setInterval(()=>{(async()=>{try{const w=await y(u.deviceCode);if(w.connected){K.success("GitHub connected"),m(null),g(),await o(t,{force:!0});return}w.status==="slow_down"&&p(C=>C?C+5e3:5e3),(w.status==="expired_token"||w.status==="access_denied")&&(K.error(w.error||"GitHub authorization failed"),m(null),g())}catch(w){console.warn("GitHub polling failed:",w)}})()},f),()=>{h.current!=null&&(window.clearInterval(h.current),h.current=null)}},[u,f,y,o,t,g]);const b=i.useCallback(async()=>{d(!0);try{if(g(),m(null),t)await t.authDisconnect();else{const w=await fetch("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}});if(!w.ok)throw new Error(w.statusText)}K.success("GitHub disconnected"),await o(t,{force:!0})}catch(w){console.error("Failed to disconnect GitHub:",w),K.error("Failed to disconnect GitHub")}finally{d(!1)}},[o,t,g]),v=i.useCallback(async w=>{if(w){d(!0);try{const C=t?await t.authActivate(w):await(async()=>{const S=await fetch("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:w})}),M=await S.json().catch(()=>null);if(!S.ok||!M)throw new Error(M?.error||S.statusText);return M})();a(C),K.success("GitHub account switched")}catch(C){console.error("Failed to switch GitHub account:",C),K.error("Failed to switch GitHub account")}finally{d(!1)}}},[t,a]);if(r)return null;const j=!!s?.connected,k=s?.user,N=s?.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."})]}),j?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:[k?.avatarUrl?e.jsx("img",{src:k.avatarUrl,alt:k.login?`${k.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:k?.name?.trim()||k?.login||"GitHub"}),k?.email?e.jsx("div",{className:"typography-body text-muted-foreground truncate",children:k.email}):null,e.jsxs("div",{className:"mt-1 flex items-center gap-2 typography-meta text-muted-foreground truncate",children:[e.jsx(uo,{className:"h-4 w-4"}),e.jsx("span",{className:"font-mono",children:k?.login||"unknown"})]}),s?.scope?e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:["Scopes: ",s.scope]}):null]})]}),e.jsx(Me,{variant:"outline",onClick:b,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(Me,{onClick:x,disabled:c,children:"Connect"})]}),j?e.jsx("div",{className:"flex justify-end",children:e.jsx(Me,{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(w=>{const C=w.user,S=!!w.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:[C?.avatarUrl?e.jsx("img",{src:C.avatarUrl,alt:C.login?`${C.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(uo,{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:C?.name?.trim()||C?.login||"GitHub"}),C?.login?e.jsx("div",{className:"typography-micro text-muted-foreground truncate font-mono",children:C.login}):null]})]}),S?e.jsx("span",{className:"typography-micro text-primary",children:"Active"}):e.jsx(Me,{size:"sm",variant:"ghost",onClick:()=>v(w.id),disabled:c,children:"Use"})]},w.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 IKanban"}),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(Me,{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(Me,{variant:"ghost",disabled:c,onClick:()=>{g(),m(null)},children:"Cancel"})})]}):null]})},QT=({children:t,title:s,description:r,divider:n=!1,className:o})=>e.jsxs("div",{className:L(n&&"border-t border-border/40 pt-6",o),children:[(s||r)&&e.jsxs("div",{className:"mb-4 space-y-1",children:[s&&e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:s}),r&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:r})]}),t]}),Qa=({value:t,onChange:s,min:r=0,max:n=1,step:o=.1,disabled:a=!1,className:l,label:c,valueFormatter:d=u=>u.toFixed(1)})=>e.jsxs("div",{className:L("flex items-center gap-3",l),children:[e.jsx("div",{className:"flex-1 relative",children:e.jsx("input",{type:"range",min:r,max:n,step:o,value:t,onChange:u=>s(parseFloat(u.target.value)),disabled:a,className:L("w-full h-2 rounded-lg appearance-none cursor-pointer bg-muted","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","disabled:cursor-not-allowed disabled:opacity-50","[&::-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","[&::-webkit-slider-thumb]:shadow-md [&::-webkit-slider-thumb]:transition-transform","[&::-webkit-slider-thumb]:hover:scale-110 [&::-webkit-slider-thumb]:active:scale-95","[&::-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 [&::-moz-range-thumb]:shadow-md"),"aria-label":c,"aria-valuemin":r,"aria-valuemax":n,"aria-valuenow":t})}),e.jsx("span",{className:"typography-mono text-xs text-muted-foreground min-w-[3ch] text-right",children:d(t)})]}),YT=[{value:"en-US",label:"English"},{value:"es-ES",label:"Español"},{value:"fr-FR",label:"Français"},{value:"de-DE",label:"Deutsch"},{value:"ja-JP",label:"日本語"},{value:"zh-CN",label:"中文"},{value:"pt-BR",label:"Português"},{value:"it-IT",label:"Italiano"},{value:"ko-KR",label:"한국어"},{value:"uk-UA",label:"Українська"}],JT=()=>{const{isSupported:t,language:s,setLanguage:r}=by(),{voiceProvider:n,setVoiceProvider:o,speechRate:a,setSpeechRate:l,speechPitch:c,setSpeechPitch:d,speechVolume:u,setSpeechVolume:m,sayVoice:f,setSayVoice:p,browserVoice:h,setBrowserVoice:g,openaiVoice:x,setOpenaiVoice:y,openaiApiKey:b,setOpenaiApiKey:v,showMessageTTSButtons:j,setShowMessageTTSButtons:k,voiceModeEnabled:N,setVoiceModeEnabled:w,summarizeMessageTTS:C,setSummarizeMessageTTS:S,summarizeVoiceConversation:M,setSummarizeVoiceConversation:D,summarizeCharacterThreshold:A,setSummarizeCharacterThreshold:P,summarizeMaxLength:$,setSummarizeMaxLength:R}=ut(),[O,T]=ne.useState(!1),[_,F]=ne.useState([]),[I,E]=ne.useState(!1),[W,V]=ne.useState(null),[ve,oe]=ne.useState(!1),[Z,ce]=ne.useState(!1),[Q,Y]=ne.useState(null),[ie,B]=ne.useState([]),[se,H]=ne.useState(!1);ne.useEffect(()=>((async()=>{const G=await ws.waitForVoices();B(G)})(),"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=()=>{B(window.speechSynthesis.getVoices())}),()=>{"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=null)}),[]);const le=ne.useMemo(()=>ie.filter(X=>X.lang).sort((X,G)=>{const ae=X.lang.startsWith("en"),me=G.lang.startsWith("en");if(ae&&!me)return-1;if(!ae&&me)return 1;const Oe=X.lang.localeCompare(G.lang);return Oe!==0?Oe:X.name.localeCompare(G.name)}),[ie]),ge=ne.useCallback(()=>{if(se){ws.cancelSpeech(),H(!1);return}const X=ie.find(Oe=>Oe.name===h),ae=`Hello! I'm ${X?.name??"your browser voice"}. This is how I sound.`;H(!0);const me=new SpeechSynthesisUtterance(ae);me.rate=a,me.pitch=c,me.volume=u,X&&(me.voice=X,me.lang=X.lang),me.onend=()=>H(!1),me.onerror=()=>H(!1),window.speechSynthesis.cancel(),window.speechSynthesis.speak(me)},[h,ie,a,c,u,se]);ne.useEffect(()=>()=>{se&&ws.cancelSpeech()},[se]);const z=[{value:"alloy",label:"Alloy"},{value:"ash",label:"Ash"},{value:"ballad",label:"Ballad"},{value:"coral",label:"Coral"},{value:"echo",label:"Echo"},{value:"fable",label:"Fable"},{value:"nova",label:"Nova"},{value:"onyx",label:"Onyx"},{value:"sage",label:"Sage"},{value:"shimmer",label:"Shimmer"},{value:"verse",label:"Verse"},{value:"marin",label:"Marin"},{value:"cedar",label:"Cedar"}];ne.useEffect(()=>{(async()=>{try{const ae=await(await fetch("/api/tts/status")).json();console.log("[VoiceSettings] OpenAI TTS status:",ae);const me=ae.available,Oe=b.trim().length>0;oe(me||Oe)}catch(G){console.error("[VoiceSettings] Failed to check OpenAI TTS status:",G),oe(b.trim().length>0)}})()},[b]),ne.useEffect(()=>{fetch("/api/tts/say/status").then(X=>X.json()).then(X=>{if(console.log("[VoiceSettings] Say TTS status:",X),T(X.available),X.voices){const G=X.voices.filter((ae,me,Oe)=>Oe.findIndex(Be=>Be.name===ae.name)===me).sort((ae,me)=>ae.name.localeCompare(me.name));F(G)}}).catch(X=>{console.error("[VoiceSettings] Failed to check Say TTS status:",X),T(!1)})},[]);const J=ne.useCallback(async()=>{if(W){W.pause(),W.currentTime=0,V(null),E(!1);return}E(!0);try{const X=await fetch("/api/tts/say/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:`Hello! I'm ${f}. This is how I sound.`,voice:f,rate:Math.round(100+(a-.5)*200)})});if(!X.ok)throw new Error("Preview failed");const G=await X.blob(),ae=URL.createObjectURL(G),me=new Audio(ae);me.onended=()=>{URL.revokeObjectURL(ae),V(null),E(!1)},me.onerror=()=>{URL.revokeObjectURL(ae),V(null),E(!1)},V(me),await me.play()}catch(X){console.error("Voice preview failed:",X),E(!1)}},[f,a,W]);ne.useEffect(()=>()=>{W&&W.pause()},[W]);const je=ne.useCallback(async()=>{if(Q){Q.pause(),Q.currentTime=0,Y(null),ce(!1);return}ce(!0);try{const X=await fetch("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:`Hello! I'm ${x}. This is how I sound.`,voice:x,speed:a,apiKey:b||void 0})});if(!X.ok){const Oe=await X.json().catch(()=>({error:"Unknown error"}));throw new Error(Oe.error||`HTTP ${X.status}`)}const G=await X.blob(),ae=URL.createObjectURL(G),me=new Audio(ae);me.onended=()=>{URL.revokeObjectURL(ae),Y(null),ce(!1)},me.onerror=()=>{URL.revokeObjectURL(ae),Y(null),ce(!1)},Y(me),await me.play()}catch(X){console.error("[VoiceSettings] OpenAI voice preview failed:",X),ce(!1)}},[x,a,Q,b]);return ne.useEffect(()=>()=>{Q&&Q.pause()},[Q]),e.jsx(QT,{title:"Voice",description:"Configure voice conversation settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Od,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Voice Mode"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enable voice conversations with microphone input"})]}),e.jsx(nr,{checked:N,onCheckedChange:w,"aria-label":"Toggle voice mode"})]}),N&&e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ma,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Voice Provider"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Choose your preferred text-to-speech provider"})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap justify-end",children:[e.jsx(Me,{variant:n==="browser"?"default":"outline",size:"sm",onClick:()=>o("browser"),className:"min-w-[80px]",children:"Browser"}),e.jsx(Me,{variant:n==="openai"?"default":"outline",size:"sm",onClick:()=>o("openai"),className:"min-w-[80px]",title:ve?"OpenAI voice":"OpenAI voice unavailable - API key not configured",children:"OpenAI"}),O&&e.jsxs(Me,{variant:n==="say"?"default":"outline",size:"sm",onClick:()=>o("say"),className:"min-w-[80px]",children:[e.jsx(Nm,{className:"w-4 h-4 mr-1"}),"Say"]})]})]}),N&&e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 border border-border/50",children:e.jsxs("p",{className:"typography-micro text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:n==="browser"?"Browser Voice:":n==="openai"?"OpenAI:":"macOS Say:"})," ",n==="browser"?"Free, works offline, but has limited mobile support. Best for desktop use.":n==="openai"?"Higher quality voice synthesis that works reliably on mobile. Requires OpenAI API key.":"Native macOS speech synthesis. Free, fast, and works offline. Desktop only."]})}),N&&n==="openai"&&!ve&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-destructive/10 border border-destructive/20",children:[e.jsx(tc,{className:"w-5 h-5 text-destructive flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui text-destructive font-medium",children:"OpenAI voice unavailable"}),e.jsx("p",{className:"typography-micro text-destructive/80",children:"OpenAI voice requires an OpenAI API key to be configured. Please set the OpenAI API key or switch to Browser voice."})]})]}),N&&n==="openai"&&e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pg,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"OpenAI API Key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:ve&&!b?"Using API key from OpenCode configuration":"Enter your OpenAI API key for voice synthesis"})]}),e.jsxs("div",{className:"flex items-center gap-2 w-[280px]",children:[e.jsx("input",{type:"password",value:b,onChange:X=>v(X.target.value),placeholder:"sk-...",className:"flex-1 px-3 py-2 text-sm bg-background border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring"}),b&&e.jsx(Me,{size:"icon",variant:"ghost",onClick:()=>v(""),title:"Clear API key",children:e.jsx(hs,{className:"w-4 h-4"})})]})]}),N&&n==="openai"&&ve&&e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ma,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"OpenAI Voice"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select an OpenAI voice for text-to-speech"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($s,{value:x,onValueChange:y,children:[e.jsx(Bs,{className:"w-[160px]","aria-label":"Select OpenAI voice",children:e.jsx(Sr,{placeholder:"Select voice"})}),e.jsx(zs,{className:"max-h-[300px]",children:z.map(X=>e.jsx(ns,{value:X.value,children:X.label},X.value))})]}),e.jsx(Me,{size:"icon",variant:"outline",onClick:je,disabled:!ve,title:Z?"Stop preview":"Preview voice",children:Z?e.jsx(il,{className:"w-4 h-4"}):e.jsx(Mc,{className:"w-4 h-4"})})]})]}),N&&n==="say"&&O&&_.length>0&&e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nm,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"macOS Voice"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a voice installed on your Mac"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($s,{value:f,onValueChange:p,children:[e.jsx(Bs,{className:"w-[160px]","aria-label":"Select macOS voice",children:e.jsx(Sr,{placeholder:"Select voice"})}),e.jsx(zs,{className:"max-h-[300px]",children:_.map(X=>e.jsx(ns,{value:X.name,children:X.name},X.name))})]}),e.jsx(Me,{size:"icon",variant:"outline",onClick:J,title:I?"Stop preview":"Preview voice",children:I?e.jsx(il,{className:"w-4 h-4"}):e.jsx(Mc,{className:"w-4 h-4"})})]})]}),N&&n==="browser"&&le.length>0&&e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lj,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Browser Voice"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a voice from your browser"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($s,{value:h||"__auto__",onValueChange:X=>g(X==="__auto__"?"":X),children:[e.jsx(Bs,{className:"w-[200px]","aria-label":"Select browser voice",children:e.jsx(Sr,{placeholder:"Auto (default)"})}),e.jsxs(zs,{className:"max-h-[300px]",children:[e.jsx(ns,{value:"__auto__",children:"Auto (default)"}),le.map(X=>e.jsxs(ns,{value:X.name,children:[X.name," (",X.lang,")"]},X.name))]})]}),e.jsx(Me,{size:"icon",variant:"outline",onClick:ge,title:se?"Stop preview":"Preview voice",children:se?e.jsx(il,{className:"w-4 h-4"}):e.jsx(Mc,{className:"w-4 h-4"})})]})]}),N&&e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Od,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Language"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Language for speech recognition and synthesis"})]}),e.jsxs($s,{value:s,onValueChange:r,disabled:!t,children:[e.jsx(Bs,{className:"w-[180px]","aria-label":"Select language",children:e.jsx(Sr,{placeholder:"Select language"})}),e.jsx(zs,{children:YT.map(X=>e.jsx(ns,{value:X.value,children:X.label},X.value))})]})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ma,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Message Read Aloud"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Show speaker button on AI responses to read them aloud"})]}),e.jsx(nr,{checked:j,onCheckedChange:k,"aria-label":"Toggle message TTS buttons"})]}),e.jsxs("div",{className:"pt-4 border-t border-border/40 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Eo,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground font-medium",children:"Summarization"})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"Summarize Message Playback"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Summarize long messages before reading them aloud"})]}),e.jsx(nr,{checked:C,onCheckedChange:S,"aria-label":"Toggle message TTS summarization"})]}),N&&e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"Summarize Voice Responses"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Summarize long AI responses during voice conversations"})]}),e.jsx(nr,{checked:M,onCheckedChange:D,"aria-label":"Toggle voice conversation summarization"})]}),(C||M)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"Character Threshold"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Summarize text longer than this (",A," chars)"]})]}),e.jsx("div",{className:"w-[180px]",children:e.jsx(Qa,{value:A,onChange:P,min:50,max:2e3,step:50,label:"Character threshold",valueFormatter:X=>`${X}`})})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"Summary Length Limit"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Max characters for the summary (",$," chars)"]})]}),e.jsx("div",{className:"w-[180px]",children:e.jsx(Qa,{value:$,onChange:R,min:50,max:2e3,step:50,label:"Summary length limit",valueFormatter:X=>`${X}`})})]})]})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cj,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Speech Rate"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Speed of speech (0.5x - 2x)"})]}),e.jsx("div",{className:"w-[180px]",children:e.jsx(Qa,{value:a,onChange:l,min:.5,max:2,step:.1,disabled:!t,label:"Speech rate",valueFormatter:X=>`${X.toFixed(1)}x`})})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dj,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Speech Pitch"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Voice pitch (0.5 - 2)"})]}),e.jsx("div",{className:"w-[180px]",children:e.jsx(Qa,{value:c,onChange:d,min:.5,max:2,step:.1,disabled:!t,label:"Speech pitch"})})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uj,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Speech Volume"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Voice volume (0 - 100%)"})]}),e.jsx("div",{className:"w-[180px]",children:e.jsx(Qa,{value:u,onChange:m,min:0,max:1,step:.1,disabled:!t,label:"Speech volume",valueFormatter:X=>`${Math.round(X*100)}%`})})]}),N&&t&&e.jsx("div",{className:"pt-4 border-t border-border/40",children:e.jsxs("p",{className:"typography-micro text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Tip:"})," ","Press ",e.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-muted typography-mono text-xs",children:"Shift"})," +"," ",e.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-muted typography-mono text-xs",children:"Click"})," ","on the voice button to quickly toggle continuous mode"]})})]})})},gb=()=>{const[t,s]=ne.useState(""),[r,n]=ne.useState(!0),[o,a]=ne.useState(!1);ne.useEffect(()=>{let d=!1;return(async()=>{try{const u=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!u.ok)return;const m=await u.json().catch(()=>null);if(d||!m)return;const f=typeof m.opencodeBinary=="string"?m.opencodeBinary.trim():"";s(f)}catch{}finally{d||n(!1)}})(),()=>{d=!0}},[]);const l=ne.useCallback(async()=>{if(typeof window>"u"||!Lr()||!As())return;const d=window.__TAURI__;if(d?.dialog?.open)try{const u=await d.dialog.open({title:"Select opencode binary",multiple:!1,directory:!1});typeof u=="string"&&u.trim().length>0&&s(u.trim())}catch{}},[]),c=ne.useCallback(async()=>{a(!0);try{await xs({opencodeBinary:t.trim()}),await ei({message:"Restarting OpenCode…",mode:"projects",scopes:["all"]})}finally{a(!1)}},[t]);return 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:"OpenCode CLI"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Optional absolute path to the ",e.jsx("code",{className:"font-mono text-xs",children:"opencode"})," binary. Useful when your desktop app launch environment has a stale PATH. If your ",e.jsx("code",{className:"font-mono text-xs",children:"opencode"})," shim requires Node/Bun (e.g. ",e.jsx("code",{className:"font-mono text-xs",children:"env node"})," or ",e.jsx("code",{className:"font-mono text-xs",children:"env bun"}),"), make sure that runtime is installed."]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Bt,{value:t,onChange:d=>s(d.target.value),placeholder:"/Users/you/.bun/bin/opencode",disabled:r||o,className:"flex-1 font-mono text-xs"}),e.jsx(Me,{type:"button",variant:"secondary",onClick:l,disabled:r||o||!Lr()||!As(),children:"Browse"}),e.jsx(Me,{type:"button",onClick:c,disabled:r||o,children:o?"Saving…":"Save + Reload"})]}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Tip: you can also use ",e.jsx("span",{className:"font-mono",children:"OPENCODE_BINARY"})," env var, but this setting persists in",e.jsx("span",{className:"font-mono",children:" ~/.config/ikanban/settings.json"}),"."]})]})},XT=({section:t})=>{const{isMobile:s}=ks(),r=s&&_o(),n=gs();if(!t)return e.jsx(Ut,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"ikanban-page-body mx-auto max-w-3xl space-y-3 p-3 sm:space-y-6 sm:p-6",children:[e.jsx(cm,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(hb,{})}),!n&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gb,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(pb,{})}),r&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(ub,{})})]})});const o=()=>{switch(t){case"visual":return e.jsx(ZT,{});case"chat":return e.jsx(eE,{});case"sessions":return e.jsx(tE,{});case"git":return e.jsx(sE,{});case"github":return e.jsx(rE,{});case"notifications":return e.jsx(nE,{});case"voice":return e.jsx(oE,{});default:return null}};return e.jsx(Ut,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsx("div",{className:"ikanban-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:o()})})},ZT=()=>e.jsx(cm,{visibleSettings:["theme","fontSize","terminalFontSize","spacing","cornerRadius","inputBarOffset","terminalQuickKeys"]}),eE=()=>e.jsx(cm,{visibleSettings:["toolOutput","diffLayout","dotfiles","reasoning","textJustificationActivity","queueMode","persistDraft"]}),tE=()=>{const t=gs();return e.jsxs("div",{className:"space-y-6",children:[e.jsx(hb,{}),!t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gb,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(pb,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(UT,{})})]})},sE=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(WT,{}),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(GT,{})]})]}),rE=()=>gs()?null:e.jsx(qT,{}),nE=()=>e.jsx(KT,{}),oE=()=>gs()?null:e.jsx(JT,{}),aE=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Zen Model","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"]},{id:"voice",label:"Voice",items:["Language","Continuous Mode"],badge:"experimental",hideInVSCode:!0}],iE=({selectedSection:t,onSelectSection:s})=>{const{isMobile:r}=ks(),n=r&&_o(),[o,a]=i.useState(!1),l=i.useMemo(()=>gs(),[]),c=i.useMemo(()=>_o(),[]),d=!l,u=i.useCallback(async()=>{a(!0);try{await ei({message:"Restarting OpenCode…",mode:"projects",scopes:["all"]})}finally{a(!1)}},[]),m=i.useMemo(()=>aE.filter(p=>!(p.webOnly&&!c||p.hideInVSCode&&l)),[c,l]),f=l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:L("grid h-full min-h-0 grid-rows-[minmax(0,1fr)_auto]",f),children:[e.jsx("div",{className:"min-h-0",children:e.jsx(Ut,{outerClassName:"h-full",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:m.map(p=>{const h=t===p.id;return e.jsx("div",{className:L("group relative rounded-md px-1.5 py-1 transition-all duration-200",h?"bg-interactive-selection":"hover:bg-interactive-hover"),children:e.jsxs("button",{onClick:()=>s(p.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.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label font-normal text-foreground",children:p.label}),p.badge&&e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border border-[var(--status-warning-border)] px-1.5 py-0.5 rounded",children:p.badge})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 leading-tight",children:p.items.join(" · ")})]})},p.id)})})}),(d||n)&&e.jsx("div",{className:L("border-t border-border bg-sidebar",n?"px-3 py-3 space-y-3":"flex-shrink-0 h-12 px-2"),children:n?e.jsxs(e.Fragment,{children:[d&&e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsxs("button",{type:"button",className:L("flex h-8 w-full items-center gap-2 rounded-md px-2","text-sm font-semibold text-sidebar-foreground/90","hover:text-sidebar-foreground hover:bg-interactive-hover","transition-all duration-200","disabled:pointer-events-none disabled:opacity-50"),onClick:()=>{u()},disabled:o,children:[e.jsx(jr,{className:"h-4 w-4"}),o?"Reloading OpenCode…":"Reload OpenCode"]})}),e.jsx(ht,{children:"Restart OpenCode and reload its configuration (agents, commands, skills, providers)."})]}),e.jsx(ub,{})]}):e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[d&&e.jsxs(gt,{delayDuration:300,children:[e.jsx(xt,{asChild:!0,children:e.jsxs("button",{type:"button",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-interactive-hover","transition-all duration-200","disabled:pointer-events-none disabled:opacity-50"),onClick:()=>{u()},disabled:o,children:[e.jsx(jr,{className:"h-4 w-4"}),o?"Reloading OpenCode…":"Reload OpenCode"]})}),e.jsx(ht,{children:"Restart OpenCode and reload its configuration (agents, commands, skills, providers)."})]}),e.jsx("div",{})]})})]})},lE=t=>{let s=cb.filter(o=>o.id!=="sessions");t&&(s=s.filter(o=>o.id!=="git-identities"));const r=s.find(o=>o.id==="settings"),n=s.filter(o=>o.id!=="settings");return r?[r,...n]:s},Ad=200,Dd=500,cE=264,dE=1024,dm=({onClose:t,forceMobile:s,isWindowed:r})=>{const n=ks(),o=s??n.isMobile,a=Te(se=>se.sidebarSection),l=Te(se=>se.setSidebarSection),c=i.useMemo(()=>a!=="sessions"?a:"settings",[a]),d=i.useCallback(se=>{l(se)},[l]),[u,m]=i.useState("visual"),[f,p]=i.useState(!1),[h,g]=i.useState(()=>typeof window<"u"?Math.min(Dd,Math.max(Ad,Math.floor(window.innerWidth*.2))):cE),[x,y]=i.useState(!1),[b,v]=i.useState(!1),[j,k]=i.useState(0),N=i.useRef(null),w=i.useRef(0),C=i.useRef(h),S=i.useMemo(()=>typeof window>"u"?!1:!!window.__TAURI__,[]),M=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),D=i.useMemo(()=>gs(),[]),A=i.useMemo(()=>lE(D),[D]),P=S;i.useEffect(()=>{const se=N.current;if(!se)return;const H=new ResizeObserver(le=>{for(const ge of le)k(ge.contentRect.width)});return H.observe(se),k(se.clientWidth),()=>H.disconnect()},[]);const $=ps(se=>se.projects),R=ps(se=>se.activeProjectId),O=ps(se=>se.setActiveProject),T=i.useMemo(()=>[...$].sort((se,H)=>(se.label||se.path).localeCompare(H.label||H.path)),[$]),_=i.useMemo(()=>T.length===0?null:T.find(se=>se.id===R)??T[0],[R,T]),F=i.useCallback(se=>se.replace(/[-_]/g," ").replace(/\b\w/g,H=>H.toUpperCase()),[]),I=i.useMemo(()=>{if(!_)return"Project";const se=_.label&&_.label.trim().length>0?_.label:_.path.split("/").filter(Boolean).pop()||_.path;return F(se)},[_,F]),E=T.length>0&&!D,W=j===0||j>=dE;i.useEffect(()=>{if(c==="agents"){setTimeout(()=>{bo.getState().loadAgents()},0);return}if(c==="commands"){setTimeout(()=>{yo.getState().loadCommands()},0);return}c==="skills"&&(pn.getState().loadSkills(),ji.getState().loadCatalog())},[R,c]),i.useEffect(()=>{if(typeof window>"u")return;const se=()=>{if(!x){const H=Math.min(Dd,Math.max(Ad,Math.floor(window.innerWidth*.2)));g(H)}};return window.addEventListener("resize",se),()=>window.removeEventListener("resize",se)},[x]),i.useEffect(()=>{if(!b)return;const se=le=>{const ge=le.clientX-w.current,z=Math.min(Dd,Math.max(Ad,C.current+ge));g(z),y(!0)},H=()=>v(!1);return window.addEventListener("pointermove",se),window.addEventListener("pointerup",H,{once:!0}),()=>{window.removeEventListener("pointermove",se),window.removeEventListener("pointerup",H)}},[b]);const V=se=>{v(!0),w.current=se.clientX,C.current=h,se.preventDefault()},ve=i.useCallback(async se=>{if(!se.target.closest("button, a, input, select, textarea")&&se.button===0&&P)try{const{getCurrentWindow:H}=await Ks(async()=>{const{getCurrentWindow:ge}=await import("@tauri-apps/api/window");return{getCurrentWindow:ge}},[]);await H().startDragging()}catch(H){console.error("Failed to start window dragging:",H)}},[P]),oe=i.useCallback(async se=>{if(se.button===0&&P)try{const{getCurrentWindow:H}=await Ks(async()=>{const{getCurrentWindow:ge}=await import("@tauri-apps/api/window");return{getCurrentWindow:ge}},[]);await H().startDragging()}catch(H){console.error("Failed to start window dragging:",H)}},[P]),Z=i.useCallback(se=>{d(se),p(!1)},[d]),ce=i.useCallback(()=>{o&&p(!0)},[o]),Q=()=>{switch(c){case"settings":return e.jsx("div",{className:"h-full",children:e.jsx(iE,{selectedSection:u,onSelectSection:se=>{m(se),ce()}})});case"agents":return e.jsx(eT,{onItemSelect:ce});case"commands":return e.jsx(cT,{onItemSelect:ce});case"skills":return e.jsx(uT,{onItemSelect:ce});case"providers":return e.jsx(jT,{onItemSelect:ce});case"usage":return e.jsx(DT,{onItemSelect:ce});case"git-identities":return e.jsx(RT,{onItemSelect:ce});default:return null}},Y=()=>{switch(c){case"agents":return e.jsx(lT,{});case"commands":return e.jsx(dT,{});case"skills":return e.jsx(vT,{});case"providers":return e.jsx(MT,{});case"usage":return e.jsx(TT,{});case"git-identities":return e.jsx(_T,{});case"settings":return e.jsx(XT,{section:u});default:return null}},ie=Ys(),B=i.useMemo(()=>r?"pl-1.5":P&&M?"pl-[5.75rem]":"",[P,M,r]);return e.jsxs("div",{ref:N,"data-settings-view":"true",className:L("flex h-full flex-col overflow-hidden bg-background"),children:[e.jsxs("div",{onMouseDown:o?void 0:ve,className:L("flex select-none items-center justify-between border-b",o?"h-auto px-3 py-2":"app-region-drag h-12",!o&&B,P?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80"),style:{borderColor:"var(--interactive-border)"},children:[o&&f&&e.jsx("button",{type:"button",onClick:()=>p(!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(ju,{className:"h-5 w-5"})}),o&&e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:L("flex items-center",o?"gap-1":"h-full"),children:e.jsx("div",{className:L("flex items-center gap-1",!o&&"p-1 bg-background/50 rounded-lg"),children:A.map(({id:se,label:H,icon:le})=>{const ge=c===se,z=le;return o?e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{onClick:()=>Z(se),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",ge?"bg-interactive-selection text-interactive-selection-foreground shadow-sm":"text-muted-foreground hover:bg-interactive-hover/50"),"aria-pressed":ge,"aria-label":H,children:e.jsx(z,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(ht,{children:e.jsx("p",{children:H})})]},se):e.jsxs("button",{onClick:()=>Z(se),onMouseDown:ge?oe:void 0,className:L("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",ge?"app-region-drag bg-interactive-selection text-interactive-selection-foreground shadow-sm":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-pressed":ge,"aria-label":H,children:[e.jsx(z,{className:"h-4 w-4",weight:"regular"}),W&&e.jsx("span",{children:H})]},se)})})}),(t||E)&&e.jsxs("div",{className:L("flex items-center gap-2",o?"":"pr-3"),children:[E&&e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:o?e.jsx("button",{type:"button","aria-label":"Switch project",title:I,className:"inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary border border-[var(--interactive-border)]",children:e.jsx(Fn,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:I,className:L("flex h-9 max-w-[18rem] items-center gap-1.5 bg-transparent px-2 rounded-lg text-foreground outline-none hover:bg-interactive-hover/50 focus-visible:ring-2 focus-visible:ring-ring border border-[var(--interactive-border)]",!o&&"app-region-no-drag"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:I}),e.jsx(is,{className:"size-4 opacity-50"})]})}),e.jsx(fs,{align:"end",className:"w-auto",children:e.jsx(Il,{value:_?.id??"",onValueChange:se=>{se&&O(se)},children:T.map(se=>{const H=se.label?.trim()?se.label.trim():se.path.split("/").filter(Boolean).pop()||se.path,le=F(H);return e.jsx(Tl,{value:se.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:le})},se.id)})})})]}),t&&e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{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 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",!o&&"app-region-no-drag"),children:e.jsx(hs,{className:"h-5 w-5"})})}),e.jsx(ht,{children:e.jsxs("p",{children:["Close Settings (",ie,"+,)"]})})]})]})]}),e.jsx("div",{className:"flex flex-1 overflow-hidden",children:o?f?e.jsx("div",{className:"flex-1 overflow-hidden bg-background","data-keyboard-avoid":"true",children:e.jsx(Gs,{children:Y()})}):e.jsx("div",{className:L("flex-1 overflow-hidden",D?"bg-background":"bg-sidebar"),children:e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx(Gs,{children:Q()})})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:L("relative flex h-full min-h-0 flex-col overflow-hidden border-r",P?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":D?"bg-background":"bg-sidebar",b?"transition-none":""),style:{width:`${h}px`,minWidth:`${h}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:V,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx(Gs,{children:Q()})})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(Gs,{children:Y()})})]})})]})},uE=({open:t,onOpenChange:s})=>{const r=i.useId();return e.jsx(eg,{open:t,onOpenChange:s,children:e.jsxs(sg,{children:[e.jsx(bu,{className:"fixed inset-0 z-50 bg-black/50 backdrop-blur-md"}),e.jsxs(tg,{"aria-describedby":r,className:L("fixed z-50 top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%]","w-[90vw] max-w-[1200px] h-[85vh] max-h-[900px]","rounded-xl border shadow-2xl overflow-hidden","bg-background"),children:[e.jsx(rg,{id:r,className:"sr-only",children:"IKanban settings window."}),e.jsx(dm,{onClose:()=>s(!1),isWindowed:!0})]})]})})},mE=()=>{const{isSidebarOpen:o,isRightSidebarOpen:a,isBottomTerminalOpen:l,setRightSidebarOpen:c,setBottomTerminalOpen:d,activeMainTab:u,setIsMobile:m,isSessionSwitcherOpen:f,isSettingsDialogOpen:p,setSettingsDialogOpen:h,isMultiRunLauncherOpen:g,setMultiRunLauncherOpen:x,multiRunLauncherPrefillPrompt:y}=Te(),{isMobile:b}=ks(),v=i.useRef(!1),j=i.useRef(!1);IM({enabled:!0});const k=ac(C=>C.checkForUpdates);i.useEffect(()=>{const C=setTimeout(()=>{k()},3e3);return()=>clearTimeout(C)},[k]),i.useEffect(()=>{Te.getState().isMobile!==b&&m(b)},[b,m]),i.useEffect(()=>{if(typeof window>"u")return;let C;const S=()=>{C!==void 0&&window.clearTimeout(C),C=window.setTimeout(()=>{Te.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",S),()=>{window.removeEventListener("resize",S),C!==void 0&&window.clearTimeout(C)}},[]),i.useEffect(()=>{if(typeof window>"u")return;let C;const S=()=>{const D=Te.getState(),A=window.innerWidth,P=window.innerHeight,$=A<1140,R=A>=1220;$?D.isRightSidebarOpen&&(c(!1),v.current=!0):R&&v.current&&(c(!0),v.current=!1);const O=P<640,T=P>=700;O?D.isBottomTerminalOpen&&(d(!1),j.current=!0):T&&j.current&&(d(!0),j.current=!1)},M=()=>{C!==void 0&&window.clearTimeout(C),C=window.setTimeout(()=>{S()},100)};return S(),window.addEventListener("resize",M),()=>{window.removeEventListener("resize",M),C!==void 0&&window.clearTimeout(C)}},[d,c]),i.useEffect(()=>{if(typeof window>"u")return;const C=Te.subscribe((S,M)=>{const D=window.innerWidth,A=window.innerHeight,P=D>=1220,$=A>=700;S.isRightSidebarOpen!==M.isRightSidebarOpen&&P&&(v.current=!1),S.isBottomTerminalOpen!==M.isBottomTerminalOpen&&$&&(j.current=!1)});return()=>{C()}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const C=document.documentElement;let S=0,M=!1,D=0,A=null;const P=Te.getState().setKeyboardOpen,$=()=>{A&&(A.style.setProperty("--oc-keyboard-avoid-offset","0px"),A.removeAttribute("data-keyboard-avoid-active"),A=null)},R=W=>{if(!W)return null;const V=W.getAttribute("data-keyboard-avoid-target-id");if(V){const oe=document.getElementById(V);if(oe instanceof HTMLElement)return oe}const ve=W.closest("[data-keyboard-avoid]");if(ve)return ve.getAttribute("data-keyboard-avoid")==="none"?null:ve;if(W.classList.contains("overlay-scrollbar-container")){const oe=W.parentElement;if(oe instanceof HTMLElement)return oe}return W},O=()=>{S=0,M=!0,C.style.setProperty("--oc-keyboard-inset","0px"),P(!1)},T=()=>{const W=window.visualViewport,V=W?Math.round(W.height):window.innerHeight,ve=W?Math.max(0,Math.round(W.offsetTop)):0;C.style.setProperty("--oc-visual-viewport-offset-top",`${ve}px`);const oe=document.activeElement,Z=oe?.tagName,Q=Z==="INPUT"||Z==="TEXTAREA"||Z==="SELECT"||!!oe?.isContentEditable,Y=Math.round(C.clientHeight||window.innerHeight),ie=V+ve,B=Math.max(0,Y-ie),H=B>=(Q?120:180)?B:0;if(M)H===0&&(M=!1),S=0;else if(S===0)H>0&&Q&&(S=H);else{const J=!Q&&V>D+6;H===0?(S=0,P(!1)):J?O():(H>0&&Q||H>S)&&(S=H,P(!0))}C.style.setProperty("--oc-keyboard-inset",`${S}px`),D=V;const ge=/iPad|iPhone|iPod/.test(navigator.userAgent)&&S>0?34:0;C.style.setProperty("--oc-keyboard-home-indicator",`${ge}px`);const z=Q?R(oe):null;if(!b||!z||!oe)$();else{z!==A&&($(),A=z);const J=ve+V,X=oe.getBoundingClientRect().bottom-J,G=8,ae=Math.max(S,H),me=X>G&&ae>0?Math.min(X,ae):0,Oe=A;Oe&&(Oe.style.setProperty("--oc-keyboard-avoid-offset",`${me}px`),Oe.setAttribute("data-keyboard-avoid-active","true"))}if(b&&Q){const J=document.scrollingElement;J&&J.scrollTop!==0&&(J.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};T();const _=window.visualViewport;_?.addEventListener("resize",T),_?.addEventListener("scroll",T),window.addEventListener("resize",T),window.addEventListener("orientationchange",T);const F=W=>{if(!W)return!1;const V=W.tagName;return V==="INPUT"||V==="TEXTAREA"||V==="SELECT"||W.isContentEditable},I=W=>{const V=W.target;F(V)&&(M=!1),T()};document.addEventListener("focusin",I,!0);const E=W=>{const V=W.target;if(!F(V))return;const ve=W.relatedTarget;F(ve)||window.requestAnimationFrame(()=>{if(F(document.activeElement))return;const oe=window.visualViewport,Z=oe?Math.round(oe.height):window.innerHeight,ce=oe?Math.max(0,Math.round(oe.offsetTop)):0,Q=Math.round(C.clientHeight||window.innerHeight),Y=Z+ce;if(Math.max(0,Q-Y)>0){T();return}O(),T()})};return document.addEventListener("focusout",E,!0),()=>{_?.removeEventListener("resize",T),_?.removeEventListener("scroll",T),window.removeEventListener("resize",T),window.removeEventListener("orientationchange",T),document.removeEventListener("focusin",I,!0),document.removeEventListener("focusout",E,!0),$()}},[b]);const N=i.useMemo(()=>{switch(u){case"plan":return e.jsx(xD,{});case"git":return e.jsx(ah,{});case"diff":return e.jsx(Yk,{});case"terminal":return e.jsx(dh,{});case"files":return e.jsx(qI,{});default:return null}},[u]),w=u==="chat";return e.jsx(Mk,{children:e.jsxs("div",{className:L("main-content-safe-area h-[100dvh]",b?"flex flex-col":"flex","bg-background"),children:[e.jsx(qC,{}),e.jsx(JC,{}),e.jsx(XC,{}),e.jsx(jM,{}),b?e.jsxs(e.Fragment,{children:[!(p||g)&&e.jsx(Pf,{}),e.jsxs("div",{className:L("flex flex-1 overflow-hidden",(p||g)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:[e.jsx("div",{className:L("flex-1 overflow-hidden bg-sidebar",!f&&"hidden"),children:e.jsx(Gs,{children:e.jsx(Ql,{mobileVariant:!0})})}),e.jsxs("main",{className:L("flex-1 overflow-hidden bg-background relative",f&&"hidden"),children:[e.jsx("div",{className:L("absolute inset-0",!w&&"invisible"),children:e.jsx(Gs,{children:e.jsx(oi,{})})}),N&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Gs,{children:N})})]})]}),g&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(Gs,{children:e.jsx(rp,{initialPrompt:y,onCreated:()=>x(!1),onCancel:()=>x(!1)})})}),p&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(Gs,{children:e.jsx(dm,{onClose:()=>h(!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",g&&"invisible"),children:[e.jsx(Pf,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx(BC,{isOpen:o,isMobile:b,children:e.jsx(Ql,{})}),e.jsxs("div",{className:"flex flex-1 min-w-0 flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:L("absolute inset-0",!w&&"invisible"),children:e.jsx(Gs,{children:e.jsx(oi,{})})}),N&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Gs,{children:N})})]}),e.jsx(zC,{isOpen:a,isMobile:b,children:e.jsx(Gs,{children:e.jsx(ah,{mode:"sidebar"})})})]}),e.jsx(SC,{isOpen:l,isMobile:b,children:e.jsx(Gs,{children:e.jsx(dh,{})})})]})]})]}),g&&e.jsx("div",{className:L("absolute inset-0 z-10 bg-background"),children:e.jsx(Gs,{children:e.jsx(rp,{initialPrompt:y,onCreated:()=>x(!1),onCancel:()=>x(!1)})})})]}),e.jsx(uE,{open:p,onOpenChange:h})]})]})})},fE=t=>{if(!t)return"-";try{return new Date(t).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}catch{return"-"}},pE=550,hE=1400,gE=280,xE=()=>{const t=Vr(),s=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),r=i.useMemo(()=>{const R=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof R=="string"&&R.trim().length>0?R.trim():null},[]),n=i.useRef(!1),o=i.useMemo(()=>{try{return!!Ae.getState().newSessionDraft?.open}catch{return!1}},[]),[a,l]=i.useState(()=>o?"chat":"sessions"),[c,d]=i.useState(0),u=i.useRef(null),m=Ae(R=>R.currentSessionId),f=Ae(R=>R.sessions),p=i.useMemo(()=>m?f.find(R=>R.id===m)?.title||"Session":null,[m,f]),h=Ae(R=>!!R.newSessionDraft?.open),g=Ae(R=>R.openNewSessionDraft),[x,y]=i.useState(()=>(typeof window<"u"?window.__IKANBAN_CONNECTION__?.status:"connecting")||"connecting"),b=ut(R=>R.isInitialized),v=ut(R=>R.initializeApp),j=Ae(R=>R.loadSessions),k=Ae(R=>R.loadMessages),N=Ae(R=>R.messages),[w,C]=i.useState(()=>b),[S,M]=i.useState(!1),D=i.useRef(0);i.useEffect(()=>{m&&l("chat")},[m]),i.useEffect(()=>{const R=t.vscode;R&&R.executeCommand("ikanban.setActiveSession",m,p)},[p,m,t.vscode]),i.useEffect(()=>{s!=="editor"&&!m&&!h&&a==="chat"&&l("sessions")},[m,h,a,s]);const A=i.useCallback(()=>{l("sessions")},[]);i.useEffect(()=>{const R=typeof window<"u"?window.__IKANBAN_CONNECTION__?.status:void 0;(R==="connected"||R==="connecting"||R==="error"||R==="disconnected")&&y(R);const O=T=>{const F=T.detail?.status;(F==="connected"||F==="connecting"||F==="error"||F==="disconnected")&&y(F)};return window.addEventListener("ikanban:connection-status",O),()=>window.removeEventListener("ikanban:connection-status",O)},[]),i.useEffect(()=>{const R=O=>{const _=O.detail?.view;_==="settings"?l("settings"):_==="chat"?l("chat"):_==="sessions"&&l("sessions")};return window.addEventListener("ikanban:navigate",R),()=>window.removeEventListener("ikanban:navigate",R)},[]),i.useEffect(()=>{(async()=>{if(S||w||x!=="connected")return;const O=Date.now();if(!(O-D.current<750)){D.current=O,M(!0);try{const T=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("ikanban_stream_debug")==="1"}catch{return!1}})();T&&console.log("[IKanban][VSCode][bootstrap] attempt",{configInitialized:b}),b||await v();const _=ut.getState();_.isConnected&&(_.providers.length===0&&await _.loadProviders(),_.agents.length===0&&await _.loadAgents());const F=ut.getState();if(!F.isInitialized||!F.isConnected||F.providers.length===0||F.agents.length===0)return;await j();const I=Ae.getState().error;if(T&&console.log("[IKanban][VSCode][bootstrap] post-load",{providers:F.providers.length,agents:F.agents.length,sessions:Ae.getState().sessions.length,sessionsError:I}),typeof I=="string"&&I.length>0)return;C(!0)}catch{}finally{M(!1)}}})()},[x,b,w,v,S,j]),i.useEffect(()=>{if(s==="editor"&&!n.current&&!(!w||x!=="connected")){if(!r){n.current=!0,g();return}f.some(R=>R.id===r)&&(n.current=!0,Ae.getState().setCurrentSession(r))}},[x,w,r,g,f,s]),i.useEffect(()=>{(async()=>{if(!(!w||x!=="connected"||a!=="chat"||h||!m||N.has(m)))try{await k(m)}catch{}})()},[x,m,a,w,k,N,h]),i.useEffect(()=>{const R=u.current;if(!R)return;const O=new ResizeObserver(T=>{for(const _ of T)d(_.contentRect.width)});return O.observe(R),d(R.clientWidth),()=>O.disconnect()},[]);const P=c>0&&c<pE,$=c>=hE;return i.useEffect(()=>{$&&a==="sessions"&&s==="sidebar"&&l("chat")},[$,a,s]),e.jsx("div",{ref:u,className:"h-full w-full bg-background text-foreground flex flex-col",children:s==="editor"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(sl,{title:f.find(R=>R.id===m)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Gs,{children:e.jsx(oi,{})})})]}):a==="settings"?e.jsx(dm,{onClose:()=>l($?"chat":"sessions"),forceMobile:P}):$?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:gE},children:e.jsx(Ql,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(sl,{title:h&&!m?"New session":f.find(R=>R.id===m)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Gs,{children:e.jsx(oi,{})})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:L("flex flex-col h-full",a!=="sessions"&&"hidden"),children:[e.jsx(sl,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ql,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>l("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}),e.jsxs("div",{className:L("flex flex-col h-full",a!=="chat"&&"hidden"),children:[e.jsx(sl,{title:h&&!m?"New session":f.find(R=>R.id===m)?.title||"Chat",showBack:!0,onBack:A,showMcp:!0,showContextUsage:!0,showRateLimits:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Gs,{children:e.jsx(oi,{})})})]})]})})},sl=({title:t,showBack:s,onBack:r,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:l,showContextUsage:c,showRateLimits:d})=>{const{getCurrentModel:u}=ut(),m=Ae(A=>A.getContextUsage),f=ts(A=>A.results),p=ts(A=>A.fetchAllQuotas),h=ts(A=>A.isLoading),g=ts(A=>A.lastUpdated),x=ts(A=>A.displayMode),y=ts(A=>A.dropdownProviderIds),b=ts(A=>A.loadSettings),v=ts(A=>A.setDisplayMode);Hu(),i.useEffect(()=>{b()},[b]);const j=u(),k=j?.limit&&typeof j.limit=="object"?j.limit:null,N=typeof k?.context=="number"?k.context:0,w=typeof k?.output=="number"?k.output:0,C=m(N,w),S=i.useMemo(()=>{const A=[];for(const P of yn){if(!y.includes(P.id))continue;const $=f.find(_=>_.providerId===P.id),R=$?.usage?.windows??{},O=Object.entries(R),T=$&&!$.ok&&$.configured?$.error:void 0;(O.length>0||T)&&A.push({providerId:P.id,providerName:P.name,entries:O,error:T})}return A},[y,f]),M=S.length>0,D=i.useCallback(async A=>{v(A);try{await xs({usageDisplayMode:A})}catch(P){console.warn("Failed to update usage display mode:",P)}},[v]);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:[s&&r&&e.jsx("button",{onClick:r,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(Mu,{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(Fs,{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(ci,{className:"h-5 w-5"})}),l&&e.jsx(Kx,{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"}),d&&e.jsxs(us,{onOpenChange:A=>{A&&f.length===0&&p()},children:[e.jsx(ms,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Rate limits",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",disabled:h,children:e.jsx(Fd,{className:"h-5 w-5"})})}),e.jsxs(fs,{align:"end",className:"w-80 max-h-[70vh] overflow-y-auto overflow-x-hidden bg-[var(--surface-elevated)] p-0",children:[e.jsx("div",{className:"sticky top-0 z-20 bg-[var(--surface-elevated)]",children:e.jsxs(Wr,{className:"flex items-center justify-between gap-3 typography-ui-header font-semibold text-foreground",children:[e.jsx("span",{children:"Rate limits"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("div",{className:"flex items-center rounded-md border border-[var(--interactive-border)] p-0.5",children:[e.jsx("button",{type:"button",className:`px-2 py-0.5 rounded-sm typography-micro text-[10px] transition-colors ${x==="usage"?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>{D("usage")},"aria-label":"Show used quota",children:"Used"}),e.jsx("button",{type:"button",className:`px-2 py-0.5 rounded-sm typography-micro text-[10px] transition-colors ${x==="remaining"?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>{D("remaining")},"aria-label":"Show remaining quota",children:"Remaining"})]}),e.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>p(),disabled:h,"aria-label":"Refresh rate limits",children:e.jsx(Mr,{className:"h-4 w-4"})})]})]})}),e.jsxs("div",{className:"border-b border-[var(--interactive-border)] px-2 pb-2 typography-micro text-muted-foreground text-[10px]",children:["Last updated ",fE(g)]}),!M&&e.jsx(Et,{className:"cursor-default",onSelect:A=>A.preventDefault(),children:e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"No rate limits available."})}),S.map((A,P)=>e.jsxs(i.Fragment,{children:[e.jsxs(Wr,{className:"flex items-center gap-2 bg-[var(--surface-elevated)] typography-ui-label text-foreground",children:[e.jsx(Os,{providerId:A.providerId,className:"h-4 w-4"}),A.providerName]}),A.entries.length===0?e.jsx(Et,{className:"cursor-default",onSelect:$=>$.preventDefault(),children:e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:A.error??"No rate limits reported."})},`${A.providerId}-empty`):A.entries.map(([$,R])=>{const O=x==="remaining"?R.remainingPercent:R.usedPercent,T=ca(R.usedPercent,R.resetAt,R.windowSeconds,$),_=T?.dailyAllocationPercent!=null?x==="remaining"?100-ln(T.elapsedRatio):ln(T.elapsedRatio):null;return e.jsx(Et,{className:"cursor-default items-start",onSelect:F=>F.preventDefault(),children:e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[e.jsxs("span",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Hl($)}),e.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Sn(O)==="-"?"":Sn(O)})]}),e.jsx(da,{percent:O,tonePercent:R.usedPercent,className:"h-1",expectedMarkerPercent:_}),T&&e.jsx("div",{className:"mt-0.5",children:e.jsx(ua,{paceInfo:T,compact:!0})}),e.jsx("span",{className:"flex items-center justify-between typography-micro text-muted-foreground text-[10px]",children:e.jsx("span",{children:R.resetAfterFormatted??R.resetAtFormatted??""})})]})},`${A.providerId}-${$}`)}),P<S.length-1&&e.jsx(lr,{})]},A.providerId))]})]}),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(Po,{className:"h-5 w-5"})}),c&&C&&C.totalTokens>0&&e.jsx(Px,{totalTokens:C.totalTokens,percentage:C.percentage,contextLimit:C.contextLimit,outputLimit:C.outputLimit??0,size:"compact"})]})},rl=t=>{const s=ps.getState(),r=s.activeProjectId,n=r?s.projects.find(o=>o.id===r)?.path:void 0;return typeof n=="string"&&n.trim().length>0?n:t?Vs(t):null},Vs=t=>{if(!t)return"";const s=t.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Fh=(t,s)=>{const r=Vs(t),n=Vs(s);if(!r||!n)return!1;if(r===n)return!0;const o=n==="/"?"/":`${n}/`;return r.startsWith(o)},xb=async(t,s)=>{const r=Vs(s);if(!r)return r;try{const n=await t.path.get({directory:r});return Vs(n.data?.directory??"")||r}catch{return r}},yb=async(t,s)=>{const r=Vs(s);if(!r)return[];const n=await xb(t,r),o=l=>l.filter(c=>{const d=Vs(c.directory??"");return d?Fh(d,r)||n!==r&&Fh(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(r));if(l.length>0)return l}catch{}if(n&&n!==r)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[]}},yE=async(t,s)=>{const r=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&r.set(Vs(o.path),o.worktreeMetadata)});const n=Array.from(new Set(t.sessions.map(o=>Vs(o.path)))).filter(Boolean).filter(o=>!r.has(o));if(n.length===0)return r;try{const o=await $o({id:`path:${s}`,path:s}),a=new Map(o.map(l=>[Vs(l.path),l]));n.forEach(l=>{const c=a.get(l);c&&r.set(l,c)})}catch{}return r},bE=async t=>{const{apiClient:s,group:r,projectDirectory:n,worktreePaths:o}=t,a=await yE(r,n),l=Ae.getState(),c=Array.from(new Set(o.map(p=>Vs(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<c.length;){const p=c[u];u+=1;const h=r.sessions.filter(v=>Vs(v.path)===p).map(v=>v.id),g=l.getSessionsByDirectory(p),x=Array.isArray(g)?g.map(v=>v.id):[];let y=[];if(x.length===0)try{y=(await yb(s,p)).map(j=>j.id)}catch{y=[]}const b=Array.from(new Set([...x,...y,...h].filter(Boolean)));m.push({worktreePath:p,sessionIds:b,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,c.length)},f)),m},Id=async t=>{const s=nt.getApiClient(),r=await bE({apiClient:s,group:t.group,projectDirectory:t.projectDirectory,worktreePaths:t.worktreePaths}),n=Ae.getState(),o=new Set;return r.forEach(({worktreePath:a,sessionIds:l,metadata:c})=>{l.forEach(d=>{o.add(d),c&&(n.setWorktreeMetadata(d,c),n.setSessionDirectory(d,a))})}),o.size===0?{failedIds:[]}:n.deleteSessions(Array.from(o),{archiveWorktree:!0,silent:!0})};function vE(t){if(!t)return null;const s=t.split("/");if(s.length<3)return null;const r=s[0];if(!r||r.includes(" "))return null;const n=s[1];if(!n)return null;const o=s[s.length-1],a=parseInt(o,10),l=s.length>=4&&!isNaN(a)&&String(a)===o,c=l?s.slice(2,-1):s.slice(2);if(c.length===0)return null;const d=c.join("/");return{groupSlug:r,provider:n,model:d,index:l?a:1}}const mo=Ls()(Us((t,s)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const r=Yt.getState().currentDirectory,n=rl(r);if(!n){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Vs(n),c={id:ps.getState().projects.find(u=>Vs(u.path)===o)?.id??`path:${o}`,path:o},d=s().groups;t({isLoading:!0,error:null});try{const u=nt.getApiClient(),m=await xb(u,o),f=m&&m!==o?{...c,path:m}:null,p=await $o(c).catch(()=>[]),h=f?await $o(f).catch(()=>[]):[],g=new Set,x=new Map;[...p,...h].forEach(C=>{if(C?.path){const S=Vs(C.path);g.add(S),x.has(S)||x.set(S,C)}});const y=async()=>{try{const S=await u.session.list({directory:o}),M=Array.isArray(S.data)?S.data:[];if(M.some(D=>{const A=Vs(D.directory??"");return A?g.has(A):!1}))return M}catch{}const C=await u.session.list(void 0);return Array.isArray(C.data)?C.data:[]},b=async C=>{const S=new Map,M=5;let D=0;const A=async()=>{for(;D<C.length;){const P=C[D];D+=1;const $=Vs(P);if($)try{(await yb(u,$)).forEach(O=>S.set(O.id,O))}catch(R){console.debug("Failed to fetch sessions from worktree:",$,R)}}};return await Promise.all(Array.from({length:Math.min(M,C.length)},A)),Array.from(S.values())};let j=(await y()).filter(C=>{const S=Vs(C.directory??"");return S?g.has(S):!1});if(j.length===0){const C=new Set;g.forEach(S=>C.add(S)),C.size>0&&(j=await b(Array.from(C)))}const k=new Map;for(const C of j){const S=C.time?.updated??0;k.set(C.id,typeof S=="number"?S:0)}const N=new Map;for(const C of j){const S=vE(C.title);if(!S)continue;const M=Vs(C.directory),D=x.get(M),A={id:C.id,path:M,providerId:S.provider,modelId:S.model,instanceNumber:S.index,branch:D?.branch??"",displayLabel:`${S.provider}/${S.model}`,worktreeMetadata:D},P=N.get(S.groupSlug);P?P.push(A):N.set(S.groupSlug,[A])}const w=Array.from(N.entries()).map(([C,S])=>{const M=S.reduce((D,A)=>{const P=k.get(A.id)??0;return Math.max(D,P)},0);return{name:C,sessions:S.sort((D,A)=>{const P=D.providerId.localeCompare(A.providerId);if(P!==0)return P;const $=D.modelId.localeCompare(A.modelId);return $!==0?$:D.instanceNumber-A.instanceNumber}),lastActive:M||Date.now(),sessionCount:S.length}});w.sort((C,S)=>C.name.localeCompare(S.name)),t({groups:w,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:r=>{const{groups:n}=s(),o=n.find(a=>a.name===r);t({selectedGroupName:r,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:r=>{t({selectedSessionId:r})},deleteGroup:async r=>{const n=s().groups.find(l=>l.name===r);if(!n)return!1;const o=Yt.getState().currentDirectory,a=rl(o);if(!a)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const{failedIds:l}=await Id({group:n,projectDirectory:Vs(a),worktreePaths:n.sessions.map(c=>c.path)});return l.length>0&&t({error:"Failed to delete some sessions"}),s().selectedGroupName===r&&t({selectedGroupName:null,selectedSessionId:null}),await s().loadGroups(),l.length===0}catch(l){return t({error:l instanceof Error?l.message:"Failed to delete group"}),!1}finally{t({isLoading:!1})}},deleteGroupWorktree:async(r,n)=>{const o=s().groups.find(d=>d.name===r);if(!o)return!1;const a=Vs(n);if(!a)return!1;const l=Yt.getState().currentDirectory,c=rl(l);if(!c)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const{failedIds:d}=await Id({group:o,projectDirectory:Vs(c),worktreePaths:[a]});d.length>0&&t({error:"Failed to delete some sessions"}),await s().loadGroups();const u=s().groups.find(m=>m.name===r);if(!u)return s().selectedGroupName===r&&t({selectedGroupName:null,selectedSessionId:null}),d.length===0;if(s().selectedGroupName===r){const m=s().selectedSessionId,f=new Set(u.sessions.map(p=>p.id));(!m||!f.has(m))&&t({selectedSessionId:u.sessions[0]?.id??null})}return d.length===0}catch(d){return t({error:d instanceof Error?d.message:"Failed to delete worktree"}),!1}finally{t({isLoading:!1})}},keepOnlyGroupWorktree:async(r,n)=>{const o=s().groups.find(m=>m.name===r);if(!o)return!1;const a=Vs(n);if(!a)return!1;const c=Array.from(new Set(o.sessions.map(m=>Vs(m.path)).filter(Boolean))).filter(m=>m!==a);if(c.length===0)return!0;const d=Yt.getState().currentDirectory,u=rl(d);if(!u)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const{failedIds:m}=await Id({group:o,projectDirectory:Vs(u),worktreePaths:c});if(m.length>0&&t({error:"Failed to delete some sessions"}),await s().loadGroups(),s().selectedGroupName===r){const f=s().groups.find(h=>h.name===r),p=f?.sessions.find(h=>Vs(h.path)===a)??f?.sessions[0]??null;t({selectedSessionId:p?.id??null})}return m.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:r,selectedGroupName:n}=s();return n?r.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:r}=s(),n=s().getSelectedGroup();return!n||!r?null:n.sessions.find(o=>o.id===r)??null},clearError:()=>{t({error:null})}}),{name:"agent-groups-store"})),wE=t=>{const r=Date.now()-t,n=Math.floor(r/(60*1e3)),o=Math.floor(r/(3600*1e3)),a=Math.floor(r/(1440*60*1e3));return n<1?"now":n<60?`${n}m`:o<24?`${o}h`:`${a}d`},jE=({group:t,isSelected:s,onSelect:r})=>{const[n,o]=i.useState(!1),[a,l]=i.useState(!1),[c,d]=i.useState(!1),u=mo(f=>f.deleteGroup),m=i.useCallback(async()=>{if(c)return;if(d(!0),K.info(`Deleting "${t.name}"...`),await u(t.name))K.success(`Deleted "${t.name}"`);else{const p=mo.getState().error;K.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",s?"bg-interactive-selection":"hover:bg-interactive-hover"),onClick:r,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(Ms,{className:"h-3 w-3"}),t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:wE(t.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(us,{open:n,onOpenChange:o,children:[e.jsx(ms,{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(Qn,{className:"h-3.5 w-3.5"})})}),e.jsx(fs,{align:"end",className:"min-w-[140px]",children:e.jsx(Et,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),l(!0)},children:"Delete"})})]})})]})}),e.jsx(bs,{open:a,onOpenChange:l,children:e.jsxs(vs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Delete agent group"}),e.jsxs(Is,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Js,{children:[e.jsx(Me,{variant:"outline",onClick:()=>l(!1),disabled:c,children:"Cancel"}),e.jsx(Me,{variant:"destructive",onClick:()=>{m()},disabled:c,children:c?"Deleting…":"Delete"})]})]})})]})},SE=({className:t,selectedGroupName:s,onGroupSelect:r,onNewAgent:n})=>{const[o,a]=i.useState(""),[l,c]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=mo(),f=Yt(y=>y.currentDirectory);i.useEffect(()=>{f&&m()},[f,m]);const p=5,h=i.useMemo(()=>{if(!o.trim())return d;const y=o.toLowerCase();return d.filter(b=>b.name.toLowerCase().includes(y))},[o,d]),g=l?h:h.slice(0,p),x=h.length-p;return e.jsxs("div",{className:L("flex h-full flex-col 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(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Bt,{value:o,onChange:y=>a(y.target.value),placeholder:"Search Agent Groups...",className:"pl-8 h-8 rounded-lg border-border/40 bg-background/50 typography-meta"})]})}),e.jsx("div",{className:"px-2.5 pb-2",children:e.jsxs(Me,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(Fs,{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(is,{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(Ut,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[g.map(y=>e.jsx(jE,{group:y,isSelected:s===y.name,onSelect:()=>r?.(y.name)},y.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"})]})]})]})},NE=10*1024*1024,kE=5,CE=({className:t,onCreateGroup:s,isCreating:r=!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,y]=i.useState(!1),[b,v]=i.useState([]),[j,k]=i.useState(!1),[N,w]=i.useState(!1),C=i.useRef(null),S=i.useRef(null),{currentTheme:M}=rn(),D=Yt(Q=>Q.currentDirectory??null),{isGitRepository:A,isLoading:P}=tm(D),$=i.useMemo(()=>{if(typeof window>"u")return null;const Q=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof Q=="string"&&Q.trim().length>0?Q.trim():null},[]),R=i.useMemo(()=>typeof window>"u"?!1:!!window.__IKANBAN_RUNTIME_APIS__?.runtime?.isVSCode,[]),O=ps(Q=>Q.activeProjectId),T=ps(Q=>Q.projects),_=i.useMemo(()=>{if(R&&$)return{id:`vscode:${$}`,path:$};if(O){const Q=T.find(Y=>Y.id===O);if(Q?.path)return{id:Q.id,path:Q.path}}return D?{id:`path:${D}`,path:D}:null},[O,T,D,$,R]);i.useEffect(()=>{if(!_)return;let Q=!1;return w(!0),(async()=>{try{const Y=await Ia(_);Q||v(Y)}catch{}finally{Q||w(!1)}})(),()=>{Q=!0}},[_]);const F=i.useCallback(Q=>{c.length>=kE||d(Y=>[...Y,Q])},[c.length]),I=i.useCallback(Q=>{d(Y=>Y.filter((ie,B)=>B!==Q))},[]),E=i.useCallback((Q,Y)=>{d(ie=>ie.map((B,se)=>se===Q?Y:B))},[]),W=async Q=>{const Y=Q.target.files;if(!Y)return;let ie=0;for(let B=0;B<Y.length;B++){const se=Y[B];if(se.size>NE){K.error(`File "${se.name}" is too large (max 10MB)`);continue}try{const H=await new Promise((ge,z)=>{const J=new FileReader;J.onload=()=>ge(J.result),J.onerror=z,J.readAsDataURL(se)}),le={id:Yl(),filename:se.name,mimeType:se.type||"application/octet-stream",size:se.size,dataUrl:H};g(ge=>[...ge,le]),ie++}catch(H){console.error("File attach failed",H),K.error(`Failed to attach "${se.name}"`)}}ie>0&&K.success(`Attached ${ie} file${ie>1?"s":""}`),C.current&&(C.current.value="")},V=Q=>{g(Y=>Y.filter(ie=>ie.id!==Q))},ve=x||r,oe=!!(n.trim()&&a.trim()&&c.length>=1&&A&&!P),Z=async Q=>{if(Q.preventDefault(),!(!oe||ve)){y(!0);try{const Y=c.map(({providerID:se,modelID:H,displayName:le,variant:ge})=>({providerID:se,modelID:H,displayName:le,variant:ge})),ie=h.length>0?h.map(se=>({mime:se.mimeType,filename:se.filename,url:se.dataUrl})):void 0,B=b.filter(se=>se.trim().length>0);await s?.({name:n.trim(),prompt:a.trim(),models:Y,agent:u||void 0,worktreeBaseBranch:f,files:ie,setupCommands:B.length>0?B:void 0}),o(""),l(""),d([]),m(""),g([]),p("HEAD")}catch(Y){console.error("Failed to create agent group:",Y),K.error("Failed to create agent group")}finally{y(!1)}}},ce=Q=>{em(Q)||Q.key==="Enter"&&!Q.shiftKey&&(Q.preventDefault(),oe&&!ve&&Z(Q))};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:Z,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(Bt,{id:"group-name",value:n,onChange:Q=>o(Q.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch naming"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-1.5",children:[e.jsx(Ms,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(my,{directory:D,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(tn,{open:j,onOpenChange:k,children:[e.jsxs(On,{className:"w-full flex items-center justify-between py-1 hover:bg-[var(--interactive-hover)] rounded-md px-1 -mx-1 transition-colors",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",b.filter(Q=>Q.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",b.filter(Q=>Q.trim()).length," configured)"]})]}),e.jsx(is,{className:L("h-4 w-4 text-muted-foreground transition-transform duration-200",j&&"rotate-180")})]}),e.jsx(sn,{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:[b.map((Q,Y)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Bt,{value:Q,onChange:ie=>{const B=[...b];B[Y]=ie.target.value,v(B)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const ie=b.filter((B,se)=>se!==Y);v(ie)},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(hs,{className:"h-4 w-4"})})]},Y)),e.jsxs("button",{type:"button",onClick:()=>v([...b,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Fs,{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(fy,{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(uy,{selectedModels:c,onAdd:F,onRemove:I,onUpdate:E,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/80 overflow-hidden focus-within:ring-1 focus-within:ring-primary/50",style:{backgroundColor:M?.colors?.surface?.subtle},children:[e.jsx(hr,{ref:S,id:"prompt",value:a,onChange:Q=>l(Q.target.value),onKeyDown:ce,placeholder:"Ask anything...",className:"min-h-[100px] max-h-[300px] resize-none border-0 bg-transparent dark:bg-transparent px-4 py-3 typography-markdown focus-visible:ring-0 focus-visible:ring-offset-0"}),h.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:h.map(Q=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[Q.mimeType.startsWith("image/")?e.jsx(Ln,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(In,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:Q.filename,children:Q.filename}),e.jsx("button",{type:"button",onClick:()=>V(Q.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(hs,{className:"h-3.5 w-3.5"})})]},Q.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40 bg-transparent",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:C,type:"file",multiple:!0,className:"hidden",onChange:W,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>C.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(mg,{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:!oe||ve,className:L("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",oe?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:ve?e.jsx(mj,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(_d,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},ME=({group:t,className:s})=>{const{selectedSessionId:r,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=mo(),{setCurrentSession:l,currentSessionId:c}=Ae(),[d,u]=i.useState(null),[m,f]=i.useState(!1),p=i.useMemo(()=>r?t.sessions.find(j=>j.id===r)??t.sessions[0]??null:t.sessions[0]??null,[t.sessions,r]),h=i.useCallback(j=>{n(j.id),l(j.id)},[n,l]);i.useEffect(()=>{if(t.sessions.length>0){const j=r?t.sessions.find(k=>k.id===r)??t.sessions[0]:t.sessions[0];j&&(j.id!==c&&l(j.id),r||n(j.id))}},[t.name,t.sessions,r,c,n,l]);const g=p?.id===c,x=i.useCallback(()=>{if(!p?.path){K.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{K.success("Worktree path copied")}).catch(()=>{K.error("Failed to copy path")})},[p?.path]),y=i.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),b=i.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),v=i.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(K.info("Removing worktree..."),await o(t.name,d.path))K.success("Worktree removed");else{const k=mo.getState().error;K.error(k||"Failed to remove worktree");return}else if(K.info("Removing other worktrees..."),await a(t.name,d.path))K.success("Removed other worktrees");else{const k=mo.getState().error;K.error(k||"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",s),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(Ms,{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(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsxs(Me,{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(Os,{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(is,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(fs,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:t.sessions.map(j=>e.jsxs(Et,{onClick:()=>h(j),className:"flex items-center gap-2 py-2",children:[e.jsx(Os,{providerId:j.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:j.modelId}),j.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",j.instanceNumber]})]}),j.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(Ms,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:j.worktreeMetadata?.label||j.branch})]})]}),p?.id===j.id&&e.jsx(ss,{className:"h-4 w-4 text-primary flex-shrink-0"})]},j.id))})]})}),e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(Me,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Qn,{className:"h-4 w-4"})})}),e.jsxs(fs,{align:"end",className:"min-w-[220px]",children:[e.jsx(Et,{onSelect:j=>{j.preventDefault(),y()},variant:"destructive",children:"Remove this worktree"}),e.jsx(Et,{onSelect:j=>{j.preventDefault(),b()},children:"Leave this one, remove others"}),e.jsxs(Et,{onClick:j=>{j.stopPropagation(),x()},disabled:!p?.path,children:[e.jsx(Hr,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(bs,{open:!!d,onOpenChange:j=>{j||u(null)},children:e.jsxs(vs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(js,{children:[e.jsx(Ss,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(Is,{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(Js,{children:[e.jsx(Me,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Me,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{v()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?g?e.jsx(Ky,{sessionId:p.id,children:e.jsx(Gy,{})}):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(Os,{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"})})})]})},AE=({className:t})=>{const s=!!(typeof window<"u"&&window.__IKANBAN_RUNTIME_APIS__?.runtime?.isVSCode),[r,n]=i.useState(()=>(typeof window<"u"?window.__IKANBAN_CONNECTION__?.status:"connecting")||"connecting"),o=ut(j=>j.isInitialized),a=ut(j=>j.initializeApp),l=Ae(j=>j.loadSessions),c=Yt(j=>j.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=mo(),{createMultiRun:h,isLoading:g}=ni();i.useEffect(()=>{if(!s)return;const j=typeof window<"u"?window.__IKANBAN_CONNECTION__?.status:void 0;(j==="connected"||j==="connecting"||j==="error"||j==="disconnected")&&n(j);const k=N=>{const C=N.detail?.status;(C==="connected"||C==="connecting"||C==="error"||C==="disconnected")&&n(C)};return window.addEventListener("ikanban:connection-status",k),()=>window.removeEventListener("ikanban:connection-status",k)},[s]),i.useEffect(()=>{if(!s||r!=="connected")return;const j=Date.now();if(j-d.current<750)return;d.current=j;const k=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof k=="string"&&k.trim().length>0)try{c(k,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const w=ut.getState();if(!w.isInitialized||!w.isConnected||w.providers.length===0||w.agents.length===0)return;await l(),tr()&&console.log("[IKanban][VSCode][agentManager] bootstrap complete",{providers:w.providers.length,agents:w.agents.length,sessions:Ae.getState().sessions.length})}catch{}})()},[r,o,a,s,l,c]);const x=i.useCallback(j=>{m(j)},[m]),y=i.useCallback(()=>{m(null)},[m]),b=i.useCallback(async j=>{K.info(`Creating agent group "${j.name}" with ${j.models.length} model(s)...`);const k=await h(j);if(k){K.success(`Agent group "${j.name}" created with ${k.sessionIds.length} session(s)`);const N=k.groupSlug,w=async(C=6)=>{for(let S=0;S<C;S+=1){if(await p(),mo.getState().groups.some(D=>D.name===N))return!0;await new Promise(D=>setTimeout(D,500))}return!1};try{await Ae.getState().loadSessions()}catch{}await w(),m(N)}else{const N=ni.getState().error;K.error(N||"Failed to create agent group")}},[h,p,m]),v=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(SE,{selectedGroupName:u,onGroupSelect:x,onNewAgent:y})}),e.jsx("div",{className:"flex-1 min-w-0",children:v?e.jsx(ME,{group:v}):e.jsx(CE,{onCreateGroup:b,isCreating:g})})]})},DE=({onClose:t})=>{const{sessions:s,messages:r,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:l}=Ae(),c=i.useMemo(()=>{let m=0;return r.forEach(f=>{m+=f.length}),m},[r]),d=i.useMemo(()=>s.map(m=>{const f=r.get(m.id)?.length||0,p=n.get(m.id);return{id:m.id,title:m.title||"Untitled",messageCount:f,isStreaming:p?.isStreaming||!1,isZombie:p?.isZombie||!1,backgroundCount:p?.backgroundMessageCount||0,lastAccessed:p?.lastAccessedAt||0,isCurrent:m.id===o}}).sort((m,f)=>f.lastAccessed-m.lastAccessed),[s,r,n,o]),u=r.size;return e.jsxs(Ju,{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(fj,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),t&&e.jsx(Me,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:t,children:e.jsx(hs,{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:c})]}),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:[u," / ",ga.MAX_SESSIONS]})]})]}),null,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:[uc()," messages"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Background Stream Limit:"}),e.jsxs("span",{children:[ga.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:[ga.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(Ut,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:d.map(m=>e.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${m.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:m.title}),m.isStreaming&&e.jsx(pj,{className:"h-3 w-3 text-primary animate-pulse"}),m.isZombie&&e.jsx("span",{className:"text-status-warning",children:"!"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-mono ${m.messageCount>cn()?"text-status-warning":""}`,children:[m.messageCount," msgs"]}),m.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",m.backgroundCount]})]})]},m.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsxs(Me,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Nr,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(ht,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{l()},children:"Evict LRU"})}),e.jsx(ht,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Me,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[MemoryDebug] Session store state:",{sessions:s.map(m=>({id:m.id,title:m.title})),currentSessionId:o,cachedSessions:Array.from(r.keys()),memoryStates:Object.fromEntries(n)})},children:"Log State"})}),e.jsx(ht,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},IE="ikanban-message-cursors",Zl="cursors",TE=1,bb="ikanban.messageCursors",um=()=>typeof window<"u",vb=()=>um()&&typeof indexedDB<"u",EE=()=>vb()?new Promise((t,s)=>{const r=indexedDB.open(IE,TE);r.onupgradeneeded=()=>{const n=r.result;n.objectStoreNames.contains(Zl)||n.createObjectStore(Zl)},r.onerror=()=>{s(r.error??new Error("Failed to open IndexedDB"))},r.onsuccess=()=>{t(r.result)}}):Promise.reject(new Error("IndexedDB not supported")),PE=()=>{if(!um())return{};try{const t=window.localStorage.getItem(bb);if(!t)return{};const s=JSON.parse(t);return s&&typeof s=="object"?s:{}}catch{return{}}},RE=t=>{if(um())try{window.localStorage.setItem(bb,JSON.stringify(t))}catch{}},FE=async(t,s,r)=>{if(!t||!s)return;if(vb())try{const o=await EE();await new Promise((a,l)=>{const c=o.transaction(Zl,"readwrite");c.objectStore(Zl).put({messageId:s,completedAt:r},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=PE();n[t]={messageId:s,completedAt:r},RE(n)},Qr=(t,s)=>{if(!t||typeof t!="object")return null;const r=t;for(let n=0;n<s.length;n++){const o=r[s[n]];if(typeof o=="string"&&o.length>0)return o}return null},LE=50,OE=750,Lh=new WeakMap,Oh=t=>{if(!t||!Array.isArray(t))return 0;const s=Lh.get(t);if(s!==void 0)return s;let r=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"&&(r+=a.length)}}return Lh.set(t,r),r},_E=10,_h=t=>{if(typeof t!="string")return null;const s=t.trim();if(!s)return null;const r=s.indexOf("_"),n=r>=0?s.slice(r+1):s;return!n||n.length<_E?null:n},$h=(t,s)=>{const r=_h(t),n=_h(s);return!r||!n||r.length!==n.length?!0:r>n},yu=new Map,Td=(t,s)=>{const r=`${t}:${s}`,n=yu.get(r);if(n&&n.sessionId===t)return n.message;const l=(Ae.getState().messages.get(t)||[]).find(c=>c.info.id===s)||null;return yu.set(r,{sessionId:t,message:l}),l},$E=()=>{const{addStreamingPart:t,completeStreamingMessage:s,updateMessageInfo:r,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:l,currentSessionId:c,applySessionMetadata:d,getWorktreeMetadata:u,loadMessages:m,loadSessions:f,updateSession:p,removeSessionFromStore:h}=Ae(),{checkConnection:g}=ut(),x=Te(De=>De.nativeNotificationsEnabled),y=Yt(De=>De.currentDirectory),b=i.useMemo(()=>{if(!c)return;try{const Fe=u?.(c);if(Fe?.path)return Fe.path}catch(Fe){console.warn("Failed to inspect worktree metadata for session directory:",Fe)}const we=Ae.getState().sessions.find(Fe=>Fe.id===c);if(we&&typeof we.directory=="string"&&we.directory.trim().length>0)return we.directory.trim()},[c,u]),v=i.useMemo(()=>{if(b&&b.length>0)return b;if(typeof y=="string"&&y.trim().length>0)return y.trim()},[b,y]);i.useEffect(()=>{let De=!1;const we=async()=>{try{const Pe=await nt.listPendingPermissions();if(De||Pe.length===0)return;for(const $e of Pe)o($e)}catch{}},Fe=async()=>{try{const $e=ps.getState().projects.map(Xe=>Xe.path),Ue=Ae.getState().sessions.map(Xe=>Xe.directory),Ee=[v,...$e,...Ue],Re=await nt.listPendingQuestions({directories:Ee});if(De||Re.length===0)return;for(const Xe of Re)a(Xe)}catch{}};return we(),Fe(),()=>{De=!0}},[o,a,v]);const j=i.useCallback(De=>{if(typeof De!="string")return null;const we=De.trim();if(!we)return null;const Fe=we.replace(/\\/g,"/");return Fe.length>1?Fe.replace(/\/+$/,""):Fe},[]),k=i.useCallback(De=>{if(!De)return null;try{const Pe=u?.(De),$e=j(Pe?.path??null);if($e)return $e}catch{}const Fe=Ae.getState().sessions.find(Pe=>Pe.id===De);return j(Fe?.directory??null)},[u,j]),N=Te(De=>De.setEventStreamStatus),w=i.useRef(null),C=i.useCallback((De,we)=>{const Fe=we??null,Pe=w.current;if(!(Pe&&Pe.status===De&&Pe.hint===Fe)){if(w.current={status:De,hint:Fe},tr()){const Ze={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[De]??"[INFO]",Ue=Fe?`${Ze} SSE ${De}: ${Fe}`:`${Ze} SSE ${De}`;console.info(Ue)}N(De,Fe)}},[N]),S=i.useCallback((De,we,Fe)=>{if(!De)return Promise.resolve();const Pe=Date.now();if(E.current)return E.current;if(Pe-W.current<OE)return Promise.resolve();const $e=m(De,Fe).catch(Ze=>{console.warn(`[useEventStream] Failed to resync messages (${we}):`,Ze)}).finally(()=>{E.current=null,W.current=Date.now()});return E.current=$e,$e},[m]),M=i.useCallback(async De=>{tr()&&console.info("[useEventStream] Bootstrapping state:",De);try{const we=cn();await Promise.all([f(),c?S(c,De,we):Promise.resolve()])}catch(we){console.warn("[useEventStream] Bootstrap failed:",De,we)}},[c,f,S]),D=i.useCallback((De,we,Fe=cn())=>{if(!De)return Promise.resolve();const $e=Ae.getState().sessionMemoryState.get(De)?.streamingCooldownUntil,Ze=Date.now();if(typeof $e=="number"&&$e>Ze){const Ue=Math.min(3e3,Math.max(0,$e-Ze));return new Promise(Ee=>{setTimeout(()=>{S(De,we,Fe).finally(Ee)},Ue)})}return S(De,we,Fe)},[S]);i.useEffect(()=>{X.current=D},[D]);const A=i.useCallback((De,we,Fe)=>{tr()&&console.debug(`[MessageTracker] ${De}: ${we}`,Fe)},[]),P=i.useCallback(De=>{tr()&&console.debug(`[MessageTracker] ${De}: reported`)},[]),$=i.useRef(null),R=i.useRef(null),O=i.useRef(0);i.useRef(new Set);const T=i.useRef(new Set),_=i.useRef(new Map),F=i.useRef(null),I=i.useRef(!1),E=i.useRef(null),W=i.useRef(0),V=i.useRef(new Set),ve=i.useRef(new Set),oe=i.useRef(new Set),Z=i.useRef(new Set),ce=i.useRef(new Set),Q=i.useRef(new Map),Y=i.useCallback(()=>{if(typeof document>"u")return"visible";const De=document.visibilityState;return De==="hidden"&&document.hasFocus()?"visible":De},[]),ie=i.useRef(Y()),B=i.useRef(typeof navigator>"u"?!0:navigator.onLine),se=i.useRef(!1),H=i.useRef(null),le=i.useRef(null),ge=i.useRef(Date.now()),z=i.useRef(new Map),J=i.useRef(new Map),je=i.useRef(new Map),X=i.useRef(()=>Promise.resolve()),G=i.useRef(()=>{}),ae=i.useCallback(De=>{const we=Date.now();we-ge.current>25e3&&(M(De),ge.current=we)},[M]),me=i.useRef(c),Oe=i.useRef(null),Be=i.useRef(null);i.useEffect(()=>{me.current=c},[c]);const fe=i.useCallback((De,we)=>{if(!De)return;const Fe=Date.now(),Pe=_.current,$e=Pe.get(De);if($e&&Fe-$e<3e3)return;Pe.set(De,Fe);const Ze=Ue=>{if(typeof we=="string"&&we.trim().length>0)return we.trim();try{const Xe=u?.(Ue);if(Xe?.path)return Xe.path}catch{}const Re=Ae.getState().sessions.find(Xe=>Xe.id===Ue);return Re&&typeof Re.directory=="string"&&Re.directory.trim().length>0?Re.directory.trim():null};setTimeout(async()=>{try{const Ue=Ze(De),Ee=Ue?await nt.withDirectory(Ue,()=>nt.getSession(De)):await nt.getSession(De);if(Ee){const Re={};typeof Ee.title=="string"&&Ee.title.length>0&&(Re.title=Ee.title),Ee.summary!==void 0&&(Re.summary=Ee.summary),Object.keys(Re).length>0&&d(De,Re)}}catch(Ue){console.warn("Failed to refresh session metadata:",Ue)}},100)},[d,u]),q=i.useCallback((De,we,Fe="unknown")=>{if(!De)return;const $e=Ae.getState().sessionStatus?.get(De)?.type??"idle",Ze=we?.type??"idle";if($e!==Ze)try{console.info("[SESSION-STATUS]",{sessionId:De,from:$e,to:Ze,source:Fe,...Ze==="retry"?{attempt:we.attempt,next:we.next,message:we.message}:{}})}catch{}const Ue=$e==="idle"&&(Ze==="busy"||Ze==="retry");if(Ze==="idle"){const Xe=J.current.get(De);Xe&&(clearTimeout(Xe),J.current.delete(De))}if(Ue){const Xe=J.current.get(De);Xe&&(clearTimeout(Xe),J.current.delete(De));const st=Date.now(),St=setTimeout(()=>{const mt=Ae.getState().sessionStatus?.get(De);if(mt?.type!=="busy"&&mt?.type!=="retry")return;const Tt=je.current.get(De)??0;Date.now()-Tt<15e3||(z.current.get(De)??0)>=st||(je.current.set(De,Date.now()),X.current(De,"status_busy_no_message",cn()).finally(()=>{G.current("No message events after busy status")}))},2e3);J.current.set(De,St)}const Re=new Map(Ae.getState().sessionStatus??new Map);if(Ze==="idle")Re.set(De,{...we,confirmedAt:Date.now()});else{const Xe=Re.get(De);Xe?.confirmedAt?Re.set(De,{...we,confirmedAt:Xe.confirmedAt}):Re.set(De,we)}Ae.setState({sessionStatus:Re})},[]);i.useEffect(()=>{const De=c??null;Oe.current;const we=k(De);Be.current,Oe.current=De,Be.current=we},[c,k]);const ye=i.useCallback(De=>{if(ge.current=Date.now(),tr()&&console.debug("[useEventStream] Received event:",De.type,De.properties),!De.properties)return;const we=De.properties;if(!new Set(["session.abort","session.error"]).has(De.type)){const Pe=(typeof we.session=="object"&&we.session!==null?we.session:null)||(typeof we.sessionInfo=="object"&&we.sessionInfo!==null?we.sessionInfo:null);if(Pe){const $e=Pe,Ze=typeof $e.id=="string"&&$e.id.length>0?$e.id:typeof $e.sessionID=="string"&&$e.sessionID.length>0?$e.sessionID:typeof we.sessionID=="string"&&we.sessionID.length>0?we.sessionID:typeof we.id=="string"&&we.id.length>0?we.id:void 0;if(Ze){const Ue=typeof $e.title=="string"?$e.title:typeof we.title=="string"?we.title:void 0,Ee=typeof $e.summary=="object"&&$e.summary!==null?$e.summary:typeof we.summary=="object"&&we.summary!==null?we.summary:void 0;if(Ue!==void 0||Ee!==void 0){const Re={};Ue!==void 0&&(Re.title=Ue),Ee!==void 0&&(Re.summary=Ee),d(Ze,Re)}}}}switch(De.type){case"server.connected":g();break;case"global.disposed":case"server.instance.disposed":{M("server_disposed_event");break}case"mcp.tools.changed":{const Pe=typeof we.directory=="string"?we.directory:v;Hn.getState().refresh({directory:Pe??null,silent:!0});break}case"session.status":{const Pe=Qr(we,["sessionID","sessionId"]),$e=typeof we.status=="object"&&we.status!==null?we.status:null,Ze=typeof $e?.type=="string"?$e.type:null,Ue=$e??{};Pe&&Ze&&(Ze==="busy"?q(Pe,{type:"busy"},"sse:session.status"):Ze==="retry"?q(Pe,{type:"retry",attempt:typeof Ue.attempt=="number"?Ue.attempt:void 0,message:typeof Ue.message=="string"?Ue.message:void 0,next:typeof Ue.next=="number"?Ue.next:void 0},"sse:session.status"):q(Pe,{type:"idle"},"sse:session.status"),fe(Pe,typeof we.directory=="string"?we.directory:null))}break;case"ikanban:session-status":{const Pe=Qr(we,["sessionId","sessionID"]),$e=typeof we.status=="string"?we.status:null,Ze=typeof we.needsAttention=="boolean"?we.needsAttention:!1,Ue=typeof we.timestamp=="number"?we.timestamp:Date.now();if(Pe&&$e){if($e==="busy")q(Pe,{type:"busy"},"sse:ikanban:session-status");else if($e==="retry"){const st=typeof we.metadata=="object"&&we.metadata!==null?we.metadata:{};q(Pe,{type:"retry",attempt:typeof st.attempt=="number"?st.attempt:void 0,message:typeof st.message=="string"?st.message:void 0,next:typeof st.next=="number"?st.next:void 0},"sse:ikanban:session-status")}else q(Pe,{type:"idle"},"sse:ikanban:session-status");const Ee=Ae.getState().sessionAttentionStates||new Map,Re=new Map(Ee),Xe=Re.get(Pe);Re.set(Pe,{needsAttention:Ze,lastStatusChangeAt:Ue,lastUserMessageAt:Xe?.lastUserMessageAt??null,status:$e,isViewed:Xe?.isViewed??!1}),Ae.setState({sessionAttentionStates:Re})}}break;case"message.part.updated":{const Pe=typeof we.part=="object"&&we.part!==null?we.part:null;if(!Pe)break;const $e=Pe,Ze=typeof we.info=="object"&&we.info!==null?we.info:we,Ue=Qr(Ze,["sessionID","sessionId"]),Ee=Qr($e,["sessionID","sessionId"])||Ue||Qr(we,["sessionID","sessionId"]),Re=Qr(Ze,["messageID","messageId","id"]),Xe=Qr($e,["messageID","messageId"])||Re||Qr(we,["messageID","messageId"]);if(!Ee||!Xe){tr()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:$e.sessionID??Ue??we.sessionID,messageID:$e.messageID??Re??we.messageID});break}const st=Ee,St=Xe;z.current.set(st,Date.now());const mt=J.current.get(st);mt&&(clearTimeout(mt),J.current.delete(st));const Tt=Ae.getState().sessionMemoryState.get(st)?.trimmedHeadMaxId;if(Tt&&!$h(St,Tt)){tr()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:st,messageId:St,trimmedHeadMaxId:Tt});break}let qt="assistant";if(Ze&&typeof Ze.role=="string")qt=Ze.role;else{const os=Td(st,St);if(os){const cs=os.info.role;typeof cs=="string"&&(qt=cs)}}if(A(St,"part_received",{role:qt}),qt==="user"&&$e.synthetic===!0){A(St,"skipped_synthetic_user_part");break}const yt={...Pe,type:Pe.type||"text"};if(qt==="assistant"){const os=yt.type,ds=typeof yt.time?.end=="number",de=yt.state?.status,ke=yt.text;if(os==="tool"?de==="running"||de==="pending":os==="reasoning"?!ds:os==="text"?typeof ke=="string"&&ke.trim().length>0&&!ds:os==="step-start"){const qe=Ae.getState().sessionStatus?.get(st),et=qe?.type==="idle"&&typeof qe.confirmedAt=="number"&&Date.now()-qe.confirmedAt<1200;if(!qe||qe.type==="idle"){if(et)break;q(st,{type:"busy"},"sse:message.part.updated")}}}A(St,"addStreamingPart_called"),t(st,St,yt,qt);break}case"message.updated":{const Pe=typeof we.info=="object"&&we.info!==null?we.info:we,$e=Pe,Ze=Qr($e,["sessionID","sessionId"])||Qr(we,["sessionID","sessionId"]),Ue=Qr($e,["messageID","messageId","id"])||Qr(we,["messageID","messageId"]);if(!Ze||!Ue){tr()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:$e.sessionID??we.sessionID,messageID:$e.id??we.messageID});break}const Ee=Ze,Re=Ue;z.current.set(Ee,Date.now());const Xe=J.current.get(Ee);Xe&&(clearTimeout(Xe),J.current.delete(Ee));const st=Ae.getState().sessionMemoryState.get(Ee)?.trimmedHeadMaxId;if(st&&!$h(Re,st)){tr()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Ee,messageId:Re,trimmedHeadMaxId:st});break}if(tr())try{const zt=we.parts||$e.parts||[],Qt=(Array.isArray(zt)?zt.filter(Mt=>Mt?.type==="text"):[]).map(Mt=>{const Zt=Mt;return typeof Zt?.text=="string"?Zt.text:typeof Zt?.content=="string"?Zt.content:""}).join(`
|
|
289
|
+
`);console.info("[STREAM-TRACE] message.updated",{messageId:Re,role:$e.role,status:$e.status,textLen:Qt.length,textPreview:Qt.slice(0,120),partsCount:Array.isArray(zt)?zt.length:0})}catch{}if(A(Re,"message_updated",{role:$e.role}),$e.role==="user"){const{sessionMemoryState:zt}=rs.getState(),Ct=zt.get(Ee);if(Ct){const pt=new Map(zt);pt.set(Ee,{...Ct,lastUserMessageAt:Date.now()}),rs.setState({sessionMemoryState:pt})}const Qt=we.parts||$e.parts,Mt=Array.isArray(Qt)?Qt:[],Zt=Td(Ee,Re),jt=(()=>{const pt=$e.agent;if(typeof pt=="string"&&pt.trim().length>0)return pt.trim();const Rt=$e.mode;return typeof Rt=="string"&&Rt.trim().length>0?Rt.trim():""})(),es=(()=>{const Rt=$e.time?.created;return typeof Rt=="number"?Rt:null})(),Ye=Mt.length>0&&Mt.every(pt=>pt?.synthetic===!0),ft=(()=>{if(!jt)return!1;if(Ye&&(jt==="plan"||jt==="build"))return!0;const pt=Q.current.get(Ee);return pt?es===null?!1:Re===pt.messageId?!0:es>=pt.created:!0})();if(jt&&ft)try{const pt=ut.getState().agents;if(Array.isArray(pt)&&pt.some(Rt=>Rt?.name===jt)){const Rt=Lt.getState();if(Rt.saveSessionAgentSelection(Ee,jt),Q.current.set(Ee,{created:es??Date.now(),messageId:Re}),me.current===Ee)try{ut.getState().setAgent(jt)}catch{}const Ft=$e.model,Pt=typeof Ft?.providerID=="string"?Ft.providerID:null,Jt=typeof Ft?.modelID=="string"?Ft.modelID:null;if(Pt&&Jt){Rt.saveSessionModelSelection(Ee,Pt,Jt),Rt.saveAgentModelForSession(Ee,jt,Pt,Jt);const Ns=typeof $e.variant=="string"?$e.variant:void 0;if(Ns&&Rt.saveAgentModelVariantForSession(Ee,jt,Pt,Jt,Ns),me.current===Ee)try{ut.getState().setProvider(Pt),ut.getState().setModel(Jt)}catch{}}}}catch{}if(Ye&&(jt==="plan"||jt==="build")&&me.current===Ee){const pt=`${Ee}:${Re}:${jt}`;ce.current.has(pt)||(ce.current.add(pt),Ks(async()=>{const{toast:Rt}=await import("./vendor-.bun-CTUAJ4e1.js").then(Ft=>Ft.d_);return{toast:Rt}},__vite__mapDeps([0,1])).then(({toast:Rt})=>{Rt.info(jt==="plan"?"Plan mode active":"Build mode active",{description:jt==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const vt={...Pe,userMessageMarker:!0,clientRole:"user",...jt?{mode:jt}:{}};if(r(Ee,Re,vt),!Zt&&Mt.length===0){const pt=`${Ee}:${Re}`;T.current.has(pt)||(T.current.add(pt),nt.getSessionMessages(Ee,50).then(Rt=>{Ae.getState().syncMessages(Ee,Rt)}).catch(()=>{}))}if(Mt.length>0)for(let pt=0;pt<Mt.length;pt++){const Rt=Mt[pt];if(Rt.synthetic===!0){const Jt=Rt.text,Ns=typeof Jt=="string"?Jt.trim():"";if(!(Ns.startsWith("User has requested to enter plan mode")||Ns.startsWith("The plan at ")))continue}const Pt={...Rt,type:Rt?.type||"text",sessionID:Rt?.sessionID||Ee,messageID:Rt?.messageID||Re};t(Ee,Re,Pt,"user")}A(Re,"user_message_created_from_event",{partsCount:Mt.length});break}const St=Td(Ee,Re),mt=Oh(St?.parts||[]),Tt=St?.info?.finish==="stop",qt=we.parts||$e.parts,yt=Array.isArray(qt)?qt:[],os=yt.length>0,ds=typeof($e.time||{})?.completed=="number",de=Pe.status,ke=typeof de=="string"?de.toLowerCase():null,We=ke==="completed"||ke==="complete",qe=Pe.finish,et=typeof qe=="string"?qe:null,ct=et==="stop";if(!os&&!ds&&!We&&!ct)break;if($e.role==="assistant"&&os){const zt=Oh(yt);if(mt>0&&zt+LE<mt&&!ct){A(Re,"skipped_shrinking_update",{incomingLen:zt,existingLen:mt});break}}if(r(Ee,Re,Pe),os&&$e.role!=="user"){const Qt=(Ae.getState().messages.get(Ee)||[]).find(jt=>jt.info.id===Re),Mt=!Qt||Qt.parts.length===0;A(Re,Mt?"server_parts_injected":"server_parts_refreshed",{count:yt.length});const Zt=yt;for(let jt=0;jt<Zt.length;jt++){const es=Zt[jt],Ye={...es,type:es?.type||"text",sessionID:es?.sessionID||Ee,messageID:es?.messageID||Re};t(Ee,Re,Ye,$e.role),A(Re,`server_part_${jt}`)}}const bt=Pe.time,at=bt?.completed,_t=typeof at=="number"&&Number.isFinite(at),Nt=et==="stop"||Tt;if(Pe.role==="assistant"&&(_t||We||Nt)&&Pe.role==="assistant"){const Ct=Ae.getState().messages.get(Ee)||[];let Qt=null,Mt="";for(let vt=0;vt<Ct.length;vt++){const pt=Ct[vt];pt.info.role==="assistant"&&pt.info.id>Mt&&(Mt=pt.info.id,Qt=pt.info.id)}if(c===Ee&&Re!==Qt)break;const jt=_t?at:Date.now();_t||r(Ee,Re,{...Pe,time:{...bt??{},completed:jt}}),A(Re,"completed",{timeCompleted:jt}),P(Re),FE(Ee,Re,jt),s(Ee,Re),q(Ee,{type:"idle"},"sse:message.updated.completed");const es=Pe.sessionID,Ye=typeof es=="string"&&es.length>0?es:Ee;fe(Ye,typeof we.directory=="string"?we.directory:null),Pe.summary&&typeof Ye=="string"&&n(Ye,null)}break}case"session.created":case"session.updated":{const Pe=typeof we.info=="object"&&we.info!==null?we.info:typeof we.sessionInfo=="object"&&we.sessionInfo!==null?we.sessionInfo:typeof we.session=="object"&&we.session!==null?we.session:we,$e=typeof Pe.id=="string"&&Pe.id.length>0?Pe.id:typeof Pe.sessionID=="string"&&Pe.sessionID.length>0?Pe.sessionID:typeof we.sessionID=="string"&&we.sessionID.length>0?we.sessionID:typeof we.id=="string"&&we.id.length>0?we.id:void 0;if($e){const Ze=typeof Pe.time=="object"&&Pe.time!==null?Pe.time:typeof we.time=="object"&&we.time!==null?we.time:null,Ue=Ze&&typeof Ze.compacting=="number"?Ze.compacting:null;n($e,Ue);const Ee=typeof Pe.directory=="string"?Pe.directory:typeof we.directory=="string"?we.directory:null,Re={...Pe,id:$e,...Ee?{directory:Ee}:{}};p(Re)}break}case"session.deleted":{const Pe=typeof we.sessionID=="string"?we.sessionID:typeof we.id=="string"?we.id:null;Pe&&h(Pe);break}case"session.abort":{const Pe=typeof we.sessionID=="string"&&we.sessionID.length>0?we.sessionID:null,$e=typeof we.messageID=="string"&&we.messageID.length>0?we.messageID:null;Pe&&q(Pe,{type:"idle"},"sse:session.abort"),Pe&&$e&&s(Pe,$e);break}case"permission.asked":{if(!("sessionID"in we)||typeof we.sessionID!="string")break;const Pe=we;o(Pe);const $e=`${Pe.sessionID}:${Pe.id}`;V.current.has($e)||setTimeout(()=>{if(me.current===Pe.sessionID||!Ae.getState().permissions.get(Pe.sessionID)?.some(Re=>Re.id===Pe.id))return;V.current.add($e);const Ee=Ae.getState().sessions.find(Re=>Re.id===Pe.sessionID)?.title||"Session";Ks(async()=>{const{toast:Re}=await import("./vendor-.bun-CTUAJ4e1.js").then(Xe=>Xe.d_);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.warning("Permission required",{description:Ee,action:{label:"Open",onClick:()=>{Te.getState().setActiveMainTab("chat"),Ae.getState().setCurrentSession(Pe.sessionID)}}})})},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in we)||typeof we.sessionID!="string")break;const Pe=we;a(Pe);const $e=`${Pe.sessionID}:${Pe.id}`;ve.current.has($e)||setTimeout(()=>{if(me.current===Pe.sessionID||!Ae.getState().questions.get(Pe.sessionID)?.some(Re=>Re.id===Pe.id))return;ve.current.add($e);const Ee=Ae.getState().sessions.find(Re=>Re.id===Pe.sessionID)?.title||"Session";Ks(async()=>{const{toast:Re}=await import("./vendor-.bun-CTUAJ4e1.js").then(Xe=>Xe.d_);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.info("Input needed",{description:Ee,action:{label:"Open",onClick:()=>{Te.getState().setActiveMainTab("chat"),Ae.getState().setCurrentSession(Pe.sessionID)}}})})},0);break}case"question.replied":{const Pe=typeof we.sessionID=="string"?we.sessionID:null,$e=typeof we.requestID=="string"?we.requestID:null;Pe&&$e&&l(Pe,$e);break}case"question.rejected":{const Pe=typeof we.sessionID=="string"?we.sessionID:null,$e=typeof we.requestID=="string"?we.requestID:null;Pe&&$e&&l(Pe,$e);break}case"ikanban:notification":{const Pe=typeof we.title=="string"?we.title:"",$e=typeof we.body=="string"?we.body:"",Ze=typeof we.tag=="string"?we.tag:void 0;if(!!we.requireHidden&&ie.current!=="hidden"||Or()&&we.desktopStdoutActive||!x)break;const Ee=Ur();Ee?.notifications&&Pe&&Ee.notifications.notifyAgentCompletion({title:Pe,body:$e,tag:Ze});break}case"todo.updated":{const Pe=typeof we.sessionID=="string"?we.sessionID:null,$e=Array.isArray(we.todos)?we.todos:null;Pe&&$e&&pA(Pe,$e);break}}},[c,x,t,s,r,o,a,l,g,fe,n,d,A,P,p,h,M,v,q]),he=i.useCallback(()=>{const De=Y();return ie.current=De,De==="visible"&&B.current},[Y]),He=i.useCallback(()=>{tr()&&console.debug("[useEventStream] Connection state:",{hasUnsubscribe:!!$.current,currentSessionId:me.current,effectiveDirectory:v,onlineStatus:B.current,visibilityState:ie.current,lastEventTimestamp:ge.current,reconnectAttempts:O.current})},[v]),ot=i.useCallback(()=>{if(I.current){tr()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(I.current=!0,R.current&&(clearTimeout(R.current),R.current=null),$.current){const De=$.current;$.current=null;try{De()}catch(we){console.warn("[useEventStream] Error during unsubscribe:",we)}}I.current=!1},[]),ue=i.useCallback(async De=>{if(He(),!he()){se.current=!0,B.current?C("paused","Paused while hidden"):C("offline","Waiting for network");return}De?.resetAttempts&&(O.current=0),ot(),ge.current=Date.now(),C("connecting",null),tr()&&console.info("[useEventStream] Starting event stream...");const we=Pe=>{console.warn("Event stream error:",Pe)},Fe=()=>{const Pe=se.current;if(O.current=0,se.current=!1,ge.current=Date.now(),C("connected",null),g(),zn(),Pe)M("sse_reconnected");else{const $e=me.current;$e&&setTimeout(()=>{D($e,"sse_reconnected",cn()).then(()=>fe($e)).catch(Ze=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Ze)})},0)}};if(tr()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:v,isCleaningUp:I.current}),I.current){tr()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Pe=nt.subscribeToGlobalEvents(Ze=>{const Ue=Ze.payload,Ee=Ze.payload,Re=typeof Ee.properties=="object"&&Ee.properties!==null?Ee.properties:{},Xe=Ze.directory&&Ze.directory!=="global"?{...Re,directory:Ze.directory}:Re;ye({type:typeof Ue.type=="string"?Ue.type:"",properties:Xe})},we,Fe),$e=()=>{try{Pe()}catch(Ze){console.warn("[useEventStream] Error during unsubscribe:",Ze)}};I.current?$e():$.current=$e}catch(Pe){console.error("[useEventStream] Error during subscription:",Pe),we(Pe)}},[he,ot,C,g,D,fe,ye,v,He,M]),Ve=i.useCallback(De=>{if(!he()){se.current=!0,ot(),B.current?C("paused","Paused while hidden"):C("offline","Waiting for network");return}if(R.current)return;const we=O.current+1;O.current=we;const Fe=De??`Retrying (${we})`;C("reconnecting",Fe);const Pe=we<=3?Math.min(1e3*Math.pow(2,we-1),8e3):Math.min(2e3*Math.pow(2,we-3),32e3),$e=Math.floor(Math.random()*250),Ze=Pe+$e;R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{ue({resetAttempts:!1})},Ze)},[he,ot,C,ue]);i.useEffect(()=>{G.current=Ve},[Ve]),i.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=A);const De=()=>{H.current&&(clearTimeout(H.current),H.current=null)},we=()=>{if(ie.current=Y(),ie.current!=="visible")return;if(De(),ae("visibility_restore"),zn(),Date.now()-ge.current>45e3&&(console.info("[useEventStream] Visibility restored with stalled stream, reconnecting..."),se.current=!0),se.current||!$.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Xe=me.current;Xe&&(D(Xe,"visibility_restore",cn()),fe(Xe)),zn(),C("connecting","Resuming stream"),ue({resetAttempts:!0})}},Fe=()=>{if(ie.current=Y(),ie.current==="visible"&&(De(),ae("window_focus"),zn(),Date.now()-ge.current>45e3&&(se.current=!0),se.current||!$.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Xe=me.current;Xe&&(fe(Xe),D(Xe,"window_focus",cn())),zn(),C("connecting","Resuming stream"),ue({resetAttempts:!0})}},Pe=()=>{B.current=!0,ae("network_restored"),(se.current||!$.current)&&(zn(),C("connecting","Network restored"),ue({resetAttempts:!0}))},$e=()=>{B.current=!1,se.current=!0,C("offline","Waiting for network"),ot()},Ze=()=>{se.current=!0,ot(),C("paused","Paused while hidden")},Ue=Re=>{if(se.current=se.current||!!Re.persisted,ie.current=Y(),ie.current==="visible"){const Xe=me.current;Xe&&(D(Xe,"page_show",cn()),fe(Xe)),zn(),ue({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",we),typeof window<"u"&&(window.addEventListener("online",Pe),window.addEventListener("offline",$e),window.addEventListener("focus",Fe),window.addEventListener("pagehide",Ze),window.addEventListener("pageshow",Ue));const Ee=setTimeout(()=>{ue({resetAttempts:!0})},100);return le.current&&clearInterval(le.current),le.current=setInterval(()=>{if(!he())return;const Re=Date.now();Array.from(Ae.getState().sessionStatus?.values?.()??[]).some(st=>st?.type==="busy"||st?.type==="retry")&&zn(),Re-ge.current>45e3&&Promise.resolve().then(async()=>{try{if(!await nt.checkHealth()){Ve("Refreshing stalled stream");return}Ve("Refreshing stalled stream")}catch(st){console.warn("Health check after stale stream failed:",st),Ve("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Ee),typeof document<"u"&&document.removeEventListener("visibilitychange",we),typeof window<"u"&&(window.removeEventListener("online",Pe),window.removeEventListener("offline",$e),window.removeEventListener("focus",Fe),window.removeEventListener("pagehide",Ze),window.removeEventListener("pageshow",Ue)),De(),le.current&&(clearInterval(le.current),le.current=null),yu.clear(),oe.current.clear(),Z.current.clear(),se.current=!1,ie.current=Y(),B.current=typeof navigator>"u"?!0:navigator.onLine,ot(),F.current&&(clearTimeout(F.current),F.current=null),C("idle",null)}},[v,A,Y,ot,C,ue,Ve,m,fe,he,f,ae,S,D])},BE=()=>{const t=Ae.getState(),s=t.currentSessionId;if(!s)return"";const r=t.sessions.find(n=>n.id===s);return typeof r?.directory=="string"?r.directory:""},zE=async(t,s=6e3)=>{const r=new AbortController,n=setTimeout(()=>r.abort(),s),o=Date.now();try{const a=await fetch(t,{method:"GET",headers:{Accept:"application/json"},signal:r.signal}),l=Date.now()-o,c=a.headers.get("content-type")||"",d=c.toLowerCase(),u=d.includes("json")&&!d.includes("text/html");let m="";if(u){const f=await a.json().catch(()=>null);if(Array.isArray(f))m=`json[array] len=${f.length}`;else if(f&&typeof f=="object"){const p=Object.keys(f).slice(0,8);m=`json[object] keys=${p.join(",")}${Object.keys(f).length>p.length?",…":""}`}else m=`json[${typeof f}]`}else m=c?`content-type=${c}`:"no content-type";return{ok:a.ok&&u,status:a.status,elapsedMs:l,summary:m}}catch(a){const l=Date.now()-o,d=r.signal.aborted||a instanceof Error&&(a.name==="AbortError"||a.message.toLowerCase().includes("aborted"))?`timeout after ${s}ms`:a instanceof Error?a.message:String(a);return{ok:!1,status:0,elapsedMs:l,summary:`error=${d}`}}finally{clearTimeout(n)}},UE=t=>{if(!t||!Number.isFinite(t))return"(n/a)";try{return new Date(t).toISOString()}catch{return"(invalid)"}},HE=async()=>{const t=new Date,s="0.1.5",r=typeof navigator<"u"?navigator.userAgent:"(no navigator)",n=BE(),o=Te.getState().eventStreamStatus,a=typeof window<"u"?window.location.origin:"",l=a?`${a.replace(/\/+$/,"")}/api/`:"",c=await(async()=>{if(!a)return null;const g=new AbortController,x=setTimeout(()=>g.abort(),5e3);try{const y=await fetch(`${a.replace(/\/+$/,"")}/health`,{method:"GET",headers:{Accept:"application/json"},signal:g.signal});if(!y.ok)return null;const b=await y.json().catch(()=>null);return!b||typeof b!="object"||Array.isArray(b)?null:b}catch{return null}finally{clearTimeout(x)}})(),d=await(async()=>{if(!a)return null;const g=new AbortController,x=setTimeout(()=>g.abort(),7e3);try{const y=await fetch(`${a.replace(/\/+$/,"")}/api/config/opencode-resolution`,{method:"GET",headers:{Accept:"application/json"},signal:g.signal}),b=y.headers.get("content-type")||"(none)";if(!y.ok)return{data:null,status:y.status,error:`http ${y.status} content-type=${b}`};const v=await y.text();let j=null;try{j=JSON.parse(v)}catch{const k=v.replace(/\s+/g," ").slice(0,120);return{data:null,status:y.status,error:`invalid json content-type=${b} body=${k||"(empty)"}`}}return!j||typeof j!="object"||Array.isArray(j)?{data:null,status:y.status,error:`invalid json-shape content-type=${b}`}:{data:j,status:y.status,error:null}}catch(y){return{data:null,status:null,error:y instanceof Error?y.message:String(y)}}finally{clearTimeout(x)}})()||{data:null,error:null},u=(g,x=!0)=>{if(!l)return null;const y=new URL(g.replace(/^\/+/,""),l);return x&&n&&y.searchParams.set("directory",n),y.toString()},m=[{label:"health",path:"/global/health",includeDirectory:!1},{label:"config",path:"/config",includeDirectory:!0},{label:"providers",path:"/config/providers",includeDirectory:!0},{label:"agents",path:"/agent",includeDirectory:!0,timeoutMs:12e3},{label:"commands",path:"/command",includeDirectory:!0,timeoutMs:1e4},{label:"project",path:"/project/current",includeDirectory:!0},{label:"path",path:"/path",includeDirectory:!0},{label:"sessions",path:"/session",includeDirectory:!0,timeoutMs:12e3},{label:"sessionStatus",path:"/session/status",includeDirectory:!0}],f=l?await Promise.all(m.map(async g=>{const x=u(g.path,g.includeDirectory!==!1);if(!x)return{label:g.label,url:"(none)",result:null};const y=await zE(x,typeof g.timeoutMs=="number"?g.timeoutMs:void 0);return{label:g.label,url:x,result:y}})):[],p=[];if(p.push(`Time: ${t.toISOString()}`),p.push(`IKanban version: ${s}`),p.push(`Runtime: ${a||"(unknown)"} (api=${a?a+"/api":"(unknown)"})`),p.push(`Event stream: ${o}`),p.push(`Directory: ${n||"(none)"}`),p.push(`Platform: ${r}`),typeof window<"u"){const g=window.__IKANBAN_MACOS_MAJOR__;typeof g=="number"&&Number.isFinite(g)&&g>0&&p.push(`macOS major: ${g}`)}if(/Mac OS X|Macintosh/.test(r)){p.push(""),p.push("OpenCode CLI resolution:");const g=d.data,x=g&&typeof g.configured=="string"?g.configured:null,y=g&&typeof g.resolved=="string"?g.resolved:c&&typeof c.opencodeBinaryResolved=="string"?c.opencodeBinaryResolved:"",b=g&&typeof g.resolvedDir=="string"?g.resolvedDir:"",v=g&&typeof g.source=="string"?g.source:c&&typeof c.opencodeBinarySource=="string"?c.opencodeBinarySource:"",j=g&&typeof g.shim=="string"?g.shim:c&&typeof c.opencodeShimInterpreter=="string"?c.opencodeShimInterpreter:"",k=g&&typeof g.node=="string"?g.node:c&&typeof c.nodeBinaryResolved=="string"?c.nodeBinaryResolved:"",N=g&&typeof g.bun=="string"?g.bun:c&&typeof c.bunBinaryResolved=="string"?c.bunBinaryResolved:"",w=g&&typeof g.detectedNow=="string"?g.detectedNow:"",C=g&&typeof g.detectedSourceNow=="string"?g.detectedSourceNow:"";if(x!==null&&p.push(`- configured: ${x.trim().length===0?"(cleared)":x}`),y){const S=b||(y.includes("/")?y.split("/").slice(0,-1).join("/")||"/":"");p.push(`- opencode: ${y}${S?` (dir=${S})`:""}`)}else p.push("- opencode: (n/a)");p.push(`- source: ${v||"(n/a)"}`),w&&(p.push(`- detected-now: ${w}`),p.push(`- detected-source: ${C||"(n/a)"}`)),p.push(`- shim: ${j||"(n/a)"}`),p.push(`- node: ${k||"(n/a)"}`),p.push(`- bun: ${N||"(n/a)"}`),!g&&d.error&&p.push(`- resolution-endpoint: ${d.error}`)}if(p.push(""),f.length){p.push("OpenCode API probes:");for(const g of f){if(!g.result){p.push(`- ${g.label}: (no url)`);continue}const{ok:x,status:y,elapsedMs:b,summary:v}=g.result,j=x?"":` url=${g.url}`;p.push(`- ${g.label}: ${x?"ok":"fail"} status=${y} time=${b}ms ${v}${j}`)}}else p.push("OpenCode API probes: (skipped)");return p.push(""),p.push(`Generated: ${UE(Date.now())}`),p.join(`
|
|
290
|
+
`)},wb=async()=>{const t=await HE(),s=Te.getState();s.setOpenCodeStatusText(t),s.setOpenCodeStatusDialogOpen(!0)},VE=()=>{const{openNewSessionDraft:t,abortCurrentOperation:s,armAbortPrompt:r,clearAbortPrompt:n,currentSessionId:o}=Ae(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,toggleRightSidebar:d,setSessionSwitcherOpen:u,setActiveMainTab:m,setSettingsDialogOpen:f,setModelSelectorOpen:p}=Te(),{themeMode:h,setThemeMode:g}=rn(),{working:x}=Iy(),y=i.useRef(null),b=i.useRef(null),v=i.useCallback(()=>{b.current&&(clearTimeout(b.current),b.current=null),y.current=null,n()},[n]);i.useEffect(()=>{const j=w=>{const C=w;if(!C)return!1;const S=C.tagName;return S==="INPUT"||S==="TEXTAREA"||S==="SELECT"||C.isContentEditable?!0:!!C.closest('[contenteditable="true"]')},k=w=>{if(w==="chat")return document.querySelector('[data-scrollbar="chat"]');if(w==="diff"){const S=Array.from(document.querySelectorAll(".overlay-scrollbar-container[data-diff-virtual-content]")).filter(M=>M.clientHeight<=0||M.scrollHeight<=M.clientHeight?!1:M.offsetParent!==null);return S.length===0?null:S.sort((M,D)=>D.scrollHeight-D.clientHeight-(M.scrollHeight-M.clientHeight))[0]}return null},N=w=>{if(kr(w)&&w.key.toLowerCase()==="p"&&(w.preventDefault(),a()),kr(w)&&w.shiftKey&&w.key.toLowerCase()==="l"){w.preventDefault(),wb();return}if(kr(w)&&w.key==="."&&(w.preventDefault(),l()),kr(w)&&w.key.toLowerCase()==="n"){w.preventDefault();const T=gs(),_=ut.getState().settingsAutoCreateWorktree;if(T?!1:_?!w.shiftKey:w.shiftKey){m("chat"),u(!1),xc();return}m("chat"),u(!1),t()}if(kr(w)&&w.key==="/"){w.preventDefault();const T=["light","dark","system"],F=(T.indexOf(h)+1)%T.length;g(T[F])}if(kr(w)&&!w.shiftKey&&w.key.toLowerCase()==="t"){w.preventDefault();const{isTimelineDialogOpen:T,setTimelineDialogOpen:_}=Te.getState();_(!T);return}if(kr(w)&&!w.shiftKey&&w.key===","){w.preventDefault();const{isSettingsDialogOpen:T}=Te.getState();f(!T);return}if(kr(w)&&!w.shiftKey&&w.key.toLowerCase()==="h"){w.preventDefault();const{isMobile:T,isSessionSwitcherOpen:_}=Te.getState();T?u(!_):c();return}if(kr(w)&&!w.shiftKey&&w.key.toLowerCase()==="l"){w.preventDefault();const{isMobile:T,isSessionSwitcherOpen:_}=Te.getState();T?u(!_):d();return}if(kr(w)&&!w.shiftKey&&w.key.toLowerCase()==="i"){w.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}const C=w.key.toLowerCase(),S=w.ctrlKey&&!w.metaKey&&!w.altKey&&!w.shiftKey,M=!kr(w)&&!w.shiftKey,D=M&&C==="j",A=M&&C==="k",P=M&&C==="d"||S&&C==="d",$=M&&C==="u"||S&&C==="u",R=M&&C==="i";if(D||A||P||$||R){if(j(w.target))return;const{isSettingsDialogOpen:T,isCommandPaletteOpen:_,isHelpDialogOpen:F,isSessionSwitcherOpen:I,isAboutDialogOpen:E,isMultiRunLauncherOpen:W,isImagePreviewOpen:V,activeMainTab:ve}=Te.getState();if(T||_||F||I||E||W||V)return;if(R){w.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}const Z=k(ve);if(!Z)return;const ce=36,Q=Math.max(Math.floor(Z.clientHeight/2),ce*3);let Y=0;if(D&&(Y=ce),A&&(Y=-ce),P&&(Y=Q),$&&(Y=-Q),Y!==0){w.preventDefault();const ie=Math.max(0,Z.scrollHeight-Z.clientHeight),B=Math.max(0,Math.min(ie,Z.scrollTop+Y));B!==Z.scrollTop&&(Z.dispatchEvent(new WheelEvent("wheel",{bubbles:!1,cancelable:!1,deltaY:0})),Z.scrollTo({top:B,behavior:"auto"}));return}}if(w.ctrlKey&&!w.metaKey&&!w.altKey&&!w.shiftKey&&(w.key==="j"||w.key==="k")){if(j(w.target))return;const{isSettingsDialogOpen:T,isCommandPaletteOpen:_,isHelpDialogOpen:F,isSessionSwitcherOpen:I,isAboutDialogOpen:E,isMultiRunLauncherOpen:W,isImagePreviewOpen:V}=Te.getState();if(T||_||F||I||E||W||V)return;const{sessions:oe,currentSessionId:Z,setCurrentSession:ce}=Ae.getState();if(oe.length<=1)return;const Q=[...oe].sort((H,le)=>(le.time?.updated||0)-(H.time?.updated||0)),Y=Q.findIndex(H=>H.id===Z),ie=w.key==="j"?1:-1,B=(Y+ie+Q.length)%Q.length,se=Q[B];se&&se.id!==Z&&(w.preventDefault(),ce(se.id));return}if(kr(w)&&w.shiftKey&&w.key.toLowerCase()==="m"){const{isSettingsDialogOpen:T,isCommandPaletteOpen:_,isHelpDialogOpen:F,isSessionSwitcherOpen:I,isAboutDialogOpen:E,activeMainTab:W,isModelSelectorOpen:V}=Te.getState();if(T||_||F||I||E||!(W==="chat"))return;w.preventDefault(),p(!V);return}if(kr(w)&&w.shiftKey&&w.key.toLowerCase()==="t"){const{isSettingsDialogOpen:T,isCommandPaletteOpen:_,isHelpDialogOpen:F,isSessionSwitcherOpen:I,isAboutDialogOpen:E,activeMainTab:W}=Te.getState();if(T||_||F||I||E||!(W==="chat"))return;const oe=ut.getState();if(oe.getCurrentModelVariants().length===0)return;w.preventDefault(),oe.cycleCurrentVariant();const ce=ut.getState().currentVariant,Q=Ae.getState(),Y=Q.currentSessionId,ie=ut.getState().currentAgentName,B=ut.getState().currentProviderId,se=ut.getState().currentModelId;Y&&ie&&B&&se&&Q.saveAgentModelVariantForSession(Y,ie,B,se,ce);return}if(w.key==="Escape"){const _=!!w.target?.closest('[role="dialog"]'),F=!!document.querySelector('[data-settings-view="true"]');if(_||F){v();return}const{isSettingsDialogOpen:I,isCommandPaletteOpen:E,isHelpDialogOpen:W,isSessionSwitcherOpen:V,isAboutDialogOpen:ve,isMultiRunLauncherOpen:oe,isImagePreviewOpen:Z,activeMainTab:ce}=Te.getState();if(I){w.preventDefault(),f(!1),v();return}if(E||W||V||ve||oe||Z||!(ce==="chat")){v();return}const ie=o;if(!(x.canAbort&&!!ie)){v();return}const se=Date.now(),H=y.current;if(H&&se<H){w.preventDefault(),v(),s();return}w.preventDefault();const le=r(3e3)??se+3e3;y.current=le,b.current&&clearTimeout(b.current);const ge=Math.max(le-se,0);b.current=setTimeout(()=>{y.current&&Date.now()>=y.current&&v()},ge||0);return}};return window.addEventListener("keydown",N),()=>{window.removeEventListener("keydown",N)}},[t,s,a,l,c,u,m,f,p,g,h,x,r,v,o]),i.useEffect(()=>()=>{v()},[v])},Bh="ikanban:menu-action",WE="ikanban:check-for-updates",GE=t=>{const{openNewSessionDraft:s}=Ae(),{toggleCommandPalette:r,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=Te(),{addProject:u}=ps(),{requestAccess:m,startAccessing:f}=yc(),{setThemeMode:p}=rn(),h=i.useCallback(()=>{As()&&m("").then(async x=>{if(!x.success||!x.path){x.error&&x.error!=="Directory selection cancelled"&&K.error("Failed to select directory",{description:x.error});return}const y=await f(x.path);if(!y.success){K.error("Failed to open directory",{description:y.error||"Desktop could not grant file access."});return}u(x.path,{id:x.projectId})||K.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(x=>{console.error("Desktop: Error selecting directory:",x),K.error("Failed to select directory")}),Na.requestDirectoryDialog()},[u,m,f]),g=i.useCallback(x=>{switch(x){case"about":d(!0);break;case"settings":c(!0);break;case"command-palette":r();break;case"new-session":l("chat"),a(!1),s();break;case"new-worktree-session":l("chat"),a(!1),xc();break;case"change-workspace":h();break;case"open-git-tab":{const{activeMainTab:y}=Te.getState();l(y==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:y}=Te.getState();l(y==="diff"?"chat":"diff");break}case"open-files-tab":{const{activeMainTab:y}=Te.getState();l(y==="files"?"chat":"files");break}case"open-terminal-tab":{const{activeMainTab:y}=Te.getState();l(y==="terminal"?"chat":"terminal");break}case"theme-light":p("light");break;case"theme-dark":p("dark");break;case"theme-system":p("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":t?.();break;case"help-dialog":n();break;case"download-logs":{wb().catch(()=>{K.error("Failed to collect OpenCode status")});break}}},[h,t,s,d,l,a,c,p,r,n,o]);i.useEffect(()=>{const x=y=>{const b=y.detail;b&&g(b)};return window.addEventListener(Bh,x),()=>window.removeEventListener(Bh,x)},[g]),i.useEffect(()=>{if(typeof window>"u")return;const y=window.__TAURI__?.event?.listen;if(typeof y!="function")return;let b=null,v=null;return y("ikanban:menu-action",j=>{const k=j?.payload;typeof k=="string"&&g(k)}).then(j=>{b=j}).catch(()=>{}),y("ikanban:check-for-updates",()=>{window.dispatchEvent(new Event(WE))}).then(j=>{v=j}).catch(()=>{}),()=>{(async()=>{try{const k=b?.();k instanceof Promise&&await k}catch{}try{const k=v?.();k instanceof Promise&&await k}catch{}})()}},[g])},KE=()=>{i.useEffect(()=>{let t=!1;return(async()=>{try{const r=await nt.getGlobalSessionStatus();if(t||!r)return;const n=new Map;Object.entries(r).forEach(([o,a])=>{if(!o||!a)return;const l=a;n.set(o,l)}),n.size>0&&Ae.setState({sessionStatus:n})}catch{}})(),()=>{t=!0}},[])},qE=["chat","git","diff","terminal","files"],QE=["settings","agents","commands","skills","providers","git-identities"],Zr={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function zh(t){const s=YE();return{sessionId:JE(s),tab:XE(s),settingsSection:ZE(s),diffFile:eP(s)}}function YE(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function JE(t){const s=t.get(Zr.SESSION);return!s||s.trim().length===0?null:s.trim()}function XE(t){const s=t.get(Zr.TAB);if(!s)return null;const r=s.toLowerCase().trim();return qE.includes(r)?r:null}function ZE(t){const s=t.get(Zr.SETTINGS);if(!s)return null;const r=s.toLowerCase().trim();return QE.includes(r)?r:r==="ikanban"||r==="general"||r==="preferences"?"settings":null}function eP(t){const s=t.get(Zr.FILE);if(!s||s.trim().length===0)return null;try{return decodeURIComponent(s.trim())}catch{return s.trim()}}function Uh(){if(typeof window>"u")return!1;try{const t=new URLSearchParams(window.location.search);return t.has(Zr.SESSION)||t.has(Zr.TAB)||t.has(Zr.SETTINGS)||t.has(Zr.FILE)}catch{return!1}}const tP="chat";function jb(t){const s=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&s.set(Zr.SESSION,t.sessionId),t.isSettingsOpen){const r=t.settingsSection==="sessions"?"settings":t.settingsSection;return s.set(Zr.SETTINGS,r),s}return t.tab!==tP&&s.set(Zr.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&s.set(Zr.FILE,t.diffFile),s}function sP(t,s){const r=typeof window<"u"?window.location.pathname:"/",n=t.toString();return n?`${r}?${n}`:r}function rP(t){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),r=jb(t),n=[...s.entries()].sort((a,l)=>a[0].localeCompare(l[0])),o=[...r.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 nP(t,s={}){if(!(typeof window>"u")&&!oP()&&!(!s.force&&rP(t)))try{const r=jb(t),n=sP(r);s.replace?window.history.replaceState({...window.history.state,route:t},"",n):window.history.pushState({route:t},"",n)}catch{}}function oP(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function aP(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function iP(){const t=i.useMemo(()=>aP(),[]),s=i.useRef(!1),r=i.useRef(!1),n=Ae(f=>f.setCurrentSession),o=Te(f=>f.setActiveMainTab),a=Te(f=>f.setSettingsDialogOpen),l=Te(f=>f.setSidebarSection),c=Te(f=>f.navigateToDiff),d=i.useCallback(async f=>{if(!r.current){r.current=!0;try{if(f.sessionId){const p=Ae.getState().currentSessionId;f.sessionId!==p&&await n(f.sessionId)}if(f.settingsSection){l(f.settingsSection),a(!0);return}Te.getState().isSettingsDialogOpen&&a(!1),f.tab&&o(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&c(f.diffFile)}finally{r.current=!1}}},[n,o,a,l,c]),u=i.useCallback(()=>{const f=Ae.getState(),p=Te.getState();return{sessionId:f.currentSessionId,tab:p.activeMainTab,isSettingsOpen:p.isSettingsDialogOpen,settingsSection:p.sidebarSection,diffFile:p.pendingDiffFile}},[]),m=i.useCallback((f={})=>{if(t||r.current)return;const p=u();nP(p,f)},[t,u]);i.useEffect(()=>{if(s.current||(s.current=!0,!Uh()))return;const f=zh();(async()=>(await d(f),t||m({replace:!0})))()},[d,t,m]),i.useEffect(()=>{if(t)return;let f=Ae.getState().currentSessionId;return Ae.subscribe(h=>{const g=h.currentSessionId;g===f||r.current||(f=g,m())})},[t,m]),i.useEffect(()=>{if(t)return;let f=Te.getState().activeMainTab,p=Te.getState().isSettingsDialogOpen,h=Te.getState().sidebarSection,g=Te.getState().pendingDiffFile;return Te.subscribe(y=>{if(r.current)return;const b=y.activeMainTab!==f,v=y.isSettingsDialogOpen!==p,j=y.sidebarSection!==h,k=y.pendingDiffFile!==g&&y.activeMainTab==="diff";f=y.activeMainTab,p=y.isSettingsDialogOpen,h=y.sidebarSection,g=y.pendingDiffFile,(b||v||j||k)&&m()})},[t,m]),i.useEffect(()=>{if(typeof window>"u"||t)return;const f=()=>{const p=zh();if(Uh())d(p);else{const h=Te.getState();h.isSettingsDialogOpen&&a(!1),h.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[d,t,o,a])}const lP=1e4,Hh=()=>{if(typeof document>"u")return"visible";const t=document.visibilityState;return t==="hidden"&&document.hasFocus()?"visible":t},Vh=t=>{if(!_o())return;const s=Ur();s?.push?.setVisibility&&s.push.setVisibility({visible:t})},cP=()=>{i.useEffect(()=>{if(!_o()||typeof document>"u")return;const t=()=>{Vh(Hh()==="visible")},s=()=>{Hh()==="visible"&&Vh(!0)};t();const r=window.setInterval(s,lP);return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),window.addEventListener("blur",t),()=>{window.clearInterval(r),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t),window.removeEventListener("blur",t)}},[])};function dP(){const{git:t}=Vr(),s=Yt(m=>m.currentDirectory),{currentSessionId:r,sessions:n,worktreeMetadata:o}=Ae(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=or(),u=i.useMemo(()=>{const m=r?o.get(r)??void 0:void 0,p=n.find(h=>h.id===r)?.directory??null;return m?.path??p??s??null},[r,n,o,s]);i.useEffect(()=>{if(!u||!t){c();return}return a(u),d(u,t),l(t),()=>{c()}},[u,t,a,l,c,d])}function uP({children:t}){return dP(),e.jsx(e.Fragment,{children:t})}const mP="curl -fsSL https://opencode.ai/install | bash",fP=3e3;function pP({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(Hr,{className:"h-4 w-4"})})]})}const hP=3e4;function gP({onCliAvailable:t}){const[s,r]=i.useState(!1),[n,o]=i.useState(!1),[a,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState("");i.useEffect(()=>{const b=setTimeout(()=>o(!0),hP);return()=>clearTimeout(b)},[]),i.useEffect(()=>{l(Lr())},[]),i.useEffect(()=>{let b=!1;return(async()=>{try{const v=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!v.ok)return;const j=await v.json().catch(()=>null);if(!j||b)return;const k=typeof j.opencodeBinary=="string"?j.opencodeBinary.trim():"";k&&m(k)}catch{}})(),()=>{b=!0}},[]);const f=i.useCallback(async b=>{if(!b.target.closest("button, a, input, select, textarea, code")&&b.button===0&&a&&As())try{const{getCurrentWindow:v}=await Ks(async()=>{const{getCurrentWindow:k}=await import("@tauri-apps/api/window");return{getCurrentWindow:k}},[]);await v().startDragging()}catch(v){console.error("Failed to start window dragging:",v)}},[a]),p=i.useCallback(async()=>{try{const b=await fetch("/health");if(!b.ok)return!1;const v=await b.json();return v.openCodeRunning===!0||v.isOpenCodeReady===!0}catch{return!1}},[]),h=i.useCallback(async()=>{d(!0);try{await fetch("/api/config/reload",{method:"POST"})}finally{setTimeout(()=>d(!1),1e3)}},[]),g=i.useCallback(async()=>{if(typeof window>"u"||!a||!As())return;const b=window.__TAURI__;if(b?.dialog?.open)try{const v=await b.dialog.open({title:"Select opencode binary",multiple:!1,directory:!1});typeof v=="string"&&v.trim().length>0&&m(v.trim())}catch{}},[a]),x=i.useCallback(async()=>{d(!0);try{await xs({opencodeBinary:u.trim()}),await fetch("/api/config/reload",{method:"POST"})}finally{setTimeout(()=>d(!1),1e3)}},[u]),y=i.useCallback(async()=>{try{await navigator.clipboard.writeText(mP),r(!0),setTimeout(()=>r(!1),2e3)}catch(b){console.error("Failed to copy:",b)}},[]);return i.useEffect(()=>{const b=async()=>{await p()&&t?.()},v=setInterval(b,fP);return b(),()=>clearInterval(v)},[p,t]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:f,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 IKanban"}),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(gn,{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:s?e.jsxs("div",{className:"flex items-center justify-center gap-2",style:{color:"var(--status-success)"},children:[e.jsx(ss,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(pP,{onCopy:y})})}),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(gn,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Waiting for OpenCode installation..."}),e.jsx("div",{className:"flex justify-center",children:e.jsx("button",{type:"button",onClick:h,disabled:c,className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:c?"Retrying…":"Retry"})}),e.jsx("div",{className:"mx-auto w-full max-w-xl pt-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Already installed? Set the OpenCode CLI path:"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Bt,{value:u,onChange:b=>m(b.target.value),placeholder:"/Users/you/.bun/bin/opencode",disabled:c,className:"flex-1 font-mono text-xs"}),e.jsx(Me,{type:"button",variant:"secondary",onClick:g,disabled:c||!a||!As(),children:"Browse"}),e.jsx(Me,{type:"button",onClick:x,disabled:c,children:"Apply"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground/70",children:["Saves to ",e.jsx("code",{className:"text-foreground/70",children:"~/.config/ikanban/settings.json"})," and reloads OpenCode configuration."]})]})})]}),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."]}),e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["If you see ",e.jsx("code",{className:"text-foreground/70",children:"env: node: No such file or directory"})," or ",e.jsx("code",{className:"text-foreground/70",children:"env: bun: No such file or directory"}),", install that runtime or ensure it is on PATH."]})]})]})}const xP=()=>{const[{isUpdating:t,message:s},r]=i.useState(()=>eS());return i.useEffect(()=>Zj(r),[]),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(rm,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:s})]}):null},Sb={getLastAssistantMessage(){const t=Ae.getState(),s=t.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const r=t.messages.get(s);if(!r||r.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=r.length-1;n>=0;n--){const o=r[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,s=80){return!t||typeof t!="string"||t.length<=s?t:t.substring(0,s)+"…"},truncateMessages(t){return t.map(s=>({...s,parts:(s.parts||[]).map(r=>{const n={...r};return"text"in r&&(n.text=this.truncateString(r.text)),"textPreview"in r&&(n.textPreview=this.truncateString(r.textPreview)),r.state&&(n.state={...r.state},"output"in r.state&&(n.state.output=this.truncateString(r.state.output)),"error"in r.state&&(n.state.error=this.truncateString(r.state.error)),r.state.metadata&&"preview"in r.state.metadata&&(n.state.metadata={...r.state.metadata,preview:this.truncateString(r.state.metadata.preview)})),n})}))},getAllMessages(t=!1){const s=Ae.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=s.messages.get(r)||[];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=Yt.getState(),s=Ae.getState(),r=ps.getState(),n=t.currentDirectory||null,o=nt.getDirectory()??null,a=s.sessions||[],l=new Set,c={};a.forEach(C=>{const S=C.directory;typeof S=="string"&&S.trim().length>0?(l.add(S),c[S]=(c[S]??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(C){return{available:!1,error:C instanceof Error?C.message:String(C)}}})(),u=typeof window<"u"?window.__IKANBAN_RUNTIME_APIS__:null,m=typeof window<"u"&&!!window.__TAURI__,f=async C=>{try{return await C.json()}catch{return null}},p=async C=>{try{return await C.text()}catch{return null}},h=async C=>{try{const S=await fetch(C);return S.ok?await f(S):{status:S.status}}catch(S){return{error:S instanceof Error?S.message:String(S)}}};let g=null,x=null,y=null,b=null;const v=n?`/api/path?directory=${encodeURIComponent(n)}`:"/api/path";g=await h(v);const j=n?`/api/project/current?directory=${encodeURIComponent(n)}`:"/api/project/current";x=await h(j),y=await h("/api/config/settings");try{const C=await fetch("/api/health"),S=C.headers.get("content-type")||"",M=await p(C);b={status:C.status,ok:C.ok,contentType:S,type:S.includes("application/json")?"json":"html",preview:M?M.slice(0,120):null}}catch(C){b={error:C instanceof Error?C.message:String(C)}}let k={isGitRepo:null};if(n)try{k.isGitRepo=await Yn(n)}catch(C){k={isGitRepo:null,error:C instanceof Error?C.message:String(C)}}const N=r.projects.map(C=>({id:C.id,path:C.path,label:C.label})),w={runtime:{platform:u?.runtime?.platform??null,isDesktop:m,isVSCode:!!u?.runtime?.isVSCode,hasRuntimeApis:!!u,desktopServerOrigin:null},location:typeof window<"u"?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:n,opencodeDirectory:g?.directory||g?.worktree||o,homeDirectory:t.homeDirectory||null,isHomeReady:t.isHomeReady,hasPersistedDirectory:t.hasPersistedDirectory,isSwitchingDirectory:t.isSwitchingDirectory},projects:{total:r.projects.length,activeProjectId:r.activeProjectId,samples:N},sessions:{total:a.length,currentSessionId:s.currentSessionId,lastLoadedDirectory:s.lastLoadedDirectory,uniqueDirectories:l.size,directorySamples:Array.from(l).slice(0,5),directoryCounts:c},worktrees:{available:s.availableWorktrees.length,metadataEntries:s.worktreeMetadata.size},git:k,localStorage:d,opencode:{pathInfo:g,projectInfo:x,health:b},ikanban:{settingsInfo:y}};return console.log("[DEBUG] App status snapshot:",w),w},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 s=t.isEmpty||t.isEmptyResponse;return s?(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!"),s},getStreamingState(){const t=Ae.getState(),s=t.currentSessionId?t.streamingMessageIds.get(t.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:s,streamingMessageIds:Array.from(t.streamingMessageIds.entries()),messageStreamStates:Array.from(t.messageStreamStates.entries())}),{streamingMessageId:s,streamingMessageIds:t.streamingMessageIds,streamStates:t.messageStreamStates}},findEmptyMessages(){const t=Ae.getState(),s=t.currentSessionId;if(!s)return console.log("[ERROR] No active session"),[];const n=(t.messages.get(s)||[]).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:
|
|
291
|
+
`),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
|
|
292
|
+
`),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
|
|
293
|
+
`),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)
|
|
294
|
+
`),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:s=!1,verbose:r=!0,maxTableRows:n=25}=t,o=Ae.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const l=o.messages.get(a)||[],c=s?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:[],y=g.time??{},b=u(y.completed),v=b!==null,j=x.filter(P=>P.type==="tool"),k=x.filter(P=>P.type==="reasoning"),N=m(j.map(P=>u(P.state?.time?.end??P.state?.time?.start))),w=m(k.map(P=>u(P.time?.end??P.time?.start))),C=m([N,w].filter(P=>P!==null)),S=j.some(P=>["pending","running","started"].includes(P.state?.status)),M=k.some(P=>typeof P.time?.end!="number");j.length>0&&(d.withTools+=1),k.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const D=!!(v&&typeof N=="number"&&b<N);D&&(d.completedBeforeTool+=1);const A=!!(v&&typeof w=="number"&&b<w);return A&&(d.completedBeforeReasoning+=1),v&&S&&(d.runningToolsWhenCompleted+=1),v&&M&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:b,latestToolTimestamp:N,latestReasoningTimestamp:w,latestPartTimestamp:C,completed_missing:!v,completed_before_tool:D,completed_before_reasoning:A,running_tools_when_completed:!!(v&&S),reasoning_open_when_completed:!!(v&&M),has_tools:j.length>0,has_reasoning:k.length>0}});return r&&(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=Ae.getState(),s=t.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const n=(t.messages.get(s)||[]).filter(y=>y.info.role==="assistant");if(n.length===0)return console.log("[ERROR] No assistant messages"),null;const o=n[n.length-1],a=o.parts.filter(y=>y.type==="step-finish"),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=Sb,tr()&&(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 s=t.message||"",r=t.filename||"";typeof s=="string"&&s.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(r))&&t.preventDefault()}catch{}}));const yP=({open:t,onOpenChange:s})=>{const[r,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 Sb.copyDiagnosticsReport()).ok?(c(!0),K.success("Diagnostics copied")):K.error("Copy failed")}catch(m){K.error("Copy failed"),console.error("Failed to copy diagnostics:",m)}finally{a(!1)}}},[o]);i.useEffect(()=>{if(!t)return;typeof window<"u"&&!!window.__TAURI__?(async()=>{try{const{getVersion:p}=await Ks(async()=>{const{getVersion:g}=await import("@tauri-apps/api/app");return{getVersion:g}},[]),h=await p();n(h)}catch{n("0.1.5")}})():n("0.1.5")},[t]);const u=r;return e.jsx(bs,{open:t,onOpenChange:s,children:e.jsx(vs,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(rm,{width:64,height:64}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"IKanban"}),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 IKanban 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/ikanban",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(uo,{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(Rg,{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(Hd,{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 Ed({apis:t,children:s}){return e.jsx(Vu.Provider,{value:t,children:s})}const bP=()=>{const{isAboutDialogOpen:t,setAboutDialogOpen:s}=Te();return e.jsx(yP,{open:t,onOpenChange:s})};function vP({apis:t}){const{initializeApp:s,isInitialized:r,isConnected:n}=ut(),{error:o,clearError:a,loadSessions:l}=Ae(),c=Yt(w=>w.currentDirectory),d=Yt(w=>w.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=ob(),h=$r(w=>w.refreshStatus),[g,x]=i.useState(()=>t.runtime.isVSCode),[y,b]=i.useState(!1),v=i.useRef(!1);i.useEffect(()=>{x(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>(Tm(t),()=>Tm(null)),[t]),i.useEffect(()=>{h(t.github,{force:!0})},[t.github,h]),i.useEffect(()=>{if(typeof document>"u")return;const w=document.documentElement,C=lh[f]?.stack??lh[kI].stack,S=ko[p]?.stack??ko[Sl].stack;w.style.setProperty("--font-sans",C),w.style.setProperty("--font-heading",C),w.style.setProperty("--font-family-sans",C),w.style.setProperty("--font-mono",S),w.style.setProperty("--font-family-mono",S),w.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=C)},[f,p]),i.useEffect(()=>{if(r){const C=setTimeout(()=>{const S=document.getElementById("initial-loading");S&&(S.classList.add("fade-out"),setTimeout(()=>{S.remove()},300))},150);return()=>clearTimeout(C)}},[r]),i.useEffect(()=>{const w=setTimeout(()=>{const C=document.getElementById("initial-loading");C&&!r&&(C.classList.add("fade-out"),setTimeout(()=>{C.remove()},300))},5e3);return()=>clearTimeout(w)},[r]),i.useEffect(()=>{(async()=>g||await s())()},[s,g]),i.useEffect(()=>{if(d)return;(async()=>g||n&&(nt.setDirectory(c),await l()))()},[c,d,l,n,g]),i.useEffect(()=>{typeof window>"u"||!r||d||v.current||(v.current=!0,window.__ikanbanAppReady=!0,window.dispatchEvent(new Event("ikanban:app-ready")))},[r,d]),$E(),W0(),cP(),iP(),VE();const j=i.useCallback(()=>{m(w=>!w)},[]);GE(j);const k=ut(w=>w.settingsAutoCreateWorktree);i.useEffect(()=>{if(!As())return;const w=window.__TAURI__;typeof w?.core?.invoke=="function"&&w.core.invoke("desktop_set_auto_worktree_menu",{enabled:k})},[k]),KE(),fb(),i.useEffect(()=>{const w=C=>{kr(C)&&C.shiftKey&&C.key==="D"&&(C.preventDefault(),m(S=>!S))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]),i.useEffect(()=>{if(!Lr()||!Or())return;let w=!1;return(async()=>{try{const S=await fetch("/health",{method:"GET"});if(!S.ok)return;const M=await S.json().catch(()=>null);if(!M||w)return;const D=M.openCodeRunning===!0,A=typeof M.lastOpenCodeError=="string"?M.lastOpenCodeError:"",P=!D&&/ENOENT|spawn\s+opencode|Unable\s+to\s+locate\s+the\s+opencode\s+CLI|OpenCode\s+CLI\s+not\s+found|opencode(\.exe)?\s+not\s+found|env:\s*(node|bun):\s*No\s+such\s+file\s+or\s+directory|(node|bun):\s*No\s+such\s+file\s+or\s+directory/i.test(A);b(P)}catch{}})(),()=>{w=!0}},[]);const N=i.useCallback(()=>{b(!1),window.location.reload()},[]);return y?e.jsx(Gs,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(gP,{onCliAvailable:N})})}):g?(typeof window<"u"?window.__IKANBAN_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(Gs,{children:e.jsx(Ed,{apis:t,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(AE,{}),e.jsx(Vc,{})]})})}):e.jsx(Gs,{children:e.jsx(Ed,{apis:t,children:e.jsx(Yp,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(xE,{}),e.jsx(Vc,{})]})})})}):e.jsx(Gs,{children:e.jsx(Ed,{apis:t,children:e.jsx(uP,{children:e.jsx(Yp,{children:e.jsx(EM,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(mE,{}),e.jsx(Vc,{}),e.jsx(xP,{}),e.jsx(bP,{}),u&&e.jsx(DE,{onClose:()=>m(!1)})]})})})})})})}const Nb=async()=>{if(typeof window>"u")return;let t=null,s=null;try{t=window.localStorage.getItem("homeDirectory"),s=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const r=Yt.getState();t&&r.homeDirectory!==t&&r.synchronizeHomeDirectory(t),s&&!gs()&&r.setDirectory(s,{showOverlay:!1})},kb="/auth/session",wP=async()=>fetch(kb,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Wh=async t=>fetch(kb,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:t})}),mm=({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})]}),jP=({message:t="Preparing workspace…"})=>e.jsx(mm,{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})})}),Gh=({onRetry:t,errorType:s="network",retryAfter:r})=>{const n=s==="rate-limit",o=r?Math.ceil(r/60):1;return e.jsx(mm,{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:n?"Too many attempts":"Unable to reach server"}),e.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:n?`Please wait ${o} minute${o>1?"s":""} before trying again.`:"We couldn't verify the UI session. Check that the service is running and try again."})]}),e.jsx(Me,{type:"button",onClick:t,className:"w-full max-w-xs",children:"Retry"})]})})},SP=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},NP=()=>{try{const t=new URL(window.location.href);t.searchParams.delete("token"),window.history.replaceState({},"",t.toString())}catch{}},kP=({children:t})=>{const s=i.useMemo(()=>gs(),[]),r=s,n=i.useMemo(()=>Lr()&&!s,[s]),[o,a]=i.useState(()=>r?"authenticated":"pending"),[l,c]=i.useState(""),[d,u]=i.useState(!1),[m,f]=i.useState(""),[p,h]=i.useState(void 0),g=i.useRef(null),x=i.useRef(r),y=i.useRef(!1),b=i.useCallback(async()=>{if(r){a("authenticated");return}a(j=>j==="authenticated"?j:"pending");try{const j=await wP();if(j.ok){a("authenticated"),f(""),h(void 0);return}if(j.status===401){a("locked"),h(void 0);return}if(j.status===429){const k=await j.json().catch(()=>({}));h(k.retryAfter),a("rate-limited");return}a("error")}catch(j){console.warn("Failed to check session status:",j),a("error")}},[r]);i.useEffect(()=>{r||b()},[b,r]),i.useEffect(()=>{!r&&o==="locked"&&(x.current=!1)},[r,o]),i.useEffect(()=>{o==="locked"&&g.current&&(g.current.focus(),g.current.select())},[o]),i.useEffect(()=>{if(r||o!=="locked"||y.current||d)return;const j=SP();j&&(y.current=!0,NP(),u(!0),f(""),Wh(j).then(k=>{if(k.ok){c(""),a("authenticated");return}if(k.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(k=>{console.warn("Failed to submit URL token:",k),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[r,o,d]),i.useEffect(()=>{r||o==="authenticated"&&!x.current&&(x.current=!0,(async()=>(await Jg(),await Xg(),await Nb()))())},[r,o]);const v=async j=>{if(j.preventDefault(),!(!l||d)){u(!0),f("");try{const k=await Wh(l);if(k.ok){c(""),a("authenticated");return}if(k.status===401){f("Incorrect password. Try again."),a("locked");return}if(k.status===429){const N=await k.json().catch(()=>({}));h(N.retryAfter),a("rate-limited");return}f("Unexpected response from server."),a("error")}catch(k){console.warn("Failed to submit UI password:",k),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(jP,{}):o==="error"?e.jsx(Gh,{onRetry:()=>{b()},errorType:"network"}):o==="rate-limited"?e.jsx(Gh,{onRetry:()=>{b()},errorType:"rate-limit",retryAfter:p}):o==="locked"?e.jsx(mm,{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 IKanban"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"This session is password-protected."})]}),e.jsxs("form",{onSubmit:v,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(hj,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(Bt,{id:"ikanban-ui-password",ref:g,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:l,onChange:j=>{c(j.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(Me,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Ot,{className:"h-4 w-4 animate-spin"}):e.jsx(gj,{className:"h-4 w-4"})})]}),m&&e.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:m})]}),n&&e.jsxs("div",{className:"w-full",children:[e.jsx(pC,{}),e.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})]})}):e.jsx(e.Fragment,{children:t})},Pd=t=>{if(!t||typeof t!="string")return null;const s=t.trim();if(!s.startsWith("#"))return null;let r=s.slice(1);if((r.length===3||r.length===4)&&(r=r.split("").map(c=>c+c).join("")),r.length===8&&(r=r.slice(0,6)),r.length!==6)return null;const n=Number.parseInt(r,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,l=n&255;return`${o} ${a} ${l}`};class CP{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(s){const r=[];return r.push(...this.generateTailwindVariables(s)),r.push(...this.generatePrimaryColors(s.colors.primary)),r.push(...this.generateSurfaceColors(s.colors.surface)),r.push(...this.generateInteractiveColors(s.colors.interactive)),r.push(...this.generateStatusColors(s.colors.status)),r.push(...this.generatePullRequestColors(s)),r.push(...this.generateSyntaxColors(s.colors.syntax)),r.push(...this.generateComponentColors(s.colors,s)),r.push(...this.generateTypographyVariables()),s.config&&r.push(...this.generateConfigVariables(s.config)),r.join(`
|
|
295
|
+
`)}generateTailwindVariables(s){const r=[];r.push(` --background: ${s.colors.surface.background} !important;`),r.push(` --foreground: ${s.colors.surface.foreground} !important;`),r.push(` --muted: ${s.colors.surface.muted} !important;`),r.push(` --muted-foreground: ${s.colors.surface.mutedForeground} !important;`),r.push(` --card: ${s.colors.surface.elevated} !important;`),r.push(` --card-foreground: ${s.colors.surface.elevatedForeground} !important;`),r.push(` --popover: ${s.colors.surface.elevated} !important;`),r.push(` --popover-foreground: ${s.colors.surface.elevatedForeground} !important;`),r.push(` --border: ${s.colors.interactive.border} !important;`),r.push(` --input: ${s.colors.interactive.border} !important;`),r.push(` --primary: ${s.colors.primary.base} !important;`),r.push(` --primary-foreground: ${s.colors.primary.foreground} !important;`),r.push(` --secondary: ${s.colors.surface.muted} !important;`),r.push(` --secondary-foreground: ${s.colors.surface.mutedForeground} !important;`),r.push(` --accent: ${s.colors.surface.subtle} !important;`),r.push(` --accent-foreground: ${s.colors.surface.foreground} !important;`),r.push(` --destructive: ${s.colors.status.error} !important;`),r.push(` --destructive-foreground: ${s.colors.status.errorForeground} !important;`),r.push(` --ring: ${s.colors.interactive.focusRing} !important;`),s.config?.radius?.md&&r.push(` --radius: ${s.config.radius.md} !important;`);const n=Pd(s.colors.surface.muted),o=Pd(s.colors.surface.subtle),a=Pd(s.colors.interactive.border);r.push(` --sidebar-base: ${s.colors.surface.muted} !important;`),n&&r.push(` --sidebar-base-rgb: ${n} !important;`),r.push(" --sidebar: var(--sidebar-base) !important;"),r.push(` --sidebar-foreground: ${s.colors.surface.mutedForeground} !important;`),r.push(` --sidebar-primary: ${s.colors.primary.base} !important;`),r.push(` --sidebar-primary-foreground: ${s.colors.primary.foreground} !important;`),r.push(` --sidebar-accent-base: ${s.colors.surface.subtle} !important;`),o&&r.push(` --sidebar-accent-base-rgb: ${o} !important;`),r.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),r.push(` --sidebar-accent-foreground: ${s.colors.surface.foreground} !important;`),r.push(` --sidebar-border: ${s.colors.interactive.border} !important;`),a&&r.push(` --sidebar-border-rgb: ${a} !important;`),r.push(` --sidebar-ring: ${s.colors.interactive.focusRing} !important;`);const l=s.metadata.variant==="dark",c=l?.8:.95,d=l?.7:.9;if(n)r.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !important;`),r.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=s.colors.surface.muted;r.push(` --sidebar-overlay-strong: ${this.opacity(u,c)} !important;`),r.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return s.colors.charts?.series&&Array.isArray(s.colors.charts.series)&&s.colors.charts.series.forEach((u,m)=>{r.push(` --chart-${m+1}: ${u};`)}),s.colors.loading?(r.push(` --loading-spinner: ${s.colors.loading.spinner||s.colors.primary.base};`),r.push(` --loading-spinner-track: ${s.colors.loading.spinnerTrack||s.colors.surface.muted};`)):(r.push(` --loading-spinner: ${s.colors.primary.base};`),r.push(` --loading-spinner-track: ${s.colors.surface.muted};`)),r}apply(s){const r=this.generate(s),n=document.createElement("style");n.id="opencode-theme-variables";let o="";s.metadata.variant==="dark"?(o=`:root {
|
|
296
|
+
${r}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
.dark {
|
|
300
|
+
${r}
|
|
301
|
+
}`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
|
|
302
|
+
${r}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
:root:not(.dark) {
|
|
306
|
+
${r}
|
|
307
|
+
}`,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",s.metadata.variant)}generatePrimaryColors(s){const r=[];return r.push(` --primary-base: ${s.base};`),r.push(` --primary-hover: ${s.hover||this.darken(s.base,10)};`),r.push(` --primary-active: ${s.active||this.darken(s.base,20)};`),r.push(` --primary-foreground: ${s.foreground||"#ffffff"};`),r.push(` --primary-muted: ${s.muted||this.opacity(s.base,.5)};`),r.push(` --primary-emphasis: ${s.emphasis||this.lighten(s.base,10)};`),r}generateSurfaceColors(s){const r=[];return r.push(` --surface-background: ${s.background};`),r.push(` --surface-foreground: ${s.foreground};`),r.push(` --surface-muted: ${s.muted};`),r.push(` --surface-muted-foreground: ${s.mutedForeground};`),r.push(` --surface-elevated: ${s.elevated};`),r.push(` --surface-elevated-foreground: ${s.elevatedForeground};`),r.push(` --surface-overlay: ${s.overlay};`),r.push(` --surface-subtle: ${s.subtle};`),r}generateInteractiveColors(s){const r=[];return r.push(` --interactive-border: ${s.border};`),r.push(` --interactive-border-hover: ${s.borderHover};`),r.push(` --interactive-border-focus: ${s.borderFocus};`),r.push(` --interactive-selection: ${s.selection};`),r.push(` --interactive-selection-foreground: ${s.selectionForeground};`),r.push(` --interactive-focus: ${s.focus};`),r.push(` --interactive-focus-ring: ${s.focusRing};`),r.push(` --interactive-cursor: ${s.cursor};`),r.push(` --interactive-hover: ${s.hover};`),r.push(` --interactive-active: ${s.active};`),r}generateStatusColors(s){const r=[];return r.push(` --status-error: ${s.error};`),r.push(` --status-error-foreground: ${s.errorForeground};`),r.push(` --status-error-background: ${s.errorBackground};`),r.push(` --status-error-border: ${s.errorBorder};`),r.push(` --status-warning: ${s.warning};`),r.push(` --status-warning-foreground: ${s.warningForeground};`),r.push(` --status-warning-background: ${s.warningBackground};`),r.push(` --status-warning-border: ${s.warningBorder};`),r.push(` --status-success: ${s.success};`),r.push(` --status-success-foreground: ${s.successForeground};`),r.push(` --status-success-background: ${s.successBackground};`),r.push(` --status-success-border: ${s.successBorder};`),r.push(` --status-info: ${s.info};`),r.push(` --status-info-foreground: ${s.infoForeground};`),r.push(` --status-info-background: ${s.infoBackground};`),r.push(` --status-info-border: ${s.infoBorder};`),r}generatePullRequestColors(s){const r=[],n=s.colors.pr;return r.push(` --pr-open: ${n?.open||s.colors.status.success};`),r.push(` --pr-draft: ${n?.draft||s.colors.surface.mutedForeground};`),r.push(` --pr-blocked: ${n?.blocked||s.colors.status.warning};`),r.push(` --pr-merged: ${n?.merged||(s.metadata.variant==="dark"?"#8957e5":"#8250df")};`),r.push(` --pr-closed: ${n?.closed||s.colors.status.error};`),r}generateSyntaxColors(s){const r=[];r.push(` --syntax-background: ${s.base.background};`),r.push(` --syntax-foreground: ${s.base.foreground};`),r.push(` --syntax-comment: ${s.base.comment};`),r.push(` --syntax-keyword: ${s.base.keyword};`),r.push(` --syntax-string: ${s.base.string};`),r.push(` --syntax-number: ${s.base.number};`),r.push(` --syntax-function: ${s.base.function};`),r.push(` --syntax-variable: ${s.base.variable};`),r.push(` --syntax-type: ${s.base.type};`),r.push(` --syntax-operator: ${s.base.operator};`);const n=this.generateSyntaxTokens(s);for(const[o,a]of Object.entries(n))r.push(` --syntax-${this.kebabCase(o)}: ${a};`);return r}generateSyntaxTokens(s){const r=s.base,n=s.tokens||{};return{commentDoc:n.commentDoc||this.lighten(r.comment,10),stringEscape:n.stringEscape||this.darken(r.string,20),stringInterpolation:n.stringInterpolation||r.variable,stringRegex:n.stringRegex||this.adjustHue(r.string,15),keywordControl:n.keywordControl||r.keyword,keywordOperator:n.keywordOperator||r.operator,keywordImport:n.keywordImport||this.lighten(r.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(r.keyword),functionCall:n.functionCall||this.lighten(r.function,5),functionBuiltin:n.functionBuiltin||this.darken(r.function,10),method:n.method||r.function,methodCall:n.methodCall||this.lighten(r.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(r.variable),variableProperty:n.variableProperty||this.lighten(r.variable,10),variableReadonly:n.variableReadonly||r.number,parameter:n.parameter||r.variable,typePrimitive:n.typePrimitive||this.darken(r.type,10),typeInterface:n.typeInterface||r.type,className:n.className||this.emphasize(r.type),enum:n.enum||r.type,boolean:n.boolean||r.number,null:n.null||this.opacity(r.number,.7),constant:n.constant||r.number,punctuation:n.punctuation||this.opacity(r.foreground,.7),delimiter:n.delimiter||this.opacity(r.foreground,.8),bracket:n.bracket||r.foreground,tag:n.tag||r.keyword,tagAttribute:n.tagAttribute||r.variable,tagAttributeValue:n.tagAttributeValue||r.string,tagBracket:n.tagBracket||this.opacity(r.foreground,.8),decorator:n.decorator||r.function,annotation:n.annotation||r.function,namespace:n.namespace||this.opacity(r.type,.8),module:n.module||this.opacity(r.type,.8),...n}}generateComponentColors(s,r){const n=[];return s.markdown?n.push(...this.generateMarkdownColors(s.markdown,r)):n.push(...this.generateDefaultMarkdownColors(r)),s.chat?n.push(...this.generateChatColors(s.chat,r)):n.push(...this.generateDefaultChatColors(r)),s.tools?n.push(...this.generateToolColors(s.tools,r)):n.push(...this.generateDefaultToolColors(r)),n}generateMarkdownColors(s,r){const n=[],o=r.colors.primary.base,a=r.colors.chat?.background||r.colors.surface.background;return n.push(` --markdown-heading1: ${s.heading1||o};`),n.push(` --markdown-heading2: ${s.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${s.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${s.heading4||r.colors.surface.foreground};`),n.push(` --markdown-link: ${s.link||o};`),n.push(` --markdown-link-hover: ${s.linkHover||r.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${s.inlineCode||r.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${s.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${s.blockquote||r.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${s.blockquoteBorder||r.colors.interactive.border};`),n.push(` --markdown-list-marker: ${s.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${s.bold||r.colors.surface.foreground};`),n.push(` --markdown-italic: ${s.italic||this.opacity(r.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${s.strikethrough||r.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${s.hr||r.colors.interactive.border};`),n}generateDefaultMarkdownColors(s){const r=[],n=s.colors.primary.base,o=s.colors.chat?.background||s.colors.surface.background;return r.push(` --markdown-heading1: ${n};`),r.push(` --markdown-heading2: ${this.opacity(n,.9)};`),r.push(` --markdown-heading3: ${this.opacity(n,.8)};`),r.push(` --markdown-heading4: ${s.colors.surface.foreground};`),r.push(` --markdown-link: ${n};`),r.push(` --markdown-link-hover: ${s.colors.primary.hover||this.darken(n,10)};`),r.push(` --markdown-inline-code: ${s.colors.syntax.base.string};`),r.push(` --markdown-inline-code-bg: ${o};`),r.push(` --markdown-blockquote: ${s.colors.surface.mutedForeground};`),r.push(` --markdown-blockquote-border: ${s.colors.interactive.border};`),r.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),r.push(` --markdown-bold: ${s.colors.surface.foreground};`),r.push(` --markdown-italic: ${this.opacity(s.colors.surface.foreground,.9)};`),r.push(` --markdown-strikethrough: ${s.colors.surface.mutedForeground};`),r.push(` --markdown-hr: ${s.colors.interactive.border};`),r}generateChatColors(s,r){const n=[],o=s.background||r.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${s.userMessage||r.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${s.userMessageBackground||r.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${s.assistantMessage||r.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${s.assistantMessageBackground||r.colors.surface.muted};`),n.push(` --chat-timestamp: ${s.timestamp||r.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${s.divider||r.colors.interactive.border};`),n.push(` --chat-typing: ${s.typing||r.colors.surface.mutedForeground};`),n}generateDefaultChatColors(s){const r=[];return r.push(` --chat-background: ${s.colors.surface.background};`),r.push(` --chat-user-message: ${s.colors.surface.foreground};`),r.push(` --chat-user-message-bg: ${s.colors.surface.elevated};`),r.push(` --chat-assistant-message: ${s.colors.surface.foreground};`),r.push(` --chat-assistant-message-bg: ${s.colors.surface.muted};`),r.push(` --chat-timestamp: ${s.colors.surface.mutedForeground};`),r.push(` --chat-divider: ${s.colors.interactive.border};`),r.push(` --chat-typing: ${s.colors.surface.mutedForeground};`),r}generateToolColors(s,r){const n=[];return n.push(` --tools-background: ${s?.background||this.opacity(r.colors.surface.muted,.2)};`),n.push(` --tools-border: ${s?.border||this.opacity(r.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${s?.headerHover||this.opacity(r.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${s?.icon||r.colors.surface.mutedForeground};`),n.push(` --tools-title: ${s?.title||r.colors.surface.foreground};`),n.push(` --tools-description: ${s?.description||this.opacity(r.colors.surface.mutedForeground,.6)};`),s?.edit?(n.push(` --tools-edit-added: ${s.edit.added||r.colors.status.success};`),n.push(` --tools-edit-added-bg: ${s.edit.addedBackground||r.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${s.edit.removed||r.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${s.edit.removedBackground||r.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${s.edit.modified||r.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${s.edit.modifiedBackground||r.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${s.edit.lineNumber||this.opacity(r.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${r.colors.status.success};`),n.push(` --tools-edit-added-bg: ${r.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${r.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${r.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${r.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${r.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(r.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(s){const r=[];return r.push(` --tools-background: ${this.opacity(s.colors.surface.muted,.2)};`),r.push(` --tools-border: ${this.opacity(s.colors.interactive.border,.3)};`),r.push(` --tools-header-hover: ${this.opacity(s.colors.surface.muted,.3)};`),r.push(` --tools-icon: ${s.colors.surface.mutedForeground};`),r.push(` --tools-title: ${s.colors.surface.foreground};`),r.push(` --tools-description: ${this.opacity(s.colors.surface.mutedForeground,.6)};`),r.push(` --tools-edit-added: ${s.colors.status.success};`),r.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.successBackground),.15)};`),r.push(` --tools-edit-removed: ${s.colors.status.error};`),r.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.errorBackground),.15)};`),r.push(` --tools-edit-modified: ${s.colors.status.info};`),r.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.infoBackground),.15)};`),r.push(` --tools-edit-line-number: ${this.opacity(s.colors.surface.mutedForeground,.6)};`),r}generateConfigVariables(s){const r=[];return s&&(s.fonts&&(s.fonts.sans&&(r.push(` --font-sans: ${s.fonts.sans};`),r.push(` --font-family-sans: ${s.fonts.sans};`)),s.fonts.mono&&(r.push(` --font-mono: ${s.fonts.mono};`),r.push(` --font-family-mono: ${s.fonts.mono};`)),s.fonts.heading&&r.push(` --font-heading: ${s.fonts.heading};`)),s.radius&&(s.radius.none&&r.push(` --radius-none: ${s.radius.none};`),s.radius.sm&&r.push(` --radius-sm: ${s.radius.sm};`),s.radius.md&&r.push(` --radius-md: ${s.radius.md};`),s.radius.lg&&r.push(` --radius-lg: ${s.radius.lg};`),s.radius.xl&&r.push(` --radius-xl: ${s.radius.xl};`),s.radius.full&&r.push(` --radius-full: ${s.radius.full};`)),s.transitions&&(s.transitions.fast&&r.push(` --transition-fast: ${s.transitions.fast};`),s.transitions.normal&&r.push(` --transition-normal: ${s.transitions.normal};`),s.transitions.slow&&r.push(` --transition-slow: ${s.transitions.slow};`))),r}generateTypographyVariables(){const s=[],r=gs()?Hj:Tu;return s.push(" /* Semantic Typography Variables */"),s.push(" --ui-regular-font-weight: 400;"),s.push(" /* Markdown content - all markdown elements use same size */"),s.push(` --text-markdown: ${r.markdown};`),s.push(" /* Code content - all code elements use same size */"),s.push(` --text-code: ${r.code};`),s.push(" /* UI headers - dialog titles, panel headers */"),s.push(` --text-ui-header: ${r.uiHeader};`),s.push(" /* UI labels - buttons, menus, navigation */"),s.push(` --text-ui-label: ${r.uiLabel};`),s.push(" /* Metadata - timestamps, status, helper text */"),s.push(` --text-meta: ${r.meta};`),s.push(" /* Micro text - badges, shortcuts, indicators */"),s.push(` --text-micro: ${r.micro};`),s.push(" /* Heading line height and letter spacing */"),s.push(" --h1-line-height: 1.25rem;"),s.push(" --h2-line-height: 1.25rem;"),s.push(" --h3-line-height: 1.5rem;"),s.push(" --h4-line-height: 1.5rem;"),s.push(" --h5-line-height: 1.5rem;"),s.push(" --h6-line-height: 1.5rem;"),s.push(" --h1-letter-spacing: -0.025em;"),s.push(" --h2-letter-spacing: -0.02em;"),s.push(" --h3-letter-spacing: -0.015em;"),s.push(" --h4-letter-spacing: -0.01em;"),s.push(" --h5-letter-spacing: 0;"),s.push(" --h6-letter-spacing: 0.01em;"),s.push(" /* UI element line height and letter spacing */"),s.push(" --ui-button-line-height: 1.375rem;"),s.push(" --ui-button-letter-spacing: 0.02em;"),s.push(" --ui-button-font-weight: 500;"),s.push(" --ui-label-line-height: 1rem;"),s.push(" --ui-label-letter-spacing: 0.03em;"),s.push(" --ui-label-font-weight: 500;"),s.push(" --ui-caption-line-height: 1rem;"),s.push(" --ui-caption-letter-spacing: 0.025em;"),s.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" /* Markdown line height and letter spacing */"),s.push(" --markdown-body-line-height: 1.5rem;"),s.push(" --markdown-body-letter-spacing: 0;"),s.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-h1-line-height: 1.25rem;"),s.push(" --markdown-h1-letter-spacing: -0.025em;"),s.push(" --markdown-h2-line-height: 1.25rem;"),s.push(" --markdown-h2-letter-spacing: -0.02em;"),s.push(" --markdown-h3-line-height: 1.5rem;"),s.push(" --markdown-h3-letter-spacing: -0.015em;"),s.push(" --markdown-h4-line-height: 1.5rem;"),s.push(" --markdown-h4-letter-spacing: -0.01em;"),s.push(" --markdown-h5-line-height: 1.5rem;"),s.push(" --markdown-h5-letter-spacing: 0;"),s.push(" --markdown-h6-line-height: 1.5rem;"),s.push(" --markdown-h6-letter-spacing: 0.01em;"),s.push(" --markdown-list-line-height: 1.375rem;"),s.push(" --markdown-code-block-line-height: 1rem;"),s.push(" --ui-button-small-line-height: 1.25rem;"),s.push(" --ui-button-small-letter-spacing: 0.02em;"),s.push(" --ui-button-small-font-weight: 500;"),s.push(" --markdown-body-small-line-height: 1.375rem;"),s.push(" --markdown-body-small-letter-spacing: 0;"),s.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --ui-button-large-line-height: 1.5rem;"),s.push(" --ui-button-large-letter-spacing: 0.02em;"),s.push(" --ui-button-large-font-weight: 500;"),s.push(" --markdown-body-large-line-height: 1.625rem;"),s.push(" --markdown-body-large-letter-spacing: 0;"),s.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" /* Code line height and letter spacing */"),s.push(" --code-inline-line-height: 1rem;"),s.push(" --code-inline-letter-spacing: 0;"),s.push(" --code-inline-font-weight: 400;"),s.push(" --code-block-line-height: 1.4rem;"),s.push(" --code-block-letter-spacing: 0;"),s.push(" --code-block-font-weight: 400;"),s.push(" --code-line-numbers-line-height: 1.25rem;"),s.push(" --code-line-numbers-letter-spacing: 0;"),s.push(" --code-line-numbers-font-weight: 400;"),s.push(" /* Additional UI element line height and letter spacing */"),s.push(" --ui-badge-line-height: 1rem;"),s.push(" --ui-badge-letter-spacing: 0.025em;"),s.push(" --ui-badge-font-weight: 500;"),s.push(" --ui-tooltip-line-height: 1rem;"),s.push(" --ui-tooltip-letter-spacing: 0.025em;"),s.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --ui-input-line-height: 1.375rem;"),s.push(" --ui-input-letter-spacing: 0.02em;"),s.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --ui-helper-text-line-height: 1rem;"),s.push(" --ui-helper-text-letter-spacing: 0.025em;"),s.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" /* Additional markdown line height and letter spacing */"),s.push(" --markdown-blockquote-line-height: 1.5rem;"),s.push(" --markdown-blockquote-letter-spacing: 0;"),s.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-list-letter-spacing: 0;"),s.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-link-line-height: 1.5rem;"),s.push(" --markdown-link-letter-spacing: 0;"),s.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-code-line-height: 1.35;"),s.push(" --markdown-code-letter-spacing: 0;"),s.push(" --markdown-code-font-weight: 400;"),s.push(" --markdown-code-block-letter-spacing: 0;"),s.push(" --markdown-code-block-font-weight: 400;"),s}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(s,r){return s.startsWith("#")?`${s}${Math.round(r*255).toString(16).padStart(2,"0")}`:s.startsWith("rgb")?s.replace("rgb","rgba").replace(")",`, ${r})`):s}removeTransparency(s){return s.startsWith("#")?s.length===9?s.slice(0,7):s.length===5?s.slice(0,4):s:s.startsWith("rgba")?s.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):s}addTransparency(s,r){if(s.startsWith("#")){const n=s.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}, ${r})`}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}, ${r})`}}return s.startsWith("rgb")?s.replace("rgb","rgba").replace(")",`, ${r})`):s}darken(s,r){if(s.startsWith("#")){const n=parseInt(s.slice(1),16),o=Math.round(2.55*r),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 s}lighten(s,r){if(s.startsWith("#")){const n=parseInt(s.slice(1),16),o=Math.round(2.55*r),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 s}adjustHue(s,r){return this.lighten(s,r/10)}emphasize(s){return this.lighten(s,15)}kebabCase(s){return s.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const MP=_x,AP=$x,DP=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,IP=t=>Bo(t==="dark"),TP=typeof window<"u"?i.useLayoutEffect:i.useEffect,EP=t=>typeof t=="string"&&t.trim().length>0,Kh=(t,s)=>s.reduce((r,n)=>r&&typeof r=="object"?r[n]:void 0,t),PP=t=>{if(!t||typeof t!="object")return!1;const s=[["metadata","id"],["metadata","name"],["metadata","variant"],["colors","primary","base"],["colors","primary","foreground"],["colors","surface","background"],["colors","surface","foreground"],["colors","surface","muted"],["colors","surface","mutedForeground"],["colors","surface","elevated"],["colors","surface","elevatedForeground"],["colors","surface","subtle"],["colors","interactive","border"],["colors","interactive","selection"],["colors","interactive","selectionForeground"],["colors","interactive","focusRing"],["colors","interactive","hover"],["colors","status","error"],["colors","status","errorForeground"],["colors","status","errorBackground"],["colors","status","errorBorder"],["colors","status","warning"],["colors","status","warningForeground"],["colors","status","warningBackground"],["colors","status","warningBorder"],["colors","status","success"],["colors","status","successForeground"],["colors","status","successBackground"],["colors","status","successBorder"],["colors","status","info"],["colors","status","infoForeground"],["colors","status","infoBackground"],["colors","status","infoBorder"],["colors","syntax","base","background"],["colors","syntax","base","foreground"],["colors","syntax","base","keyword"],["colors","syntax","base","string"],["colors","syntax","base","number"],["colors","syntax","base","function"],["colors","syntax","base","variable"],["colors","syntax","base","type"],["colors","syntax","base","comment"],["colors","syntax","base","operator"],["colors","syntax","highlights","diffAdded"],["colors","syntax","highlights","diffRemoved"],["colors","syntax","highlights","lineNumber"]];for(const n of s)if(!EP(Kh(t,n)))return!1;const r=Kh(t,["metadata","variant"]);return r==="light"||r==="dark"},RP=t=>{let s=MP,r=AP,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=ru(d);f&&(n=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?r=f.metadata.id:s=f.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);typeof a=="string"&&a.trim().length>0&&(s=a.trim()),typeof l=="string"&&l.trim().length>0&&(r=l.trim())}if(t){const o=ru(t);o&&(o.metadata.variant==="light"?s=o.metadata.id:r=o.metadata.id)}return{themeMode:n,lightThemeId:s,darkThemeId:r}};function FP({children:t,defaultThemeId:s}){const r=ne.useMemo(()=>new CP,[]),[n,o]=ne.useState(()=>RP(s)),[a,l]=ne.useState(()=>DP()),[c,d]=ne.useState([]),[u,m]=ne.useState(!1),[f,p]=ne.useState(()=>typeof window>"u"||!gs()?null:window.__IKANBAN_VSCODE_THEME__||null),h=ne.useMemo(()=>gs(),[]),g=ne.useMemo(()=>Or(),[]),x=ne.useMemo(()=>{const P=[],$=new Set,R=O=>{const T=O.metadata.id;$.has(T)||($.add(T),P.push(O))};return h&&f&&R(f),c.forEach(R),Gl.forEach(R),P},[c,h,f]),y=ne.useCallback(P=>x.find($=>$.metadata.id===P),[x]),b=ne.useCallback((P,$)=>{const R=y(P);return R&&R.metadata.variant===$?R:x.find(T=>T.metadata.variant===$)??IP($)},[x,y]),v=ne.useMemo(()=>h&&f?f:n.themeMode==="light"?b(n.lightThemeId,"light"):n.themeMode==="dark"||a?b(n.darkThemeId,"dark"):b(n.lightThemeId,"light"),[b,h,n,a,f]),j=ne.useCallback(async()=>{if(!(typeof window>"u"||h)){m(!0);try{const P=await fetch("/api/config/themes",{method:"GET",credentials:g?"omit":"include",headers:{Accept:"application/json"}});if(P.status===401||!P.ok)return;const $=await P.json(),O=(Array.isArray($?.themes)?$.themes:[]).filter(PP);d(O)}catch{}finally{m(!1)}}},[g,h]);ne.useEffect(()=>{j()},[j]),ne.useEffect(()=>{if(!h)return;const P=O=>{p(O)},$=O=>{const T=O.detail;T?.theme&&P(T.theme)},R=window.__IKANBAN_VSCODE_THEME__;return R&&P(R),window.addEventListener("ikanban:vscode-theme",$),()=>window.removeEventListener("ikanban:vscode-theme",$)},[h]);const k=ne.useCallback(P=>{if(typeof document>"u")return;const $=P.colors.surface.background;document.body.style.backgroundColor=$;let R=document.querySelector('meta[name="theme-color"]');R||(R=document.createElement("meta"),R.setAttribute("name","theme-color"),document.head.appendChild(R)),R.setAttribute("content",$);const O=P.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let T=document.querySelector(`meta[name="theme-color"][media="${O}"]`);T||(T=document.createElement("meta"),T.setAttribute("name","theme-color"),T.setAttribute("media",O),document.head.appendChild(T)),T.setAttribute("content",$)},[]),N=ne.useCallback(P=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",P)},[]);TP(()=>{if(typeof window>"u")return;r.apply(v),N(h),k(v);const P=document.documentElement;P.classList.remove("light","dark"),P.classList.add(v.metadata.variant)},[N,r,v,h,k]),ne.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const P=window.matchMedia("(prefers-color-scheme: dark)"),$=R=>{l(R.matches)};return l(P.matches),P.addEventListener("change",$),()=>P.removeEventListener("change",$)},[n.themeMode]),ne.useEffect(()=>{if(typeof window>"u")return;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",v.metadata.id),localStorage.setItem("selectedThemeVariant",v.metadata.variant==="light"?"light":"dark");const P=b(n.lightThemeId,"light"),$=b(n.darkThemeId,"dark");localStorage.setItem("splashBgLight",P.colors.surface.background),localStorage.setItem("splashFgLight",P.colors.surface.foreground),localStorage.setItem("splashBgDark",$.colors.surface.background),localStorage.setItem("splashFgDark",$.colors.surface.foreground)},[n,v,b]),ne.useEffect(()=>{xs({themeId:v.metadata.id,themeVariant:v.metadata.variant==="light"?"light":"dark",useSystemTheme:n.themeMode==="system",lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId})},[v.metadata.id,v.metadata.variant,n.themeMode,n.lightThemeId,n.darkThemeId]),ne.useEffect(()=>{if(typeof window>"u")return;const P=$=>{const R=$.detail;R&&o(O=>{let T=O.themeMode;R.useSystemTheme===!0?T="system":R.useSystemTheme===!1&&(R.themeVariant==="dark"||R.themeVariant==="light")&&(T=R.themeVariant);let _=O.lightThemeId;typeof R.lightThemeId=="string"&&R.lightThemeId.length>0&&(_=R.lightThemeId.trim());let F=O.darkThemeId;return typeof R.darkThemeId=="string"&&R.darkThemeId.length>0&&(F=R.darkThemeId.trim()),T===O.themeMode&&_===O.lightThemeId&&F===O.darkThemeId?O:{themeMode:T,lightThemeId:_,darkThemeId:F}})};return window.addEventListener("ikanban:settings-synced",P),()=>window.removeEventListener("ikanban:settings-synced",P)},[]);const w=ne.useCallback(P=>{const $=x.find(R=>R.metadata.id===P);$&&o(R=>$.metadata.variant==="dark"?R.darkThemeId===$.metadata.id&&R.themeMode==="dark"?R:{...R,darkThemeId:$.metadata.id,themeMode:"dark"}:R.lightThemeId===$.metadata.id&&R.themeMode==="light"?R:{...R,lightThemeId:$.metadata.id,themeMode:"light"})},[x]),C=ne.useCallback(P=>{o($=>$.themeMode===P?$:{...$,themeMode:P})},[]),S=ne.useCallback(P=>{if(P){o(R=>R.themeMode==="system"?R:{...R,themeMode:"system"});return}const $=v.metadata.variant==="dark"?"dark":"light";o(R=>R.themeMode===$?R:{...R,themeMode:$})},[v.metadata.variant]),M=ne.useCallback(P=>{const $=x.find(R=>R.metadata.id===P&&R.metadata.variant==="light");$&&o(R=>R.lightThemeId===$.metadata.id?R:{...R,lightThemeId:$.metadata.id})},[x]),D=ne.useCallback(P=>{const $=x.find(R=>R.metadata.id===P&&R.metadata.variant==="dark");$&&o(R=>R.darkThemeId===$.metadata.id?R:{...R,darkThemeId:$.metadata.id})},[x]),A={currentTheme:v,availableThemes:x,setTheme:w,customThemesLoading:u,reloadCustomThemes:j,isSystemPreference:n.themeMode==="system",setSystemPreference:S,themeMode:n.themeMode,setThemeMode:C,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:M,setDarkThemePreference:D};return e.jsx(Ku.Provider,{value:A,children:t})}const LP=({children:t})=>{const{fontSize:s,applyTypography:r,padding:n,applyPadding:o}=Te();return i.useLayoutEffect(()=>{r(),o()},[s,r,n,o]),e.jsx(e.Fragment,{children:t})};let qh=!1;const OP=()=>{if(qh||typeof window>"u")return;qh=!0;let t={showReasoningTraces:Te.getState().showReasoningTraces,showTextJustificationActivity:Te.getState().showTextJustificationActivity,nativeNotificationsEnabled:Te.getState().nativeNotificationsEnabled,notificationMode:Te.getState().notificationMode,notifyOnSubtasks:Te.getState().notifyOnSubtasks,notifyOnCompletion:Te.getState().notifyOnCompletion,notifyOnError:Te.getState().notifyOnError,notifyOnQuestion:Te.getState().notifyOnQuestion,notificationTemplates:Te.getState().notificationTemplates,summarizeLastMessage:Te.getState().summarizeLastMessage,summaryThreshold:Te.getState().summaryThreshold,summaryLength:Te.getState().summaryLength,maxLastMessageLength:Te.getState().maxLastMessageLength,autoDeleteEnabled:Te.getState().autoDeleteEnabled,autoDeleteAfterDays:Te.getState().autoDeleteAfterDays,toolCallExpansion:Te.getState().toolCallExpansion,fontSize:Te.getState().fontSize,terminalFontSize:Te.getState().terminalFontSize,padding:Te.getState().padding,cornerRadius:Te.getState().cornerRadius,inputBarOffset:Te.getState().inputBarOffset,diffLayoutPreference:Te.getState().diffLayoutPreference,diffViewMode:Te.getState().diffViewMode},s=null,r=null;const n=()=>{const a=s;s=null,r=null,a&&Object.keys(a).length>0&&xs(a)},o=a=>{s={...s??{},...a},!r&&(r=setTimeout(n,150))};Te.subscribe(a=>{const l={showReasoningTraces:a.showReasoningTraces,showTextJustificationActivity:a.showTextJustificationActivity,nativeNotificationsEnabled:a.nativeNotificationsEnabled,notificationMode:a.notificationMode,notifyOnSubtasks:a.notifyOnSubtasks,notifyOnCompletion:a.notifyOnCompletion,notifyOnError:a.notifyOnError,notifyOnQuestion:a.notifyOnQuestion,notificationTemplates:a.notificationTemplates,summarizeLastMessage:a.summarizeLastMessage,summaryThreshold:a.summaryThreshold,summaryLength:a.summaryLength,maxLastMessageLength:a.maxLastMessageLength,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays,toolCallExpansion:a.toolCallExpansion,fontSize:a.fontSize,terminalFontSize:a.terminalFontSize,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.notifyOnSubtasks!==t.notifyOnSubtasks&&(c.notifyOnSubtasks=l.notifyOnSubtasks),l.notifyOnCompletion!==t.notifyOnCompletion&&(c.notifyOnCompletion=l.notifyOnCompletion),l.notifyOnError!==t.notifyOnError&&(c.notifyOnError=l.notifyOnError),l.notifyOnQuestion!==t.notifyOnQuestion&&(c.notifyOnQuestion=l.notifyOnQuestion),JSON.stringify(l.notificationTemplates)!==JSON.stringify(t.notificationTemplates)&&(c.notificationTemplates=l.notificationTemplates),l.summarizeLastMessage!==t.summarizeLastMessage&&(c.summarizeLastMessage=l.summarizeLastMessage),l.summaryThreshold!==t.summaryThreshold&&(c.summaryThreshold=l.summaryThreshold),l.summaryLength!==t.summaryLength&&(c.summaryLength=l.summaryLength),l.maxLastMessageLength!==t.maxLastMessageLength&&(c.maxLastMessageLength=l.maxLastMessageLength),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.terminalFontSize!==t.terminalFontSize&&(c.terminalFontSize=l.terminalFontSize),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 Qh=!1;const Yh="ikanban-typography-base",_P=()=>{if(typeof document>"u")return;const s=`:root {
|
|
308
|
+
${Object.entries(Tu).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
|
|
309
|
+
`)}
|
|
310
|
+
}
|
|
311
|
+
`,r=document.getElementById(Yh);if(r){r.textContent=s;return}const n=document.createElement("style");n.id=Yh,n.textContent=s,document.head.appendChild(n)},$P=()=>{Qh||typeof window>"u"||(Qh=!0,_P())},nl=(t,s)=>{if(t===s)return!0;if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r]?.providerID!==s[r]?.providerID||t[r]?.modelID!==s[r]?.modelID)return!1;return!0},BP=()=>{if(typeof window>"u")return()=>{};if(gs())return()=>{};let t=null,s=null,r=!1;const n=()=>{t=null;const l=Te.getState(),c={favoriteModels:l.favoriteModels,recentModels:l.recentModels};s&&nl(s.favoriteModels,c.favoriteModels)&&nl(s.recentModels,c.recentModels)||(s={favoriteModels:c.favoriteModels.slice(),recentModels:c.recentModels.slice()},xs(c).catch(()=>{}))},o=()=>{if(!r){r=!0;return}t!==null&&window.clearTimeout(t),t=window.setTimeout(n,1200)},a=Te.subscribe((l,c)=>{const d={favoriteModels:l.favoriteModels,recentModels:l.recentModels},u={favoriteModels:c.favoriteModels,recentModels:c.recentModels};nl(d.favoriteModels,u.favoriteModels)&&nl(d.recentModels,u.recentModels)||o()});return()=>{a(),t!==null&&window.clearTimeout(t)}},zP=typeof window<"u"&&window.__IKANBAN_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await Jg();await Xg();OP();BP();$P();await Nb();typeof window<"u"&&(window.debugContextTokens=()=>{const t=window.__zustand_session_store__;if(!t)return;const s=t.getState(),r=s.currentSessionId;if(!r)return;const o=(s.messages.get(r)||[]).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}),s.sessionContextUsage.get(r);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&&s.getContextUsage(u,m)}});const Cb=document.getElementById("root");if(!Cb)throw new Error("Root element not found");xj.createRoot(Cb).render(e.jsx(ne.StrictMode,{children:e.jsx(FP,{children:e.jsx(LP,{children:e.jsx(kP,{children:e.jsx(vP,{apis:zP})})})})}));const WP=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{bs as D,zr as S,vs as a,Lx as b,L as c,JA as d,XA as e,Mp as f,Jn as g,ZA as h,t1 as i,WP as m,Ty as p,e1 as r,cl as t};
|