ikanban-web 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-KwPUu5oc.js","assets/vendor--DEobTDja.css","assets/ToolOutputDialog-BgFj3J4u.js","assets/index-MBuF9PXk.js","assets/index-BQJPAP5f.css"])))=>i.map(i=>d[i]);
2
- import{t as Db,c as Mb,F as Eb,j as e,R as Ib,T as Bb,P as Tb,C as Pb,A as Rb,a as Lb,b as Ob,d as _b,e as $b,f as zb,L as Hb,g as Ub,i as Vb,I as Wb,s as ns,S as Gb,k as qb,l as i,m as Ps,n as Hs,p as Ar,o as Fr,q as hm,_ as qs,r as co,u as fs,v as Kb,w as Jh,x as Qb,y as Yb,z as Jb,B as Xb,D as Zb,E as ev,G as ee,V as vi,H as as,J as tv,K as go,M as kr,W as sv,N as rv,O as nv,Q as Xh,U as ov,X as av,Y as Ba,Z as iv,$ as lv,a0 as cv,a1 as ur,a2 as Rt,a3 as ec,a4 as Td,a5 as Zh,a6 as dv,a7 as Cr,a8 as bu,a9 as eg,aa as tg,ab as uv,ac as sg,ad as mv,ae as rg,af as vu,ag as Qn,ah as wu,ai as Cn,aj as Do,ak as ng,al as Bs,am as fv,an as pv,ao as hv,ap as Hr,aq as og,ar as Io,as as Sn,at as fo,au as As,av as Pd,aw as xo,ax as ju,ay as gv,az as Bo,aA as Su,aB as To,aC as xv,aD as uo,aE as Rd,aF as ag,aG as Nl,aH as jr,aI as yv,aJ as po,aK as bv,aL as ol,aM as vv,aN as Cl,aO as hn,aP as dr,aQ as Po,aR as Ir,aS as Uo,aT as ai,aU as gn,aV as Bn,aW as wv,aX as jv,aY as ig,aZ as ku,a_ as Ro,a$ as Ya,b0 as Tn,b1 as lg,b2 as ii,b3 as Sv,b4 as Nu,b5 as qn,b6 as Kn,b7 as no,b8 as kv,b9 as cg,ba as Nv,bb as kc,bc as Cv,bd as fn,be as Av,bf as Fv,bg as gm,bh as Cu,bi as xm,bj as Dv,bk as Mv,bl as Ev,bm as Iv,bn as Bv,bo as Tv,bp as Pv,bq as Rv,br as Lv,bs as Nc,bt as Ov,bu as Pn,bv as _v,bw as $v,bx as zv,by as Hv,bz as Uv,bA as Vv,bB as Wv,bC as Gv,bD as qv,bE as Kv,bF as Qv,bG as Yv,bH as Jv,bI as Al,bJ as Rn,bK as Dn,bL as tc,bM as ma,bN as Ld,bO as dg,bP as Xv,bQ as Zv,bR as ew,bS as sc,bT as tw,bU as oo,bV as sw,bW as rw,bX as nw,bY as Lo,bZ as ow,b_ as aw,b$ as iw,c0 as lw,c1 as cw,c2 as dw,c3 as ra,c4 as al,c5 as rc,c6 as uw,c7 as mw,c8 as Od,c9 as ug,ca as fw,cb as en,cc as Vn,cd as mg,ce as pw,cf as hw,cg as _d,ch as fg,ci as pg,cj as gw,ck as xw,cl as yw,cm as $d,cn as il,co as ym,cp as ba,cq as bw,cr as vw,cs as kn,ct as ww,cu as Fa,cv as bm,cw as jw,cx as Sw,cy as Cc,cz as kw,cA as Nw,cB as Cw,cC as vm,cD as Aw,cE as hg,cF as gg,cG as Fw,cH as wm,cI as Dw,cJ as Mw,cK as Ew,cL as Iw,cM as Bw,cN as Tw,cO as xg,cP as vt,cQ as ll,cR as Pw,cS as Rw,cT as Vo,cU as Lw,cV as Ow,cW as _w,cX as $w,cY as zw,cZ as Hw,c_ as Uw,c$ as Vw,d0 as Fl,d1 as yg,d2 as bg,d3 as vg,d4 as wg,d5 as jg,d6 as Ww,d7 as Sg,d8 as kg,d9 as oa,da as Gw,db as qw,dc as zd,dd as Ng,de as Hd,df as Au,dg as Cg,dh as Kw,di as Ag,dj as Fu,dk as Du,dl as Mu,dm as Qw,dn as Yw,dp as Mo,dq as Jw,dr as Xw,ds as Zw,dt as e0,du as t0,dv as jm,dw as Sm,dx as Fg,dy as s0,dz as r0,dA as n0,dB as o0,dC as li,dD as Dg,dE as Mg,dF as Ta,dG as nc,dH as Eg,dI as a0,dJ as Ig,dK as Bg,dL as Ud,dM as km,dN as Ac,dO as i0,dP as l0,dQ as c0,dR as d0,dS as u0,dT as m0,dU as f0,dV as p0,dW as h0,dX as g0}from"./vendor-.bun-KwPUu5oc.js";import{c as x0,l as y0,d as b0,a as v0,v as w0,g as j0,b as S0,e as k0,f as N0,u as C0,h as A0,i as F0,j as D0,k as M0,m as E0,n as I0,o as B0,r as T0,p as P0,q as R0,s as L0}from"./index-MBuF9PXk.js";const Ds=()=>typeof window>"u"?!1:typeof window.__TAURI__?.core?.invoke=="function",Nm=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}}},Pr=()=>{if(typeof window>"u")return!1;const t=typeof window.__IKANBAN_LOCAL_ORIGIN__=="string"?window.__IKANBAN_LOCAL_ORIGIN__:"",s=Nm(t),r=Nm(window.location.origin)||window.location.origin;return!!(s&&r&&s===r)},Tr=()=>typeof window>"u"?!1:typeof window.__IKANBAN_LOCAL_ORIGIN__=="string"&&window.__IKANBAN_LOCAL_ORIGIN__.length>0?!0:Ds(),ps=()=>typeof window>"u"?!1:window.__IKANBAN_RUNTIME_APIS__?.runtime?.isVSCode===!0,Oo=()=>{if(typeof window>"u")return!1;const s=window.__IKANBAN_RUNTIME_APIS__?.runtime?.platform;return s==="web"?!0:s==="desktop"||s==="vscode"?!1:!ps()},oc=async()=>{if(typeof window<"u"){const t=window.__IKANBAN_HOME__;if(t&&t.length>0)return t}return null},Tg=async t=>{if(Ds()&&Pr())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}},Pg=async t=>({success:!0}),Rg=async t=>({success:!0}),Lg=async()=>{if(!Ds()||!Pr())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}},Og=async t=>{if(!Ds()||!Pr())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{}}},_g=async()=>{if(!Ds()||!Pr())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}},$g=async(t,s)=>{if(!Ds()||!Pr())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}},zg=async(t,s)=>{if(!Ds()||!Pr())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}}},O0=Object.freeze(Object.defineProperty({__proto__:null,checkForDesktopUpdates:Lg,downloadDesktopUpdate:Og,fetchDesktopInstalledApps:zg,getDesktopHomeDirectory:oc,isDesktopLocalOriginActive:Pr,isDesktopShell:Tr,isTauriShell:Ds,isVSCodeRuntime:ps,isWebRuntime:Oo,openDesktopPath:$g,requestDirectoryAccess:Tg,restartToApplyUpdate:_g,startAccessingDirectory:Pg,stopAccessingDirectory:Rg},Symbol.toStringTag,{value:"Module"}));function R(...t){return Db(Mb(t))}const Hg=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Lr=t=>Hg()&&Ds()?t.metaKey:t.ctrlKey,Qs=()=>Hg()&&Ds()?"⌘":"Ctrl",Ug=(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(Lb,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function ht({delayDuration:t=0,...s}){return e.jsx(Vd,{delayDuration:t,children:e.jsx(Ib,{"data-slot":"tooltip",...s})})}function gt({...t}){return e.jsx(Bb,{"data-slot":"tooltip-trigger",...t})}function pt({className:t,sideOffset:s=0,children:r,...n}){return e.jsx(Tb,{children:e.jsxs(Pb,{"data-slot":"tooltip-content",sideOffset:s,className:R("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",t),...n,children:[r,e.jsx(Rb,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}function cs({...t}){return e.jsx(Ob,{"data-slot":"dropdown-menu",...t})}function ds({...t}){return e.jsx(_b,{"data-slot":"dropdown-menu-trigger",...t})}function us({className:t,sideOffset:s=4,...r}){return e.jsx($b,{children:e.jsx(zb,{"data-slot":"dropdown-menu-content",sideOffset:s,style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:R("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 It({className:t,inset:s,variant:r="default",...n}){return e.jsx(qb,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":r,className:R("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 Ml({...t}){return e.jsx(Ub,{"data-slot":"dropdown-menu-radio-group",...t})}function El({className:t,children:s,...r}){return e.jsxs(Vb,{"data-slot":"dropdown-menu-radio-item",className:R("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(Wb,{children:e.jsx(ns,{className:"size-3"})})}),s]})}function Wr({className:t,inset:s,...r}){return e.jsx(Hb,{"data-slot":"dropdown-menu-label","data-inset":s,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",t),...r})}function cr({className:t,...s}){return e.jsx(Gb,{"data-slot":"dropdown-menu-separator",className:R("bg-border -mx-1 my-0.5 h-px",t),...s})}function ci({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:w}=x,v=Math.max(0,Math.min(100,b/y*100)),k=Math.max(0,Math.min(100,(b+w)/y*100));g.style.clipPath=`inset(0 ${Number(100-k).toFixed(2)}% 0 ${Number(v).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:R("relative isolate w-full",c&&"@container/animated-tabs",n),children:[e.jsx("div",{ref:u,"aria-hidden":!0,className:R("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a&&f?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:R("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:R("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:R(d==="sm"?"h-3.5 w-3.5":"h-4 w-4")}):null,e.jsx("span",{className:R("animated-tabs__label truncate",l?"hidden sm:inline":null),children:g.label})]},g.value)})})}),e.jsx("div",{className:R("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:R("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:R(d==="sm"?"h-3.5 w-3.5":"h-4 w-4",x?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:R("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 Fc=null,Dc=null;const Il=()=>{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}}},_0=()=>{if(typeof window>"u"||!window.localStorage)return Il();const t=window.localStorage,s=Il();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}}},Vs=()=>(Fc||(Fc=_0()),Fc),$0=()=>{if(typeof window>"u"||!window.sessionStorage)return Il();const t=window.sessionStorage,s=Il();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}}},z0=()=>(Dc||(Dc=$0()),Dc),Eu={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},H0={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Am(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Hn={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:()=>({...Hn.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:cl.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Hn.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:cl.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Hn.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:cl.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Hn.tool.inline})},Ii={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:""}},Bi=(t,s)=>t?t.title===s.title&&t.message===s.message:!1,U0=t=>{if(!t||typeof t!="object")return!1;const s=t;return Bi(s.completion,Ii.completion)&&Bi(s.error,Ii.error)&&Bi(s.question,Ii.question)&&Bi(s.subtask,Ii.subtask)},Me=Ps()(Hs(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(Eu);if(o===1){for(const[l]of a)n.style.removeProperty(Am(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Am(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:Fr(()=>Vs()),version:3,migrate:(t,s)=>{if(!t||typeof t!="object")return t;const r=t;if(s<1&&U0(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 V0(){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 W0(){return Ds()?Pr()?"desktop":"web":Oo()?"web":null}const Fm={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},ac=Ps()((t,s)=>({...Fm,checkForUpdates:async()=>{const r=W0();if(r){t({checking:!0,error:null,runtimeType:r});try{let n=null;r==="desktop"?n=await Lg():r==="web"&&(n=await V0()),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 Og(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 _g())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(Fm)}})),G0="/api",q0=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,K0=t=>{const s=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(q0.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}},Q0=()=>{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},Ti=t=>t.replace(/\\/g,"/"),Mc=()=>{if(typeof window>"u")return null;const t=window.__IKANBAN_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class Y0{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=G0){const n=Q0()||s;this.baseUrl=K0(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 qs(async()=>{const{default:f}=await import("./vendor-.bun-KwPUu5oc.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(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-KwPUu5oc.js","assets/vendor--DEobTDja.css","assets/ToolOutputDialog-Cq56vLok.js","assets/index-DTPWfiSs.js","assets/index-BQJPAP5f.css"])))=>i.map(i=>d[i]);
2
+ import{t as Db,c as Mb,F as Eb,j as e,R as Ib,T as Bb,P as Tb,C as Pb,A as Rb,a as Lb,b as Ob,d as _b,e as $b,f as zb,L as Hb,g as Ub,i as Vb,I as Wb,s as ns,S as Gb,k as qb,l as i,m as Ps,n as Hs,p as Ar,o as Fr,q as hm,_ as qs,r as co,u as fs,v as Kb,w as Jh,x as Qb,y as Yb,z as Jb,B as Xb,D as Zb,E as ev,G as ee,V as vi,H as as,J as tv,K as go,M as kr,W as sv,N as rv,O as nv,Q as Xh,U as ov,X as av,Y as Ba,Z as iv,$ as lv,a0 as cv,a1 as ur,a2 as Rt,a3 as ec,a4 as Td,a5 as Zh,a6 as dv,a7 as Cr,a8 as bu,a9 as eg,aa as tg,ab as uv,ac as sg,ad as mv,ae as rg,af as vu,ag as Qn,ah as wu,ai as Cn,aj as Do,ak as ng,al as Bs,am as fv,an as pv,ao as hv,ap as Hr,aq as og,ar as Io,as as Sn,at as fo,au as As,av as Pd,aw as xo,ax as ju,ay as gv,az as Bo,aA as Su,aB as To,aC as xv,aD as uo,aE as Rd,aF as ag,aG as Nl,aH as jr,aI as yv,aJ as po,aK as bv,aL as ol,aM as vv,aN as Cl,aO as hn,aP as dr,aQ as Po,aR as Ir,aS as Uo,aT as ai,aU as gn,aV as Bn,aW as wv,aX as jv,aY as ig,aZ as ku,a_ as Ro,a$ as Ya,b0 as Tn,b1 as lg,b2 as ii,b3 as Sv,b4 as Nu,b5 as qn,b6 as Kn,b7 as no,b8 as kv,b9 as cg,ba as Nv,bb as kc,bc as Cv,bd as fn,be as Av,bf as Fv,bg as gm,bh as Cu,bi as xm,bj as Dv,bk as Mv,bl as Ev,bm as Iv,bn as Bv,bo as Tv,bp as Pv,bq as Rv,br as Lv,bs as Nc,bt as Ov,bu as Pn,bv as _v,bw as $v,bx as zv,by as Hv,bz as Uv,bA as Vv,bB as Wv,bC as Gv,bD as qv,bE as Kv,bF as Qv,bG as Yv,bH as Jv,bI as Al,bJ as Rn,bK as Dn,bL as tc,bM as ma,bN as Ld,bO as dg,bP as Xv,bQ as Zv,bR as ew,bS as sc,bT as tw,bU as oo,bV as sw,bW as rw,bX as nw,bY as Lo,bZ as ow,b_ as aw,b$ as iw,c0 as lw,c1 as cw,c2 as dw,c3 as ra,c4 as al,c5 as rc,c6 as uw,c7 as mw,c8 as Od,c9 as ug,ca as fw,cb as en,cc as Vn,cd as mg,ce as pw,cf as hw,cg as _d,ch as fg,ci as pg,cj as gw,ck as xw,cl as yw,cm as $d,cn as il,co as ym,cp as ba,cq as bw,cr as vw,cs as kn,ct as ww,cu as Fa,cv as bm,cw as jw,cx as Sw,cy as Cc,cz as kw,cA as Nw,cB as Cw,cC as vm,cD as Aw,cE as hg,cF as gg,cG as Fw,cH as wm,cI as Dw,cJ as Mw,cK as Ew,cL as Iw,cM as Bw,cN as Tw,cO as xg,cP as vt,cQ as ll,cR as Pw,cS as Rw,cT as Vo,cU as Lw,cV as Ow,cW as _w,cX as $w,cY as zw,cZ as Hw,c_ as Uw,c$ as Vw,d0 as Fl,d1 as yg,d2 as bg,d3 as vg,d4 as wg,d5 as jg,d6 as Ww,d7 as Sg,d8 as kg,d9 as oa,da as Gw,db as qw,dc as zd,dd as Ng,de as Hd,df as Au,dg as Cg,dh as Kw,di as Ag,dj as Fu,dk as Du,dl as Mu,dm as Qw,dn as Yw,dp as Mo,dq as Jw,dr as Xw,ds as Zw,dt as e0,du as t0,dv as jm,dw as Sm,dx as Fg,dy as s0,dz as r0,dA as n0,dB as o0,dC as li,dD as Dg,dE as Mg,dF as Ta,dG as nc,dH as Eg,dI as a0,dJ as Ig,dK as Bg,dL as Ud,dM as km,dN as Ac,dO as i0,dP as l0,dQ as c0,dR as d0,dS as u0,dT as m0,dU as f0,dV as p0,dW as h0,dX as g0}from"./vendor-.bun-KwPUu5oc.js";import{c as x0,l as y0,d as b0,a as v0,v as w0,g as j0,b as S0,e as k0,f as N0,u as C0,h as A0,i as F0,j as D0,k as M0,m as E0,n as I0,o as B0,r as T0,p as P0,q as R0,s as L0}from"./index-DTPWfiSs.js";const Ds=()=>typeof window>"u"?!1:typeof window.__TAURI__?.core?.invoke=="function",Nm=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}}},Pr=()=>{if(typeof window>"u")return!1;const t=typeof window.__IKANBAN_LOCAL_ORIGIN__=="string"?window.__IKANBAN_LOCAL_ORIGIN__:"",s=Nm(t),r=Nm(window.location.origin)||window.location.origin;return!!(s&&r&&s===r)},Tr=()=>typeof window>"u"?!1:typeof window.__IKANBAN_LOCAL_ORIGIN__=="string"&&window.__IKANBAN_LOCAL_ORIGIN__.length>0?!0:Ds(),ps=()=>typeof window>"u"?!1:window.__IKANBAN_RUNTIME_APIS__?.runtime?.isVSCode===!0,Oo=()=>{if(typeof window>"u")return!1;const s=window.__IKANBAN_RUNTIME_APIS__?.runtime?.platform;return s==="web"?!0:s==="desktop"||s==="vscode"?!1:!ps()},oc=async()=>{if(typeof window<"u"){const t=window.__IKANBAN_HOME__;if(t&&t.length>0)return t}return null},Tg=async t=>{if(Ds()&&Pr())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}},Pg=async t=>({success:!0}),Rg=async t=>({success:!0}),Lg=async()=>{if(!Ds()||!Pr())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}},Og=async t=>{if(!Ds()||!Pr())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{}}},_g=async()=>{if(!Ds()||!Pr())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}},$g=async(t,s)=>{if(!Ds()||!Pr())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}},zg=async(t,s)=>{if(!Ds()||!Pr())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}}},O0=Object.freeze(Object.defineProperty({__proto__:null,checkForDesktopUpdates:Lg,downloadDesktopUpdate:Og,fetchDesktopInstalledApps:zg,getDesktopHomeDirectory:oc,isDesktopLocalOriginActive:Pr,isDesktopShell:Tr,isTauriShell:Ds,isVSCodeRuntime:ps,isWebRuntime:Oo,openDesktopPath:$g,requestDirectoryAccess:Tg,restartToApplyUpdate:_g,startAccessingDirectory:Pg,stopAccessingDirectory:Rg},Symbol.toStringTag,{value:"Module"}));function R(...t){return Db(Mb(t))}const Hg=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Lr=t=>Hg()&&Ds()?t.metaKey:t.ctrlKey,Qs=()=>Hg()&&Ds()?"⌘":"Ctrl",Ug=(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(Lb,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function ht({delayDuration:t=0,...s}){return e.jsx(Vd,{delayDuration:t,children:e.jsx(Ib,{"data-slot":"tooltip",...s})})}function gt({...t}){return e.jsx(Bb,{"data-slot":"tooltip-trigger",...t})}function pt({className:t,sideOffset:s=0,children:r,...n}){return e.jsx(Tb,{children:e.jsxs(Pb,{"data-slot":"tooltip-content",sideOffset:s,className:R("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",t),...n,children:[r,e.jsx(Rb,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}function cs({...t}){return e.jsx(Ob,{"data-slot":"dropdown-menu",...t})}function ds({...t}){return e.jsx(_b,{"data-slot":"dropdown-menu-trigger",...t})}function us({className:t,sideOffset:s=4,...r}){return e.jsx($b,{children:e.jsx(zb,{"data-slot":"dropdown-menu-content",sideOffset:s,style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:R("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 It({className:t,inset:s,variant:r="default",...n}){return e.jsx(qb,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":r,className:R("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 Ml({...t}){return e.jsx(Ub,{"data-slot":"dropdown-menu-radio-group",...t})}function El({className:t,children:s,...r}){return e.jsxs(Vb,{"data-slot":"dropdown-menu-radio-item",className:R("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(Wb,{children:e.jsx(ns,{className:"size-3"})})}),s]})}function Wr({className:t,inset:s,...r}){return e.jsx(Hb,{"data-slot":"dropdown-menu-label","data-inset":s,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",t),...r})}function cr({className:t,...s}){return e.jsx(Gb,{"data-slot":"dropdown-menu-separator",className:R("bg-border -mx-1 my-0.5 h-px",t),...s})}function ci({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:w}=x,v=Math.max(0,Math.min(100,b/y*100)),k=Math.max(0,Math.min(100,(b+w)/y*100));g.style.clipPath=`inset(0 ${Number(100-k).toFixed(2)}% 0 ${Number(v).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:R("relative isolate w-full",c&&"@container/animated-tabs",n),children:[e.jsx("div",{ref:u,"aria-hidden":!0,className:R("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a&&f?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:R("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:R("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:R(d==="sm"?"h-3.5 w-3.5":"h-4 w-4")}):null,e.jsx("span",{className:R("animated-tabs__label truncate",l?"hidden sm:inline":null),children:g.label})]},g.value)})})}),e.jsx("div",{className:R("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:R("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:R(d==="sm"?"h-3.5 w-3.5":"h-4 w-4",x?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:R("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 Fc=null,Dc=null;const Il=()=>{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}}},_0=()=>{if(typeof window>"u"||!window.localStorage)return Il();const t=window.localStorage,s=Il();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}}},Vs=()=>(Fc||(Fc=_0()),Fc),$0=()=>{if(typeof window>"u"||!window.sessionStorage)return Il();const t=window.sessionStorage,s=Il();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}}},z0=()=>(Dc||(Dc=$0()),Dc),Eu={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},H0={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Am(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Hn={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:()=>({...Hn.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:cl.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Hn.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:cl.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Hn.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:cl.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Hn.tool.inline})},Ii={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:""}},Bi=(t,s)=>t?t.title===s.title&&t.message===s.message:!1,U0=t=>{if(!t||typeof t!="object")return!1;const s=t;return Bi(s.completion,Ii.completion)&&Bi(s.error,Ii.error)&&Bi(s.question,Ii.question)&&Bi(s.subtask,Ii.subtask)},Me=Ps()(Hs(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(Eu);if(o===1){for(const[l]of a)n.style.removeProperty(Am(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Am(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:Fr(()=>Vs()),version:3,migrate:(t,s)=>{if(!t||typeof t!="object")return t;const r=t;if(s<1&&U0(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 V0(){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 W0(){return Ds()?Pr()?"desktop":"web":Oo()?"web":null}const Fm={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},ac=Ps()((t,s)=>({...Fm,checkForUpdates:async()=>{const r=W0();if(r){t({checking:!0,error:null,runtimeType:r});try{let n=null;r==="desktop"?n=await Lg():r==="web"&&(n=await V0()),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 Og(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 _g())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(Fm)}})),G0="/api",q0=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,K0=t=>{const s=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(q0.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}},Q0=()=>{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},Ti=t=>t.replace(/\\/g,"/"),Mc=()=>{if(typeof window>"u")return null;const t=window.__IKANBAN_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class Y0{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=G0){const n=Q0()||s;this.baseUrl=K0(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 qs(async()=>{const{default:f}=await import("./vendor-.bun-KwPUu5oc.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
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
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
5
  `);const h=u.split(`
@@ -206,7 +206,7 @@ ${ct}`)}const lt=Ne.map(ct=>{if(!ct?.dataUrl)return null;try{const[Ke,Dt]=ct.dat
206
206
  `).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
207
207
  `).trim(),LM=({part:t,messageId:s,onContentChange:r})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>RM(o),[o]);return!a||a.trim().length===0?null:e.jsx(Ry,{text:a,variant:"justification",onContentChange:r,blockId:t.id||`${s}-justification`})},OM=i.memo(LM),Fp=6,_M=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},$M=({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 N=u.current===!1;if(u.current=s,c?.("structural"),s&&N){h(D=>D+1),f(!0),g.current.clear();const F=setTimeout(()=>f(!1),50);return()=>clearTimeout(F)}else f(!1)},[s,c]);const x=i.useMemo(()=>_M(t),[t]),y=Dp(x),b=i.useMemo(()=>x.slice(-Fp),[x]),w=i.useMemo(()=>{const N=new Set;return b.forEach(F=>{F.part.id&&N.add(F.part.id)}),N},[b]),v=i.useMemo(()=>Dp(b),[b]),k=Math.max(0,x.length-Fp);if(x.length===0)return null;const S=s?x:b,j=s?y:v,C=k>0;return e.jsx(Yr,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl",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:R("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),style:{color:"var(--tools-icon)"},children:e.jsx(To,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:R("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(as,{className:"h-3.5 w-3.5"}):e.jsx(ur,{className:"h-3.5 w-3.5"})})]}):e.jsx(To,{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:R("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..."]}),S.map((N,F)=>{const D=N.part.id||`group-part-${F}`,A=j[D],E=`${D}-exp${p}`,P=N.part.id?w.has(N.part.id):!1;let T=!1;switch(m&&P?T=!0:!s&&N.part.id&&(g.current.has(N.part.id)?T=!0:g.current.add(N.part.id)),N.kind){case"tool":return e.jsx(Yr,{skipAnimation:T,children:e.jsx(mu,{part:N.part,isExpanded:a.has(D),onToggle:l,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:A?.hasPrev??!1,hasNextTool:A?.hasNext??!1})},E);case"reasoning":return e.jsx(Yr,{skipAnimation:T,children:e.jsx(Ly,{part:N.part,messageId:N.messageId,onContentChange:c})},E);case"justification":return e.jsx(Yr,{skipAnimation:T,children:e.jsx(OM,{part:N.part,messageId:N.messageId,onContentChange:c})},E);default:return null}})]})]})})},zM=i.memo($M),nm=t=>{const s=t,r=s.text;return typeof r=="string"?r:s.content||s.value||""},Oy=t=>{if(t.type!=="text")return!1;const s=nm(t);return!s||s.trim().length===0},HM=(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 UM(){const[t,s]=ee.useState(!1),{voiceProvider:r,speechRate:n,speechPitch:o,speechVolume:a,sayVoice:l,browserVoice:c,openaiVoice:d,summarizeMessageTTS:u,summarizeCharacterThreshold:m}=ft(),{speak:f,stop:p,isAvailable:h}=fy(),{speak:g,stop:x,isAvailable:y}=py(),b=ee.useCallback(()=>{s(!1),p(),x(),ws.cancelSpeech()},[p,x]),w=ee.useCallback(async v=>{if(v.trim()){b(),s(!0);try{let k=v;if(u&&gy(v,"message")?k=await hy(v,{threshold:m}):k=xy(v),r==="openai"&&h)await f(k,{voice:d,speed:n,summarize:!1,onEnd:()=>s(!1),onError:()=>s(!1)});else if(r==="say"&&y){const S=Math.round(100+(n-.5)*200);await g(k,{voice:l,rate:S,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:w,stop:b}}const VM=200,WM=({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(N=>N.createSession),y=Ae(N=>N.setPendingInputText),b=Me(N=>N.isMobile);i.useEffect(()=>()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),g.current!==null&&(window.cancelAnimationFrame(g.current),g.current=null)},[]);const w=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(N=>({...N,show:!1})),o(""),p.current=null,d(!1),h.current=null},VM)},[]),v=i.useCallback(()=>{if(!p.current)return;h.current!==null&&(window.clearTimeout(h.current),h.current=null),d(!1);const{text:N,rect:F}=p.current,D=!s.show,A=F.left+F.width/2,E=F.top-10;o(N),r({x:A,y:E,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 N=window.getSelection(),F=t.current;if(!N||!F){a||w();return}const D=N.toString().trim();if(!D){a||w();return}const A=N.getRangeAt(0);if(!F.contains(A.commonAncestorContainer)){a||w();return}const E=A.getBoundingClientRect();p.current={text:D,rect:E},a||v()},[t,w,v,a]);i.useEffect(()=>{const N=t.current;if(!N)return;const F=()=>{l(!0),w()},D=()=>{l(!1),p.current&&setTimeout(()=>{const E=window.getSelection();E&&E.toString().trim()?v():w()},10)};document.addEventListener("selectionchange",k),N.addEventListener("mousedown",F),document.addEventListener("mouseup",D);const A=E=>{f.current&&!f.current.contains(E.target)&&!window.getSelection()?.toString().trim()&&w()};return document.addEventListener("mousedown",A),()=>{document.removeEventListener("selectionchange",k),N.removeEventListener("mousedown",F),document.removeEventListener("mouseup",D),document.removeEventListener("mousedown",A)}},[t,k,w,v]);const S=i.useCallback(()=>{n&&(y(n,"append"),w(),window.getSelection()?.removeAllRanges())},[n,y,w]),j=i.useCallback(async()=>{if(!n)return;await x(void 0,null,null)&&y(n,"replace"),w(),window.getSelection()?.removeAllRanges()},[n,x,y,w]),C=i.useCallback(async()=>{if(n){try{await navigator.clipboard.writeText(n)}catch(N){console.error("Failed to copy:",N)}w(),window.getSelection()?.removeAllRanges()}},[n,w]);return s.show?b?co.createPortal(e.jsxs("div",{ref:f,className:R("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:S,className:R("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(Bs,{className:"h-5 w-5"}),e.jsx("span",{children:"Add to chat"})]}),e.jsxs("button",{onClick:j,className:R("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($d,{className:"h-5 w-5"}),e.jsx("span",{children:"New session"})]}),e.jsxs("button",{onClick:C,className:R("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:R("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:S,className:R("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(Bs,{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:j,className:R("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($d,{className:"h-4 w-4"}),e.jsx("span",{children:"New session"})]})]})}),document.body):null},GM=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`},qM=new Set(["task"]),Zi=t=>typeof t=="string"&&qM.has(t.toLowerCase()),KM=({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(N=>N.type!=="text"?!1:!Oy(N)),[s]),x=d?.token;let y=!1;const b=!!a,w=!!l,v=!!(n??r),k=!!o,S=i.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),j=i.useCallback(()=>{!v||!b||!k||typeof window>"u"||(S(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[b,S,k,v]);i.useEffect(()=>{k||(p(!1),S())},[S,k]);const C=i.useCallback(N=>{!a||!k||(N.stopPropagation(),N.preventDefault(),a(),v&&j())},[k,v,a,j]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:v&&b&&k?j:void 0,children:[e.jsx("div",{className:"leading-relaxed overflow-hidden text-foreground/90 text-base",children:g.map((N,F)=>{let D;return d&&x&&!y&&nm(N).includes(x)&&(D=d,y=!0),e.jsx(Yr,{children:e.jsx(gM,{part:N,messageId:t,isMobile:r,agentMention:D})},`user-text-${F}`)})}),e.jsx(by,{files:s,onShowPopup:c,compact:!0}),b&&k||u||m?e.jsx("div",{className:R("absolute top-full left-0 right-0 z-10 group/user-actions",r?"pt-2 pb-3":"pt-5"),children:e.jsxs("div",{className:R("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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{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:N=>N.stopPropagation(),onClick:N=>{N.stopPropagation(),u()},children:e.jsx(Lo,{className:"h-3 w-3"})})}),e.jsx(pt,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{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:N=>N.stopPropagation(),onClick:N=>{N.stopPropagation(),m()},children:e.jsx(As,{className:"h-3 w-3"})})}),e.jsx(pt,{sideOffset:6,children:"Fork from here"})]}),b&&k&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","data-visible":f||w?"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:N=>N.stopPropagation(),onClick:C,onFocus:()=>p(!0),onBlur:()=>{w||p(!1)},children:w?e.jsx(ns,{className:"h-3 w-3 text-[color:var(--status-success)]"}):e.jsx(Hr,{className:"h-3 w-3"})})}),e.jsx(pt,{sideOffset:6,children:"Copy message"})]})]})}):null]})},QM=({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:w=!1,turnGroupingContext:v,errorMessage:k})=>{const[S,j]=i.useState(!1),C=i.useRef(null),N=i.useRef(null),F=!!x,D=!!y,A=!!(c??l),E=!r,P=i.useMemo(()=>s.filter(je=>!Oy(je)).filter(je=>je.type!=="compaction"),[s]),T=i.useMemo(()=>P.filter(je=>je.type==="tool"),[P]),L=i.useMemo(()=>P.filter(je=>je.type==="text"),[P]),I=Ae(je=>je.createSessionFromAssistantMessage),_=Me(je=>je.openMultiRunLauncherWithPrompt),O=v?.isLastAssistantInTurn??!1,M=n==="stop",{isPlaying:B,play:G,stop:W}=UM(),ve=ft(je=>je.showMessageTTSButtons),oe=ft(je=>je.voiceProvider),te=i.useMemo(()=>B?"Stop speaking":`Read aloud (${oe==="browser"?"Browser":oe==="openai"?"OpenAI":"Say"} voice)`,[B,oe]),he=T.length>0,Y=i.useMemo(()=>T.some(je=>{const Ge=(je.state??{})?.status;return Ge==="pending"||Ge==="running"||Ge==="started"}),[T]),Z=i.useCallback(je=>{const We=je.state??{},Ge=We?.status;if(Ge==="pending"||Ge==="running"||Ge==="started")return!1;const Je=We?.time??{},ut=typeof Je?.end=="number"?Je.end:void 0,wt=typeof Je?.start=="number"?Je.start:void 0;return!(typeof ut!="number"||typeof wt=="number"&&ut<wt)},[]),ie=i.useMemo(()=>T.length===0?!0:Y?!1:T.every(je=>Z(je)),[T,Y,Z]),$=i.useMemo(()=>P.filter(je=>je.type==="reasoning"),[P]),ne=i.useMemo(()=>$.length===0?!0:$.every(je=>typeof je.time?.end=="number"),[$]),V=typeof n!="string",ce=$.length>0&&he&&(Y||V||!ie),ge=E||he&&(Y||V||!ie),H=E||ce,J=he||$.length>0,we=L.length===0,X=J&&we&&!ge&&!H&&ie&&ne,q=i.useRef(!1),re=i.useRef(!1);i.useEffect(()=>{re.current=!1},[t]),i.useEffect(()=>{if(!X){q.current=!1;return}q.current||(q.current=!0,b?.())},[X,b]),i.useEffect(()=>{if(E){re.current=!1;return}if(he){re.current=!1;return}$.length!==0&&(H||!ne||re.current||(re.current=!0,h?.("structural")))},[E,he,h,ne,$.length,H]);const ue=!!g&&!E,Re=i.useCallback(()=>{C.current!==null&&typeof window<"u"&&(window.clearTimeout(C.current),C.current=null)},[]),_e=i.useCallback(()=>{!A||!F||!ue||typeof window>"u"||(Re(),j(!0),C.current=window.setTimeout(()=>{j(!1),C.current=null},1800))},[F,Re,ue,A]);i.useEffect(()=>{ue||(j(!1),Re())},[Re,ue]);const me=i.useCallback(je=>{!x||!ue||(je.stopPropagation(),je.preventDefault(),x(),A&&_e())},[ue,A,x,_e]),Q=i.useCallback(je=>{je.stopPropagation(),je.preventDefault(),I&&I(t)},[I,t]),xe=i.useCallback(je=>{je.stopPropagation(),je.preventDefault();const We=Hl(L);if(!We.trim())return;const Ge=`${QS}
208
208
 
209
- ${We}`;_(Ge)},[L,_]),fe=i.useCallback(je=>{if(je.stopPropagation(),je.preventDefault(),B){W();return}const We=Hl(L);We.trim()&&G(We)},[L,B,G,W]);i.useEffect(()=>()=>{Re()},[Re]);const He=i.useMemo(()=>{const je={},We=T.filter(Ge=>Zi(Ge.tool)||ge?!1:Z(Ge));return We.forEach((Ge,Je)=>{je[Ge.id]={hasPrev:Je>0,hasNext:Je<We.length-1}}),je},[T,ge,Z]),it=i.useMemo(()=>v?.activityParts??[],[v]),de=i.useMemo(()=>v?it.filter(je=>je.messageId===t):[],[it,t,v]),Ue=i.useMemo(()=>v?v.activityGroupSegments.filter(je=>je.anchorMessageId===t):[],[t,v]),Fe=i.useMemo(()=>{const je=new Map;return de.forEach(We=>{je.set(We.part,We)}),je},[de]),be=i.useMemo(()=>v?(w?it:it.filter(We=>We.kind!=="reasoning")).filter(We=>{if(We.kind!=="tool")return!0;const Ge=We.part.tool;return!Zi(Ge)}):[],[it,w,v]),[Te,Ie]=i.useState(!1);i.useEffect(()=>{if(!v)return;const je=v.activityGroupSegments.some(Ge=>Ge.afterToolPartId!==null),We=be.some(Ge=>Ge.kind==="reasoning");(be.length>1||je&&be.length>0||We)&&Ie(!0)},[v,be]);const Oe=!!(v&&Te),et=!!(v&&Oe&&be.length>0&&Ue.length>0),ze=i.useMemo(()=>T.filter(je=>Zi(je.tool)),[T]),Ee=i.useMemo(()=>{const je=[],We=Je=>{!v||!et||Ue.filter(ut=>(ut.afterToolPartId??null)===Je).forEach(ut=>{const wt=w?ut.parts:ut.parts.filter(rt=>rt.kind!=="reasoning");wt.length!==0&&je.push(e.jsx(zM,{parts:wt,isExpanded:v.isGroupExpanded,onToggle:v.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,diffStats:v.diffStats},`progressive-group-${ut.id}`))})};We(null),ze.forEach(Je=>{je.push(e.jsx(Yr,{children:e.jsx(mu,{part:Je,isExpanded:d.has(Je.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Je.id}`)),We(Je.id)});const Ge=[];return P.forEach((Je,ut)=>{const wt=Fe.get(Je);if(!wt||!v)return;let rt=null,_t=null;if(!Oe){if(wt.kind==="tool"){const kt=Je;if(Zi(kt.tool))return;const Ct=kt.state?.time,Lt=Z(kt);if(!(!ge&&Lt))return;const At=He[kt.id];_t=e.jsx(Yr,{children:e.jsx(mu,{part:kt,isExpanded:d.has(kt.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:At?.hasPrev??!1,hasNextTool:At?.hasNext??!1})},`tool-${kt.id}`),rt=Lt&&typeof Ct?.end=="number"?Ct.end:null}else if(wt.kind==="reasoning"&&w){const kt=Je.time,qt=typeof kt?.end=="number"?kt.end:null;_t=e.jsx(Yr,{children:e.jsx(Ly,{part:Je,messageId:t,onContentChange:h})},`reasoning-${wt.id}`),rt=qt}_t&&Ge.push({part:Je,index:ut,endTime:rt,element:_t})}}),Ge.sort((Je,ut)=>Je.endTime===null&&ut.endTime===null?Je.index-ut.index:Je.endTime===null?1:ut.endTime===null?-1:Je.endTime-ut.endTime),Ge.forEach(({element:Je})=>{je.push(Je)}),je},[Fe,Ue,d,l,Z,t,h,m,u,ge,Oe,w,a,He,v,P,ze,et]),Be=v?.turnId,Ze=Ae(je=>je.currentSessionId),tt=ss(je=>{if(!Be||!Ze)return;const We=je.messages.get(Ze);if(!We)return;const Ge=We.find(wt=>wt.info?.id===Be);if(!Ge)return;const ut=Ge.info.summary?.body;return typeof ut=="string"&&ut.trim().length>0?ut:void 0}),jt=typeof v?.summaryBody=="string"&&v.summaryBody.trim().length>0?v.summaryBody:tt,xt=i.useRef(void 0);jt&&jt.trim().length>0&&(xt.current=jt);const Et=i.useRef(Be);Et.current!==Be&&(Et.current=Be,xt.current=void 0);const yt=xt.current,Xt=v?.isLastAssistantInTurn&&yt&&yt.trim().length>0,os=!!k,is=O&&g&&(M||!!k),hs=i.useMemo(()=>{if(!O||!M)return;const je=v?.userMessageCreatedAt;if(!(typeof je!="number"||typeof o!="number")&&!(o<=je))return GM(o-je)},[O,M,v?.userMessageCreatedAt,o]),ae=e.jsxs(e.Fragment,{children:[x&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","data-visible":S||D?"true":void 0,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!ue&&"opacity-50"),disabled:!ue,"aria-label":"Copy message text","aria-hidden":!ue,onPointerDown:je=>je.stopPropagation(),onClick:me,onFocus:()=>{ue&&j(!0)},onBlur:()=>{D||j(!1)},children:D?e.jsx(ns,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Hr,{className:"h-3.5 w-3.5"})})}),e.jsx(pt,{sideOffset:6,children:"Copy answer"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{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:je=>je.stopPropagation(),onClick:Q,children:e.jsx($d,{className:"h-4 w-4"})})}),e.jsx(pt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{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:je=>je.stopPropagation(),onClick:xe,children:e.jsx(Zu,{className:"h-4 w-4"})})}),e.jsx(pt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),ve&&ue&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon",className:R("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",B?"text-green-500":"text-muted-foreground hover:text-foreground"),"aria-label":B?"Stop speaking":"Read aloud",onPointerDown:je=>je.stopPropagation(),onClick:fe,children:B?e.jsx(il,{className:"h-3.5 w-3.5"}):e.jsx(ma,{className:"h-3.5 w-3.5"})})}),e.jsx(pt,{sideOffset:6,children:te})]})]});return e.jsxs("div",{ref:N,className:R("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:A&&F&&ue?_e:void 0,children:[e.jsx(WM,{containerRef:N}),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($r,{content:k??""})})},"assistant-error"),Xt&&e.jsx(Yr,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",children:[e.jsx($r,{content:yt}),is&&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:ae}),hs?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"}),hs]}):null]})]})},"summary-body")]}),e.jsx(by,{files:s,onShowPopup:m}),!Xt&&is&&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:ae}),hs?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"}),hs]}):null]})]})]})},YM=({isUser:t,...s})=>t?e.jsx(KM,{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(QM,{...s}),Mp=i.memo(YM),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}},JM=i.lazy(()=>qs(()=>import("./ToolOutputDialog-BgFj3J4u.js"),__vite__mapDeps([2,0,1,3,4]))),XM=new Set(["task","edit","multiedit","write","bash"]),Ep=t=>typeof t=="string"&&XM.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 Kr=(t,s)=>{if(typeof t=="object"&&t!==null)return t[s]},ZM=({message:t,previousMessage:s,nextMessage:r,onContentChange:n,animationHandlers:o,turnGroupingContext:a})=>{const{isMobile:l,hasTouchInput:c}=Ns(),{currentTheme:d}=rn(),u=i.useRef(null),m=Ae(oo(Qe=>({lifecyclePhase:Qe.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const mt=t.info.sessionID??Qe.currentSessionId??null;return mt?(Qe.streamingMessageIds.get(mt)??null)===t.info.id:!1})(),currentSessionId:Qe.currentSessionId,getAgentModelForSession:Qe.getAgentModelForSession,getSessionModelSelection:Qe.getSessionModelSelection,revertToMessage:Qe.revertToMessage,forkFromMessage:Qe.forkFromMessage}))),{lifecyclePhase:f,isStreamingMessage:p,currentSessionId:h,getAgentModelForSession:g,getSessionModelSelection:x,revertToMessage:y,forkFromMessage:b}=m,w=ft(Qe=>Qe.providers),{showReasoningTraces:v,toolCallExpansion:k}=Me(oo(Qe=>({showReasoningTraces:Qe.showReasoningTraces,toolCallExpansion:Qe.toolCallExpansion})));i.useEffect(()=>{h&&lo.getInstance().recordSessionStart(h)},[h]);const[S,j]=i.useState(null),[C,N]=i.useState(!1),[F,D]=i.useState(new Set),[A,E]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{D(new Set)},[t.info.id,k]);const T=i.useMemo(()=>ld(t.info),[t.info]).isUser,L=t.info.sessionID,{currentContextAgent:I,savedSessionAgentSelection:_}=Pt(oo(Qe=>({currentContextAgent:L?Qe.currentAgentContext.get(L):void 0,savedSessionAgentSelection:L?Qe.sessionAgentSelections.get(L):void 0}))),O=i.useMemo(()=>{if(!T)return t.parts;const Qe=mt=>{const bt=mt.trim();return!!(bt.startsWith("User has requested to enter plan mode")||bt.startsWith("The plan at "))};return t.parts.filter(mt=>{if(!(mt?.synthetic===!0))return!0;if(mt.type!=="text")return!1;const dt=mt?.text;return typeof dt=="string"?Qe(dt):!1}).map(mt=>mt.type==="compaction"?{type:"text",text:"/compact"}:mt)},[T,t.parts]),M=i.useMemo(()=>{if(T||!s)return null;const Qe=Kr(s.info,"clientRole"),mt=Kr(s.info,"role");if((typeof Qe=="string"?Qe:typeof mt=="string"?mt:void 0)!=="user")return null;const dt=Kr(s.info,"mode"),Tt=Kr(s.info,"agent"),$t=Kr(s.info,"providerID"),Bt=Kr(s.info,"modelID"),Qt=Kr(s.info,"variant"),ms=typeof dt=="string"&&dt.trim().length>0?dt:typeof Tt=="string"&&Tt.trim().length>0?Tt:void 0,Ws=typeof $t=="string"&&$t.trim().length>0?$t:void 0,Js=typeof Bt=="string"&&Bt.trim().length>0?Bt:void 0,Xs=typeof Qt=="string"&&Qt.trim().length>0?Qt:void 0;return!ms&&!Ws&&!Js&&!Xs?null:{agentName:ms,providerId:Ws,modelId:Js,variant:Xs}},[T,s]),B=i.useMemo(()=>{if(T||!s)return!1;const Qe=Array.isArray(s.parts)?s.parts:[];for(let mt=0;mt<Qe.length;mt++){const bt=Qe[mt];if(bt?.type!=="text"||bt?.synthetic!==!0)continue;const dt=typeof bt.text=="string"?bt.text.trim():"";if(dt.startsWith("User has requested to enter plan mode")||dt.startsWith("The plan at "))return!0}return!1},[T,s]),G=i.useMemo(()=>{if(T)return;const Qe=t.info.time;if(!(typeof Qe?.completed=="number"&&Qe.completed>0)&&B&&M?.agentName)return M.agentName;const bt=Kr(t.info,"mode");if(typeof bt=="string"&&bt.trim().length>0)return bt;const dt=Kr(t.info,"agent");if(typeof dt=="string"&&dt.trim().length>0)return dt;if(M?.agentName)return M.agentName;if(L)return I||(_??void 0)},[T,t.info,B,M,L,I,_]),W=T?null:Kr(t.info,"providerID"),ve=T?null:Kr(t.info,"modelID"),oe=i.useMemo(()=>{if(T||!L)return null;if(M?.providerId&&M?.modelId)return{providerId:M.providerId,modelId:M.modelId};if(G){const mt=g(L,G);if(mt?.providerId&&mt?.modelId)return mt}const Qe=x(L);return Qe?.providerId&&Qe?.modelId?Qe:null},[T,L,G,M,g,x]),te=i.useMemo(()=>T?null:typeof W=="string"&&W.trim().length>0?W:oe?.providerId??null,[T,W,oe]),he=i.useMemo(()=>T?null:typeof ve=="string"&&ve.trim().length>0?ve:oe?.modelId??null,[T,ve,oe]),Y=i.useMemo(()=>{if(!T&&te&&he&&w.length>0){const Qe=w.find(mt=>mt.id===te);if(Qe?.models&&Array.isArray(Qe.models)){const dt=Qe.models.find(Tt=>Tt.id===he)?.name;return typeof dt=="string"?dt:void 0}}},[T,te,he,w]),Z=i.useMemo(()=>{if(T||!te||!he)return!1;const Qe=w.find(dt=>dt.id===te);if(!Qe?.models||!Array.isArray(Qe.models))return!1;const bt=Qe.models.find(dt=>dt.id===he)?.variants;return!!(bt&&Object.keys(bt).length>0)},[T,he,te,w]),ie=cd(G),$=cd(te??void 0),ne=cd(Y),V=ie??void 0,ce=$??null,ge=ne??void 0,H=i.useMemo(()=>{const Qe=t.info.time;return typeof Qe?.completed=="number"?Qe.completed:null},[t.info.time]),J=i.useMemo(()=>T?!0:!!(H&&H>0),[T,H]),we=i.useMemo(()=>{const Qe=t.info.finish;return typeof Qe=="string"?Qe:void 0},[t.info]),X=i.useMemo(()=>HM(O,{includeReasoning:v}),[O,v]),q=i.useMemo(()=>T||J?X:[],[T,J,X]),re=i.useMemo(()=>T?[]:X.filter(Qe=>Qe.type==="text"),[T,X]),ue=i.useMemo(()=>T?[]:X.filter(mt=>mt.type==="tool"),[T,X]),Re=i.useMemo(()=>{if(k==="collapsed"||k==="activity")return F;const Qe=new Set;for(const bt of ue){const dt=bt.tool;bt.id&&Ep(dt)&&Qe.add(bt.id)}if(a?.isFirstAssistantInTurn)for(const bt of a.activityParts){if(bt.kind!=="tool")continue;const dt=bt.part;dt.id&&Ep(dt.tool)&&Qe.add(dt.id)}const mt=new Set(Qe);for(const bt of F)mt.has(bt)?mt.delete(bt):mt.add(bt);return mt},[F,k,ue,a]),_e=i.useMemo(()=>{if(!T)return;const Qe=t.parts.find(Tt=>Tt.type==="agent");if(!Qe)return;const mt=Qe,bt=typeof mt.name=="string"?mt.name:void 0;if(!bt)return;const dt=mt.source&&typeof mt.source.value=="string"&&mt.source.value.trim().length>0?mt.source.value:`#${bt}`;return{name:bt,token:dt}},[T,t.parts]),me=typeof we!="string",Q=i.useMemo(()=>T?!1:re.length===0||ue.length===0?me:!0,[re.length,ue.length,me,T]),xe=d?.metadata.variant,fe=i.useMemo(()=>xe?xe==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[xe]),He=i.useMemo(()=>d?wc(d):fe?dM:uM,[d,fe]),it=i.useMemo(()=>T?!1:lo.getInstance().shouldAnimateMessage(t.info,h||t.info.sessionID),[t.info,h,T]),de=i.useRef(!1),Ue=i.useMemo(()=>s?ld(s.info):null,[s]),Fe=i.useMemo(()=>r?ld(r.info):null,[r]),be=i.useMemo(()=>T||!Fe?!1:!Fe.isUser&&Fe.role==="assistant",[T,Fe]),Te=i.useMemo(()=>J?"completed":f||(p?"streaming":"completed"),[J,f,p]),Ie=i.useMemo(()=>{if(T)return!0;const Qe=a?.headerMessageId;if(Qe){if(t.info.id===Qe){if(Te==="completed")return!0;const bt=Te==="streaming"||Te==="cooldown",dt=de.current;return bt&&!dt&&(de.current=!0),dt||bt}return!1}return Ue?Ue.isUser:!0},[T,Ue,a,Te,t.info]),Oe=i.useCallback(Qe=>{navigator.clipboard.writeText(Qe),j(Qe),setTimeout(()=>j(null),2e3)},[]),et=a?.turnId,{assistantSummaryFromStore:ze,variantFromTurnStore:Ee}=ss(oo(Qe=>{if(!et||!t.info.sessionID)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const mt=Qe.messages.get(t.info.sessionID);if(!mt)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const bt=mt.find(Bt=>Bt.info?.id===et);if(!bt)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const Tt=bt.info.summary?.body,$t=bt.info.variant;return{assistantSummaryFromStore:typeof Tt=="string"&&Tt.trim().length>0?Tt:void 0,variantFromTurnStore:typeof $t=="string"&&$t.trim().length>0?$t:void 0}})),Be=T?void 0:Ee??M?.variant,Ze=!T&&Z?Be??"Default":void 0,tt=typeof a?.summaryBody=="string"&&a.summaryBody.trim().length>0?a.summaryBody:ze,jt=i.useRef(void 0);tt&&tt.trim().length>0&&(jt.current=tt);const xt=i.useRef(et);xt.current!==et&&(xt.current=et,jt.current=void 0);const Et=jt.current,yt=i.useMemo(()=>{if(T)return;const Qe=t.info?.error;if(!Qe)return;const mt=typeof Qe.data?.message=="string"?Qe.data.message:void 0,bt=typeof Qe.message=="string"?Qe.message:void 0,dt=typeof Qe.name=="string"?Qe.name:void 0,Tt=mt||bt||dt;if(Tt)return`Opencode failed to send message with error:
209
+ ${We}`;_(Ge)},[L,_]),fe=i.useCallback(je=>{if(je.stopPropagation(),je.preventDefault(),B){W();return}const We=Hl(L);We.trim()&&G(We)},[L,B,G,W]);i.useEffect(()=>()=>{Re()},[Re]);const He=i.useMemo(()=>{const je={},We=T.filter(Ge=>Zi(Ge.tool)||ge?!1:Z(Ge));return We.forEach((Ge,Je)=>{je[Ge.id]={hasPrev:Je>0,hasNext:Je<We.length-1}}),je},[T,ge,Z]),it=i.useMemo(()=>v?.activityParts??[],[v]),de=i.useMemo(()=>v?it.filter(je=>je.messageId===t):[],[it,t,v]),Ue=i.useMemo(()=>v?v.activityGroupSegments.filter(je=>je.anchorMessageId===t):[],[t,v]),Fe=i.useMemo(()=>{const je=new Map;return de.forEach(We=>{je.set(We.part,We)}),je},[de]),be=i.useMemo(()=>v?(w?it:it.filter(We=>We.kind!=="reasoning")).filter(We=>{if(We.kind!=="tool")return!0;const Ge=We.part.tool;return!Zi(Ge)}):[],[it,w,v]),[Te,Ie]=i.useState(!1);i.useEffect(()=>{if(!v)return;const je=v.activityGroupSegments.some(Ge=>Ge.afterToolPartId!==null),We=be.some(Ge=>Ge.kind==="reasoning");(be.length>1||je&&be.length>0||We)&&Ie(!0)},[v,be]);const Oe=!!(v&&Te),et=!!(v&&Oe&&be.length>0&&Ue.length>0),ze=i.useMemo(()=>T.filter(je=>Zi(je.tool)),[T]),Ee=i.useMemo(()=>{const je=[],We=Je=>{!v||!et||Ue.filter(ut=>(ut.afterToolPartId??null)===Je).forEach(ut=>{const wt=w?ut.parts:ut.parts.filter(rt=>rt.kind!=="reasoning");wt.length!==0&&je.push(e.jsx(zM,{parts:wt,isExpanded:v.isGroupExpanded,onToggle:v.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,diffStats:v.diffStats},`progressive-group-${ut.id}`))})};We(null),ze.forEach(Je=>{je.push(e.jsx(Yr,{children:e.jsx(mu,{part:Je,isExpanded:d.has(Je.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Je.id}`)),We(Je.id)});const Ge=[];return P.forEach((Je,ut)=>{const wt=Fe.get(Je);if(!wt||!v)return;let rt=null,_t=null;if(!Oe){if(wt.kind==="tool"){const kt=Je;if(Zi(kt.tool))return;const Ct=kt.state?.time,Lt=Z(kt);if(!(!ge&&Lt))return;const At=He[kt.id];_t=e.jsx(Yr,{children:e.jsx(mu,{part:kt,isExpanded:d.has(kt.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:At?.hasPrev??!1,hasNextTool:At?.hasNext??!1})},`tool-${kt.id}`),rt=Lt&&typeof Ct?.end=="number"?Ct.end:null}else if(wt.kind==="reasoning"&&w){const kt=Je.time,qt=typeof kt?.end=="number"?kt.end:null;_t=e.jsx(Yr,{children:e.jsx(Ly,{part:Je,messageId:t,onContentChange:h})},`reasoning-${wt.id}`),rt=qt}_t&&Ge.push({part:Je,index:ut,endTime:rt,element:_t})}}),Ge.sort((Je,ut)=>Je.endTime===null&&ut.endTime===null?Je.index-ut.index:Je.endTime===null?1:ut.endTime===null?-1:Je.endTime-ut.endTime),Ge.forEach(({element:Je})=>{je.push(Je)}),je},[Fe,Ue,d,l,Z,t,h,m,u,ge,Oe,w,a,He,v,P,ze,et]),Be=v?.turnId,Ze=Ae(je=>je.currentSessionId),tt=ss(je=>{if(!Be||!Ze)return;const We=je.messages.get(Ze);if(!We)return;const Ge=We.find(wt=>wt.info?.id===Be);if(!Ge)return;const ut=Ge.info.summary?.body;return typeof ut=="string"&&ut.trim().length>0?ut:void 0}),jt=typeof v?.summaryBody=="string"&&v.summaryBody.trim().length>0?v.summaryBody:tt,xt=i.useRef(void 0);jt&&jt.trim().length>0&&(xt.current=jt);const Et=i.useRef(Be);Et.current!==Be&&(Et.current=Be,xt.current=void 0);const yt=xt.current,Xt=v?.isLastAssistantInTurn&&yt&&yt.trim().length>0,os=!!k,is=O&&g&&(M||!!k),hs=i.useMemo(()=>{if(!O||!M)return;const je=v?.userMessageCreatedAt;if(!(typeof je!="number"||typeof o!="number")&&!(o<=je))return GM(o-je)},[O,M,v?.userMessageCreatedAt,o]),ae=e.jsxs(e.Fragment,{children:[x&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","data-visible":S||D?"true":void 0,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!ue&&"opacity-50"),disabled:!ue,"aria-label":"Copy message text","aria-hidden":!ue,onPointerDown:je=>je.stopPropagation(),onClick:me,onFocus:()=>{ue&&j(!0)},onBlur:()=>{D||j(!1)},children:D?e.jsx(ns,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Hr,{className:"h-3.5 w-3.5"})})}),e.jsx(pt,{sideOffset:6,children:"Copy answer"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{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:je=>je.stopPropagation(),onClick:Q,children:e.jsx($d,{className:"h-4 w-4"})})}),e.jsx(pt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{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:je=>je.stopPropagation(),onClick:xe,children:e.jsx(Zu,{className:"h-4 w-4"})})}),e.jsx(pt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),ve&&ue&&e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon",className:R("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",B?"text-green-500":"text-muted-foreground hover:text-foreground"),"aria-label":B?"Stop speaking":"Read aloud",onPointerDown:je=>je.stopPropagation(),onClick:fe,children:B?e.jsx(il,{className:"h-3.5 w-3.5"}):e.jsx(ma,{className:"h-3.5 w-3.5"})})}),e.jsx(pt,{sideOffset:6,children:te})]})]});return e.jsxs("div",{ref:N,className:R("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:A&&F&&ue?_e:void 0,children:[e.jsx(WM,{containerRef:N}),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($r,{content:k??""})})},"assistant-error"),Xt&&e.jsx(Yr,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",children:[e.jsx($r,{content:yt}),is&&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:ae}),hs?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"}),hs]}):null]})]})},"summary-body")]}),e.jsx(by,{files:s,onShowPopup:m}),!Xt&&is&&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:ae}),hs?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"}),hs]}):null]})]})]})},YM=({isUser:t,...s})=>t?e.jsx(KM,{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(QM,{...s}),Mp=i.memo(YM),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}},JM=i.lazy(()=>qs(()=>import("./ToolOutputDialog-Cq56vLok.js"),__vite__mapDeps([2,0,1,3,4]))),XM=new Set(["task","edit","multiedit","write","bash"]),Ep=t=>typeof t=="string"&&XM.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 Kr=(t,s)=>{if(typeof t=="object"&&t!==null)return t[s]},ZM=({message:t,previousMessage:s,nextMessage:r,onContentChange:n,animationHandlers:o,turnGroupingContext:a})=>{const{isMobile:l,hasTouchInput:c}=Ns(),{currentTheme:d}=rn(),u=i.useRef(null),m=Ae(oo(Qe=>({lifecyclePhase:Qe.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const mt=t.info.sessionID??Qe.currentSessionId??null;return mt?(Qe.streamingMessageIds.get(mt)??null)===t.info.id:!1})(),currentSessionId:Qe.currentSessionId,getAgentModelForSession:Qe.getAgentModelForSession,getSessionModelSelection:Qe.getSessionModelSelection,revertToMessage:Qe.revertToMessage,forkFromMessage:Qe.forkFromMessage}))),{lifecyclePhase:f,isStreamingMessage:p,currentSessionId:h,getAgentModelForSession:g,getSessionModelSelection:x,revertToMessage:y,forkFromMessage:b}=m,w=ft(Qe=>Qe.providers),{showReasoningTraces:v,toolCallExpansion:k}=Me(oo(Qe=>({showReasoningTraces:Qe.showReasoningTraces,toolCallExpansion:Qe.toolCallExpansion})));i.useEffect(()=>{h&&lo.getInstance().recordSessionStart(h)},[h]);const[S,j]=i.useState(null),[C,N]=i.useState(!1),[F,D]=i.useState(new Set),[A,E]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{D(new Set)},[t.info.id,k]);const T=i.useMemo(()=>ld(t.info),[t.info]).isUser,L=t.info.sessionID,{currentContextAgent:I,savedSessionAgentSelection:_}=Pt(oo(Qe=>({currentContextAgent:L?Qe.currentAgentContext.get(L):void 0,savedSessionAgentSelection:L?Qe.sessionAgentSelections.get(L):void 0}))),O=i.useMemo(()=>{if(!T)return t.parts;const Qe=mt=>{const bt=mt.trim();return!!(bt.startsWith("User has requested to enter plan mode")||bt.startsWith("The plan at "))};return t.parts.filter(mt=>{if(!(mt?.synthetic===!0))return!0;if(mt.type!=="text")return!1;const dt=mt?.text;return typeof dt=="string"?Qe(dt):!1}).map(mt=>mt.type==="compaction"?{type:"text",text:"/compact"}:mt)},[T,t.parts]),M=i.useMemo(()=>{if(T||!s)return null;const Qe=Kr(s.info,"clientRole"),mt=Kr(s.info,"role");if((typeof Qe=="string"?Qe:typeof mt=="string"?mt:void 0)!=="user")return null;const dt=Kr(s.info,"mode"),Tt=Kr(s.info,"agent"),$t=Kr(s.info,"providerID"),Bt=Kr(s.info,"modelID"),Qt=Kr(s.info,"variant"),ms=typeof dt=="string"&&dt.trim().length>0?dt:typeof Tt=="string"&&Tt.trim().length>0?Tt:void 0,Ws=typeof $t=="string"&&$t.trim().length>0?$t:void 0,Js=typeof Bt=="string"&&Bt.trim().length>0?Bt:void 0,Xs=typeof Qt=="string"&&Qt.trim().length>0?Qt:void 0;return!ms&&!Ws&&!Js&&!Xs?null:{agentName:ms,providerId:Ws,modelId:Js,variant:Xs}},[T,s]),B=i.useMemo(()=>{if(T||!s)return!1;const Qe=Array.isArray(s.parts)?s.parts:[];for(let mt=0;mt<Qe.length;mt++){const bt=Qe[mt];if(bt?.type!=="text"||bt?.synthetic!==!0)continue;const dt=typeof bt.text=="string"?bt.text.trim():"";if(dt.startsWith("User has requested to enter plan mode")||dt.startsWith("The plan at "))return!0}return!1},[T,s]),G=i.useMemo(()=>{if(T)return;const Qe=t.info.time;if(!(typeof Qe?.completed=="number"&&Qe.completed>0)&&B&&M?.agentName)return M.agentName;const bt=Kr(t.info,"mode");if(typeof bt=="string"&&bt.trim().length>0)return bt;const dt=Kr(t.info,"agent");if(typeof dt=="string"&&dt.trim().length>0)return dt;if(M?.agentName)return M.agentName;if(L)return I||(_??void 0)},[T,t.info,B,M,L,I,_]),W=T?null:Kr(t.info,"providerID"),ve=T?null:Kr(t.info,"modelID"),oe=i.useMemo(()=>{if(T||!L)return null;if(M?.providerId&&M?.modelId)return{providerId:M.providerId,modelId:M.modelId};if(G){const mt=g(L,G);if(mt?.providerId&&mt?.modelId)return mt}const Qe=x(L);return Qe?.providerId&&Qe?.modelId?Qe:null},[T,L,G,M,g,x]),te=i.useMemo(()=>T?null:typeof W=="string"&&W.trim().length>0?W:oe?.providerId??null,[T,W,oe]),he=i.useMemo(()=>T?null:typeof ve=="string"&&ve.trim().length>0?ve:oe?.modelId??null,[T,ve,oe]),Y=i.useMemo(()=>{if(!T&&te&&he&&w.length>0){const Qe=w.find(mt=>mt.id===te);if(Qe?.models&&Array.isArray(Qe.models)){const dt=Qe.models.find(Tt=>Tt.id===he)?.name;return typeof dt=="string"?dt:void 0}}},[T,te,he,w]),Z=i.useMemo(()=>{if(T||!te||!he)return!1;const Qe=w.find(dt=>dt.id===te);if(!Qe?.models||!Array.isArray(Qe.models))return!1;const bt=Qe.models.find(dt=>dt.id===he)?.variants;return!!(bt&&Object.keys(bt).length>0)},[T,he,te,w]),ie=cd(G),$=cd(te??void 0),ne=cd(Y),V=ie??void 0,ce=$??null,ge=ne??void 0,H=i.useMemo(()=>{const Qe=t.info.time;return typeof Qe?.completed=="number"?Qe.completed:null},[t.info.time]),J=i.useMemo(()=>T?!0:!!(H&&H>0),[T,H]),we=i.useMemo(()=>{const Qe=t.info.finish;return typeof Qe=="string"?Qe:void 0},[t.info]),X=i.useMemo(()=>HM(O,{includeReasoning:v}),[O,v]),q=i.useMemo(()=>T||J?X:[],[T,J,X]),re=i.useMemo(()=>T?[]:X.filter(Qe=>Qe.type==="text"),[T,X]),ue=i.useMemo(()=>T?[]:X.filter(mt=>mt.type==="tool"),[T,X]),Re=i.useMemo(()=>{if(k==="collapsed"||k==="activity")return F;const Qe=new Set;for(const bt of ue){const dt=bt.tool;bt.id&&Ep(dt)&&Qe.add(bt.id)}if(a?.isFirstAssistantInTurn)for(const bt of a.activityParts){if(bt.kind!=="tool")continue;const dt=bt.part;dt.id&&Ep(dt.tool)&&Qe.add(dt.id)}const mt=new Set(Qe);for(const bt of F)mt.has(bt)?mt.delete(bt):mt.add(bt);return mt},[F,k,ue,a]),_e=i.useMemo(()=>{if(!T)return;const Qe=t.parts.find(Tt=>Tt.type==="agent");if(!Qe)return;const mt=Qe,bt=typeof mt.name=="string"?mt.name:void 0;if(!bt)return;const dt=mt.source&&typeof mt.source.value=="string"&&mt.source.value.trim().length>0?mt.source.value:`#${bt}`;return{name:bt,token:dt}},[T,t.parts]),me=typeof we!="string",Q=i.useMemo(()=>T?!1:re.length===0||ue.length===0?me:!0,[re.length,ue.length,me,T]),xe=d?.metadata.variant,fe=i.useMemo(()=>xe?xe==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[xe]),He=i.useMemo(()=>d?wc(d):fe?dM:uM,[d,fe]),it=i.useMemo(()=>T?!1:lo.getInstance().shouldAnimateMessage(t.info,h||t.info.sessionID),[t.info,h,T]),de=i.useRef(!1),Ue=i.useMemo(()=>s?ld(s.info):null,[s]),Fe=i.useMemo(()=>r?ld(r.info):null,[r]),be=i.useMemo(()=>T||!Fe?!1:!Fe.isUser&&Fe.role==="assistant",[T,Fe]),Te=i.useMemo(()=>J?"completed":f||(p?"streaming":"completed"),[J,f,p]),Ie=i.useMemo(()=>{if(T)return!0;const Qe=a?.headerMessageId;if(Qe){if(t.info.id===Qe){if(Te==="completed")return!0;const bt=Te==="streaming"||Te==="cooldown",dt=de.current;return bt&&!dt&&(de.current=!0),dt||bt}return!1}return Ue?Ue.isUser:!0},[T,Ue,a,Te,t.info]),Oe=i.useCallback(Qe=>{navigator.clipboard.writeText(Qe),j(Qe),setTimeout(()=>j(null),2e3)},[]),et=a?.turnId,{assistantSummaryFromStore:ze,variantFromTurnStore:Ee}=ss(oo(Qe=>{if(!et||!t.info.sessionID)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const mt=Qe.messages.get(t.info.sessionID);if(!mt)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const bt=mt.find(Bt=>Bt.info?.id===et);if(!bt)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const Tt=bt.info.summary?.body,$t=bt.info.variant;return{assistantSummaryFromStore:typeof Tt=="string"&&Tt.trim().length>0?Tt:void 0,variantFromTurnStore:typeof $t=="string"&&$t.trim().length>0?$t:void 0}})),Be=T?void 0:Ee??M?.variant,Ze=!T&&Z?Be??"Default":void 0,tt=typeof a?.summaryBody=="string"&&a.summaryBody.trim().length>0?a.summaryBody:ze,jt=i.useRef(void 0);tt&&tt.trim().length>0&&(jt.current=tt);const xt=i.useRef(et);xt.current!==et&&(xt.current=et,jt.current=void 0);const Et=jt.current,yt=i.useMemo(()=>{if(T)return;const Qe=t.info?.error;if(!Qe)return;const mt=typeof Qe.data?.message=="string"?Qe.data.message:void 0,bt=typeof Qe.message=="string"?Qe.message:void 0,dt=typeof Qe.name=="string"?Qe.name:void 0,Tt=mt||bt||dt;if(Tt)return`Opencode failed to send message with error:
210
210
  \`${Tt}\``},[T,t.info]),Xt=i.useMemo(()=>T?q.filter(bt=>bt.type==="text").map(bt=>(bt.text||bt.content||"").trim()).filter(bt=>bt.length>0).join(`
211
211
  `).replace(/\n\s*\n+/g,`
212
212
  `):yt&&yt.trim().length>0?yt:Et&&Et.trim().length>0?Et:Hl(q),[yt,Et,q,T]),os=Xt.length>0,is=i.useCallback(async Qe=>{if(!Qe)return!1;if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(Qe),!0}catch{}if(typeof document>"u")return!1;const mt=document.createElement("textarea");mt.value=Qe,mt.setAttribute("readonly",""),mt.style.position="fixed",mt.style.top="-1000px",mt.style.left="-1000px",document.body.appendChild(mt),mt.select(),mt.setSelectionRange(0,mt.value.length);const bt=document.execCommand("copy");return document.body.removeChild(mt),bt},[]),hs=i.useCallback(async()=>{await is(Xt)&&(N(!0),setTimeout(()=>N(!1),2e3))},[is,Xt]),ae=i.useCallback(()=>{!L||!t.info.id||y(L,t.info.id)},[L,t.info.id,y]),je=i.useCallback(()=>{!L||!t.info.id||b(L,t.info.id)},[L,t.info.id,b]),We=i.useCallback(Qe=>{D(mt=>{const bt=new Set(mt);return bt.has(Qe)?bt.delete(Qe):bt.add(Qe),bt})},[]),Ge=o??null,Je=i.useRef(!1),ut=i.useRef(!1),wt=i.useRef(!1),rt=i.useRef(!1),_t=i.useRef(!1);i.useEffect(()=>{ut.current=!1,wt.current=!1,rt.current=!1,_t.current=!1,Je.current=!1},[t.info.id]);const kt=i.useCallback(()=>{T||Je.current||(Je.current=!0,n?.("structural"))},[T,n]),qt=Me(Qe=>Qe.setImagePreviewOpen),Ct=i.useCallback(Qe=>{Qe.image&&(E(Qe),qt(!0))},[qt]),Lt=i.useCallback(Qe=>{E(mt=>({...mt,open:Qe})),qt(Qe)},[qt]),Kt=!!Kr(t.info,"animationSettled"),At=Te==="streaming",Yt=i.useMemo(()=>T?!1:X.some(Qe=>Qe.type==="reasoning"),[T,X]),St=it&&!Kt&&!At,ts=!T&&it&&re.length>0&&!Q;return i.useEffect(()=>{if(Ge?.onStreamingCandidate){if(!ts){wt.current&&(Yt&&Ge?.onReasoningBlock?Ge.onReasoningBlock():Ge?.onReservationCancelled&&Ge.onReservationCancelled(),wt.current=!1);return}_t.current||(_t.current=!0,Ge.onStreamingCandidate(),wt.current=!0)}},[Ge,ts,Yt]),i.useEffect(()=>{Ge?.onAnimationStart&&St&&(rt.current||(Ge.onAnimationStart(),rt.current=!0))},[Ge,St]),i.useEffect(()=>{if(T)return;const Qe=Ge?.onAnimatedHeightChange;if(!Qe||!(St||ts))return;const bt=u.current;if(!bt)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Qe(bt.getBoundingClientRect().height);return}let dt=null;const Tt=Bt=>{if(typeof window>"u"){Qe(Bt);return}dt!==null&&window.cancelAnimationFrame(dt),dt=window.requestAnimationFrame(()=>{Qe(Bt)})},$t=new ResizeObserver(Bt=>{const Qt=Bt[0];Qt&&Tt(Qt.contentRect.height)});return $t.observe(bt),Tt(bt.getBoundingClientRect().height),()=>{dt!==null&&(window.cancelAnimationFrame(dt),dt=null),$t.disconnect()}},[St,T,Ge,ts]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("group w-full",Ie?l?"pt-10":"pt-6":"pt-0",T||be?"pb-0":"pb-8"),"data-message-id":t.info.id,ref:u,children:e.jsx("div",{className:"chat-message-column relative",children:T?q.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(Mp,{messageId:t.info.id,parts:q,isUser:T,isMessageCompleted:J,messageFinish:we,syntaxTheme:He,isMobile:l,hasTouchInput:c,copiedCode:S,onCopyCode:Oe,expandedTools:F,onToggleTool:We,onShowPopup:Ct,streamPhase:Te,allowAnimation:St,onContentChange:n,shouldShowHeader:!1,hasTextContent:os,onCopyMessage:hs,copiedMessage:C,showReasoningTraces:v,onAuxiliaryContentComplete:kt,agentMention:_e,onRevert:ae,onFork:T?je:void 0,errorMessage:yt})})})}):e.jsxs("div",{className:"relative",children:[Ie&&e.jsx(fM,{isUser:T,providerID:ce,agentName:V,modelName:ge,variant:Ze,isDarkTheme:fe}),e.jsx(Mp,{messageId:t.info.id,parts:X,isUser:T,isMessageCompleted:J,messageFinish:we,messageCompletedAt:H??void 0,syntaxTheme:He,isMobile:l,hasTouchInput:c,copiedCode:S,onCopyCode:Oe,expandedTools:Re,onToggleTool:We,onShowPopup:Ct,streamPhase:Te,allowAnimation:St,onContentChange:n,shouldShowHeader:Ie,hasTextContent:os,onCopyMessage:hs,copiedMessage:C,onAuxiliaryContentComplete:kt,showReasoningTraces:v,agentMention:_e,turnGroupingContext:a,errorMessage:yt})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(JM,{popup:A,onOpenChange:Lt,syntaxTheme:He,isMobile:l})})]})},_y=i.memo(ZM),e2=({diff:t,syntaxTheme:s,filePath:r})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:My(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:R("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"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))}),t2=({content:t,syntaxTheme:s,filePath:r})=>{const n=t.split(`
@@ -286,12 +286,12 @@ ${JSON.stringify({directory:n,operation:g.operation,headInfo:g.headInfo,statusPo
286
286
  Use $ARGUMENTS to reference user input.
287
287
  Use !\`shell command\` to inject shell output.
288
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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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(Ce,{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"})]})})},R5=({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}=Me(),{isMobile:w}=Ns(),v=i.useMemo(()=>ps(),[]);i.useEffect(()=>{x()},[x]);const k=v?"bg-background":"bg-sidebar",S=()=>{const P="new-skill";let T=P,L=1;for(;m.some(I=>I.name===T);)T=`${P}-${L}`,L++;p({name:T,scope:"user",description:""}),f(T),t?.(),w&&b(!1)},j=async P=>{l(P)},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)},N=async P=>{const T=P.name;let L=1,I=`${T}-copy`;for(;m.some(O=>O.name===I);)L++,I=`${T}-copy-${L}`;const _=await y(P.name);if(!_){K.error("Failed to load skill details for duplication");return}p({name:I,scope:P.scope||"user",description:(_.sources.md.fields.includes("description"),""),instructions:""}),f(I),w&&b(!1)},F=P=>{o(P.name),r(P)},D=async()=>{if(!s)return;const P=n.trim().replace(/\s+/g,"-").toLowerCase();if(!P){K.error("Skill name is required");return}if(P===s.name){r(null);return}if(m.some(I=>I.name===P)){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:P,description:"Renamed skill",scope:s.scope})?await g(s.name)?(K.success(`Skill renamed to "${P}"`),f(P)):K.error("Failed to remove old skill after rename"):K.error("Failed to rename skill"),r(null)},A=m.filter(P=>P.scope==="project"),E=m.filter(P=>P.scope==="user");return e.jsxs("div",{className:R("flex h-full flex-col",k),children:[e.jsx("div",{className:R("border-b px-3",w?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",m.length]}),e.jsx(Ce,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:S,children:e.jsx(Bs,{className:"size-4"})})]})}),e.jsx(Vt,{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(P=>e.jsx(bh,{skill:P,isSelected:u===P.name,onSelect:()=>{f(P.name),t?.(),w&&b(!1)},onRename:()=>F(P),onDelete:()=>j(P),onDuplicate:()=>N(P)},P.name))]}),E.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"}),E.map(P=>e.jsx(bh,{skill:P,isSelected:u===P.name,onSelect:()=>{f(P.name),t?.(),w&&b(!1)},onRename:()=>F(P),onDelete:()=>j(P),onDuplicate:()=>N(P)},P.name))]})]})}),e.jsx(bs,{open:a!==null,onOpenChange:P=>{!P&&!c&&l(null)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Delete Skill"}),e.jsxs(Es,{children:['Are you sure you want to delete skill "',a?.name,'"?']})]}),e.jsxs(Ys,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>l(null),disabled:c,className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(yn,{onClick:C,disabled:c,children:"Delete"})]})]})}),e.jsx(bs,{open:s!==null,onOpenChange:P=>!P&&r(null),children:e.jsxs(vs,{children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Rename Skill"}),e.jsxs(Es,{children:['Enter a new name for the skill "',s?.name,'"']})]}),e.jsx(Ot,{value:n,onChange:P=>o(P.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:P=>{P.key==="Enter"&&D()}}),e.jsxs(Ys,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>r(null),className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(yn,{onClick:D,children:"Rename"})]})]})})]})},bh=({skill:t,isSelected:s,onSelect:r,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",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(cs,{children:[e.jsx(ds,{asChild:!0,children:e.jsx(Ce,{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(us,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(It,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(go,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(It,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(Hr,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(It,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(kr,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),L5=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,O5=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},_5=async()=>{try{const t=zr()?.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}},$5=({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,w]=i.useState(!1),[v,k]=i.useState([]),[S,j]=i.useState(null);i.useEffect(()=>{t&&(d(""),m(""),p(""),y(null),w(!1),k([]),j(null),l(),(async()=>{const D=await _5(),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(E=>{const P=(E.source||"").trim(),T=(E.subpath||"").trim();return P===D&&T===A})},[h,u,f]),N=async()=>{const D=u.trim();if(!D){K.error("Repository source is required");return}c.trim()||d(O5(D)),w(!1),y(null);const A=await r({source:D,subpath:f.trim()||void 0,gitIdentityId:S||void 0});if(!A.ok){if(A.error?.kind==="authRequired"){if(ps()){K.error("Private repositories are not supported in VS Code yet");return}const P=A.error.identities||[];if(k(P),!S&&P.length>0){const T=a&&a!=="global"&&P.some(L=>L.id===a)?a:P[0].id;j(T)}K.error("Authentication required. Select a Git identity and scan again.");return}K.error(A.error?.message||"Failed to scan repository");return}const E=A.items?.length||0;if(y(E),E===0){K.error("No skills found in this repository"),w(!1);return}k([]),w(!0),K.success(`Found ${E} skill(s)`)},F=async()=>{const D=c.trim(),A=u.trim(),E=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 P={id:L5(),label:D,source:A,...E?{subpath:E}:{},...S?{gitIdentityId:S}:{}},T=[...h,P];try{await xs({skillCatalogs:T}),g(T),K.success("Catalog added"),await n({refresh:!0}),s(!1)}catch(L){K.error(L instanceof Error?L.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(Es,{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(Ot,{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(Ot,{value:u,onChange:D=>{m(D.target.value),w(!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(Ot,{value:f,onChange:D=>{p(D.target.value),w(!1),y(null)},placeholder:"e.g. skills"})]}),v.length>0&&!ps()?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:S||"",onValueChange:D=>j(D),children:[e.jsx($s,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:v.find(D=>D.id===S)?.name||"Choose identity"})}),e.jsx(zs,{align:"start",children:v.map(D=>e.jsx(rs,{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(Ys,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>s(!1),children:"Cancel"}),e.jsxs(Ce,{variant:"outline",onClick:()=>{N()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(Cg,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Ce,{variant:"default",onClick:()=>{F()},disabled:!b||C||!c.trim()||!u.trim(),children:"Add catalog"})]})]})})},z5=({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(Es,{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(Ce,{variant:"outline",size:"sm",onClick:()=>l("skip"),children:"Skip all"}),e.jsx(Ce,{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($s,{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(rs,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(rs,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Ys,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>s(!1),children:"Cancel"}),e.jsx(yn,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},H5=({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(Es,{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(Ys,{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($s,{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(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(zs,{align:"start",children:[e.jsx(rs,{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(rs,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pn,{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(Ce,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>s(!1),children:"Cancel"}),e.jsx(Ce,{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(z5,{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},U5=async()=>{try{const t=zr()?.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}},V5=({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,w]=i.useState(!1),[v,k]=i.useState(!1),[S,j]=i.useState(null),[C,N]=i.useState(!1),[F,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]),E=i.useMemo(()=>{const O=x.trim().toLowerCase();return O?A.filter(M=>{const B=M.skillName.toLowerCase(),G=(M.description||"").toLowerCase(),W=(M.frontmatterName||"").toLowerCase();return B.includes(O)||G.includes(O)||W.includes(O)}):A},[A,x]),P=i.useMemo(()=>r.find(O=>O.id===o)||null,[r,o]),T=!!(o&&o.startsWith("custom:")),L=P?.source==="clawdhub:registry"||P?.sourceType==="clawdhub",I=!!(o&&(h[o]??!0)),_=async()=>{if(!(!o||!T)){N(!0);try{const O=await U5(),B=(Array.isArray(O?.skillCatalogs)?O?.skillCatalogs:[]).filter(G=>G.id!==o);await xs({skillCatalogs:B}),await l({refresh:!0}),D(!1)}finally{N(!1)}}};return e.jsx(Vt,{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(ci,{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:O=>a(O),children:[e.jsx($s,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:P?.label||"Select source"})}),e.jsx(zs,{align:"start",children:r.map(O=>e.jsx(rs,{value:O.id,className:"pr-2 [&>span:first-child]:hidden",children:O.label},O.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ce,{type:"button",variant:"outline",onClick:()=>{o?c(o,{refresh:!0}):l({refresh:!0})},disabled:u||m,className:"gap-2",children:[e.jsx(Cr,{className:"h-4 w-4"}),"Refresh"]}),T?e.jsxs(Ce,{type:"button",variant:"outline",onClick:()=>D(!0),disabled:C,className:"gap-2",children:[e.jsx(kr,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Ce,{type:"button",variant:"default",onClick:()=>w(!0),className:"gap-2",children:[e.jsx(Bs,{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(Ot,{value:x,onChange:O=>y(O.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:u?"Loading…":`${E.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:E.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:[E.map(O=>{const M=O.installed?.isInstalled,B=O.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:O.skillName}),M?e.jsxs("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:["installed (",B||"unknown",")"]}):null,O.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"})]}),O.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:O.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),O.clawdhub?e.jsxs("div",{className:"typography-micro text-muted-foreground mt-1 flex items-center gap-3",children:[O.clawdhub.owner?e.jsxs("span",{children:["by ",O.clawdhub.owner]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(po,{className:"h-3 w-3"}),O.clawdhub.downloads?.toLocaleString()??0]}),(O.clawdhub.stars??0)>0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Do,{className:"h-3 w-3"}),O.clawdhub.stars]}):null,e.jsxs("span",{children:["v",O.clawdhub.version]})]}):null,O.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:O.warnings.join(" · ")}):null]}),e.jsx(Ce,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!O.installable,onClick:()=>{j(O),k(!0)},children:"Install"})]})},`${O.sourceId}:${O.skillDir}`)}),L&&I?e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(Ce,{type:"button",variant:"outline",onClick:()=>{d()},disabled:f||m,children:f?"Loading…":"Load more"})}):null]})}),e.jsx($5,{open:b,onOpenChange:w}),e.jsx(H5,{open:v,onOpenChange:k,item:S}),e.jsx(bs,{open:F,onOpenChange:O=>{C||D(O)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Remove Catalog"}),e.jsx(Es,{children:"Are you sure you want to remove this catalog?"})]}),e.jsxs(Ys,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>D(!1),disabled:C,children:"Cancel"}),e.jsx(Ce,{variant:"destructive",onClick:()=>{_()},disabled:C,children:"Remove"})]})]})})]})})},W5=()=>{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(ci,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[x,y]=i.useState(""),[b,w]=i.useState("user"),[v,k]=i.useState(""),[S,j]=i.useState(""),[C,N]=i.useState([]),[F,D]=i.useState([]),[A,E]=i.useState(!1),[P,T]=i.useState(!1),[L,I]=i.useState(""),[_,O]=i.useState(""),[M,B]=i.useState(!1),[G,W]=i.useState(""),[ve,oe]=i.useState(""),[te,he]=i.useState(null),[Y,Z]=i.useState(!1),[ie,$]=i.useState(""),[ne,V]=i.useState(null),[ce,ge]=i.useState(!1),H=m?x.trim()!==""||v.trim()!==""||S.trim()!==""||F.length>0:v!==L||S!==_,J=te?ve!==ie:G.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&l)y(l.name||""),w(l.scope||"user"),k(l.description||""),j(l.instructions||""),I(""),O(""),N([]),D(l.pendingFiles||[]);else if(t&&u){T(!0);try{const me=await r(t);if(me){const Q=me.sources.md;k(Q.description||""),j(Q.instructions||""),I(Q.description||""),O(Q.instructions||""),N(Q.supportingFiles||[])}}catch(me){console.error("Failed to load skill details:",me)}finally{T(!1)}}})()},[u,m,t,a,l,r,p]);const we=async()=>{const _e=m?x.trim().replace(/\s+/g,"-").toLowerCase():t?.trim();if(!_e){K.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(_e)||_e.length>64){K.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!v.trim()){K.error("Description is required");return}if(m&&a.some(me=>me.name===_e)){K.error("A skill with this name already exists");return}E(!0);try{const me={name:_e,description:v.trim(),instructions:S.trim()||void 0,scope:m?b:void 0,supportingFiles:m&&F.length>0?F:void 0};let Q;m?(Q=await n(me),Q&&(c(null),D([]),d(_e))):(Q=await o(_e,me),Q&&(I(v.trim()),O(S.trim()))),Q?K.success(m?"Skill created successfully":"Skill updated successfully"):K.error(m?"Failed to create skill":"Failed to update skill")}catch(me){console.error("Error saving skill:",me),K.error("An error occurred while saving")}finally{E(!1)}},X=()=>{he(null),W(""),oe(""),$(""),B(!0)},q=async _e=>{if(he(_e),W(_e),m){const Q=F.find(xe=>xe.path===_e)?.content||"";oe(Q),$(Q),B(!0);return}if(t){Z(!0),B(!0);try{const{readSupportingFile:me}=pn.getState(),Q=await me(t,_e);oe(Q||""),$(Q||"")}catch{K.error("Failed to load file content"),oe(""),$("")}finally{Z(!1)}}},re=async()=>{if(!G.trim()){K.error("File name is required");return}const _e=G.trim(),me=te!==null;if(m){if(me)D(fe=>fe.map(He=>He.path===te?{path:_e,content:ve}:He)),K.success(`File "${_e}" updated`);else{if(F.some(fe=>fe.path===_e)){K.error("A file with this name already exists");return}D(fe=>[...fe,{path:_e,content:ve}]),K.success(`File "${_e}" added`)}B(!1),he(null);return}if(!t){K.error("No skill selected");return}const{writeSupportingFile:Q}=pn.getState();if(await Q(t,_e,ve)){K.success(me?`File "${_e}" updated`:`File "${_e}" created`),B(!1),he(null);const fe=await r(t);fe&&N(fe.sources.md.supportingFiles||[])}else K.error(me?"Failed to update file":"Failed to create file")},ue=_e=>{if(m){D(me=>me.filter(Q=>Q.path!==_e)),K.success(`File "${_e}" removed`);return}t&&V(_e)},Re=async()=>{if(!ne||!t)return;ge(!0);const{deleteSupportingFile:_e}=pn.getState();if(await _e(t,ne)){K.success(`File "${ne}" deleted`);const Q=await r(t);Q&&N(Q.sources.md.supportingFiles||[]),V(null)}else K.error("Failed to delete file");ge(!1)};return m&&p==="external"?e.jsx(V5,{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"})]})}):P?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Loading skill details..."})})}):e.jsx(Vt,{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(Ot,{value:x,onChange:_e=>y(_e.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(_s,{value:b,onValueChange:_e=>w(_e),children:[e.jsxs($s,{className:"!h-9 w-auto gap-1.5",children:[b==="user"?e.jsx(en,{className:"h-4 w-4"}):e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:b})]}),e.jsxs(zs,{align:"end",children:[e.jsx(rs,{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(rs,{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(Pn,{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:v,onChange:_e=>k(_e.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:S,onChange:_e=>j(_e.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(Ce,{variant:"outline",size:"sm",onClick:X,className:"gap-1.5",children:[e.jsx(Bs,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const _e=m?F:C;return _e.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:_e.map(me=>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:()=>q(me.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Dn,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:me.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(Ce,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Q=>{Q.stopPropagation(),ue(me.path)},children:e.jsx(kr,{className:"h-3.5 w-3.5"})})]},me.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ce,{size:"sm",variant:"default",onClick:we,disabled:A||!H,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:ne!==null,onOpenChange:_e=>{!_e&&!ce&&V(null)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Delete Supporting File"}),e.jsxs(Es,{children:['Are you sure you want to delete "',ne,'"?']})]}),e.jsxs(Ys,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>V(null),disabled:ce,className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(yn,{onClick:Re,disabled:ce,children:"Delete"})]})]})}),e.jsx(bs,{open:M,onOpenChange:_e=>{B(_e),_e||he(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:te?"Edit Supporting File":"Add Supporting File"}),e.jsx(Es,{children:te?"Modify the file content":"Create a new file in the skill directory"})]}),Y?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(Ot,{value:G,onChange:_e=>W(_e.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:te!==null}),!te&&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:_e=>oe(_e.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Ys,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>{B(!1),he(null)},className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:"Cancel"}),e.jsx(yn,{onClick:re,disabled:Y||!J,children:te?"Save Changes":"Create File"})]})]})})]})})},G5="__add_provider__",q5=({onItemSelect:t})=>{const s=ft(c=>c.providers),r=ft(c=>c.selectedProviderId),n=ft(c=>c.setSelectedProvider),{isMobile:o}=Ns(),l=i.useMemo(()=>ps(),[])?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",l),children:[e.jsx("div",{className:R("border-b px-3",o?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",s.length]}),e.jsx(Ce,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(G5),t?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(Bs,{className:"size-4"})})]})}),e.jsx(Vt,{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(To,{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:R("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(Rs,{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)})})]})},K5=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=K5.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()},Q5=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},Y5=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}},J5=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=>Y5(o)).filter(o=>!!o),n=new Set;return r.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},X5=()=>{const t=ft(H=>H.providers),s=ft(H=>H.selectedProviderId),r=ft(H=>H.setSelectedProvider),n=ft(H=>H.getModelMetadata),[o,a]=i.useState({}),[l,c]=i.useState(!1),[d,u]=i.useState({}),[m,f]=i.useState(null),[p,h]=i.useState(""),[g,x]=i.useState(null),[y,b]=i.useState({}),[w,v]=i.useState({}),[k,S]=i.useState([]),[j,C]=i.useState(!1),[N,F]=i.useState(null),[D,A]=i.useState(""),[E,P]=i.useState(""),[T,L]=i.useState(!1),[I,_]=i.useState({}),[O,M]=i.useState(!1);i.useEffect(()=>{!s&&t.length>0&&r(t[0].id)},[t,s,r]),i.useEffect(()=>{let H=!0;return(async()=>{c(!0);try{const we=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!we.ok)throw new Error(`Auth methods request failed (${we.status})`);const X=await we.json().catch(()=>({}));if(!H)return;a(Q5(X))}catch(we){if(!H)return;console.error("Failed to load provider auth methods:",we),K.error("Failed to load provider authentication methods")}finally{H&&c(!1)}})(),()=>{H=!1}},[]),i.useEffect(()=>{let H=!0;return(async()=>{C(!0),F(null);try{const we=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!we.ok)throw new Error(`Provider list request failed (${we.status})`);const X=await we.json().catch(()=>({}));if(!H)return;S(J5(X))}catch(we){if(!H)return;console.error("Failed to load available providers:",we),F("Unable to load provider list")}finally{H&&C(!1)}})(),()=>{H=!1}},[]);const B=i.useMemo(()=>new Set(t.map(H=>H.id)),[t]),G=i.useMemo(()=>k.filter(H=>!B.has(H.id)),[k,B]);i.useEffect(()=>{if(s===sa){if(!D&&G.length>0){A(G[0].id);return}D&&!G.some(H=>H.id===D)&&A(G[0]?.id??"")}},[s,D,G]),i.useEffect(()=>{if(s===sa){M(!0);return}M(!1)},[s]),i.useEffect(()=>{if(!s||s===sa)return;let H=!1;return(async()=>{try{const we=await fetch(`/api/provider/${encodeURIComponent(s)}/source`,{method:"GET",headers:{Accept:"application/json"}}),X=await we.json().catch(()=>null);if(!we.ok)throw new Error(X?.error||"Failed to load provider sources");const q=X?.sources??X?.data?.sources;!H&&q&&_(re=>({...re,[s]:q}))}catch(we){H||console.error("Failed to load provider sources:",we)}})(),()=>{H=!0}},[s]);const W=t.find(H=>H.id===s),ve=s?I[s]:void 0,oe=async H=>{const J=d[H]?.trim()??"";if(!J){K.error("API key is required");return}const we=`api:${H}`;f(we);try{const X=await fetch(`/api/auth/${encodeURIComponent(H)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:J})}),q=await X.json().catch(()=>null);if(!X.ok){const re=q?.error||"Failed to save API key";throw new Error(re)}K.success("API key saved"),u(re=>({...re,[H]:""})),await Za({scopes:["providers"],mode:"active"}),r(H)}catch(X){console.error("Failed to save API key:",X),K.error("Failed to save API key")}finally{f(null)}},te=async(H,J)=>{const we=`oauth:${H}:${J}`;f(we);try{const X=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:J})}),q=await X.json().catch(()=>null);if(!X.ok){const xe=q?.error||"Failed to start OAuth flow";throw new Error(xe)}const re=Aa(q)?q:{},ue=Aa(re.data)?re.data:re,Re=typeof ue.url=="string"&&ue.url||typeof ue.verification_uri_complete=="string"&&ue.verification_uri_complete||typeof ue.verification_uri=="string"&&ue.verification_uri||void 0,_e=typeof ue.instructions=="string"&&ue.instructions||typeof ue.message=="string"&&ue.message||void 0,me=typeof ue.user_code=="string"&&ue.user_code||typeof ue.code=="string"&&ue.code||typeof ue.userCode=="string"&&ue.userCode||void 0;if(!Re&&!_e&&!me)throw new Error("No OAuth details returned");const Q=`${H}:${J}`;v(xe=>({...xe,[Q]:{url:Re,instructions:_e,userCode:me}})),Re&&window.open(Re,"_blank","noopener,noreferrer"),x({providerId:H,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)}},he=async(H,J)=>{const we=`${H}:${J}`,X=y[we]?.trim(),q=`oauth-complete:${H}:${J}`;f(q);try{const re={method:J};X&&(re.code=X);const ue=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(re)}),Re=await ue.json().catch(()=>null);if(!ue.ok){const _e=Re?.error||"Failed to complete OAuth flow";throw new Error(_e)}K.success("OAuth connection completed"),b(_e=>({..._e,[we]:""})),x(null),await Za({scopes:["providers"],mode:"active"}),r(H)}catch(re){console.error("Failed to complete OAuth flow:",re),K.error("Failed to complete OAuth flow")}finally{f(null)}},Y=async H=>{try{await navigator.clipboard.writeText(H),K.success("OAuth link copied")}catch(J){console.error("Failed to copy OAuth link:",J),K.error("Failed to copy OAuth link")}},Z=async H=>{try{await navigator.clipboard.writeText(H),K.success("Device code copied")}catch(J){console.error("Failed to copy device code:",J),K.error("Failed to copy device code")}},ie=async H=>{const J=`disconnect:${H}`;f(J);try{const we=await fetch(`/api/provider/${encodeURIComponent(H)}/auth?scope=all`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),X=await we.json().catch(()=>null);if(!we.ok){const q=X?.error||"Failed to disconnect provider";throw new Error(q)}K.success("Provider disconnected"),await Za({scopes:["providers"],mode:"active"})}catch(we){console.error("Failed to disconnect provider:",we),K.error("Failed to disconnect provider")}finally{f(null)}},$=s===sa;if(!$&&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(To,{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($)return e.jsx(Vt,{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."})]}),j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):N?e.jsx("p",{className:"typography-meta text-muted-foreground",children:N}):G.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(cs,{open:T,onOpenChange:H=>{L(H),H||P("")},children:[e.jsx(ds,{asChild:!0,children:e.jsxs("button",{type:"button",className:R("flex w-fit items-center justify-between gap-2 rounded-lg border border-input bg-transparent px-3 py-2 typography-ui-label","hover:bg-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?G.find(H=>H.id===D)?.name||D:"Select provider"}),e.jsx(as,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(us,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:H=>H.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:H=>H.stopPropagation(),children:[e.jsx(Ir,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:E,onChange:H=>P(H.target.value),onKeyDown:H=>H.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(Vt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const H=G.filter(J=>{const we=E.toLowerCase();return(J.name||J.id).toLowerCase().includes(we)||J.id.toLowerCase().includes(we)});return H.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):H.map(J=>e.jsxs(It,{onSelect:()=>{A(J.id),L(!1),P("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:J.name||J.id}),D===J.id&&e.jsx(ns,{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(Ot,{type:"password",value:d[D]??"",onChange:H=>u(J=>({...J,[D]:H.target.value})),placeholder:"sk-..."}),e.jsx(Ce,{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(we=>wh(we)==="oauth");return J.length===0?null:e.jsx("div",{className:"space-y-3",children:J.map((we,X)=>{const q=we.label||we.name||`OAuth method ${X+1}`,re=`${D}:${X}`,ue=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:q}),(we.description||we.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(we.description||we.help)})]}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>te(D,X),disabled:m===`oauth:${D}:${X}`,className:"h-8",children:"Connect"})]}),w[re]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:w[re]?.instructions}),w[re]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Ot,{value:w[re]?.userCode,readOnly:!0}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>Z(w[re]?.userCode??""),className:"h-8",children:"Copy code"})]}),w[re]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Ot,{value:w[re]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ce,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:w[re]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>Y(w[re]?.url??""),className:"h-8",children:"Copy link"})]})]}),ue&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Ot,{value:y[re]??"",onChange:Re=>b(_e=>({..._e,[re]:Re.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Ce,{size:"sm",onClick:()=>he(D,X),disabled:m===`oauth-complete:${D}:${X}`,className:"h-8",children:m===`oauth-complete:${D}:${X}`?"Saving…":"Complete"})]})]},`${D}-${q}`)})})})()]})]})]})});if(!W)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(To,{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 ne=Array.isArray(W.models)?W.models:[],ce=(o[W.id]??[]).filter(H=>wh(H)==="oauth"),ge=ne.filter(H=>{const J=typeof H?.name=="string"?H.name:"",we=typeof H?.id=="string"?H.id:"",X=p.trim().toLowerCase();return X?J.toLowerCase().includes(X)||we.toLowerCase().includes(X):!0});return e.jsx(Vt,{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(Rs,{providerId:W.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:W.name||W.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",W.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(Ce,{size:"sm",variant:"outline",onClick:()=>M(H=>!H),className:"h-8",children:O?"Hide":"Reconnect"})]}),!O&&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(Ot,{type:"password",value:d[W.id]??"",onChange:H=>u(J=>({...J,[W.id]:H.target.value})),placeholder:"sk-..."}),e.jsx(Ce,{size:"sm",onClick:()=>oe(W.id),disabled:m===`api:${W.id}`,className:"h-8",children:m===`api:${W.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."})]}),ce.length>0&&e.jsx("div",{className:"space-y-3",children:ce.map((H,J)=>{const we=H.label||H.name||`OAuth method ${J+1}`,X=`${W.id}:${J}`,q=g?.providerId===W.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:we}),(H.description||H.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(H.description||H.help)})]}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>te(W.id,J),disabled:m===`oauth:${W.id}:${J}`,className:"h-8",children:"Connect"})]}),w[X]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:w[X]?.instructions}),w[X]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Ot,{value:w[X]?.userCode,readOnly:!0}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>Z(w[X]?.userCode??""),className:"h-8",children:"Copy code"})]}),w[X]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Ot,{value:w[X]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ce,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:w[X]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>Y(w[X]?.url??""),className:"h-8",children:"Copy link"})]})]}),q&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(Ot,{value:y[X]??"",onChange:re=>b(ue=>({...ue,[X]:re.target.value})),placeholder:"Paste authorization code"}),e.jsx(Ce,{size:"sm",onClick:()=>he(W.id,J),disabled:m===`oauth-complete:${W.id}:${J}`,className:"h-8",children:m===`oauth-complete:${W.id}:${J}`?"Saving…":"Complete"})]})]},`${W.id}-${we}`)})})]})]}),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(Ce,{size:"sm",variant:"outline",onClick:()=>ie(W.id),disabled:m===`disconnect:${W.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${W.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(Ot,{value:p,onChange:H=>h(H.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(H=>{const J=typeof H?.id=="string"?H.id:"",we=typeof H?.name=="string"?H.name:J,X=J?n(W.id,J):void 0,q=vh(X?.limit?.context),re=vh(X?.limit?.output),ue=[];return X?.tool_call&&ue.push({key:"tools",icon:rc,label:"Tool calling"}),X?.reasoning&&ue.push({key:"reasoning",icon:Tn,label:"Reasoning"}),X?.attachment&&ue.push({key:"image",icon:Rn,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:we}),(q||re)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[q?`${q} ctx`:"",q&&re?" · ":"",re?`${re} out`:""]}),ue.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:ue.map(({key:Re,icon:_e,label:me})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:me,"aria-label":me,children:e.jsx(_e,{className:"h-3 w-3"})},Re))})]},J)})})]})]})})},Z5=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)},eI=({onItemSelect:t})=>{const s=es(k=>k.results),r=es(k=>k.selectedProviderId),n=es(k=>k.setSelectedProvider),o=es(k=>k.fetchAllQuotas),a=es(k=>k.isLoading),l=es(k=>k.autoRefresh),c=es(k=>k.refreshIntervalMs),d=es(k=>k.displayMode),u=es(k=>k.setAutoRefresh),m=es(k=>k.setRefreshInterval),f=es(k=>k.setDisplayMode),p=es(k=>k.loadSettings),{isMobile:h}=Ns(),g=i.useMemo(()=>ps(),[]);i.useEffect(()=>{p()},[p]);const x=i.useCallback(async k=>{try{await xs(k)}catch(S){console.warn("Failed to save usage settings:",S)}},[]),y=i.useCallback(k=>{u(k),x({usageAutoRefresh:k})},[x,u]),b=i.useCallback(k=>{const S=Number(k);Number.isFinite(S)&&(m(S),x({usageRefreshIntervalMs:S}))},[x,m]),w=i.useCallback(k=>{k!=="usage"&&k!=="remaining"||(f(k),x({usageDisplayMode:k}))},[x,f]),v=g?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",v),children:[e.jsxs("div",{className:R("border-b px-3",h?"mt-2 py-3":"py-3"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",xn.length]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ht,{delayDuration:700,children:[e.jsx(gt,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(ar,{checked:l,onCheckedChange:y,"aria-label":"Toggle auto refresh",className:"data-[state=checked]:bg-[var(--status-info)]"})})}),e.jsx(pt,{side:"bottom",children:"Auto-refresh usage data at set interval"})]}),e.jsxs(_s,{value:String(c),onValueChange:b,disabled:!l,children:[e.jsx($s,{size:"sm",className:"min-w-[72px]",children:e.jsx(Sr,{placeholder:"Interval"})}),e.jsxs(zs,{children:[e.jsx(rs,{value:"30000",className:"pr-2 [&>span:first-child]:hidden",children:"30s"}),e.jsx(rs,{value:"60000",className:"pr-2 [&>span:first-child]:hidden",children:"1m"}),e.jsx(rs,{value:"300000",className:"pr-2 [&>span:first-child]:hidden",children:"5m"})]})]}),e.jsx(Ce,{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(Cr,{className:R("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:w,children:[e.jsx($s,{size:"sm",className:"min-w-[140px]",children:e.jsx(Sr,{placeholder:"Display mode"})}),e.jsxs(zs,{children:[e.jsx(rs,{value:"usage",className:"pr-2 [&>span:first-child]:hidden",children:"Usage"}),e.jsx(rs,{value:"remaining",className:"pr-2 [&>span:first-child]:hidden",children:"Quota remaining"})]})]})]})]}),e.jsx(Vt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:xn.map(k=>{const S=s.find(A=>A.providerId===k.id),j=Z5(S?.usage),C=Cx(j),N=k.id===r,F=S?.configured??!1,D=F?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:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",N?"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(Rs,{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}),!F&&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=es(g=>g.displayMode),c=l==="remaining"?s.remainingPercent:s.usedPercent,d=l==="remaining"?"remaining":"used",u=s.valueLabel??jn(c),m=s.resetAfterFormatted??s.resetAtFormatted??"",f=Ul(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(ar,{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})]})]})},tI=t=>{if(!t)return"-";try{return new Date(t).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}catch{return"-"}},sI=()=>{const t=es(A=>A.results),s=es(A=>A.selectedProviderId),r=es(A=>A.setSelectedProvider),n=es(A=>A.loadSettings),o=es(A=>A.fetchAllQuotas),a=es(A=>A.isLoading),l=es(A=>A.lastUpdated),c=es(A=>A.error),d=es(A=>A.dropdownProviderIds),u=es(A=>A.setDropdownProviderIds),m=es(A=>A.selectedModels),f=es(A=>A.toggleModelSelected),p=es(A=>A.applyDefaultSelections);Uu(),i.useEffect(()=>{n(),o()},[n,o]),i.useEffect(()=>{if(s||t.length===0)return;const A=t.find(E=>E.configured)?.providerId;r(A??xn[0]?.id??null)},[t,s,r]);const h=t.find(A=>A.providerId===s)??null,x=xn.find(A=>A.id===s)?.name??s??"Usage",y=h?.usage,b=s?d.includes(s):!1,w=i.useCallback(A=>{if(!s)return;const E=A?Array.from(new Set([...d,s])):d.filter(P=>P!==s);u(E),xs({usageDropdownProviders:E})},[d,s,u]),v=i.useMemo(()=>y?.models?Object.entries(y.models).map(([A,E])=>({name:A,windows:E})).filter(A=>Object.keys(A.windows.windows).length>0):[],[y?.models]);i.useEffect(()=>{s&&v.length>0&&p(s,v.map(A=>A.name))},[s,v,p]);const k=i.useMemo(()=>!s||v.length===0?new Map:Sk(v,A=>A.name,s),[v,s]),S=i.useMemo(()=>{if(!s)return[];const A=Dx(s);return Mx(A)},[s]),[j,C]=i.useState(()=>({})),N=i.useCallback(A=>{C(E=>({...E,[A]:!E[A]}))},[]),F=i.useCallback(A=>{if(!s)return;f(s,A);const E=m[s]??[],T=E.includes(A)?E.filter(I=>I!==A):[...E,A],L={...m,[s]:T};xs({usageSelectedModels:L})},[s,m,f]),D=s?m[s]??[]:[];return s?e.jsx(Vt,{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(Rs,{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 ${tI(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(ar,{checked:b,onCheckedChange:w,"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,E])=>e.jsx(Sd,{title:A,window:E},A))}),v.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"})]}),S.map(A=>{const E=k.get(A.id)??[];if(E.length===0)return null;const P=j[A.id]??!1;return e.jsxs(tn,{open:!P,onOpenChange:()=>N(A.id),children:[e.jsxs(Ln,{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:[E.length," model",E.length!==1?"s":""]})]}),P?e.jsx(ur,{className:"h-5 w-5 text-muted-foreground group-hover:text-foreground transition-colors"}):e.jsx(as,{className:"h-5 w-5 text-muted-foreground group-hover:text-foreground transition-colors"})]}),e.jsx(sn,{className:"pt-2 space-y-3",children:E.map(T=>{const L=Object.entries(T.windows.windows);if(L.length===0)return null;const[I,_]=L[0],O=D.includes(T.name);return e.jsx(Sd,{title:I,subtitle:Vl(T.name),window:_,showToggle:!0,toggleEnabled:O,onToggle:()=>F(T.name)},T.name)})})]},A.id)}),(()=>{const A=k.get(null)??[];if(A.length===0)return null;const E=j.other??!1;return e.jsxs(tn,{open:!E,onOpenChange:()=>N("other"),children:[e.jsxs(Ln,{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":""]})]}),E?e.jsx(ur,{className:"h-5 w-5 text-muted-foreground group-hover:text-foreground transition-colors"}):e.jsx(as,{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(P=>{const T=Object.entries(P.windows.windows);if(T.length===0)return null;const[L,I]=T[0],_=D.includes(P.name);return e.jsx(Sd,{title:L,subtitle:Vl(P.name),window:I,showToggle:!0,toggleEnabled:_,onToggle:()=>F(P.name)},P.name)})})]})})()]}),h?.configured&&y&&Object.keys(y.windows??{}).length===0&&v.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."})})},rI={branch:As,briefcase:Mu,house:Du,graduation:Fu,code:gn,heart:Ag},nI={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},oI=({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}=Me(),{isMobile:w}=Ns(),v=i.useMemo(()=>ps(),[]),k=y();i.useEffect(()=>{f(),p(),h(),g()},[f,p,h,g]);const S=A=>{u(`import:${A.host}:${A.username}`),t?.(),w&&b(!1)},j=v?"bg-background":"bg-sidebar",C=()=>{u("new"),t?.(),w&&b(!1)},N=async A=>{r(A)},F=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 E=l===A?null:A;if(!await x(E)){K.error("Failed to update default identity");return}K.success(E?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:R("flex h-full flex-col",j),children:[e.jsx("div",{className:R("border-b px-3",w?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",c.length]}),e.jsx(Ce,{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(Bs,{className:"size-4"})})]})}),e.jsxs(Vt,{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?.(),w&&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(As,{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?.(),w&&b(!1)},onToggleDefault:()=>D(A.id),onDelete:()=>N(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(iI,{credential:A,onImport:()=>S(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(Es,{children:['Are you sure you want to delete profile "',s?.name,'"?']})]}),e.jsxs(Ys,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>r(null),disabled:n,children:"Cancel"}),e.jsx(Ce,{variant:"destructive",onClick:()=>{F()},disabled:n,children:"Delete"})]})]})})]})},jh=({profile:t,isSelected:s,isDefault:r=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:l=!1})=>{const c=rI[t.icon||"branch"]||As,d=nI[t.color||""],u=t.authType||"ssh";return e.jsx("div",{className:R("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(cs,{children:[e.jsx(ds,{asChild:!0,children:e.jsx(Ce,{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(us,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(It,{onClick:m=>{m.stopPropagation(),o()},children:r?"Unset default":"Set as default"}),!l&&a&&e.jsxs(It,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(kr,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},aI=t=>{const s=t.split("/");return s.length>=3?s[s.length-1]:t},iI=({credential:t,onImport:s})=>{const r=aI(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(Ce,{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)"}],lI=[{key:"branch",Icon:As,label:"Branch"},{key:"briefcase",Icon:Mu,label:"Work"},{key:"house",Icon:Du,label:"Personal"},{key:"graduation",Icon:Fu,label:"School"},{key:"code",Icon:gn,label:"Code"}],cI=()=>{const{selectedProfileId:t,getProfileById:s,createProfile:r,updateProfile:n,deleteProfile:o}=ka(),a=i.useMemo(()=>{if(t?.startsWith("import:")){const[,M,B]=t.split(":");return{host:M,username:B}}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,w]=i.useState(""),[v,k]=i.useState(""),[S,j]=i.useState("keyword"),[C,N]=i.useState("branch"),[F,D]=i.useState(!1),[A,E]=i.useState(!1),[P,T]=i.useState(!1);i.useEffect(()=>{if(a){const M=a.host.split("/"),B=M.length>=3?M[M.length-1]:a.host;m(B),p(a.username),g(""),y("token"),w(""),k(a.host),j("string"),N("code")}else c?(m(""),p(""),g(""),y("ssh"),w(""),k(""),j("keyword"),N("branch")):l&&(m(l.name),p(l.userName),g(l.userEmail),y(l.authType||"ssh"),w(l.sshKey||""),k(l.host||""),j(l.color||"keyword"),N(l.icon||"branch"))},[l,c,t,a]);const L=async()=>{if(!f.trim()||!h.trim()){K.error("User name and email are required");return}if(x==="token"&&!v.trim()){K.error("Host is required for token-based authentication");return}D(!0);try{const M={name:u.trim()||f.trim(),userName:f.trim(),userEmail:h.trim(),authType:x,sshKey:x==="ssh"&&b.trim()||null,host:x==="token"&&v.trim()||null,color:S,icon:C};let B;if(c)B=await r(M);else if(t)B=await n(t,M);else return;B?K.success(c?"Profile created successfully":"Profile updated successfully"):K.error(c?"Failed to create profile":"Failed to update profile")}catch(M){console.error("Error saving profile:",M),K.error("An error occurred while saving")}finally{D(!1)}},I=()=>{!t||c||E(!0)},_=async()=>{if(!(!t||c)){T(!0);try{await o(t)?(K.success("Profile deleted successfully"),E(!1)):K.error("Failed to delete profile")}catch(M){console.error("Error deleting profile:",M),K.error("An error occurred while deleting")}finally{T(!1)}}},O=i.useMemo(()=>Sh.find(B=>B.key===S)?.cssVar||"var(--syntax-keyword)",[S]);return t?e.jsx(Vt,{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(Ot,{value:u,onChange:M=>m(M.target.value),placeholder:"Work Profile, Personal, etc."}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Friendly name to identify this profile (optional, defaults to user name)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Color"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Sh.map(M=>e.jsx("button",{onClick:()=>j(M.key),className:R("w-8 h-8 rounded-lg border-2 transition-all",S===M.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:M.cssVar},title:M.label},M.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Icon"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:lI.map(M=>{const B=M.Icon;return e.jsx("button",{onClick:()=>N(M.key),className:R("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",C===M.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:M.label,children:e.jsx(B,{className:"w-4 h-4",style:{color:O}})},M.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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(Ot,{value:f,onChange:M=>p(M.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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(Ot,{type:"email",value:h,onChange:M=>g(M.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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:R("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(a0,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>y("token"),className:R("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(Ig,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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(Ot,{value:b,onChange:M=>w(M.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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(Ot,{value:v,onChange:M=>k(M.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(Ce,{size:"sm",variant:"destructive",onClick:I,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(kr,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:R("flex gap-2",c&&"ml-auto"),children:e.jsxs(Ce,{size:"sm",variant:"default",onClick:L,disabled:F,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(nc,{className:"h-3 w-3"}),F?"Saving...":"Save Profile"]})})]})]}),e.jsx(bs,{open:A,onOpenChange:M=>{P||E(M)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(Ss,{children:"Delete Profile"}),e.jsxs(Es,{children:['Are you sure you want to delete profile "',l?.name||u||"this profile",'"?']})]}),e.jsxs(Ys,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>E(!1),disabled:P,children:"Cancel"}),e.jsx(Ce,{variant:"destructive",onClick:()=>{_()},disabled:P,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 kd(t,s,r){return Math.min(r,Math.max(s,t))}const ro=ee.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=ee.useRef(null);ee.useImperativeHandle(f,()=>p.current);const[h,g]=ee.useState(()=>String(t));ee.useEffect(()=>{document.activeElement!==p.current&&g(String(t))},[t]);const x=ee.useCallback(()=>{p.current?.focus()},[]),y=ee.useCallback(D=>{const A=kd(D,r,n);s(A),g(String(A))},[n,r,s]),b=ee.useCallback(()=>{const D=Number(h);return Number.isFinite(D)?D:t},[h,t]),w=ee.useCallback(()=>{y(b()+o),x()},[y,b,x,o]),v=ee.useCallback(()=>{y(b()-o),x()},[y,b,x,o]),k=D=>{const A=D.target.value;g(A);const E=Number(A);Number.isFinite(E)&&s(kd(E,r,n))},S=D=>{const A=Number(h);if(!Number.isFinite(A))g(String(t));else{const E=kd(A,r,n);E!==A&&s(E),g(String(E))}c?.(D)},j=D=>{if(D.key==="ArrowUp"){D.preventDefault(),w();return}if(D.key==="ArrowDown"){D.preventDefault(),v();return}d?.(D)},C=b(),N=u||C<=r,F=u||C>=n;return e.jsxs("div",{className:R("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",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:S,onKeyDown:j,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:R("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:F,onClick:w,className:R("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:N,onClick:v,className:R("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(as,{className:"h-3.5 w-3.5"})})]})]})});ro.displayName="NumberInput";const dI=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],kh=[{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"}],Nh=[{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}=Ns(),r=wi(),n=Me($=>$.showReasoningTraces),o=Me($=>$.setShowReasoningTraces),a=Me($=>$.showTextJustificationActivity),l=Me($=>$.setShowTextJustificationActivity),c=Me($=>$.toolCallExpansion),d=Me($=>$.setToolCallExpansion),u=Me($=>$.fontSize),m=Me($=>$.setFontSize),f=Me($=>$.terminalFontSize),p=Me($=>$.setTerminalFontSize),h=Me($=>$.padding),g=Me($=>$.setPadding),x=Me($=>$.cornerRadius),y=Me($=>$.setCornerRadius),b=Me($=>$.inputBarOffset),w=Me($=>$.setInputBarOffset),v=Me($=>$.diffLayoutPreference),k=Me($=>$.setDiffLayoutPreference),S=Me($=>$.diffViewMode),j=Me($=>$.setDiffViewMode),C=Me($=>$.showTerminalQuickKeysOnDesktop),N=Me($=>$.setShowTerminalQuickKeysOnDesktop),F=Fn($=>$.queueModeEnabled),D=Fn($=>$.setQueueMode),A=Me($=>$.persistChatDraft),E=Me($=>$.setPersistChatDraft),{themeMode:P,setThemeMode:T,availableThemes:L,customThemesLoading:I,reloadCustomThemes:_,lightThemeId:O,darkThemeId:M,setLightThemePreference:B,setDarkThemePreference:G}=rn(),[W,ve]=i.useState(!1),oe=i.useMemo(()=>L.filter($=>$.metadata.variant==="light").sort(($,ne)=>$.metadata.name.localeCompare(ne.metadata.name)),[L]),te=i.useMemo(()=>L.filter($=>$.metadata.variant==="dark").sort(($,ne)=>$.metadata.name.localeCompare(ne.metadata.name)),[L]),he=i.useMemo(()=>oe.find($=>$.metadata.id===O)??oe[0],[oe,O]),Y=i.useMemo(()=>te.find($=>$.metadata.id===M)??te[0],[te,M]),Z=i.useCallback(($,ne)=>{const V=ne==="dark"?" Dark":" Light";return $.endsWith(V)?$.slice(0,-V.length):$},[]),ie=$=>t?t.includes($):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[ie("theme")&&!ps()&&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:dI.map($=>e.jsx(pr,{variant:P===$.value?"default":"outline",className:R(P===$.value?void 0:"text-foreground"),onClick:()=>T($.value),children:$.label},$.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:he?.metadata.id??"",onValueChange:B,children:[e.jsx($s,{"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($=>e.jsx(rs,{value:$.metadata.id,children:Z($.metadata.name,"light")},$.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:Y?.metadata.id??"",onValueChange:G,children:[e.jsx($s,{"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:te.map($=>e.jsx(rs,{value:$.metadata.id,children:Z($.metadata.name,"dark")},$.metadata.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("button",{type:"button",disabled:I||W,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:R("h-3.5 w-3.5",W&&"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:$=>m(Number($.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:$=>p(Number($.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:$=>p(Number($.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:$=>g(Number($.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:$=>g(Number($.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(ar,{checked:C,onCheckedChange:N,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:$=>y(Number($.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:$=>y(Number($.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:$=>w(Number($.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:()=>w(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:$=>w(Number($.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:w,min:0,max:100,step:5,"aria-label":"Input bar offset in pixels"}),e.jsx(pr,{type:"button",variant:"ghost",onClick:()=>w(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:kh.find($=>$.value===c)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:kh.map($=>e.jsx(pr,{variant:c===$.value?"default":"outline",className:R(c===$.value?void 0:"text-foreground"),onClick:()=>d($.value),children:$.label},$.value))})]}),ie("diffLayout")&&!s&&!ps()&&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:Nh.map($=>e.jsx(pr,{variant:v===$.id?"default":"outline",className:R(v===$.id?void 0:"text-foreground"),onClick:()=>k($.id),children:$.label},$.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Nh.find($=>$.id===v)?.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($=>e.jsx(pr,{variant:S===$.id?"default":"outline",className:R(S===$.id?void 0:"text-foreground"),onClick:()=>j($.id),children:$.label},$.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Ch.find($=>$.id===S)?.description})]})]}),ie("dotfiles")&&!ps()&&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($=>e.jsx(pr,{variant:r===$.value?"default":"outline",className:R(r===$.value?void 0:"text-foreground"),onClick:()=>Bu($.value),children:$.label},$.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:F,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:F?`Enter queues messages, ${Qs()}+Enter sends immediately.`:`Enter sends immediately, ${Qs()}+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:E}),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."})]})]})},Ah="https://github.com/btriapitsyn/ikanban",uI=800,db=()=>{const[t,s]=i.useState(!1),[r,n]=i.useState(!1),o=ac(),{isMobile:a}=Ns(),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)},uI);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:R("typography-meta text-muted-foreground/60 hover:text-muted-foreground disabled:cursor-default",d&&"animate-pulse [animation-duration:1s]"),children:"Check updates"}),!d&&o.available&&e.jsxs("button",{onClick:()=>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:Ah,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(Bg,{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(Ud,{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:R("flex items-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(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:R("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:"Check for updates"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("a",{href:Ah,target:"_blank",rel:"noopener noreferrer",className:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(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:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Ud,{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})]})},mI=1440*60*1e3,ub=5,Fh=1440*60*1e3,Nd=t=>t.time?.updated??t.time?.created??0,Dh=({sessions:t,currentSessionId:s,cutoffDays:r,keepRecent:n=ub,now:o=Date.now()})=>{if(!Array.isArray(t)||r<=0)return[];const a=o-r*mI,l=[...t].sort((d,u)=>Nd(u)-Nd(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=Nd(d);return u?u<a:!1}).map(d=>d.id)},mb=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=Me(x=>x.autoDeleteEnabled),c=Me(x=>x.autoDeleteAfterDays),d=Me(x=>x.autoDeleteLastRunAt),u=Me(x=>x.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),h=i.useMemo(()=>c<=0?[]: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<Fh)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<Fh||g()},[c,l,d,s,o,r.length,g]),{candidates:h,isRunning:m,runCleanup:g,keepRecentCount:ub}},Cd=1,Ad=365,fb=()=>{const{isMobile:t}=Ns(),s=Me(p=>p.autoDeleteEnabled),r=Me(p=>p.autoDeleteAfterDays),n=Me(p=>p.setAutoDeleteEnabled),o=Me(p=>p.setAutoDeleteAfterDays),[a,l]=i.useState(String(r));i.useEffect(()=>{l(String(r))},[r]);const{candidates:c,isRunning:d,runCleanup:u}=mb({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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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(Ad,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(Ad,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:Ad,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]})]})},Mh=10,Eh=500,fI=()=>{const{isMobile:t}=Ns(),s=Me(c=>c.messageLimit),r=Me(c=>c.setMessageLimit),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let d=null;if(!d){const u=zr()?.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(pt,{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(pI,{value:s,min:Mh,max:Eh,onChange:a}):e.jsx(ro,{value:s,onValueChange:a,min:Mh,max:Eh,step:10,"aria-label":"Message limit"})]})]})})})]})},pI=({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"})},Ih="opencode",Bh="big-pickle",hI=(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===Ih)?.models.some(o=>o.id===Bh))return{providerId:Ih,modelId:Bh};const n=s[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},pb=()=>{const t=ft(M=>M.setProvider),s=ft(M=>M.setModel),r=ft(M=>M.setAgent),n=ft(M=>M.setCurrentVariant),o=ft(M=>M.setSettingsDefaultModel),a=ft(M=>M.setSettingsDefaultVariant),l=ft(M=>M.setSettingsDefaultAgent),c=ft(M=>M.settingsAutoCreateWorktree),d=ft(M=>M.setSettingsAutoCreateWorktree),u=ft(M=>M.settingsZenModel),m=ft(M=>M.setSettingsZenModel),f=ft(M=>M.providers),[p,h]=i.useState(),[g,x]=i.useState(),[y,b]=i.useState(),[w,v]=i.useState(!0),[k,S]=i.useState([]),[j,C]=i.useState(!0),N=i.useMemo(()=>hI(p,f),[p,f]),F=i.useMemo(()=>ps(),[]);i.useEffect(()=>{(async()=>{try{const B=await fetch("/api/zen/models",{method:"GET",headers:{Accept:"application/json"}});if(B.ok){const G=await B.json();Array.isArray(G?.models)&&S(G.models)}}catch(B){console.warn("Failed to load zen models:",B)}finally{C(!1)}})()},[]);const D=i.useMemo(()=>u&&k.some(M=>M.id===u)?u:k[0]?.id??"",[u,k]);i.useEffect(()=>{(async()=>{try{let B=null;if(!B){const G=zr()?.settings;if(G)try{const ve=(await G.load())?.settings;ve&&(B={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(!B){const G=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});G.ok&&(B=await G.json())}if(B){const G=typeof B.defaultModel=="string"&&B.defaultModel.trim().length>0?B.defaultModel.trim():void 0,W=typeof B.defaultVariant=="string"&&B.defaultVariant.trim().length>0?B.defaultVariant.trim():void 0,ve=typeof B.defaultAgent=="string"&&B.defaultAgent.trim().length>0?B.defaultAgent.trim():void 0,oe=typeof B.zenModel=="string"&&B.zenModel.trim().length>0?B.zenModel.trim():void 0;G!==void 0&&h(G),W!==void 0&&x(W),ve!==void 0&&b(ve),oe!==void 0&&m(oe)}}catch(B){console.warn("Failed to load defaults settings:",B)}finally{v(!1)}})()},[m]);const A=i.useCallback(async(M,B)=>{const G=M&&B?`${M}/${B}`:void 0;h(G),x(void 0),a(void 0),n(void 0),o(G),M&&B&&f.find(ve=>ve.id===M)&&(t(M),s(B));try{await xs({defaultModel:G??"",defaultVariant:""});{const W=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:G})});W.ok||console.warn("Failed to save default model to server:",W.status,W.statusText)}}catch(W){console.warn("Failed to save default model:",W)}},[f,n,t,s,o,a]),E="__default__",P=i.useCallback(async M=>{const B=M===E?void 0:M||void 0;x(B),a(B),n(B);try{await xs({defaultVariant:B??""})}catch(G){console.warn("Failed to save default variant:",G)}},[n,a]),T=i.useCallback(async M=>{const B=M||void 0;b(B),l(B),M&&r(M);try{await xs({defaultAgent:B??""})}catch(G){console.warn("Failed to save default agent:",G)}},[r,l]),L=i.useMemo(()=>{if(!N.providerId||!N.modelId)return[];const G=f.find(W=>W.id===N.providerId)?.models.find(W=>W.id===N.modelId)?.variants;return G?Object.keys(G):[]},[N.modelId,N.providerId,f]),I=L.length>0;i.useEffect(()=>{!I&&g&&(x(void 0),a(void 0),n(void 0),xs({defaultVariant:""}).catch(()=>{}))},[g,n,a,I]);const _=i.useCallback(async M=>{const B=M.target.checked;d(B);try{await xs({autoCreateWorktree:B})}catch(G){console.warn("Failed to save auto create worktree setting:",G)}},[d]),O=i.useCallback(async M=>{m(M);try{await xs({zenModel:M})}catch(B){console.warn("Failed to save zen model setting:",B)}},[m]);return w?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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(pt,{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:N.providerId,modelId:N.modelId,onChange:A})]}),I&&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??E,onValueChange:P,children:[e.jsx($s,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Sr,{placeholder:"Thinking"})}),e.jsxs(zs,{children:[e.jsx(rs,{value:E,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),L.map(M=>e.jsx(rs,{value:M,className:"pr-2 [&>span:first-child]:hidden",children:M},M))]})]})]}),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(cb,{agentName:y||"",onChange:T})]})]}),(N.providerId||y)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",N.providerId&&e.jsxs("span",{className:"text-foreground",children:[N.providerId,"/",N.modelId,I?` (${g??"default"})`:""]}),N.providerId&&y&&" / ",y&&e.jsx("span",{className:"text-foreground",children:y})]}),!F&&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:M=>_({target:{checked:M}})}),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): ${Qs()} + N • New session (Standard): Shift + ${Qs()} + N`:`New session (Standard): ${Qs()} + N • New session (Worktree): Shift + ${Qs()} + 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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(pt,{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"}),j?e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Loading models..."}):k.length>0?e.jsxs(_s,{value:D,onValueChange:O,children:[e.jsx($s,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Sr,{placeholder:"Select model"})}),e.jsx(zs,{children:k.map(M=>e.jsx(rs,{value:M.id,className:"pr-2 [&>span:first-child]:hidden",children:M.id},M.id))})]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No free models available"})]})]})]})},gI=()=>{const t=ft(l=>l.settingsGitmojiEnabled),s=ft(l=>l.setSettingsGitmojiEnabled),r=lc(),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let c=null;if(!c){const d=zr()?.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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(pt,{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:Gg}),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."})]})})]})},xI=()=>{const t=gs(N=>N.getActiveProject()),s=t?.path??null,{sessions:r,getWorktreeMetadata:n}=Ae(),o=Jt(N=>N.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 N=await _o(x);p(N)}catch{}},[x,u]);i.useEffect(()=>{if(!s)return;let N=!1;return m(null),(async()=>{try{const F=await Yn(s);if(N)return;m(F)}catch{}})(),()=>{N=!0}},[s]),i.useEffect(()=>{if(!x){p([]),g(!1);return}if(u===!1){p([]),g(!1);return}let N=!1;return g(!0),p([]),(async()=>{try{const F=await _o(x);if(N)return;p(F)}catch{}finally{N||g(!1)}})(),()=>{N=!0}},[x,u]),i.useEffect(()=>{if(!x)return;let N=!1;return d(!0),(async()=>{try{const F=await Da(x);N||l(F.length>0?F:[""])}catch{N||l([""])}finally{N||d(!1)}})(),()=>{N=!0}},[x]);const b=i.useCallback((N,F)=>{l(D=>{const A=[...D];return A[N]=F,A})},[]),w=i.useCallback(()=>{l(N=>[...N,""])},[]),v=i.useCallback(async N=>{if(!x)return;const F=N.filter(D=>D.trim().length>0);await gx(x,F)},[x]),k=i.useCallback(N=>{l(F=>{const D=F.filter((A,E)=>E!==N);return v(D),D.length>0?D:[""]})},[v]),S=i.useCallback(()=>{v(a)},[v,a]),j=i.useCallback(N=>{const F=_=>_.replace(/\\/g,"/").replace(/\/+$/,""),D=F(N.path),A=r.filter(_=>{const O=n(_.id);if(O?.path&&F(O.path)===D)return!0;const M=_.directory;return!!(M&&F(M)===D)}),E=new Set(A.map(_=>_.id)),P=_=>{const O=r.filter(B=>{const G=B.parentID;return G&&_.has(G)});if(O.length===0)return[];const M=new Set(O.map(B=>B.id));return[...O,...P(M)]},T=P(E),L=new Set,I=[...A,...T].filter(_=>L.has(_.id)?!1:(L.add(_.id),!0));Sa.requestDelete({sessions:I,mode:"worktree",worktree:N})},[r,n]),C=i.useMemo(()=>r.map(N=>N.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((N,F)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ot,{value:N,onChange:D=>b(F,D.target.value),onBlur:S,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{k(F)},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(fs,{className:"h-4 w-4"})})]},F)),e.jsxs("button",{type:"button",onClick:w,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Bs,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(dr,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(pt,{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(N=>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:N.label||N.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(N.path,o)})]}),e.jsx("button",{type:"button",onClick:()=>j(N),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 ${N.branch||N.label}`,children:e.jsx(kr,{className:"h-4 w-4"})})]},N.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to manage worktrees."})},Th={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"}},yI=()=>{const t=i.useMemo(()=>Tr(),[]),s=i.useMemo(()=>ps(),[]),r=!t&&!s,n=Me(Z=>Z.nativeNotificationsEnabled),o=Me(Z=>Z.setNativeNotificationsEnabled),a=Me(Z=>Z.notificationMode),l=Me(Z=>Z.setNotificationMode),c=Me(Z=>Z.notifyOnSubtasks),d=Me(Z=>Z.setNotifyOnSubtasks),u=Me(Z=>Z.notifyOnCompletion),m=Me(Z=>Z.setNotifyOnCompletion),f=Me(Z=>Z.notifyOnError),p=Me(Z=>Z.setNotifyOnError),h=Me(Z=>Z.notifyOnQuestion),g=Me(Z=>Z.setNotifyOnQuestion),x=Me(Z=>Z.notificationTemplates),y=Me(Z=>Z.setNotificationTemplates),b=Me(Z=>Z.summarizeLastMessage),w=Me(Z=>Z.setSummarizeLastMessage),v=Me(Z=>Z.summaryThreshold),k=Me(Z=>Z.setSummaryThreshold),S=Me(Z=>Z.summaryLength),j=Me(Z=>Z.setSummaryLength),C=Me(Z=>Z.maxLastMessageLength),N=Me(Z=>Z.setMaxLastMessageLength),[F,D]=i.useState("default"),[A,E]=i.useState(!1),[P,T]=i.useState(!1),[L,I]=i.useState(!1);i.useEffect(()=>{if(!r){E(!1),T(!1);return}typeof Notification<"u"&&D(Notification.permission);const Z=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;E(Z),(async()=>{if(!Z){T(!1);return}try{const $=await navigator.serviceWorker.getRegistration();if(!$){T(!1);return}const ne=await $.pushManager.getSubscription();T(!!ne)}catch{T(!1)}})()},[r]);const _=async Z=>{if(t){o(Z);return}if(!r){o(Z);return}if(Z&&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(!!(Z&&F==="granted"))},O=t||r&&typeof Notification<"u"&&Notification.permission==="granted",M=(Z,ie,$)=>{y({...x,[Z]:{...x[Z],[ie]:$}})},B=Z=>{const ie="=".repeat((4-Z.length%4)%4),$=(Z+ie).replace(/-/g,"+").replace(/_/g,"/"),ne=atob($),V=new Uint8Array(ne.length);for(let ce=0;ce<ne.length;ce+=1)V[ce]=ne.charCodeAt(ce);return V},G=async(Z,ie,$)=>{let ne=null;const V=new Promise((ce,ge)=>{ne=setTimeout(()=>{ge(new Error($))},ie)});try{return await Promise.race([Z,V])}finally{ne&&clearTimeout(ne)}},W=async Z=>{if(Z.active)return;const ie=Z.installing||Z.waiting;ie&&ie.state!=="activated"&&await G(new Promise($=>{const ne=()=>{ie.state==="activated"&&(ie.removeEventListener("statechange",ne),$())};ie.addEventListener("statechange",ne),ne()}),15e3,"Service worker activation timed out")},ve=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const Z=[{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 $ of Z)try{const ne=$.opts?navigator.serviceWorker.register("/sw.js",$.opts):navigator.serviceWorker.register("/sw.js");return await G(ne,1e4,`Service worker registration timed out (${$.label})`)}catch(ne){ie=ne}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 Z=await navigator.serviceWorker.getRegistration();if(Z)return Z;const ie=await ve();try{await ie.update()}catch{}return await W(ie),ie},te=Z=>{const ie=Z,$=[`type=${typeof Z}`,`toString=${String(Z)}`,`name=${String(ie?.name??"")}`,`message=${String(ie?.message??"")}`];let ne="";try{ne=JSON.stringify(Z)}catch{}return{summary:$.filter(Boolean).join(" | "),json:ne,stack:typeof ie?.stack=="string"?ie.stack:""}},he=async()=>{if(!A){K.error("Push notifications not supported");return}const Z=zr();if(!Z?.push){K.error("Push API not available");return}I(!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 Z.push.getVapidPublicKey();if(!ie?.publicKey){K.error("Failed to load push key");return}const $=await oe();await W($);const ne=await $.pushManager.getSubscription();if(!("pushManager"in $)||!$.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const ce=(ne??await G($.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:B(ie.publicKey)}),15e3,"Push subscription timed out")).toJSON(),ge=ce.keys;if(!ce.endpoint||!ge?.p256dh||!ge.auth)throw new Error("Push subscription missing keys");if(!(await G(Z.push.subscribe({endpoint:ce.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}T(!0),K.success("Background notifications enabled")}catch(ie){console.error("[Push] Enable failed:",ie);const $=te(ie);K.error("Failed to enable background notifications",{description:$.summary})}finally{I(!1)}},Y=async()=>{if(!A){T(!1);return}const Z=zr();if(!Z?.push){K.error("Push API not available");return}I(!0);try{const $=await(await oe()).pushManager.getSubscription();if(!$){T(!1);return}const ne=$.endpoint;await $.unsubscribe(),await Z.push.unsubscribe({endpoint:ne}),T(!1),K.success("Background notifications disabled")}finally{I(!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(ar,{checked:n&&O,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&&O&&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(ar,{checked:a==="always",onCheckedChange:Z=>l(Z?"always":"hidden-only"),className:"data-[state=checked]:bg-status-info"})]}),n&&O&&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(ar,{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(ar,{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(ar,{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(ar,{checked:c,onCheckedChange:Z=>d(Z),className:"data-[state=checked]:bg-status-info"})]})]}),n&&O&&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(Z=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"typography-ui text-foreground font-medium capitalize",children:Z}),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[Z].title,onChange:ie=>M(Z,"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:Th[Z].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[Z].message,onChange:ie=>M(Z,"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:Th[Z].message})]})]})]},Z))]}),n&&O&&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(ar,{checked:b,onCheckedChange:w,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:[v," 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:v,onChange:Z=>k(Number(Z.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:[S," 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:S,onChange:Z=>j(Number(Z.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:Z=>N(Number(Z.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:[F==="denied"&&e.jsx("p",{className:"typography-micro text-destructive",children:"Notification permission denied. Enable it in your browser settings."}),F==="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:[L&&e.jsx("div",{className:"text-muted-foreground",children:e.jsx(iy,{size:"sm"})}),e.jsx(ar,{checked:P,disabled:L,onCheckedChange:Z=>{Z?he():Y()},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."})]})]})},bI=()=>{const t=zr()?.github,s=Or(j=>j.status),r=Or(j=>j.isLoading),n=Or(j=>j.hasChecked),o=Or(j=>j.refreshStatus),a=Or(j=>j.setStatus),l=i.useCallback(async j=>{if(typeof window>"u")return;const C=window.__TAURI__;if(C?.shell?.open)try{await C.shell.open(j);return}catch{}try{window.open(j,"_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(j){console.warn("Failed to load GitHub auth status:",j)}})(),()=>{g()}),[n,o,t,g]);const x=i.useCallback(async()=>{d(!0);try{const j=t?await t.authStart():await(async()=>{const N=await fetch("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),F=await N.json().catch(()=>null);if(!N.ok||!F||!("deviceCode"in F))throw new Error(F?.error||N.statusText);return F})();m(j),p(Math.max(1,j.interval)*1e3);const C=j.verificationUriComplete||j.verificationUri;l(C)}catch(j){console.error("Failed to start GitHub connect:",j),K.error("Failed to start GitHub connect")}finally{d(!1)}},[l,t]),y=i.useCallback(async j=>{if(t)return t.authComplete(j);const C=await fetch("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:j})}),N=await C.json().catch(()=>null);if(!C.ok||!N)throw new Error(N?.error||C.statusText);return N},[t]);i.useEffect(()=>{if(!(!u?.deviceCode||!f)&&h.current==null)return h.current=window.setInterval(()=>{(async()=>{try{const j=await y(u.deviceCode);if(j.connected){K.success("GitHub connected"),m(null),g(),await o(t,{force:!0});return}j.status==="slow_down"&&p(C=>C?C+5e3:5e3),(j.status==="expired_token"||j.status==="access_denied")&&(K.error(j.error||"GitHub authorization failed"),m(null),g())}catch(j){console.warn("GitHub polling failed:",j)}})()},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 j=await fetch("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}});if(!j.ok)throw new Error(j.statusText)}K.success("GitHub disconnected"),await o(t,{force:!0})}catch(j){console.error("Failed to disconnect GitHub:",j),K.error("Failed to disconnect GitHub")}finally{d(!1)}},[o,t,g]),w=i.useCallback(async j=>{if(j){d(!0);try{const C=t?await t.authActivate(j):await(async()=>{const N=await fetch("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:j})}),F=await N.json().catch(()=>null);if(!N.ok||!F)throw new Error(F?.error||N.statusText);return F})();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 v=!!s?.connected,k=s?.user,S=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."})]}),v?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(Ce,{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(Ce,{onClick:x,disabled:c,children:"Connect"})]}),v?e.jsx("div",{className:"flex justify-end",children:e.jsx(Ce,{variant:"ghost",onClick:x,disabled:c,children:"Add account"})}):null,S.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:S.map(j=>{const C=j.user,N=!!j.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]})]}),N?e.jsx("span",{className:"typography-micro text-primary",children:"Active"}):e.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>w(j.id),disabled:c,children:"Use"})]},j.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(Ce,{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(Ce,{variant:"ghost",disabled:c,onClick:()=>{g(),m(null)},children:"Cancel"})})]}):null]})},vI=({children:t,title:s,description:r,divider:n=!1,className:o})=>e.jsxs("div",{className:R(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]}),Ka=({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:R("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:R("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)})]}),wI=[{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:"Українська"}],jI=()=>{const{isSupported:t,language:s,setLanguage:r}=yy(),{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:w,showMessageTTSButtons:v,setShowMessageTTSButtons:k,voiceModeEnabled:S,setVoiceModeEnabled:j,summarizeMessageTTS:C,setSummarizeMessageTTS:N,summarizeVoiceConversation:F,setSummarizeVoiceConversation:D,summarizeCharacterThreshold:A,setSummarizeCharacterThreshold:E,summarizeMaxLength:P,setSummarizeMaxLength:T}=ft(),[L,I]=ee.useState(!1),[_,O]=ee.useState([]),[M,B]=ee.useState(!1),[G,W]=ee.useState(null),[ve,oe]=ee.useState(!1),[te,he]=ee.useState(!1),[Y,Z]=ee.useState(null),[ie,$]=ee.useState([]),[ne,V]=ee.useState(!1);ee.useEffect(()=>((async()=>{const q=await ws.waitForVoices();$(q)})(),"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=()=>{$(window.speechSynthesis.getVoices())}),()=>{"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=null)}),[]);const ce=ee.useMemo(()=>ie.filter(X=>X.lang).sort((X,q)=>{const re=X.lang.startsWith("en"),ue=q.lang.startsWith("en");if(re&&!ue)return-1;if(!re&&ue)return 1;const Re=X.lang.localeCompare(q.lang);return Re!==0?Re:X.name.localeCompare(q.name)}),[ie]),ge=ee.useCallback(()=>{if(ne){ws.cancelSpeech(),V(!1);return}const X=ie.find(Re=>Re.name===h),re=`Hello! I'm ${X?.name??"your browser voice"}. This is how I sound.`;V(!0);const ue=new SpeechSynthesisUtterance(re);ue.rate=a,ue.pitch=c,ue.volume=u,X&&(ue.voice=X,ue.lang=X.lang),ue.onend=()=>V(!1),ue.onerror=()=>V(!1),window.speechSynthesis.cancel(),window.speechSynthesis.speak(ue)},[h,ie,a,c,u,ne]);ee.useEffect(()=>()=>{ne&&ws.cancelSpeech()},[ne]);const H=[{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"}];ee.useEffect(()=>{(async()=>{try{const re=await(await fetch("/api/tts/status")).json();console.log("[VoiceSettings] OpenAI TTS status:",re);const ue=re.available,Re=b.trim().length>0;oe(ue||Re)}catch(q){console.error("[VoiceSettings] Failed to check OpenAI TTS status:",q),oe(b.trim().length>0)}})()},[b]),ee.useEffect(()=>{fetch("/api/tts/say/status").then(X=>X.json()).then(X=>{if(console.log("[VoiceSettings] Say TTS status:",X),I(X.available),X.voices){const q=X.voices.filter((re,ue,Re)=>Re.findIndex(_e=>_e.name===re.name)===ue).sort((re,ue)=>re.name.localeCompare(ue.name));O(q)}}).catch(X=>{console.error("[VoiceSettings] Failed to check Say TTS status:",X),I(!1)})},[]);const J=ee.useCallback(async()=>{if(G){G.pause(),G.currentTime=0,W(null),B(!1);return}B(!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 q=await X.blob(),re=URL.createObjectURL(q),ue=new Audio(re);ue.onended=()=>{URL.revokeObjectURL(re),W(null),B(!1)},ue.onerror=()=>{URL.revokeObjectURL(re),W(null),B(!1)},W(ue),await ue.play()}catch(X){console.error("Voice preview failed:",X),B(!1)}},[f,a,G]);ee.useEffect(()=>()=>{G&&G.pause()},[G]);const we=ee.useCallback(async()=>{if(Y){Y.pause(),Y.currentTime=0,Z(null),he(!1);return}he(!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 Re=await X.json().catch(()=>({error:"Unknown error"}));throw new Error(Re.error||`HTTP ${X.status}`)}const q=await X.blob(),re=URL.createObjectURL(q),ue=new Audio(re);ue.onended=()=>{URL.revokeObjectURL(re),Z(null),he(!1)},ue.onerror=()=>{URL.revokeObjectURL(re),Z(null),he(!1)},Z(ue),await ue.play()}catch(X){console.error("[VoiceSettings] OpenAI voice preview failed:",X),he(!1)}},[x,a,Y,b]);return ee.useEffect(()=>()=>{Y&&Y.pause()},[Y]),e.jsx(vI,{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(Ld,{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(ar,{checked:S,onCheckedChange:j,"aria-label":"Toggle voice mode"})]}),S&&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(Ce,{variant:n==="browser"?"default":"outline",size:"sm",onClick:()=>o("browser"),className:"min-w-[80px]",children:"Browser"}),e.jsx(Ce,{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"}),L&&e.jsxs(Ce,{variant:n==="say"?"default":"outline",size:"sm",onClick:()=>o("say"),className:"min-w-[80px]",children:[e.jsx(km,{className:"w-4 h-4 mr-1"}),"Say"]})]})]}),S&&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."]})}),S&&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."})]})]}),S&&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(Ig,{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=>w(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(Ce,{size:"icon",variant:"ghost",onClick:()=>w(""),title:"Clear API key",children:e.jsx(fs,{className:"w-4 h-4"})})]})]}),S&&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($s,{className:"w-[160px]","aria-label":"Select OpenAI voice",children:e.jsx(Sr,{placeholder:"Select voice"})}),e.jsx(zs,{className:"max-h-[300px]",children:H.map(X=>e.jsx(rs,{value:X.value,children:X.label},X.value))})]}),e.jsx(Ce,{size:"icon",variant:"outline",onClick:we,disabled:!ve,title:te?"Stop preview":"Preview voice",children:te?e.jsx(il,{className:"w-4 h-4"}):e.jsx(Ac,{className:"w-4 h-4"})})]})]}),S&&n==="say"&&L&&_.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(km,{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($s,{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(rs,{value:X.name,children:X.name},X.name))})]}),e.jsx(Ce,{size:"icon",variant:"outline",onClick:J,title:M?"Stop preview":"Preview voice",children:M?e.jsx(il,{className:"w-4 h-4"}):e.jsx(Ac,{className:"w-4 h-4"})})]})]}),S&&n==="browser"&&ce.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(i0,{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($s,{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(rs,{value:"__auto__",children:"Auto (default)"}),ce.map(X=>e.jsxs(rs,{value:X.name,children:[X.name," (",X.lang,")"]},X.name))]})]}),e.jsx(Ce,{size:"icon",variant:"outline",onClick:ge,title:ne?"Stop preview":"Preview voice",children:ne?e.jsx(il,{className:"w-4 h-4"}):e.jsx(Ac,{className:"w-4 h-4"})})]})]}),S&&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(Ld,{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($s,{className:"w-[180px]","aria-label":"Select language",children:e.jsx(Sr,{placeholder:"Select language"})}),e.jsx(zs,{children:wI.map(X=>e.jsx(rs,{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(ar,{checked:v,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(Io,{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(ar,{checked:C,onCheckedChange:N,"aria-label":"Toggle message TTS summarization"})]}),S&&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(ar,{checked:F,onCheckedChange:D,"aria-label":"Toggle voice conversation summarization"})]}),(C||F)&&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(Ka,{value:A,onChange:E,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 (",P," chars)"]})]}),e.jsx("div",{className:"w-[180px]",children:e.jsx(Ka,{value:P,onChange:T,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(l0,{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(Ka,{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(c0,{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(Ka,{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(d0,{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(Ka,{value:u,onChange:m,min:0,max:1,step:.1,disabled:!t,label:"Speech volume",valueFormatter:X=>`${Math.round(X*100)}%`})})]}),S&&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"]})})]})})},hb=()=>{const[t,s]=ee.useState(""),[r,n]=ee.useState(!0),[o,a]=ee.useState(!1);ee.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=ee.useCallback(async()=>{if(typeof window>"u"||!Tr()||!Ds())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=ee.useCallback(async()=>{a(!0);try{await xs({opencodeBinary:t.trim()}),await Za({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(Ot,{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(Ce,{type:"button",variant:"secondary",onClick:l,disabled:r||o||!Tr()||!Ds(),children:"Browse"}),e.jsx(Ce,{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"}),"."]})]})},SI=({section:t})=>{const{isMobile:s}=Ns(),r=s&&Oo(),n=ps();if(!t)return e.jsx(Vt,{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(pb,{})}),!n&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(hb,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(fb,{})}),r&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(db,{})})]})});const o=()=>{switch(t){case"visual":return e.jsx(kI,{});case"chat":return e.jsx(NI,{});case"sessions":return e.jsx(CI,{});case"git":return e.jsx(AI,{});case"github":return e.jsx(FI,{});case"notifications":return e.jsx(DI,{});case"voice":return e.jsx(MI,{});default:return null}};return e.jsx(Vt,{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()})})},kI=()=>e.jsx(cm,{visibleSettings:["theme","fontSize","terminalFontSize","spacing","cornerRadius","inputBarOffset","terminalQuickKeys"]}),NI=()=>e.jsx(cm,{visibleSettings:["toolOutput","diffLayout","dotfiles","reasoning","textJustificationActivity","queueMode","persistDraft"]}),CI=()=>{const t=ps();return e.jsxs("div",{className:"space-y-6",children:[e.jsx(pb,{}),!t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(hb,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(fb,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(fI,{})})]})},AI=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(gI,{}),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(xI,{})]})]}),FI=()=>ps()?null:e.jsx(bI,{}),DI=()=>e.jsx(yI,{}),MI=()=>ps()?null:e.jsx(jI,{}),EI=[{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}],II=({selectedSection:t,onSelectSection:s})=>{const{isMobile:r}=Ns(),n=r&&Oo(),[o,a]=i.useState(!1),l=i.useMemo(()=>ps(),[]),c=i.useMemo(()=>Oo(),[]),d=!l,u=i.useCallback(async()=>{a(!0);try{await Za({message:"Restarting OpenCode…",mode:"projects",scopes:["all"]})}finally{a(!1)}},[]),m=i.useMemo(()=>EI.filter(p=>!(p.webOnly&&!c||p.hideInVSCode&&l)),[c,l]),f=l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("grid h-full min-h-0 grid-rows-[minmax(0,1fr)_auto]",f),children:[e.jsx("div",{className:"min-h-0",children:e.jsx(Vt,{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:R("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:R("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(ht,{delayDuration:300,children:[e.jsx(gt,{asChild:!0,children:e.jsxs("button",{type:"button",className:R("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(pt,{children:"Restart OpenCode and reload its configuration (agents, commands, skills, providers)."})]}),e.jsx(db,{})]}):e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[d&&e.jsxs(ht,{delayDuration:300,children:[e.jsx(gt,{asChild:!0,children:e.jsxs("button",{type:"button",className:R("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(pt,{children:"Restart OpenCode and reload its configuration (agents, commands, skills, providers)."})]}),e.jsx("div",{})]})})]})},BI=t=>{let s=lb.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},Fd=200,Dd=500,TI=264,PI=1024,dm=({onClose:t,forceMobile:s,isWindowed:r})=>{const n=Ns(),o=s??n.isMobile,a=Me(ne=>ne.sidebarSection),l=Me(ne=>ne.setSidebarSection),c=i.useMemo(()=>a!=="sessions"?a:"settings",[a]),d=i.useCallback(ne=>{l(ne)},[l]),[u,m]=i.useState("visual"),[f,p]=i.useState(!1),[h,g]=i.useState(()=>typeof window<"u"?Math.min(Dd,Math.max(Fd,Math.floor(window.innerWidth*.2))):TI),[x,y]=i.useState(!1),[b,w]=i.useState(!1),[v,k]=i.useState(0),S=i.useRef(null),j=i.useRef(0),C=i.useRef(h),N=i.useMemo(()=>typeof window>"u"?!1:!!window.__TAURI__,[]),F=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),D=i.useMemo(()=>ps(),[]),A=i.useMemo(()=>BI(D),[D]),E=N;i.useEffect(()=>{const ne=S.current;if(!ne)return;const V=new ResizeObserver(ce=>{for(const ge of ce)k(ge.contentRect.width)});return V.observe(ne),k(ne.clientWidth),()=>V.disconnect()},[]);const P=gs(ne=>ne.projects),T=gs(ne=>ne.activeProjectId),L=gs(ne=>ne.setActiveProject),I=i.useMemo(()=>[...P].sort((ne,V)=>(ne.label||ne.path).localeCompare(V.label||V.path)),[P]),_=i.useMemo(()=>I.length===0?null:I.find(ne=>ne.id===T)??I[0],[T,I]),O=i.useCallback(ne=>ne.replace(/[-_]/g," ").replace(/\b\w/g,V=>V.toUpperCase()),[]),M=i.useMemo(()=>{if(!_)return"Project";const ne=_.label&&_.label.trim().length>0?_.label:_.path.split("/").filter(Boolean).pop()||_.path;return O(ne)},[_,O]),B=I.length>0&&!D,G=v===0||v>=PI;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())},[T,c]),i.useEffect(()=>{if(typeof window>"u")return;const ne=()=>{if(!x){const V=Math.min(Dd,Math.max(Fd,Math.floor(window.innerWidth*.2)));g(V)}};return window.addEventListener("resize",ne),()=>window.removeEventListener("resize",ne)},[x]),i.useEffect(()=>{if(!b)return;const ne=ce=>{const ge=ce.clientX-j.current,H=Math.min(Dd,Math.max(Fd,C.current+ge));g(H),y(!0)},V=()=>w(!1);return window.addEventListener("pointermove",ne),window.addEventListener("pointerup",V,{once:!0}),()=>{window.removeEventListener("pointermove",ne),window.removeEventListener("pointerup",V)}},[b]);const W=ne=>{w(!0),j.current=ne.clientX,C.current=h,ne.preventDefault()},ve=i.useCallback(async ne=>{if(!ne.target.closest("button, a, input, select, textarea")&&ne.button===0&&E)try{const{getCurrentWindow:V}=await qs(async()=>{const{getCurrentWindow:ge}=await import("@tauri-apps/api/window");return{getCurrentWindow:ge}},[]);await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[E]),oe=i.useCallback(async ne=>{if(ne.button===0&&E)try{const{getCurrentWindow:V}=await qs(async()=>{const{getCurrentWindow:ge}=await import("@tauri-apps/api/window");return{getCurrentWindow:ge}},[]);await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[E]),te=i.useCallback(ne=>{d(ne),p(!1)},[d]),he=i.useCallback(()=>{o&&p(!0)},[o]),Y=()=>{switch(c){case"settings":return e.jsx("div",{className:"h-full",children:e.jsx(II,{selectedSection:u,onSelectSection:ne=>{m(ne),he()}})});case"agents":return e.jsx(N5,{onItemSelect:he});case"commands":return e.jsx(T5,{onItemSelect:he});case"skills":return e.jsx(R5,{onItemSelect:he});case"providers":return e.jsx(q5,{onItemSelect:he});case"usage":return e.jsx(eI,{onItemSelect:he});case"git-identities":return e.jsx(oI,{onItemSelect:he});default:return null}},Z=()=>{switch(c){case"agents":return e.jsx(B5,{});case"commands":return e.jsx(P5,{});case"skills":return e.jsx(W5,{});case"providers":return e.jsx(X5,{});case"usage":return e.jsx(sI,{});case"git-identities":return e.jsx(cI,{});case"settings":return e.jsx(SI,{section:u});default:return null}},ie=Qs(),$=i.useMemo(()=>r?"pl-1.5":E&&F?"pl-[5.75rem]":"",[E,F,r]);return e.jsxs("div",{ref:S,"data-settings-view":"true",className:R("flex h-full flex-col overflow-hidden bg-background"),children:[e.jsxs("div",{onMouseDown:o?void 0:ve,className:R("flex select-none items-center justify-between border-b",o?"h-auto px-3 py-2":"app-region-drag h-12",!o&&$,E?"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:R("flex items-center",o?"gap-1":"h-full"),children:e.jsx("div",{className:R("flex items-center gap-1",!o&&"p-1 bg-background/50 rounded-lg"),children:A.map(({id:ne,label:V,icon:ce})=>{const ge=c===ne,H=ce;return o?e.jsxs(ht,{delayDuration:500,children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{onClick:()=>te(ne),className:R("relative flex h-9 w-9 items-center justify-center rounded-md transition-colors","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",ge?"bg-interactive-selection text-interactive-selection-foreground shadow-sm":"text-muted-foreground hover:bg-interactive-hover/50"),"aria-pressed":ge,"aria-label":V,children:e.jsx(H,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(pt,{children:e.jsx("p",{children:V})})]},ne):e.jsxs("button",{onClick:()=>te(ne),onMouseDown:ge?oe:void 0,className:R("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":V,children:[e.jsx(H,{className:"h-4 w-4",weight:"regular"}),G&&e.jsx("span",{children:V})]},ne)})})}),(t||B)&&e.jsxs("div",{className:R("flex items-center gap-2",o?"":"pr-3"),children:[B&&e.jsxs(cs,{children:[e.jsx(ds,{asChild:!0,children:o?e.jsx("button",{type:"button","aria-label":"Switch project",title:M,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(Pn,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:M,className:R("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:M}),e.jsx(as,{className:"size-4 opacity-50"})]})}),e.jsx(us,{align:"end",className:"w-auto",children:e.jsx(Ml,{value:_?.id??"",onValueChange:ne=>{ne&&L(ne)},children:I.map(ne=>{const V=ne.label?.trim()?ne.label.trim():ne.path.split("/").filter(Boolean).pop()||ne.path,ce=O(V);return e.jsx(El,{value:ne.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:ce})},ne.id)})})})]}),t&&e.jsxs(ht,{delayDuration:500,children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,"aria-label":"Close settings",className:R("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(fs,{className:"h-5 w-5"})})}),e.jsx(pt,{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:Z()})}):e.jsx("div",{className:R("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:Y()})})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:R("relative flex h-full min-h-0 flex-col overflow-hidden border-r",E?"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:R("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:W,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:Y()})})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(Gs,{children:Z()})})]})})]})},RI=({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:R("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})]})]})})},LI=()=>{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}=Me(),{isMobile:b}=Ns(),w=i.useRef(!1),v=i.useRef(!1);Z1({enabled:!0});const k=ac(C=>C.checkForUpdates);i.useEffect(()=>{const C=setTimeout(()=>{k()},3e3);return()=>clearTimeout(C)},[k]),i.useEffect(()=>{Me.getState().isMobile!==b&&m(b)},[b,m]),i.useEffect(()=>{if(typeof window>"u")return;let C;const N=()=>{C!==void 0&&window.clearTimeout(C),C=window.setTimeout(()=>{Me.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",N),()=>{window.removeEventListener("resize",N),C!==void 0&&window.clearTimeout(C)}},[]),i.useEffect(()=>{if(typeof window>"u")return;let C;const N=()=>{const D=Me.getState(),A=window.innerWidth,E=window.innerHeight,P=A<1140,T=A>=1220;P?D.isRightSidebarOpen&&(c(!1),w.current=!0):T&&w.current&&(c(!0),w.current=!1);const L=E<640,I=E>=700;L?D.isBottomTerminalOpen&&(d(!1),v.current=!0):I&&v.current&&(d(!0),v.current=!1)},F=()=>{C!==void 0&&window.clearTimeout(C),C=window.setTimeout(()=>{N()},100)};return N(),window.addEventListener("resize",F),()=>{window.removeEventListener("resize",F),C!==void 0&&window.clearTimeout(C)}},[d,c]),i.useEffect(()=>{if(typeof window>"u")return;const C=Me.subscribe((N,F)=>{const D=window.innerWidth,A=window.innerHeight,E=D>=1220,P=A>=700;N.isRightSidebarOpen!==F.isRightSidebarOpen&&E&&(w.current=!1),N.isBottomTerminalOpen!==F.isBottomTerminalOpen&&P&&(v.current=!1)});return()=>{C()}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const C=document.documentElement;let N=0,F=!1,D=0,A=null;const E=Me.getState().setKeyboardOpen,P=()=>{A&&(A.style.setProperty("--oc-keyboard-avoid-offset","0px"),A.removeAttribute("data-keyboard-avoid-active"),A=null)},T=G=>{if(!G)return null;const W=G.getAttribute("data-keyboard-avoid-target-id");if(W){const oe=document.getElementById(W);if(oe instanceof HTMLElement)return oe}const ve=G.closest("[data-keyboard-avoid]");if(ve)return ve.getAttribute("data-keyboard-avoid")==="none"?null:ve;if(G.classList.contains("overlay-scrollbar-container")){const oe=G.parentElement;if(oe instanceof HTMLElement)return oe}return G},L=()=>{N=0,F=!0,C.style.setProperty("--oc-keyboard-inset","0px"),E(!1)},I=()=>{const G=window.visualViewport,W=G?Math.round(G.height):window.innerHeight,ve=G?Math.max(0,Math.round(G.offsetTop)):0;C.style.setProperty("--oc-visual-viewport-offset-top",`${ve}px`);const oe=document.activeElement,te=oe?.tagName,Y=te==="INPUT"||te==="TEXTAREA"||te==="SELECT"||!!oe?.isContentEditable,Z=Math.round(C.clientHeight||window.innerHeight),ie=W+ve,$=Math.max(0,Z-ie),V=$>=(Y?120:180)?$:0;if(F)V===0&&(F=!1),N=0;else if(N===0)V>0&&Y&&(N=V);else{const J=!Y&&W>D+6;V===0?(N=0,E(!1)):J?L():(V>0&&Y||V>N)&&(N=V,E(!0))}C.style.setProperty("--oc-keyboard-inset",`${N}px`),D=W;const ge=/iPad|iPhone|iPod/.test(navigator.userAgent)&&N>0?34:0;C.style.setProperty("--oc-keyboard-home-indicator",`${ge}px`);const H=Y?T(oe):null;if(!b||!H||!oe)P();else{H!==A&&(P(),A=H);const J=ve+W,X=oe.getBoundingClientRect().bottom-J,q=8,re=Math.max(N,V),ue=X>q&&re>0?Math.min(X,re):0,Re=A;Re&&(Re.style.setProperty("--oc-keyboard-avoid-offset",`${ue}px`),Re.setAttribute("data-keyboard-avoid-active","true"))}if(b&&Y){const J=document.scrollingElement;J&&J.scrollTop!==0&&(J.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};I();const _=window.visualViewport;_?.addEventListener("resize",I),_?.addEventListener("scroll",I),window.addEventListener("resize",I),window.addEventListener("orientationchange",I);const O=G=>{if(!G)return!1;const W=G.tagName;return W==="INPUT"||W==="TEXTAREA"||W==="SELECT"||G.isContentEditable},M=G=>{const W=G.target;O(W)&&(F=!1),I()};document.addEventListener("focusin",M,!0);const B=G=>{const W=G.target;if(!O(W))return;const ve=G.relatedTarget;O(ve)||window.requestAnimationFrame(()=>{if(O(document.activeElement))return;const oe=window.visualViewport,te=oe?Math.round(oe.height):window.innerHeight,he=oe?Math.max(0,Math.round(oe.offsetTop)):0,Y=Math.round(C.clientHeight||window.innerHeight),Z=te+he;if(Math.max(0,Y-Z)>0){I();return}L(),I()})};return document.addEventListener("focusout",B,!0),()=>{_?.removeEventListener("resize",I),_?.removeEventListener("scroll",I),window.removeEventListener("resize",I),window.removeEventListener("orientationchange",I),document.removeEventListener("focusin",M,!0),document.removeEventListener("focusout",B,!0),P()}},[b]);const S=i.useMemo(()=>{switch(u){case"plan":return e.jsx(H2,{});case"git":return e.jsx(ah,{});case"diff":return e.jsx(bF,{});case"terminal":return e.jsx(dh,{});case"files":return e.jsx(b5,{});default:return null}},[u]),j=u==="chat";return e.jsx(YA,{children:e.jsxs("div",{className:R("main-content-safe-area h-[100dvh]",b?"flex flex-col":"flex","bg-background"),children:[e.jsx(x1,{}),e.jsx(v1,{}),e.jsx(w1,{}),e.jsx(W1,{}),b?e.jsxs(e.Fragment,{children:[!(p||g)&&e.jsx(Bf,{}),e.jsxs("div",{className:R("flex flex-1 overflow-hidden",(p||g)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:[e.jsx("div",{className:R("flex-1 overflow-hidden bg-sidebar",!f&&"hidden"),children:e.jsx(Gs,{children:e.jsx(Ql,{mobileVariant:!0})})}),e.jsxs("main",{className:R("flex-1 overflow-hidden bg-background relative",f&&"hidden"),children:[e.jsx("div",{className:R("absolute inset-0",!j&&"invisible"),children:e.jsx(Gs,{children:e.jsx(ni,{})})}),S&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Gs,{children:S})})]})]}),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:R("absolute inset-0 flex flex-col",g&&"invisible"),children:[e.jsx(Bf,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx(c1,{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:R("absolute inset-0",!j&&"invisible"),children:e.jsx(Gs,{children:e.jsx(ni,{})})}),S&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Gs,{children:S})})]}),e.jsx(d1,{isOpen:a,isMobile:b,children:e.jsx(Gs,{children:e.jsx(ah,{mode:"sidebar"})})})]}),e.jsx(GF,{isOpen:l,isMobile:b,children:e.jsx(Gs,{children:e.jsx(dh,{})})})]})]})]}),g&&e.jsx("div",{className:R("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(RI,{open:p,onOpenChange:h})]})]})})},OI=t=>{if(!t)return"-";try{return new Date(t).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}catch{return"-"}},_I=550,$I=1400,zI=280,HI=()=>{const t=Ur(),s=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),r=i.useMemo(()=>{const T=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof T=="string"&&T.trim().length>0?T.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(T=>T.currentSessionId),f=Ae(T=>T.sessions),p=i.useMemo(()=>m?f.find(T=>T.id===m)?.title||"Session":null,[m,f]),h=Ae(T=>!!T.newSessionDraft?.open),g=Ae(T=>T.openNewSessionDraft),[x,y]=i.useState(()=>(typeof window<"u"?window.__IKANBAN_CONNECTION__?.status:"connecting")||"connecting"),b=ft(T=>T.isInitialized),w=ft(T=>T.initializeApp),v=Ae(T=>T.loadSessions),k=Ae(T=>T.loadMessages),S=Ae(T=>T.messages),[j,C]=i.useState(()=>b),[N,F]=i.useState(!1),D=i.useRef(0);i.useEffect(()=>{m&&l("chat")},[m]),i.useEffect(()=>{const T=t.vscode;T&&T.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 T=typeof window<"u"?window.__IKANBAN_CONNECTION__?.status:void 0;(T==="connected"||T==="connecting"||T==="error"||T==="disconnected")&&y(T);const L=I=>{const O=I.detail?.status;(O==="connected"||O==="connecting"||O==="error"||O==="disconnected")&&y(O)};return window.addEventListener("ikanban:connection-status",L),()=>window.removeEventListener("ikanban:connection-status",L)},[]),i.useEffect(()=>{const T=L=>{const _=L.detail?.view;_==="settings"?l("settings"):_==="chat"?l("chat"):_==="sessions"&&l("sessions")};return window.addEventListener("ikanban:navigate",T),()=>window.removeEventListener("ikanban:navigate",T)},[]),i.useEffect(()=>{(async()=>{if(N||j||x!=="connected")return;const L=Date.now();if(!(L-D.current<750)){D.current=L,F(!0);try{const I=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("ikanban_stream_debug")==="1"}catch{return!1}})();I&&console.log("[IKanban][VSCode][bootstrap] attempt",{configInitialized:b}),b||await w();const _=ft.getState();_.isConnected&&(_.providers.length===0&&await _.loadProviders(),_.agents.length===0&&await _.loadAgents());const O=ft.getState();if(!O.isInitialized||!O.isConnected||O.providers.length===0||O.agents.length===0)return;await v();const M=Ae.getState().error;if(I&&console.log("[IKanban][VSCode][bootstrap] post-load",{providers:O.providers.length,agents:O.agents.length,sessions:Ae.getState().sessions.length,sessionsError:M}),typeof M=="string"&&M.length>0)return;C(!0)}catch{}finally{F(!1)}}})()},[x,b,j,w,N,v]),i.useEffect(()=>{if(s==="editor"&&!n.current&&!(!j||x!=="connected")){if(!r){n.current=!0,g();return}f.some(T=>T.id===r)&&(n.current=!0,Ae.getState().setCurrentSession(r))}},[x,j,r,g,f,s]),i.useEffect(()=>{(async()=>{if(!(!j||x!=="connected"||a!=="chat"||h||!m||S.has(m)))try{await k(m)}catch{}})()},[x,m,a,j,k,S,h]),i.useEffect(()=>{const T=u.current;if(!T)return;const L=new ResizeObserver(I=>{for(const _ of I)d(_.contentRect.width)});return L.observe(T),d(T.clientWidth),()=>L.disconnect()},[]);const E=c>0&&c<_I,P=c>=$I;return i.useEffect(()=>{P&&a==="sessions"&&s==="sidebar"&&l("chat")},[P,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(T=>T.id===m)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Gs,{children:e.jsx(ni,{})})})]}):a==="settings"?e.jsx(dm,{onClose:()=>l(P?"chat":"sessions"),forceMobile:E}):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:zI},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(T=>T.id===m)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Gs,{children:e.jsx(ni,{})})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:R("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:R("flex flex-col h-full",a!=="chat"&&"hidden"),children:[e.jsx(sl,{title:h&&!m?"New session":f.find(T=>T.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(ni,{})})})]})]})})},sl=({title:t,showBack:s,onBack:r,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:l,showContextUsage:c,showRateLimits:d})=>{const{getCurrentModel:u}=ft(),m=Ae(A=>A.getContextUsage),f=es(A=>A.results),p=es(A=>A.fetchAllQuotas),h=es(A=>A.isLoading),g=es(A=>A.lastUpdated),x=es(A=>A.displayMode),y=es(A=>A.dropdownProviderIds),b=es(A=>A.loadSettings),w=es(A=>A.setDisplayMode);Uu(),i.useEffect(()=>{b()},[b]);const v=u(),k=v?.limit&&typeof v.limit=="object"?v.limit:null,S=typeof k?.context=="number"?k.context:0,j=typeof k?.output=="number"?k.output:0,C=m(S,j),N=i.useMemo(()=>{const A=[];for(const E of xn){if(!y.includes(E.id))continue;const P=f.find(_=>_.providerId===E.id),T=P?.usage?.windows??{},L=Object.entries(T),I=P&&!P.ok&&P.configured?P.error:void 0;(L.length>0||I)&&A.push({providerId:E.id,providerName:E.name,entries:L,error:I})}return A},[y,f]),F=N.length>0,D=i.useCallback(async A=>{w(A);try{await xs({usageDisplayMode:A})}catch(E){console.warn("Failed to update usage display mode:",E)}},[w]);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(Au,{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(Bs,{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(li,{className:"h-5 w-5"})}),l&&e.jsx(Gx,{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(cs,{onOpenChange:A=>{A&&f.length===0&&p()},children:[e.jsx(ds,{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(Pd,{className:"h-5 w-5"})})}),e.jsxs(us,{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(Cr,{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 ",OI(g)]}),!F&&e.jsx(It,{className:"cursor-default",onSelect:A=>A.preventDefault(),children:e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"No rate limits available."})}),N.map((A,E)=>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(Rs,{providerId:A.providerId,className:"h-4 w-4"}),A.providerName]}),A.entries.length===0?e.jsx(It,{className:"cursor-default",onSelect:P=>P.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(([P,T])=>{const L=x==="remaining"?T.remainingPercent:T.usedPercent,I=ca(T.usedPercent,T.resetAt,T.windowSeconds,P),_=I?.dailyAllocationPercent!=null?x==="remaining"?100-ln(I.elapsedRatio):ln(I.elapsedRatio):null;return e.jsx(It,{className:"cursor-default items-start",onSelect:O=>O.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:Ul(P)}),e.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:jn(L)==="-"?"":jn(L)})]}),e.jsx(da,{percent:L,tonePercent:T.usedPercent,className:"h-1",expectedMarkerPercent:_}),I&&e.jsx("div",{className:"mt-0.5",children:e.jsx(ua,{paceInfo:I,compact:!0})}),e.jsx("span",{className:"flex items-center justify-between typography-micro text-muted-foreground text-[10px]",children:e.jsx("span",{children:T.resetAfterFormatted??T.resetAtFormatted??""})})]})},`${A.providerId}-${P}`)}),E<N.length-1&&e.jsx(cr,{})]},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(Bo,{className:"h-5 w-5"})}),c&&C&&C.totalTokens>0&&e.jsx(Ix,{totalTokens:C.totalTokens,percentage:C.percentage,contextLimit:C.contextLimit,outputLimit:C.outputLimit??0,size:"compact"})]})},rl=t=>{const s=gs.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?Us(t):null},Us=t=>{if(!t)return"";const s=t.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Ph=(t,s)=>{const r=Us(t),n=Us(s);if(!r||!n)return!1;if(r===n)return!0;const o=n==="/"?"/":`${n}/`;return r.startsWith(o)},gb=async(t,s)=>{const r=Us(s);if(!r)return r;try{const n=await t.path.get({directory:r});return Us(n.data?.directory??"")||r}catch{return r}},xb=async(t,s)=>{const r=Us(s);if(!r)return[];const n=await gb(t,r),o=l=>l.filter(c=>{const d=Us(c.directory??"");return d?Ph(d,r)||n!==r&&Ph(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[]}},UI=async(t,s)=>{const r=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&r.set(Us(o.path),o.worktreeMetadata)});const n=Array.from(new Set(t.sessions.map(o=>Us(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=>[Us(l.path),l]));n.forEach(l=>{const c=a.get(l);c&&r.set(l,c)})}catch{}return r},VI=async t=>{const{apiClient:s,group:r,projectDirectory:n,worktreePaths:o}=t,a=await UI(r,n),l=Ae.getState(),c=Array.from(new Set(o.map(p=>Us(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(w=>Us(w.path)===p).map(w=>w.id),g=l.getSessionsByDirectory(p),x=Array.isArray(g)?g.map(w=>w.id):[];let y=[];if(x.length===0)try{y=(await xb(s,p)).map(v=>v.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},Md=async t=>{const s=ot.getApiClient(),r=await VI({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 WI(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=Ps()(Hs((t,s)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const r=Jt.getState().currentDirectory,n=rl(r);if(!n){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Us(n),c={id:gs.getState().projects.find(u=>Us(u.path)===o)?.id??`path:${o}`,path:o},d=s().groups;t({isLoading:!0,error:null});try{const u=ot.getApiClient(),m=await gb(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 N=Us(C.path);g.add(N),x.has(N)||x.set(N,C)}});const y=async()=>{try{const N=await u.session.list({directory:o}),F=Array.isArray(N.data)?N.data:[];if(F.some(D=>{const A=Us(D.directory??"");return A?g.has(A):!1}))return F}catch{}const C=await u.session.list(void 0);return Array.isArray(C.data)?C.data:[]},b=async C=>{const N=new Map,F=5;let D=0;const A=async()=>{for(;D<C.length;){const E=C[D];D+=1;const P=Us(E);if(P)try{(await xb(u,P)).forEach(L=>N.set(L.id,L))}catch(T){console.debug("Failed to fetch sessions from worktree:",P,T)}}};return await Promise.all(Array.from({length:Math.min(F,C.length)},A)),Array.from(N.values())};let v=(await y()).filter(C=>{const N=Us(C.directory??"");return N?g.has(N):!1});if(v.length===0){const C=new Set;g.forEach(N=>C.add(N)),C.size>0&&(v=await b(Array.from(C)))}const k=new Map;for(const C of v){const N=C.time?.updated??0;k.set(C.id,typeof N=="number"?N:0)}const S=new Map;for(const C of v){const N=WI(C.title);if(!N)continue;const F=Us(C.directory),D=x.get(F),A={id:C.id,path:F,providerId:N.provider,modelId:N.model,instanceNumber:N.index,branch:D?.branch??"",displayLabel:`${N.provider}/${N.model}`,worktreeMetadata:D},E=S.get(N.groupSlug);E?E.push(A):S.set(N.groupSlug,[A])}const j=Array.from(S.entries()).map(([C,N])=>{const F=N.reduce((D,A)=>{const E=k.get(A.id)??0;return Math.max(D,E)},0);return{name:C,sessions:N.sort((D,A)=>{const E=D.providerId.localeCompare(A.providerId);if(E!==0)return E;const P=D.modelId.localeCompare(A.modelId);return P!==0?P:D.instanceNumber-A.instanceNumber}),lastActive:F||Date.now(),sessionCount:N.length}});j.sort((C,N)=>C.name.localeCompare(N.name)),t({groups:j,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=Jt.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 Md({group:n,projectDirectory:Us(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=Us(n);if(!a)return!1;const l=Jt.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 Md({group:o,projectDirectory:Us(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=Us(n);if(!a)return!1;const c=Array.from(new Set(o.sessions.map(m=>Us(m.path)).filter(Boolean))).filter(m=>m!==a);if(c.length===0)return!0;const d=Jt.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 Md({group:o,projectDirectory:Us(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=>Us(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"})),GI=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`},qI=({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:R("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(As,{className:"h-3 w-3"}),t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:GI(t.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(cs,{open:n,onOpenChange:o,children:[e.jsx(ds,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","opacity-0 group-hover:opacity-100",n&&"opacity-100"),"aria-label":"Group menu",onClick:f=>f.stopPropagation(),children:e.jsx(Qn,{className:"h-3.5 w-3.5"})})}),e.jsx(us,{align:"end",className:"min-w-[140px]",children:e.jsx(It,{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(Es,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Ys,{children:[e.jsx(Ce,{variant:"outline",onClick:()=>l(!1),disabled:c,children:"Cancel"}),e.jsx(Ce,{variant:"destructive",onClick:()=>{m()},disabled:c,children:c?"Deleting…":"Delete"})]})]})})]})},KI=({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=Jt(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:R("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(Ir,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ot,{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(Ce,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(Bs,{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(as,{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(Vt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[g.map(y=>e.jsx(qI,{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"})]})]})]})},QI=10*1024*1024,YI=5,JI=({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,w]=i.useState([]),[v,k]=i.useState(!1),[S,j]=i.useState(!1),C=i.useRef(null),N=i.useRef(null),{currentTheme:F}=rn(),D=Jt(Y=>Y.currentDirectory??null),{isGitRepository:A,isLoading:E}=tm(D),P=i.useMemo(()=>{if(typeof window>"u")return null;const Y=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof Y=="string"&&Y.trim().length>0?Y.trim():null},[]),T=i.useMemo(()=>typeof window>"u"?!1:!!window.__IKANBAN_RUNTIME_APIS__?.runtime?.isVSCode,[]),L=gs(Y=>Y.activeProjectId),I=gs(Y=>Y.projects),_=i.useMemo(()=>{if(T&&P)return{id:`vscode:${P}`,path:P};if(L){const Y=I.find(Z=>Z.id===L);if(Y?.path)return{id:Y.id,path:Y.path}}return D?{id:`path:${D}`,path:D}:null},[L,I,D,P,T]);i.useEffect(()=>{if(!_)return;let Y=!1;return j(!0),(async()=>{try{const Z=await Da(_);Y||w(Z)}catch{}finally{Y||j(!1)}})(),()=>{Y=!0}},[_]);const O=i.useCallback(Y=>{c.length>=YI||d(Z=>[...Z,Y])},[c.length]),M=i.useCallback(Y=>{d(Z=>Z.filter((ie,$)=>$!==Y))},[]),B=i.useCallback((Y,Z)=>{d(ie=>ie.map(($,ne)=>ne===Y?Z:$))},[]),G=async Y=>{const Z=Y.target.files;if(!Z)return;let ie=0;for(let $=0;$<Z.length;$++){const ne=Z[$];if(ne.size>QI){K.error(`File "${ne.name}" is too large (max 10MB)`);continue}try{const V=await new Promise((ge,H)=>{const J=new FileReader;J.onload=()=>ge(J.result),J.onerror=H,J.readAsDataURL(ne)}),ce={id:Yl(),filename:ne.name,mimeType:ne.type||"application/octet-stream",size:ne.size,dataUrl:V};g(ge=>[...ge,ce]),ie++}catch(V){console.error("File attach failed",V),K.error(`Failed to attach "${ne.name}"`)}}ie>0&&K.success(`Attached ${ie} file${ie>1?"s":""}`),C.current&&(C.current.value="")},W=Y=>{g(Z=>Z.filter(ie=>ie.id!==Y))},ve=x||r,oe=!!(n.trim()&&a.trim()&&c.length>=1&&A&&!E),te=async Y=>{if(Y.preventDefault(),!(!oe||ve)){y(!0);try{const Z=c.map(({providerID:ne,modelID:V,displayName:ce,variant:ge})=>({providerID:ne,modelID:V,displayName:ce,variant:ge})),ie=h.length>0?h.map(ne=>({mime:ne.mimeType,filename:ne.filename,url:ne.dataUrl})):void 0,$=b.filter(ne=>ne.trim().length>0);await s?.({name:n.trim(),prompt:a.trim(),models:Z,agent:u||void 0,worktreeBaseBranch:f,files:ie,setupCommands:$.length>0?$:void 0}),o(""),l(""),d([]),m(""),g([]),p("HEAD")}catch(Z){console.error("Failed to create agent group:",Z),K.error("Failed to create agent group")}finally{y(!1)}}},he=Y=>{em(Y)||Y.key==="Enter"&&!Y.shiftKey&&(Y.preventDefault(),oe&&!ve&&te(Y))};return e.jsx("div",{className:R("flex flex-col items-center justify-center h-full w-full p-4",t),children:e.jsxs("form",{onSubmit:te,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(Ot,{id:"group-name",value:n,onChange:Y=>o(Y.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch naming"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-1.5",children:[e.jsx(As,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(uy,{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:v,onOpenChange:k,children:[e.jsxs(Ln,{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(Y=>Y.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",b.filter(Y=>Y.trim()).length," configured)"]})]}),e.jsx(as,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",v&&"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."]}),S?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[b.map((Y,Z)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ot,{value:Y,onChange:ie=>{const $=[...b];$[Z]=ie.target.value,w($)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const ie=b.filter(($,ne)=>ne!==Z);w(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(fs,{className:"h-4 w-4"})})]},Z)),e.jsxs("button",{type:"button",onClick:()=>w([...b,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Bs,{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(my,{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(dy,{selectedModels:c,onAdd:O,onRemove:M,onUpdate:B,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:F?.colors?.surface?.subtle},children:[e.jsx(hr,{ref:N,id:"prompt",value:a,onChange:Y=>l(Y.target.value),onKeyDown:he,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(Y=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[Y.mimeType.startsWith("image/")?e.jsx(Rn,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Dn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:Y.filename,children:Y.filename}),e.jsx("button",{type:"button",onClick:()=>W(Y.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(fs,{className:"h-3.5 w-3.5"})})]},Y.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40 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:G,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(ug,{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:R("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(u0,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Od,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},XI=({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(v=>v.id===r)??t.sessions[0]??null:t.sessions[0]??null,[t.sessions,r]),h=i.useCallback(v=>{n(v.id),l(v.id)},[n,l]);i.useEffect(()=>{if(t.sessions.length>0){const v=r?t.sessions.find(k=>k.id===r)??t.sessions[0]:t.sessions[0];v&&(v.id!==c&&l(v.id),r||n(v.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]),w=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:R("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(As,{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(cs,{children:[e.jsx(ds,{asChild:!0,children:e.jsxs(Ce,{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(Rs,{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(as,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(us,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:t.sessions.map(v=>e.jsxs(It,{onClick:()=>h(v),className:"flex items-center gap-2 py-2",children:[e.jsx(Rs,{providerId:v.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:v.modelId}),v.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",v.instanceNumber]})]}),v.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(As,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:v.worktreeMetadata?.label||v.branch})]})]}),p?.id===v.id&&e.jsx(ns,{className:"h-4 w-4 text-primary flex-shrink-0"})]},v.id))})]})}),e.jsxs(cs,{children:[e.jsx(ds,{asChild:!0,children:e.jsx(Ce,{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(us,{align:"end",className:"min-w-[220px]",children:[e.jsx(It,{onSelect:v=>{v.preventDefault(),y()},variant:"destructive",children:"Remove this worktree"}),e.jsx(It,{onSelect:v=>{v.preventDefault(),b()},children:"Leave this one, remove others"}),e.jsxs(It,{onClick:v=>{v.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:v=>{v||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(Es,{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(Ys,{children:[e.jsx(Ce,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Ce,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{w()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?g?e.jsx(Gy,{sessionId:p.id,children:e.jsx(Wy,{})}):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(Rs,{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"})})})]})},ZI=({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=ft(v=>v.isInitialized),a=ft(v=>v.initializeApp),l=Ae(v=>v.loadSessions),c=Jt(v=>v.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=mo(),{createMultiRun:h,isLoading:g}=ri();i.useEffect(()=>{if(!s)return;const v=typeof window<"u"?window.__IKANBAN_CONNECTION__?.status:void 0;(v==="connected"||v==="connecting"||v==="error"||v==="disconnected")&&n(v);const k=S=>{const C=S.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 v=Date.now();if(v-d.current<750)return;d.current=v;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 j=ft.getState();if(!j.isInitialized||!j.isConnected||j.providers.length===0||j.agents.length===0)return;await l(),sr()&&console.log("[IKanban][VSCode][agentManager] bootstrap complete",{providers:j.providers.length,agents:j.agents.length,sessions:Ae.getState().sessions.length})}catch{}})()},[r,o,a,s,l,c]);const x=i.useCallback(v=>{m(v)},[m]),y=i.useCallback(()=>{m(null)},[m]),b=i.useCallback(async v=>{K.info(`Creating agent group "${v.name}" with ${v.models.length} model(s)...`);const k=await h(v);if(k){K.success(`Agent group "${v.name}" created with ${k.sessionIds.length} session(s)`);const S=k.groupSlug,j=async(C=6)=>{for(let N=0;N<C;N+=1){if(await p(),mo.getState().groups.some(D=>D.name===S))return!0;await new Promise(D=>setTimeout(D,500))}return!1};try{await Ae.getState().loadSessions()}catch{}await j(),m(S)}else{const S=ri.getState().error;K.error(S||"Failed to create agent group")}},[h,p,m]),w=f();return e.jsxs("div",{className:R("flex h-full w-full bg-background",t),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(KI,{selectedGroupName:u,onGroupSelect:x,onNewAgent:y})}),e.jsx("div",{className:"flex-1 min-w-0",children:w?e.jsx(XI,{group:w}):e.jsx(JI,{onCreateGroup:b,isCreating:g})})]})},eB=({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(m0,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),t&&e.jsx(Ce,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:t,children:e.jsx(fs,{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(Vt,{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(f0,{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(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsxs(Ce,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(kr,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(pt,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{l()},children:"Evict LRU"})}),e.jsx(pt,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(ht,{delayDuration:1e3,children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{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(pt,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},tB="ikanban-message-cursors",Zl="cursors",sB=1,yb="ikanban.messageCursors",um=()=>typeof window<"u",bb=()=>um()&&typeof indexedDB<"u",rB=()=>bb()?new Promise((t,s)=>{const r=indexedDB.open(tB,sB);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")),nB=()=>{if(!um())return{};try{const t=window.localStorage.getItem(yb);if(!t)return{};const s=JSON.parse(t);return s&&typeof s=="object"?s:{}}catch{return{}}},oB=t=>{if(um())try{window.localStorage.setItem(yb,JSON.stringify(t))}catch{}},aB=async(t,s,r)=>{if(!t||!s)return;if(bb())try{const o=await rB();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=nB();n[t]={messageId:s,completedAt:r},oB(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},iB=50,lB=750,Rh=new WeakMap,Lh=t=>{if(!t||!Array.isArray(t))return 0;const s=Rh.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 Rh.set(t,r),r},cB=10,Oh=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<cB?null:n},_h=(t,s)=>{const r=Oh(t),n=Oh(s);return!r||!n||r.length!==n.length?!0:r>n},yu=new Map,Ed=(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},dB=()=>{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}=ft(),x=Me(Fe=>Fe.nativeNotificationsEnabled),y=Jt(Fe=>Fe.currentDirectory),b=i.useMemo(()=>{if(!c)return;try{const Te=u?.(c);if(Te?.path)return Te.path}catch(Te){console.warn("Failed to inspect worktree metadata for session directory:",Te)}const be=Ae.getState().sessions.find(Te=>Te.id===c);if(be&&typeof be.directory=="string"&&be.directory.trim().length>0)return be.directory.trim()},[c,u]),w=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 Fe=!1;const be=async()=>{try{const Ie=await ot.listPendingPermissions();if(Fe||Ie.length===0)return;for(const Oe of Ie)o(Oe)}catch{}},Te=async()=>{try{const Oe=gs.getState().projects.map(Ze=>Ze.path),ze=Ae.getState().sessions.map(Ze=>Ze.directory),Ee=[w,...Oe,...ze],Be=await ot.listPendingQuestions({directories:Ee});if(Fe||Be.length===0)return;for(const Ze of Be)a(Ze)}catch{}};return be(),Te(),()=>{Fe=!0}},[o,a,w]);const v=i.useCallback(Fe=>{if(typeof Fe!="string")return null;const be=Fe.trim();if(!be)return null;const Te=be.replace(/\\/g,"/");return Te.length>1?Te.replace(/\/+$/,""):Te},[]),k=i.useCallback(Fe=>{if(!Fe)return null;try{const Ie=u?.(Fe),Oe=v(Ie?.path??null);if(Oe)return Oe}catch{}const Te=Ae.getState().sessions.find(Ie=>Ie.id===Fe);return v(Te?.directory??null)},[u,v]),S=Me(Fe=>Fe.setEventStreamStatus),j=i.useRef(null),C=i.useCallback((Fe,be)=>{const Te=be??null,Ie=j.current;if(!(Ie&&Ie.status===Fe&&Ie.hint===Te)){if(j.current={status:Fe,hint:Te},sr()){const et={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[Fe]??"[INFO]",ze=Te?`${et} SSE ${Fe}: ${Te}`:`${et} SSE ${Fe}`;console.info(ze)}S(Fe,Te)}},[S]),N=i.useCallback((Fe,be,Te)=>{if(!Fe)return Promise.resolve();const Ie=Date.now();if(B.current)return B.current;if(Ie-G.current<lB)return Promise.resolve();const Oe=m(Fe,Te).catch(et=>{console.warn(`[useEventStream] Failed to resync messages (${be}):`,et)}).finally(()=>{B.current=null,G.current=Date.now()});return B.current=Oe,Oe},[m]),F=i.useCallback(async Fe=>{sr()&&console.info("[useEventStream] Bootstrapping state:",Fe);try{const be=cn();await Promise.all([f(),c?N(c,Fe,be):Promise.resolve()])}catch(be){console.warn("[useEventStream] Bootstrap failed:",Fe,be)}},[c,f,N]),D=i.useCallback((Fe,be,Te=cn())=>{if(!Fe)return Promise.resolve();const Oe=Ae.getState().sessionMemoryState.get(Fe)?.streamingCooldownUntil,et=Date.now();if(typeof Oe=="number"&&Oe>et){const ze=Math.min(3e3,Math.max(0,Oe-et));return new Promise(Ee=>{setTimeout(()=>{N(Fe,be,Te).finally(Ee)},ze)})}return N(Fe,be,Te)},[N]);i.useEffect(()=>{X.current=D},[D]);const A=i.useCallback((Fe,be,Te)=>{sr()&&console.debug(`[MessageTracker] ${Fe}: ${be}`,Te)},[]),E=i.useCallback(Fe=>{sr()&&console.debug(`[MessageTracker] ${Fe}: reported`)},[]),P=i.useRef(null),T=i.useRef(null),L=i.useRef(0);i.useRef(new Set);const I=i.useRef(new Set),_=i.useRef(new Map),O=i.useRef(null),M=i.useRef(!1),B=i.useRef(null),G=i.useRef(0),W=i.useRef(new Set),ve=i.useRef(new Set),oe=i.useRef(new Set),te=i.useRef(new Set),he=i.useRef(new Set),Y=i.useRef(new Map),Z=i.useCallback(()=>{if(typeof document>"u")return"visible";const Fe=document.visibilityState;return Fe==="hidden"&&document.hasFocus()?"visible":Fe},[]),ie=i.useRef(Z()),$=i.useRef(typeof navigator>"u"?!0:navigator.onLine),ne=i.useRef(!1),V=i.useRef(null),ce=i.useRef(null),ge=i.useRef(Date.now()),H=i.useRef(new Map),J=i.useRef(new Map),we=i.useRef(new Map),X=i.useRef(()=>Promise.resolve()),q=i.useRef(()=>{}),re=i.useCallback(Fe=>{const be=Date.now();be-ge.current>25e3&&(F(Fe),ge.current=be)},[F]),ue=i.useRef(c),Re=i.useRef(null),_e=i.useRef(null);i.useEffect(()=>{ue.current=c},[c]);const me=i.useCallback((Fe,be)=>{if(!Fe)return;const Te=Date.now(),Ie=_.current,Oe=Ie.get(Fe);if(Oe&&Te-Oe<3e3)return;Ie.set(Fe,Te);const et=ze=>{if(typeof be=="string"&&be.trim().length>0)return be.trim();try{const Ze=u?.(ze);if(Ze?.path)return Ze.path}catch{}const Be=Ae.getState().sessions.find(Ze=>Ze.id===ze);return Be&&typeof Be.directory=="string"&&Be.directory.trim().length>0?Be.directory.trim():null};setTimeout(async()=>{try{const ze=et(Fe),Ee=ze?await ot.withDirectory(ze,()=>ot.getSession(Fe)):await ot.getSession(Fe);if(Ee){const Be={};typeof Ee.title=="string"&&Ee.title.length>0&&(Be.title=Ee.title),Ee.summary!==void 0&&(Be.summary=Ee.summary),Object.keys(Be).length>0&&d(Fe,Be)}}catch(ze){console.warn("Failed to refresh session metadata:",ze)}},100)},[d,u]),Q=i.useCallback((Fe,be,Te="unknown")=>{if(!Fe)return;const Oe=Ae.getState().sessionStatus?.get(Fe)?.type??"idle",et=be?.type??"idle";if(Oe!==et)try{console.info("[SESSION-STATUS]",{sessionId:Fe,from:Oe,to:et,source:Te,...et==="retry"?{attempt:be.attempt,next:be.next,message:be.message}:{}})}catch{}const ze=Oe==="idle"&&(et==="busy"||et==="retry");if(et==="idle"){const Ze=J.current.get(Fe);Ze&&(clearTimeout(Ze),J.current.delete(Fe))}if(ze){const Ze=J.current.get(Fe);Ze&&(clearTimeout(Ze),J.current.delete(Fe));const tt=Date.now(),jt=setTimeout(()=>{const xt=Ae.getState().sessionStatus?.get(Fe);if(xt?.type!=="busy"&&xt?.type!=="retry")return;const Et=we.current.get(Fe)??0;Date.now()-Et<15e3||(H.current.get(Fe)??0)>=tt||(we.current.set(Fe,Date.now()),X.current(Fe,"status_busy_no_message",cn()).finally(()=>{q.current("No message events after busy status")}))},2e3);J.current.set(Fe,jt)}const Be=new Map(Ae.getState().sessionStatus??new Map);if(et==="idle")Be.set(Fe,{...be,confirmedAt:Date.now()});else{const Ze=Be.get(Fe);Ze?.confirmedAt?Be.set(Fe,{...be,confirmedAt:Ze.confirmedAt}):Be.set(Fe,be)}Ae.setState({sessionStatus:Be})},[]);i.useEffect(()=>{const Fe=c??null;Re.current;const be=k(Fe);_e.current,Re.current=Fe,_e.current=be},[c,k]);const xe=i.useCallback(Fe=>{if(ge.current=Date.now(),sr()&&console.debug("[useEventStream] Received event:",Fe.type,Fe.properties),!Fe.properties)return;const be=Fe.properties;if(!new Set(["session.abort","session.error"]).has(Fe.type)){const Ie=(typeof be.session=="object"&&be.session!==null?be.session:null)||(typeof be.sessionInfo=="object"&&be.sessionInfo!==null?be.sessionInfo:null);if(Ie){const Oe=Ie,et=typeof Oe.id=="string"&&Oe.id.length>0?Oe.id:typeof Oe.sessionID=="string"&&Oe.sessionID.length>0?Oe.sessionID:typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:typeof be.id=="string"&&be.id.length>0?be.id:void 0;if(et){const ze=typeof Oe.title=="string"?Oe.title:typeof be.title=="string"?be.title:void 0,Ee=typeof Oe.summary=="object"&&Oe.summary!==null?Oe.summary:typeof be.summary=="object"&&be.summary!==null?be.summary:void 0;if(ze!==void 0||Ee!==void 0){const Be={};ze!==void 0&&(Be.title=ze),Ee!==void 0&&(Be.summary=Ee),d(et,Be)}}}}switch(Fe.type){case"server.connected":g();break;case"global.disposed":case"server.instance.disposed":{F("server_disposed_event");break}case"mcp.tools.changed":{const Ie=typeof be.directory=="string"?be.directory:w;Un.getState().refresh({directory:Ie??null,silent:!0});break}case"session.status":{const Ie=Qr(be,["sessionID","sessionId"]),Oe=typeof be.status=="object"&&be.status!==null?be.status:null,et=typeof Oe?.type=="string"?Oe.type:null,ze=Oe??{};Ie&&et&&(et==="busy"?Q(Ie,{type:"busy"},"sse:session.status"):et==="retry"?Q(Ie,{type:"retry",attempt:typeof ze.attempt=="number"?ze.attempt:void 0,message:typeof ze.message=="string"?ze.message:void 0,next:typeof ze.next=="number"?ze.next:void 0},"sse:session.status"):Q(Ie,{type:"idle"},"sse:session.status"),me(Ie,typeof be.directory=="string"?be.directory:null))}break;case"ikanban:session-status":{const Ie=Qr(be,["sessionId","sessionID"]),Oe=typeof be.status=="string"?be.status:null,et=typeof be.needsAttention=="boolean"?be.needsAttention:!1,ze=typeof be.timestamp=="number"?be.timestamp:Date.now();if(Ie&&Oe){if(Oe==="busy")Q(Ie,{type:"busy"},"sse:ikanban:session-status");else if(Oe==="retry"){const tt=typeof be.metadata=="object"&&be.metadata!==null?be.metadata:{};Q(Ie,{type:"retry",attempt:typeof tt.attempt=="number"?tt.attempt:void 0,message:typeof tt.message=="string"?tt.message:void 0,next:typeof tt.next=="number"?tt.next:void 0},"sse:ikanban:session-status")}else Q(Ie,{type:"idle"},"sse:ikanban:session-status");const Ee=Ae.getState().sessionAttentionStates||new Map,Be=new Map(Ee),Ze=Be.get(Ie);Be.set(Ie,{needsAttention:et,lastStatusChangeAt:ze,lastUserMessageAt:Ze?.lastUserMessageAt??null,status:Oe,isViewed:Ze?.isViewed??!1}),Ae.setState({sessionAttentionStates:Be})}}break;case"message.part.updated":{const Ie=typeof be.part=="object"&&be.part!==null?be.part:null;if(!Ie)break;const Oe=Ie,et=typeof be.info=="object"&&be.info!==null?be.info:be,ze=Qr(et,["sessionID","sessionId"]),Ee=Qr(Oe,["sessionID","sessionId"])||ze||Qr(be,["sessionID","sessionId"]),Be=Qr(et,["messageID","messageId","id"]),Ze=Qr(Oe,["messageID","messageId"])||Be||Qr(be,["messageID","messageId"]);if(!Ee||!Ze){sr()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:Oe.sessionID??ze??be.sessionID,messageID:Oe.messageID??Be??be.messageID});break}const tt=Ee,jt=Ze;H.current.set(tt,Date.now());const xt=J.current.get(tt);xt&&(clearTimeout(xt),J.current.delete(tt));const Et=Ae.getState().sessionMemoryState.get(tt)?.trimmedHeadMaxId;if(Et&&!_h(jt,Et)){sr()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:tt,messageId:jt,trimmedHeadMaxId:Et});break}let yt="assistant";if(et&&typeof et.role=="string")yt=et.role;else{const os=Ed(tt,jt);if(os){const is=os.info.role;typeof is=="string"&&(yt=is)}}if(A(jt,"part_received",{role:yt}),yt==="user"&&Oe.synthetic===!0){A(jt,"skipped_synthetic_user_part");break}const Xt={...Ie,type:Ie.type||"text"};if(yt==="assistant"){const os=Xt.type,hs=typeof Xt.time?.end=="number",ae=Xt.state?.status,je=Xt.text;if(os==="tool"?ae==="running"||ae==="pending":os==="reasoning"?!hs:os==="text"?typeof je=="string"&&je.trim().length>0&&!hs:os==="step-start"){const Ge=Ae.getState().sessionStatus?.get(tt),Je=Ge?.type==="idle"&&typeof Ge.confirmedAt=="number"&&Date.now()-Ge.confirmedAt<1200;if(!Ge||Ge.type==="idle"){if(Je)break;Q(tt,{type:"busy"},"sse:message.part.updated")}}}A(jt,"addStreamingPart_called"),t(tt,jt,Xt,yt);break}case"message.updated":{const Ie=typeof be.info=="object"&&be.info!==null?be.info:be,Oe=Ie,et=Qr(Oe,["sessionID","sessionId"])||Qr(be,["sessionID","sessionId"]),ze=Qr(Oe,["messageID","messageId","id"])||Qr(be,["messageID","messageId"]);if(!et||!ze){sr()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:Oe.sessionID??be.sessionID,messageID:Oe.id??be.messageID});break}const Ee=et,Be=ze;H.current.set(Ee,Date.now());const Ze=J.current.get(Ee);Ze&&(clearTimeout(Ze),J.current.delete(Ee));const tt=Ae.getState().sessionMemoryState.get(Ee)?.trimmedHeadMaxId;if(tt&&!_h(Be,tt)){sr()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Ee,messageId:Be,trimmedHeadMaxId:tt});break}if(sr())try{const Ct=be.parts||Oe.parts||[],Kt=(Array.isArray(Ct)?Ct.filter(At=>At?.type==="text"):[]).map(At=>{const Yt=At;return typeof Yt?.text=="string"?Yt.text:typeof Yt?.content=="string"?Yt.content:""}).join(`
289
- `);console.info("[STREAM-TRACE] message.updated",{messageId:Be,role:Oe.role,status:Oe.status,textLen:Kt.length,textPreview:Kt.slice(0,120),partsCount:Array.isArray(Ct)?Ct.length:0})}catch{}if(A(Be,"message_updated",{role:Oe.role}),Oe.role==="user"){const{sessionMemoryState:Ct}=ss.getState(),Lt=Ct.get(Ee);if(Lt){const dt=new Map(Ct);dt.set(Ee,{...Lt,lastUserMessageAt:Date.now()}),ss.setState({sessionMemoryState:dt})}const Kt=be.parts||Oe.parts,At=Array.isArray(Kt)?Kt:[],Yt=Ed(Ee,Be),St=(()=>{const dt=Oe.agent;if(typeof dt=="string"&&dt.trim().length>0)return dt.trim();const Tt=Oe.mode;return typeof Tt=="string"&&Tt.trim().length>0?Tt.trim():""})(),ts=(()=>{const Tt=Oe.time?.created;return typeof Tt=="number"?Tt:null})(),Qe=At.length>0&&At.every(dt=>dt?.synthetic===!0),mt=(()=>{if(!St)return!1;if(Qe&&(St==="plan"||St==="build"))return!0;const dt=Y.current.get(Ee);return dt?ts===null?!1:Be===dt.messageId?!0:ts>=dt.created:!0})();if(St&&mt)try{const dt=ft.getState().agents;if(Array.isArray(dt)&&dt.some(Tt=>Tt?.name===St)){const Tt=Pt.getState();if(Tt.saveSessionAgentSelection(Ee,St),Y.current.set(Ee,{created:ts??Date.now(),messageId:Be}),ue.current===Ee)try{ft.getState().setAgent(St)}catch{}const $t=Oe.model,Bt=typeof $t?.providerID=="string"?$t.providerID:null,Qt=typeof $t?.modelID=="string"?$t.modelID:null;if(Bt&&Qt){Tt.saveSessionModelSelection(Ee,Bt,Qt),Tt.saveAgentModelForSession(Ee,St,Bt,Qt);const ms=typeof Oe.variant=="string"?Oe.variant:void 0;if(ms&&Tt.saveAgentModelVariantForSession(Ee,St,Bt,Qt,ms),ue.current===Ee)try{ft.getState().setProvider(Bt),ft.getState().setModel(Qt)}catch{}}}}catch{}if(Qe&&(St==="plan"||St==="build")&&ue.current===Ee){const dt=`${Ee}:${Be}:${St}`;he.current.has(dt)||(he.current.add(dt),qs(async()=>{const{toast:Tt}=await import("./vendor-.bun-KwPUu5oc.js").then($t=>$t.dZ);return{toast:Tt}},__vite__mapDeps([0,1])).then(({toast:Tt})=>{Tt.info(St==="plan"?"Plan mode active":"Build mode active",{description:St==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const bt={...Ie,userMessageMarker:!0,clientRole:"user",...St?{mode:St}:{}};if(r(Ee,Be,bt),!Yt&&At.length===0){const dt=`${Ee}:${Be}`;I.current.has(dt)||(I.current.add(dt),ot.getSessionMessages(Ee,50).then(Tt=>{Ae.getState().syncMessages(Ee,Tt)}).catch(()=>{}))}if(At.length>0)for(let dt=0;dt<At.length;dt++){const Tt=At[dt];if(Tt.synthetic===!0){const Qt=Tt.text,ms=typeof Qt=="string"?Qt.trim():"";if(!(ms.startsWith("User has requested to enter plan mode")||ms.startsWith("The plan at ")))continue}const Bt={...Tt,type:Tt?.type||"text",sessionID:Tt?.sessionID||Ee,messageID:Tt?.messageID||Be};t(Ee,Be,Bt,"user")}A(Be,"user_message_created_from_event",{partsCount:At.length});break}const jt=Ed(Ee,Be),xt=Lh(jt?.parts||[]),Et=jt?.info?.finish==="stop",yt=be.parts||Oe.parts,Xt=Array.isArray(yt)?yt:[],os=Xt.length>0,hs=typeof(Oe.time||{})?.completed=="number",ae=Ie.status,je=typeof ae=="string"?ae.toLowerCase():null,We=je==="completed"||je==="complete",Ge=Ie.finish,Je=typeof Ge=="string"?Ge:null,ut=Je==="stop";if(!os&&!hs&&!We&&!ut)break;if(Oe.role==="assistant"&&os){const Ct=Lh(Xt);if(xt>0&&Ct+iB<xt&&!ut){A(Be,"skipped_shrinking_update",{incomingLen:Ct,existingLen:xt});break}}if(r(Ee,Be,Ie),os&&Oe.role!=="user"){const Kt=(Ae.getState().messages.get(Ee)||[]).find(St=>St.info.id===Be),At=!Kt||Kt.parts.length===0;A(Be,At?"server_parts_injected":"server_parts_refreshed",{count:Xt.length});const Yt=Xt;for(let St=0;St<Yt.length;St++){const ts=Yt[St],Qe={...ts,type:ts?.type||"text",sessionID:ts?.sessionID||Ee,messageID:ts?.messageID||Be};t(Ee,Be,Qe,Oe.role),A(Be,`server_part_${St}`)}}const wt=Ie.time,rt=wt?.completed,_t=typeof rt=="number"&&Number.isFinite(rt),kt=Je==="stop"||Et;if(Ie.role==="assistant"&&(_t||We||kt)&&Ie.role==="assistant"){const Lt=Ae.getState().messages.get(Ee)||[];let Kt=null,At="";for(let bt=0;bt<Lt.length;bt++){const dt=Lt[bt];dt.info.role==="assistant"&&dt.info.id>At&&(At=dt.info.id,Kt=dt.info.id)}if(c===Ee&&Be!==Kt)break;const St=_t?rt:Date.now();_t||r(Ee,Be,{...Ie,time:{...wt??{},completed:St}}),A(Be,"completed",{timeCompleted:St}),E(Be),aB(Ee,Be,St),s(Ee,Be),Q(Ee,{type:"idle"},"sse:message.updated.completed");const ts=Ie.sessionID,Qe=typeof ts=="string"&&ts.length>0?ts:Ee;me(Qe,typeof be.directory=="string"?be.directory:null),Ie.summary&&typeof Qe=="string"&&n(Qe,null)}break}case"session.created":case"session.updated":{const Ie=typeof be.info=="object"&&be.info!==null?be.info:typeof be.sessionInfo=="object"&&be.sessionInfo!==null?be.sessionInfo:typeof be.session=="object"&&be.session!==null?be.session:be,Oe=typeof Ie.id=="string"&&Ie.id.length>0?Ie.id:typeof Ie.sessionID=="string"&&Ie.sessionID.length>0?Ie.sessionID:typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:typeof be.id=="string"&&be.id.length>0?be.id:void 0;if(Oe){const et=typeof Ie.time=="object"&&Ie.time!==null?Ie.time:typeof be.time=="object"&&be.time!==null?be.time:null,ze=et&&typeof et.compacting=="number"?et.compacting:null;n(Oe,ze);const Ee=typeof Ie.directory=="string"?Ie.directory:typeof be.directory=="string"?be.directory:null,Be={...Ie,id:Oe,...Ee?{directory:Ee}:{}};p(Be)}break}case"session.deleted":{const Ie=typeof be.sessionID=="string"?be.sessionID:typeof be.id=="string"?be.id:null;Ie&&h(Ie);break}case"session.abort":{const Ie=typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:null,Oe=typeof be.messageID=="string"&&be.messageID.length>0?be.messageID:null;Ie&&Q(Ie,{type:"idle"},"sse:session.abort"),Ie&&Oe&&s(Ie,Oe);break}case"permission.asked":{if(!("sessionID"in be)||typeof be.sessionID!="string")break;const Ie=be;o(Ie);const Oe=`${Ie.sessionID}:${Ie.id}`;W.current.has(Oe)||setTimeout(()=>{if(ue.current===Ie.sessionID||!Ae.getState().permissions.get(Ie.sessionID)?.some(Be=>Be.id===Ie.id))return;W.current.add(Oe);const Ee=Ae.getState().sessions.find(Be=>Be.id===Ie.sessionID)?.title||"Session";qs(async()=>{const{toast:Be}=await import("./vendor-.bun-KwPUu5oc.js").then(Ze=>Ze.dZ);return{toast:Be}},__vite__mapDeps([0,1])).then(({toast:Be})=>{Be.warning("Permission required",{description:Ee,action:{label:"Open",onClick:()=>{Me.getState().setActiveMainTab("chat"),Ae.getState().setCurrentSession(Ie.sessionID)}}})})},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in be)||typeof be.sessionID!="string")break;const Ie=be;a(Ie);const Oe=`${Ie.sessionID}:${Ie.id}`;ve.current.has(Oe)||setTimeout(()=>{if(ue.current===Ie.sessionID||!Ae.getState().questions.get(Ie.sessionID)?.some(Be=>Be.id===Ie.id))return;ve.current.add(Oe);const Ee=Ae.getState().sessions.find(Be=>Be.id===Ie.sessionID)?.title||"Session";qs(async()=>{const{toast:Be}=await import("./vendor-.bun-KwPUu5oc.js").then(Ze=>Ze.dZ);return{toast:Be}},__vite__mapDeps([0,1])).then(({toast:Be})=>{Be.info("Input needed",{description:Ee,action:{label:"Open",onClick:()=>{Me.getState().setActiveMainTab("chat"),Ae.getState().setCurrentSession(Ie.sessionID)}}})})},0);break}case"question.replied":{const Ie=typeof be.sessionID=="string"?be.sessionID:null,Oe=typeof be.requestID=="string"?be.requestID:null;Ie&&Oe&&l(Ie,Oe);break}case"question.rejected":{const Ie=typeof be.sessionID=="string"?be.sessionID:null,Oe=typeof be.requestID=="string"?be.requestID:null;Ie&&Oe&&l(Ie,Oe);break}case"ikanban:notification":{const Ie=typeof be.title=="string"?be.title:"",Oe=typeof be.body=="string"?be.body:"",et=typeof be.tag=="string"?be.tag:void 0;if(!!be.requireHidden&&ie.current!=="hidden"||Pr()&&be.desktopStdoutActive||!x)break;const Ee=zr();Ee?.notifications&&Ie&&Ee.notifications.notifyAgentCompletion({title:Ie,body:Oe,tag:et});break}case"todo.updated":{const Ie=typeof be.sessionID=="string"?be.sessionID:null,Oe=Array.isArray(be.todos)?be.todos:null;Ie&&Oe&&LD(Ie,Oe);break}}},[c,x,t,s,r,o,a,l,g,me,n,d,A,E,p,h,F,w,Q]),fe=i.useCallback(()=>{const Fe=Z();return ie.current=Fe,Fe==="visible"&&$.current},[Z]),He=i.useCallback(()=>{sr()&&console.debug("[useEventStream] Connection state:",{hasUnsubscribe:!!P.current,currentSessionId:ue.current,effectiveDirectory:w,onlineStatus:$.current,visibilityState:ie.current,lastEventTimestamp:ge.current,reconnectAttempts:L.current})},[w]),it=i.useCallback(()=>{if(M.current){sr()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(M.current=!0,T.current&&(clearTimeout(T.current),T.current=null),P.current){const Fe=P.current;P.current=null;try{Fe()}catch(be){console.warn("[useEventStream] Error during unsubscribe:",be)}}M.current=!1},[]),de=i.useCallback(async Fe=>{if(He(),!fe()){ne.current=!0,$.current?C("paused","Paused while hidden"):C("offline","Waiting for network");return}Fe?.resetAttempts&&(L.current=0),it(),ge.current=Date.now(),C("connecting",null),sr()&&console.info("[useEventStream] Starting event stream...");const be=Ie=>{console.warn("Event stream error:",Ie)},Te=()=>{const Ie=ne.current;if(L.current=0,ne.current=!1,ge.current=Date.now(),C("connected",null),g(),zn(),Ie)F("sse_reconnected");else{const Oe=ue.current;Oe&&setTimeout(()=>{D(Oe,"sse_reconnected",cn()).then(()=>me(Oe)).catch(et=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",et)})},0)}};if(sr()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:w,isCleaningUp:M.current}),M.current){sr()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Ie=ot.subscribeToGlobalEvents(et=>{const ze=et.payload,Ee=et.payload,Be=typeof Ee.properties=="object"&&Ee.properties!==null?Ee.properties:{},Ze=et.directory&&et.directory!=="global"?{...Be,directory:et.directory}:Be;xe({type:typeof ze.type=="string"?ze.type:"",properties:Ze})},be,Te),Oe=()=>{try{Ie()}catch(et){console.warn("[useEventStream] Error during unsubscribe:",et)}};M.current?Oe():P.current=Oe}catch(Ie){console.error("[useEventStream] Error during subscription:",Ie),be(Ie)}},[fe,it,C,g,D,me,xe,w,He,F]),Ue=i.useCallback(Fe=>{if(!fe()){ne.current=!0,it(),$.current?C("paused","Paused while hidden"):C("offline","Waiting for network");return}if(T.current)return;const be=L.current+1;L.current=be;const Te=Fe??`Retrying (${be})`;C("reconnecting",Te);const Ie=be<=3?Math.min(1e3*Math.pow(2,be-1),8e3):Math.min(2e3*Math.pow(2,be-3),32e3),Oe=Math.floor(Math.random()*250),et=Ie+Oe;T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{de({resetAttempts:!1})},et)},[fe,it,C,de]);i.useEffect(()=>{q.current=Ue},[Ue]),i.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=A);const Fe=()=>{V.current&&(clearTimeout(V.current),V.current=null)},be=()=>{if(ie.current=Z(),ie.current!=="visible")return;if(Fe(),re("visibility_restore"),zn(),Date.now()-ge.current>45e3&&(console.info("[useEventStream] Visibility restored with stalled stream, reconnecting..."),ne.current=!0),ne.current||!P.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ze=ue.current;Ze&&(D(Ze,"visibility_restore",cn()),me(Ze)),zn(),C("connecting","Resuming stream"),de({resetAttempts:!0})}},Te=()=>{if(ie.current=Z(),ie.current==="visible"&&(Fe(),re("window_focus"),zn(),Date.now()-ge.current>45e3&&(ne.current=!0),ne.current||!P.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ze=ue.current;Ze&&(me(Ze),D(Ze,"window_focus",cn())),zn(),C("connecting","Resuming stream"),de({resetAttempts:!0})}},Ie=()=>{$.current=!0,re("network_restored"),(ne.current||!P.current)&&(zn(),C("connecting","Network restored"),de({resetAttempts:!0}))},Oe=()=>{$.current=!1,ne.current=!0,C("offline","Waiting for network"),it()},et=()=>{ne.current=!0,it(),C("paused","Paused while hidden")},ze=Be=>{if(ne.current=ne.current||!!Be.persisted,ie.current=Z(),ie.current==="visible"){const Ze=ue.current;Ze&&(D(Ze,"page_show",cn()),me(Ze)),zn(),de({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",be),typeof window<"u"&&(window.addEventListener("online",Ie),window.addEventListener("offline",Oe),window.addEventListener("focus",Te),window.addEventListener("pagehide",et),window.addEventListener("pageshow",ze));const Ee=setTimeout(()=>{de({resetAttempts:!0})},100);return ce.current&&clearInterval(ce.current),ce.current=setInterval(()=>{if(!fe())return;const Be=Date.now();Array.from(Ae.getState().sessionStatus?.values?.()??[]).some(tt=>tt?.type==="busy"||tt?.type==="retry")&&zn(),Be-ge.current>45e3&&Promise.resolve().then(async()=>{try{if(!await ot.checkHealth()){Ue("Refreshing stalled stream");return}Ue("Refreshing stalled stream")}catch(tt){console.warn("Health check after stale stream failed:",tt),Ue("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Ee),typeof document<"u"&&document.removeEventListener("visibilitychange",be),typeof window<"u"&&(window.removeEventListener("online",Ie),window.removeEventListener("offline",Oe),window.removeEventListener("focus",Te),window.removeEventListener("pagehide",et),window.removeEventListener("pageshow",ze)),Fe(),ce.current&&(clearInterval(ce.current),ce.current=null),yu.clear(),oe.current.clear(),te.current.clear(),ne.current=!1,ie.current=Z(),$.current=typeof navigator>"u"?!0:navigator.onLine,it(),O.current&&(clearTimeout(O.current),O.current=null),C("idle",null)}},[w,A,Z,it,C,de,Ue,m,me,fe,f,re,N,D])},uB=()=>{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:""},mB=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)}},fB=t=>{if(!t||!Number.isFinite(t))return"(n/a)";try{return new Date(t).toISOString()}catch{return"(invalid)"}},pB=async()=>{const t=new Date,s="0.1.0",r=typeof navigator<"u"?navigator.userAgent:"(no navigator)",n=uB(),o=Me.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 w=await y.text();let v=null;try{v=JSON.parse(w)}catch{const k=w.replace(/\s+/g," ").slice(0,120);return{data:null,status:y.status,error:`invalid json content-type=${b} body=${k||"(empty)"}`}}return!v||typeof v!="object"||Array.isArray(v)?{data:null,status:y.status,error:`invalid json-shape content-type=${b}`}:{data:v,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 mB(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:"",w=g&&typeof g.source=="string"?g.source:c&&typeof c.opencodeBinarySource=="string"?c.opencodeBinarySource:"",v=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:"",S=g&&typeof g.bun=="string"?g.bun:c&&typeof c.bunBinaryResolved=="string"?c.bunBinaryResolved:"",j=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 N=b||(y.includes("/")?y.split("/").slice(0,-1).join("/")||"/":"");p.push(`- opencode: ${y}${N?` (dir=${N})`:""}`)}else p.push("- opencode: (n/a)");p.push(`- source: ${w||"(n/a)"}`),j&&(p.push(`- detected-now: ${j}`),p.push(`- detected-source: ${C||"(n/a)"}`)),p.push(`- shim: ${v||"(n/a)"}`),p.push(`- node: ${k||"(n/a)"}`),p.push(`- bun: ${S||"(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:w}=g.result,v=x?"":` url=${g.url}`;p.push(`- ${g.label}: ${x?"ok":"fail"} status=${y} time=${b}ms ${w}${v}`)}}else p.push("OpenCode API probes: (skipped)");return p.push(""),p.push(`Generated: ${fB(Date.now())}`),p.join(`
289
+ `);console.info("[STREAM-TRACE] message.updated",{messageId:Be,role:Oe.role,status:Oe.status,textLen:Kt.length,textPreview:Kt.slice(0,120),partsCount:Array.isArray(Ct)?Ct.length:0})}catch{}if(A(Be,"message_updated",{role:Oe.role}),Oe.role==="user"){const{sessionMemoryState:Ct}=ss.getState(),Lt=Ct.get(Ee);if(Lt){const dt=new Map(Ct);dt.set(Ee,{...Lt,lastUserMessageAt:Date.now()}),ss.setState({sessionMemoryState:dt})}const Kt=be.parts||Oe.parts,At=Array.isArray(Kt)?Kt:[],Yt=Ed(Ee,Be),St=(()=>{const dt=Oe.agent;if(typeof dt=="string"&&dt.trim().length>0)return dt.trim();const Tt=Oe.mode;return typeof Tt=="string"&&Tt.trim().length>0?Tt.trim():""})(),ts=(()=>{const Tt=Oe.time?.created;return typeof Tt=="number"?Tt:null})(),Qe=At.length>0&&At.every(dt=>dt?.synthetic===!0),mt=(()=>{if(!St)return!1;if(Qe&&(St==="plan"||St==="build"))return!0;const dt=Y.current.get(Ee);return dt?ts===null?!1:Be===dt.messageId?!0:ts>=dt.created:!0})();if(St&&mt)try{const dt=ft.getState().agents;if(Array.isArray(dt)&&dt.some(Tt=>Tt?.name===St)){const Tt=Pt.getState();if(Tt.saveSessionAgentSelection(Ee,St),Y.current.set(Ee,{created:ts??Date.now(),messageId:Be}),ue.current===Ee)try{ft.getState().setAgent(St)}catch{}const $t=Oe.model,Bt=typeof $t?.providerID=="string"?$t.providerID:null,Qt=typeof $t?.modelID=="string"?$t.modelID:null;if(Bt&&Qt){Tt.saveSessionModelSelection(Ee,Bt,Qt),Tt.saveAgentModelForSession(Ee,St,Bt,Qt);const ms=typeof Oe.variant=="string"?Oe.variant:void 0;if(ms&&Tt.saveAgentModelVariantForSession(Ee,St,Bt,Qt,ms),ue.current===Ee)try{ft.getState().setProvider(Bt),ft.getState().setModel(Qt)}catch{}}}}catch{}if(Qe&&(St==="plan"||St==="build")&&ue.current===Ee){const dt=`${Ee}:${Be}:${St}`;he.current.has(dt)||(he.current.add(dt),qs(async()=>{const{toast:Tt}=await import("./vendor-.bun-KwPUu5oc.js").then($t=>$t.dZ);return{toast:Tt}},__vite__mapDeps([0,1])).then(({toast:Tt})=>{Tt.info(St==="plan"?"Plan mode active":"Build mode active",{description:St==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const bt={...Ie,userMessageMarker:!0,clientRole:"user",...St?{mode:St}:{}};if(r(Ee,Be,bt),!Yt&&At.length===0){const dt=`${Ee}:${Be}`;I.current.has(dt)||(I.current.add(dt),ot.getSessionMessages(Ee,50).then(Tt=>{Ae.getState().syncMessages(Ee,Tt)}).catch(()=>{}))}if(At.length>0)for(let dt=0;dt<At.length;dt++){const Tt=At[dt];if(Tt.synthetic===!0){const Qt=Tt.text,ms=typeof Qt=="string"?Qt.trim():"";if(!(ms.startsWith("User has requested to enter plan mode")||ms.startsWith("The plan at ")))continue}const Bt={...Tt,type:Tt?.type||"text",sessionID:Tt?.sessionID||Ee,messageID:Tt?.messageID||Be};t(Ee,Be,Bt,"user")}A(Be,"user_message_created_from_event",{partsCount:At.length});break}const jt=Ed(Ee,Be),xt=Lh(jt?.parts||[]),Et=jt?.info?.finish==="stop",yt=be.parts||Oe.parts,Xt=Array.isArray(yt)?yt:[],os=Xt.length>0,hs=typeof(Oe.time||{})?.completed=="number",ae=Ie.status,je=typeof ae=="string"?ae.toLowerCase():null,We=je==="completed"||je==="complete",Ge=Ie.finish,Je=typeof Ge=="string"?Ge:null,ut=Je==="stop";if(!os&&!hs&&!We&&!ut)break;if(Oe.role==="assistant"&&os){const Ct=Lh(Xt);if(xt>0&&Ct+iB<xt&&!ut){A(Be,"skipped_shrinking_update",{incomingLen:Ct,existingLen:xt});break}}if(r(Ee,Be,Ie),os&&Oe.role!=="user"){const Kt=(Ae.getState().messages.get(Ee)||[]).find(St=>St.info.id===Be),At=!Kt||Kt.parts.length===0;A(Be,At?"server_parts_injected":"server_parts_refreshed",{count:Xt.length});const Yt=Xt;for(let St=0;St<Yt.length;St++){const ts=Yt[St],Qe={...ts,type:ts?.type||"text",sessionID:ts?.sessionID||Ee,messageID:ts?.messageID||Be};t(Ee,Be,Qe,Oe.role),A(Be,`server_part_${St}`)}}const wt=Ie.time,rt=wt?.completed,_t=typeof rt=="number"&&Number.isFinite(rt),kt=Je==="stop"||Et;if(Ie.role==="assistant"&&(_t||We||kt)&&Ie.role==="assistant"){const Lt=Ae.getState().messages.get(Ee)||[];let Kt=null,At="";for(let bt=0;bt<Lt.length;bt++){const dt=Lt[bt];dt.info.role==="assistant"&&dt.info.id>At&&(At=dt.info.id,Kt=dt.info.id)}if(c===Ee&&Be!==Kt)break;const St=_t?rt:Date.now();_t||r(Ee,Be,{...Ie,time:{...wt??{},completed:St}}),A(Be,"completed",{timeCompleted:St}),E(Be),aB(Ee,Be,St),s(Ee,Be),Q(Ee,{type:"idle"},"sse:message.updated.completed");const ts=Ie.sessionID,Qe=typeof ts=="string"&&ts.length>0?ts:Ee;me(Qe,typeof be.directory=="string"?be.directory:null),Ie.summary&&typeof Qe=="string"&&n(Qe,null)}break}case"session.created":case"session.updated":{const Ie=typeof be.info=="object"&&be.info!==null?be.info:typeof be.sessionInfo=="object"&&be.sessionInfo!==null?be.sessionInfo:typeof be.session=="object"&&be.session!==null?be.session:be,Oe=typeof Ie.id=="string"&&Ie.id.length>0?Ie.id:typeof Ie.sessionID=="string"&&Ie.sessionID.length>0?Ie.sessionID:typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:typeof be.id=="string"&&be.id.length>0?be.id:void 0;if(Oe){const et=typeof Ie.time=="object"&&Ie.time!==null?Ie.time:typeof be.time=="object"&&be.time!==null?be.time:null,ze=et&&typeof et.compacting=="number"?et.compacting:null;n(Oe,ze);const Ee=typeof Ie.directory=="string"?Ie.directory:typeof be.directory=="string"?be.directory:null,Be={...Ie,id:Oe,...Ee?{directory:Ee}:{}};p(Be)}break}case"session.deleted":{const Ie=typeof be.sessionID=="string"?be.sessionID:typeof be.id=="string"?be.id:null;Ie&&h(Ie);break}case"session.abort":{const Ie=typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:null,Oe=typeof be.messageID=="string"&&be.messageID.length>0?be.messageID:null;Ie&&Q(Ie,{type:"idle"},"sse:session.abort"),Ie&&Oe&&s(Ie,Oe);break}case"permission.asked":{if(!("sessionID"in be)||typeof be.sessionID!="string")break;const Ie=be;o(Ie);const Oe=`${Ie.sessionID}:${Ie.id}`;W.current.has(Oe)||setTimeout(()=>{if(ue.current===Ie.sessionID||!Ae.getState().permissions.get(Ie.sessionID)?.some(Be=>Be.id===Ie.id))return;W.current.add(Oe);const Ee=Ae.getState().sessions.find(Be=>Be.id===Ie.sessionID)?.title||"Session";qs(async()=>{const{toast:Be}=await import("./vendor-.bun-KwPUu5oc.js").then(Ze=>Ze.dZ);return{toast:Be}},__vite__mapDeps([0,1])).then(({toast:Be})=>{Be.warning("Permission required",{description:Ee,action:{label:"Open",onClick:()=>{Me.getState().setActiveMainTab("chat"),Ae.getState().setCurrentSession(Ie.sessionID)}}})})},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in be)||typeof be.sessionID!="string")break;const Ie=be;a(Ie);const Oe=`${Ie.sessionID}:${Ie.id}`;ve.current.has(Oe)||setTimeout(()=>{if(ue.current===Ie.sessionID||!Ae.getState().questions.get(Ie.sessionID)?.some(Be=>Be.id===Ie.id))return;ve.current.add(Oe);const Ee=Ae.getState().sessions.find(Be=>Be.id===Ie.sessionID)?.title||"Session";qs(async()=>{const{toast:Be}=await import("./vendor-.bun-KwPUu5oc.js").then(Ze=>Ze.dZ);return{toast:Be}},__vite__mapDeps([0,1])).then(({toast:Be})=>{Be.info("Input needed",{description:Ee,action:{label:"Open",onClick:()=>{Me.getState().setActiveMainTab("chat"),Ae.getState().setCurrentSession(Ie.sessionID)}}})})},0);break}case"question.replied":{const Ie=typeof be.sessionID=="string"?be.sessionID:null,Oe=typeof be.requestID=="string"?be.requestID:null;Ie&&Oe&&l(Ie,Oe);break}case"question.rejected":{const Ie=typeof be.sessionID=="string"?be.sessionID:null,Oe=typeof be.requestID=="string"?be.requestID:null;Ie&&Oe&&l(Ie,Oe);break}case"ikanban:notification":{const Ie=typeof be.title=="string"?be.title:"",Oe=typeof be.body=="string"?be.body:"",et=typeof be.tag=="string"?be.tag:void 0;if(!!be.requireHidden&&ie.current!=="hidden"||Pr()&&be.desktopStdoutActive||!x)break;const Ee=zr();Ee?.notifications&&Ie&&Ee.notifications.notifyAgentCompletion({title:Ie,body:Oe,tag:et});break}case"todo.updated":{const Ie=typeof be.sessionID=="string"?be.sessionID:null,Oe=Array.isArray(be.todos)?be.todos:null;Ie&&Oe&&LD(Ie,Oe);break}}},[c,x,t,s,r,o,a,l,g,me,n,d,A,E,p,h,F,w,Q]),fe=i.useCallback(()=>{const Fe=Z();return ie.current=Fe,Fe==="visible"&&$.current},[Z]),He=i.useCallback(()=>{sr()&&console.debug("[useEventStream] Connection state:",{hasUnsubscribe:!!P.current,currentSessionId:ue.current,effectiveDirectory:w,onlineStatus:$.current,visibilityState:ie.current,lastEventTimestamp:ge.current,reconnectAttempts:L.current})},[w]),it=i.useCallback(()=>{if(M.current){sr()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(M.current=!0,T.current&&(clearTimeout(T.current),T.current=null),P.current){const Fe=P.current;P.current=null;try{Fe()}catch(be){console.warn("[useEventStream] Error during unsubscribe:",be)}}M.current=!1},[]),de=i.useCallback(async Fe=>{if(He(),!fe()){ne.current=!0,$.current?C("paused","Paused while hidden"):C("offline","Waiting for network");return}Fe?.resetAttempts&&(L.current=0),it(),ge.current=Date.now(),C("connecting",null),sr()&&console.info("[useEventStream] Starting event stream...");const be=Ie=>{console.warn("Event stream error:",Ie)},Te=()=>{const Ie=ne.current;if(L.current=0,ne.current=!1,ge.current=Date.now(),C("connected",null),g(),zn(),Ie)F("sse_reconnected");else{const Oe=ue.current;Oe&&setTimeout(()=>{D(Oe,"sse_reconnected",cn()).then(()=>me(Oe)).catch(et=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",et)})},0)}};if(sr()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:w,isCleaningUp:M.current}),M.current){sr()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Ie=ot.subscribeToGlobalEvents(et=>{const ze=et.payload,Ee=et.payload,Be=typeof Ee.properties=="object"&&Ee.properties!==null?Ee.properties:{},Ze=et.directory&&et.directory!=="global"?{...Be,directory:et.directory}:Be;xe({type:typeof ze.type=="string"?ze.type:"",properties:Ze})},be,Te),Oe=()=>{try{Ie()}catch(et){console.warn("[useEventStream] Error during unsubscribe:",et)}};M.current?Oe():P.current=Oe}catch(Ie){console.error("[useEventStream] Error during subscription:",Ie),be(Ie)}},[fe,it,C,g,D,me,xe,w,He,F]),Ue=i.useCallback(Fe=>{if(!fe()){ne.current=!0,it(),$.current?C("paused","Paused while hidden"):C("offline","Waiting for network");return}if(T.current)return;const be=L.current+1;L.current=be;const Te=Fe??`Retrying (${be})`;C("reconnecting",Te);const Ie=be<=3?Math.min(1e3*Math.pow(2,be-1),8e3):Math.min(2e3*Math.pow(2,be-3),32e3),Oe=Math.floor(Math.random()*250),et=Ie+Oe;T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{de({resetAttempts:!1})},et)},[fe,it,C,de]);i.useEffect(()=>{q.current=Ue},[Ue]),i.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=A);const Fe=()=>{V.current&&(clearTimeout(V.current),V.current=null)},be=()=>{if(ie.current=Z(),ie.current!=="visible")return;if(Fe(),re("visibility_restore"),zn(),Date.now()-ge.current>45e3&&(console.info("[useEventStream] Visibility restored with stalled stream, reconnecting..."),ne.current=!0),ne.current||!P.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ze=ue.current;Ze&&(D(Ze,"visibility_restore",cn()),me(Ze)),zn(),C("connecting","Resuming stream"),de({resetAttempts:!0})}},Te=()=>{if(ie.current=Z(),ie.current==="visible"&&(Fe(),re("window_focus"),zn(),Date.now()-ge.current>45e3&&(ne.current=!0),ne.current||!P.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ze=ue.current;Ze&&(me(Ze),D(Ze,"window_focus",cn())),zn(),C("connecting","Resuming stream"),de({resetAttempts:!0})}},Ie=()=>{$.current=!0,re("network_restored"),(ne.current||!P.current)&&(zn(),C("connecting","Network restored"),de({resetAttempts:!0}))},Oe=()=>{$.current=!1,ne.current=!0,C("offline","Waiting for network"),it()},et=()=>{ne.current=!0,it(),C("paused","Paused while hidden")},ze=Be=>{if(ne.current=ne.current||!!Be.persisted,ie.current=Z(),ie.current==="visible"){const Ze=ue.current;Ze&&(D(Ze,"page_show",cn()),me(Ze)),zn(),de({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",be),typeof window<"u"&&(window.addEventListener("online",Ie),window.addEventListener("offline",Oe),window.addEventListener("focus",Te),window.addEventListener("pagehide",et),window.addEventListener("pageshow",ze));const Ee=setTimeout(()=>{de({resetAttempts:!0})},100);return ce.current&&clearInterval(ce.current),ce.current=setInterval(()=>{if(!fe())return;const Be=Date.now();Array.from(Ae.getState().sessionStatus?.values?.()??[]).some(tt=>tt?.type==="busy"||tt?.type==="retry")&&zn(),Be-ge.current>45e3&&Promise.resolve().then(async()=>{try{if(!await ot.checkHealth()){Ue("Refreshing stalled stream");return}Ue("Refreshing stalled stream")}catch(tt){console.warn("Health check after stale stream failed:",tt),Ue("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Ee),typeof document<"u"&&document.removeEventListener("visibilitychange",be),typeof window<"u"&&(window.removeEventListener("online",Ie),window.removeEventListener("offline",Oe),window.removeEventListener("focus",Te),window.removeEventListener("pagehide",et),window.removeEventListener("pageshow",ze)),Fe(),ce.current&&(clearInterval(ce.current),ce.current=null),yu.clear(),oe.current.clear(),te.current.clear(),ne.current=!1,ie.current=Z(),$.current=typeof navigator>"u"?!0:navigator.onLine,it(),O.current&&(clearTimeout(O.current),O.current=null),C("idle",null)}},[w,A,Z,it,C,de,Ue,m,me,fe,f,re,N,D])},uB=()=>{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:""},mB=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)}},fB=t=>{if(!t||!Number.isFinite(t))return"(n/a)";try{return new Date(t).toISOString()}catch{return"(invalid)"}},pB=async()=>{const t=new Date,s="0.1.2",r=typeof navigator<"u"?navigator.userAgent:"(no navigator)",n=uB(),o=Me.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 w=await y.text();let v=null;try{v=JSON.parse(w)}catch{const k=w.replace(/\s+/g," ").slice(0,120);return{data:null,status:y.status,error:`invalid json content-type=${b} body=${k||"(empty)"}`}}return!v||typeof v!="object"||Array.isArray(v)?{data:null,status:y.status,error:`invalid json-shape content-type=${b}`}:{data:v,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 mB(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:"",w=g&&typeof g.source=="string"?g.source:c&&typeof c.opencodeBinarySource=="string"?c.opencodeBinarySource:"",v=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:"",S=g&&typeof g.bun=="string"?g.bun:c&&typeof c.bunBinaryResolved=="string"?c.bunBinaryResolved:"",j=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 N=b||(y.includes("/")?y.split("/").slice(0,-1).join("/")||"/":"");p.push(`- opencode: ${y}${N?` (dir=${N})`:""}`)}else p.push("- opencode: (n/a)");p.push(`- source: ${w||"(n/a)"}`),j&&(p.push(`- detected-now: ${j}`),p.push(`- detected-source: ${C||"(n/a)"}`)),p.push(`- shim: ${v||"(n/a)"}`),p.push(`- node: ${k||"(n/a)"}`),p.push(`- bun: ${S||"(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:w}=g.result,v=x?"":` url=${g.url}`;p.push(`- ${g.label}: ${x?"ok":"fail"} status=${y} time=${b}ms ${w}${v}`)}}else p.push("OpenCode API probes: (skipped)");return p.push(""),p.push(`Generated: ${fB(Date.now())}`),p.join(`
290
290
  `)},vb=async()=>{const t=await pB(),s=Me.getState();s.setOpenCodeStatusText(t),s.setOpenCodeStatusDialogOpen(!0)},hB=()=>{const{openNewSessionDraft:t,abortCurrentOperation:s,armAbortPrompt:r,clearAbortPrompt:n,currentSessionId:o}=Ae(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=Me(),{themeMode:p,setThemeMode:h}=rn(),{working:g}=Dy(),x=i.useRef(null),y=i.useRef(null),b=i.useCallback(()=>{y.current&&(clearTimeout(y.current),y.current=null),x.current=null,n()},[n]);i.useEffect(()=>{const w=v=>{if(Lr(v)&&v.key==="k"&&(v.preventDefault(),a()),Lr(v)&&v.shiftKey&&v.key.toLowerCase()==="l"){v.preventDefault(),vb();return}if(Lr(v)&&v.key==="."&&(v.preventDefault(),l()),Lr(v)&&v.key.toLowerCase()==="n"){v.preventDefault();const k=ps(),S=ft.getState().settingsAutoCreateWorktree;if(k?!1:S?!v.shiftKey:v.shiftKey){u("chat"),d(!1),xc();return}u("chat"),d(!1),t()}if(Lr(v)&&v.key==="/"){v.preventDefault();const k=["light","dark","system"],j=(k.indexOf(p)+1)%k.length;h(k[j])}if(Lr(v)&&!v.shiftKey&&v.key.toLowerCase()==="t"){v.preventDefault();const{isTimelineDialogOpen:k,setTimelineDialogOpen:S}=Me.getState();S(!k);return}if(Lr(v)&&!v.shiftKey&&v.key===","){v.preventDefault();const{isSettingsDialogOpen:k}=Me.getState();m(!k);return}if(Lr(v)&&!v.shiftKey&&v.key.toLowerCase()==="l"){v.preventDefault();const{isMobile:k,isSessionSwitcherOpen:S}=Me.getState();k?d(!S):c();return}if(Lr(v)&&!v.shiftKey&&v.key.toLowerCase()==="i"){v.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Lr(v)&&v.shiftKey&&v.key.toLowerCase()==="m"){const{isSettingsDialogOpen:k,isCommandPaletteOpen:S,isHelpDialogOpen:j,isSessionSwitcherOpen:C,isAboutDialogOpen:N,activeMainTab:F,isModelSelectorOpen:D}=Me.getState();if(k||S||j||C||N||!(F==="chat"))return;v.preventDefault(),f(!D);return}if(Lr(v)&&v.shiftKey&&v.key.toLowerCase()==="t"){const{isSettingsDialogOpen:k,isCommandPaletteOpen:S,isHelpDialogOpen:j,isSessionSwitcherOpen:C,isAboutDialogOpen:N,activeMainTab:F}=Me.getState();if(k||S||j||C||N||!(F==="chat"))return;const E=ft.getState();if(E.getCurrentModelVariants().length===0)return;v.preventDefault(),E.cycleCurrentVariant();const T=ft.getState().currentVariant,L=Ae.getState(),I=L.currentSessionId,_=ft.getState().currentAgentName,O=ft.getState().currentProviderId,M=ft.getState().currentModelId;I&&_&&O&&M&&L.saveAgentModelVariantForSession(I,_,O,M,T);return}if(v.key==="Escape"){const S=!!v.target?.closest('[role="dialog"]'),j=!!document.querySelector('[data-settings-view="true"]');if(S||j){b();return}const{isSettingsDialogOpen:C,isCommandPaletteOpen:N,isHelpDialogOpen:F,isSessionSwitcherOpen:D,isAboutDialogOpen:A,isMultiRunLauncherOpen:E,isImagePreviewOpen:P,activeMainTab:T}=Me.getState();if(C){v.preventDefault(),m(!1),b();return}if(N||F||D||A||E||P||!(T==="chat")){b();return}const _=o;if(!(g.canAbort&&!!_)){b();return}const M=Date.now(),B=x.current;if(B&&M<B){v.preventDefault(),b(),s();return}v.preventDefault();const G=r(3e3)??M+3e3;x.current=G,y.current&&clearTimeout(y.current);const W=Math.max(G-M,0);y.current=setTimeout(()=>{x.current&&Date.now()>=x.current&&b()},W||0);return}};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[t,s,a,l,c,d,u,m,f,h,p,g,r,b,o]),i.useEffect(()=>()=>{b()},[b])},$h="ikanban:menu-action",gB="ikanban:check-for-updates",xB=t=>{const{openNewSessionDraft:s}=Ae(),{toggleCommandPalette:r,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=Me(),{addProject:u}=gs(),{requestAccess:m,startAccessing:f}=yc(),{setThemeMode:p}=rn(),h=i.useCallback(()=>{Ds()&&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")}),Sa.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}=Me.getState();l(y==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:y}=Me.getState();l(y==="diff"?"chat":"diff");break}case"open-files-tab":{const{activeMainTab:y}=Me.getState();l(y==="files"?"chat":"files");break}case"open-terminal-tab":{const{activeMainTab:y}=Me.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":{vb().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($h,x),()=>window.removeEventListener($h,x)},[g]),i.useEffect(()=>{if(typeof window>"u")return;const y=window.__TAURI__?.event?.listen;if(typeof y!="function")return;let b=null,w=null;return y("ikanban:menu-action",v=>{const k=v?.payload;typeof k=="string"&&g(k)}).then(v=>{b=v}).catch(()=>{}),y("ikanban:check-for-updates",()=>{window.dispatchEvent(new Event(gB))}).then(v=>{w=v}).catch(()=>{}),()=>{(async()=>{try{const k=b?.();k instanceof Promise&&await k}catch{}try{const k=w?.();k instanceof Promise&&await k}catch{}})()}},[g])},yB=()=>{i.useEffect(()=>{let t=!1;return(async()=>{try{const r=await ot.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}},[])},bB=["chat","git","diff","terminal","files"],vB=["settings","agents","commands","skills","providers","git-identities"],Zr={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function zh(t){const s=wB();return{sessionId:jB(s),tab:SB(s),settingsSection:kB(s),diffFile:NB(s)}}function wB(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function jB(t){const s=t.get(Zr.SESSION);return!s||s.trim().length===0?null:s.trim()}function SB(t){const s=t.get(Zr.TAB);if(!s)return null;const r=s.toLowerCase().trim();return bB.includes(r)?r:null}function kB(t){const s=t.get(Zr.SETTINGS);if(!s)return null;const r=s.toLowerCase().trim();return vB.includes(r)?r:r==="ikanban"||r==="general"||r==="preferences"?"settings":null}function NB(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 Hh(){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 CB="chat";function wb(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!==CB&&s.set(Zr.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&s.set(Zr.FILE,t.diffFile),s}function AB(t,s){const r=typeof window<"u"?window.location.pathname:"/",n=t.toString();return n?`${r}?${n}`:r}function FB(t){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),r=wb(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 DB(t,s={}){if(!(typeof window>"u")&&!MB()&&!(!s.force&&FB(t)))try{const r=wb(t),n=AB(r);s.replace?window.history.replaceState({...window.history.state,route:t},"",n):window.history.pushState({route:t},"",n)}catch{}}function MB(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function EB(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function IB(){const t=i.useMemo(()=>EB(),[]),s=i.useRef(!1),r=i.useRef(!1),n=Ae(f=>f.setCurrentSession),o=Me(f=>f.setActiveMainTab),a=Me(f=>f.setSettingsDialogOpen),l=Me(f=>f.setSidebarSection),c=Me(f=>f.navigateToDiff),d=i.useCallback(async f=>{if(!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}Me.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=Me.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();DB(p,f)},[t,u]);i.useEffect(()=>{if(s.current||(s.current=!0,!Hh()))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=Me.getState().activeMainTab,p=Me.getState().isSettingsDialogOpen,h=Me.getState().sidebarSection,g=Me.getState().pendingDiffFile;return Me.subscribe(y=>{if(r.current)return;const b=y.activeMainTab!==f,w=y.isSettingsDialogOpen!==p,v=y.sidebarSection!==h,k=y.pendingDiffFile!==g&&y.activeMainTab==="diff";f=y.activeMainTab,p=y.isSettingsDialogOpen,h=y.sidebarSection,g=y.pendingDiffFile,(b||w||v||k)&&m()})},[t,m]),i.useEffect(()=>{if(typeof window>"u"||t)return;const f=()=>{const p=zh();if(Hh())d(p);else{const h=Me.getState();h.isSettingsDialogOpen&&a(!1),h.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[d,t,o,a])}const BB=1e4,Uh=()=>{if(typeof document>"u")return"visible";const t=document.visibilityState;return t==="hidden"&&document.hasFocus()?"visible":t},Vh=t=>{if(!Oo())return;const s=zr();s?.push?.setVisibility&&s.push.setVisibility({visible:t})},TB=()=>{i.useEffect(()=>{if(!Oo()||typeof document>"u")return;const t=()=>{Vh(Uh()==="visible")},s=()=>{Uh()==="visible"&&Vh(!0)};t();const r=window.setInterval(s,BB);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 PB(){const{git:t}=Ur(),s=Jt(m=>m.currentDirectory),{currentSessionId:r,sessions:n,worktreeMetadata:o}=Ae(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=ir(),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 RB({children:t}){return PB(),e.jsx(e.Fragment,{children:t})}const LB="curl -fsSL https://opencode.ai/install | bash",OB=3e3;function _B({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 $B=3e4;function zB({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),$B);return()=>clearTimeout(b)},[]),i.useEffect(()=>{l(Tr())},[]),i.useEffect(()=>{let b=!1;return(async()=>{try{const w=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!w.ok)return;const v=await w.json().catch(()=>null);if(!v||b)return;const k=typeof v.opencodeBinary=="string"?v.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&&Ds())try{const{getCurrentWindow:w}=await qs(async()=>{const{getCurrentWindow:k}=await import("@tauri-apps/api/window");return{getCurrentWindow:k}},[]);await w().startDragging()}catch(w){console.error("Failed to start window dragging:",w)}},[a]),p=i.useCallback(async()=>{try{const b=await fetch("/health");if(!b.ok)return!1;const w=await b.json();return w.openCodeRunning===!0||w.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||!Ds())return;const b=window.__TAURI__;if(b?.dialog?.open)try{const w=await b.dialog.open({title:"Select opencode binary",multiple:!1,directory:!1});typeof w=="string"&&w.trim().length>0&&m(w.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(LB),r(!0),setTimeout(()=>r(!1),2e3)}catch(b){console.error("Failed to copy:",b)}},[]);return i.useEffect(()=>{const b=async()=>{await p()&&t?.()},w=setInterval(b,OB);return b(),()=>clearInterval(w)},[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(hn,{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(ns,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(_B,{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(hn,{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(Ot,{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(Ce,{type:"button",variant:"secondary",onClick:g,disabled:c||!a||!Ds(),children:"Browse"}),e.jsx(Ce,{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 HB=()=>{const[{isUpdating:t,message:s},r]=i.useState(()=>Z0());return i.useEffect(()=>X0(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},jb={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=Jt.getState(),s=Ae.getState(),r=gs.getState(),n=t.currentDirectory||null,o=ot.getDirectory()??null,a=s.sessions||[],l=new Set,c={};a.forEach(C=>{const N=C.directory;typeof N=="string"&&N.trim().length>0?(l.add(N),c[N]=(c[N]??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 N=await fetch(C);return N.ok?await f(N):{status:N.status}}catch(N){return{error:N instanceof Error?N.message:String(N)}}};let g=null,x=null,y=null,b=null;const w=n?`/api/path?directory=${encodeURIComponent(n)}`:"/api/path";g=await h(w);const v=n?`/api/project/current?directory=${encodeURIComponent(n)}`:"/api/project/current";x=await h(v),y=await h("/api/config/settings");try{const C=await fetch("/api/health"),N=C.headers.get("content-type")||"",F=await p(C);b={status:C.status,ok:C.ok,contentType:N,type:N.includes("application/json")?"json":"html",preview:F?F.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 S=r.projects.map(C=>({id:C.id,path:C.path,label:C.label})),j={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:S},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:",j),j},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
291
  `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
292
292
  `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
293
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),w=b!==null,v=x.filter(E=>E.type==="tool"),k=x.filter(E=>E.type==="reasoning"),S=m(v.map(E=>u(E.state?.time?.end??E.state?.time?.start))),j=m(k.map(E=>u(E.time?.end??E.time?.start))),C=m([S,j].filter(E=>E!==null)),N=v.some(E=>["pending","running","started"].includes(E.state?.status)),F=k.some(E=>typeof E.time?.end!="number");v.length>0&&(d.withTools+=1),k.length>0&&(d.withReasoning+=1),w||(d.completedMissing+=1);const D=!!(w&&typeof S=="number"&&b<S);D&&(d.completedBeforeTool+=1);const A=!!(w&&typeof j=="number"&&b<j);return A&&(d.completedBeforeReasoning+=1),w&&N&&(d.runningToolsWhenCompleted+=1),w&&F&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:b,latestToolTimestamp:S,latestReasoningTimestamp:j,latestPartTimestamp:C,completed_missing:!w,completed_before_tool:D,completed_before_reasoning:A,running_tools_when_completed:!!(w&&N),reasoning_open_when_completed:!!(w&&F),has_tools:v.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=jb,sr()&&(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 UB=({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 jb.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 qs(async()=>{const{getVersion:g}=await import("@tauri-apps/api/app");return{getVersion:g}},[]),h=await p();n(h)}catch{n("0.1.0")}})():n("0.1.0")},[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:R("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(Bg,{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(Ud,{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 Id({apis:t,children:s}){return e.jsx(Vu.Provider,{value:t,children:s})}const VB=()=>{const{isAboutDialogOpen:t,setAboutDialogOpen:s}=Me();return e.jsx(UB,{open:t,onOpenChange:s})};function WB({apis:t}){const{initializeApp:s,isInitialized:r,isConnected:n}=ft(),{error:o,clearError:a,loadSessions:l}=Ae(),c=Jt(j=>j.currentDirectory),d=Jt(j=>j.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=nb(),h=Or(j=>j.refreshStatus),[g,x]=i.useState(()=>t.runtime.isVSCode),[y,b]=i.useState(!1),w=i.useRef(!1);i.useEffect(()=>{x(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>(Em(t),()=>Em(null)),[t]),i.useEffect(()=>{h(t.github,{force:!0})},[t.github,h]),i.useEffect(()=>{if(typeof document>"u")return;const j=document.documentElement,C=lh[f]?.stack??lh[YE].stack,N=No[p]?.stack??No[Sl].stack;j.style.setProperty("--font-sans",C),j.style.setProperty("--font-heading",C),j.style.setProperty("--font-family-sans",C),j.style.setProperty("--font-mono",N),j.style.setProperty("--font-family-mono",N),j.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=C)},[f,p]),i.useEffect(()=>{if(r){const C=setTimeout(()=>{const N=document.getElementById("initial-loading");N&&(N.classList.add("fade-out"),setTimeout(()=>{N.remove()},300))},150);return()=>clearTimeout(C)}},[r]),i.useEffect(()=>{const j=setTimeout(()=>{const C=document.getElementById("initial-loading");C&&!r&&(C.classList.add("fade-out"),setTimeout(()=>{C.remove()},300))},5e3);return()=>clearTimeout(j)},[r]),i.useEffect(()=>{(async()=>g||await s())()},[s,g]),i.useEffect(()=>{if(d)return;(async()=>g||n&&(ot.setDirectory(c),await l()))()},[c,d,l,n,g]),i.useEffect(()=>{typeof window>"u"||!r||d||w.current||(w.current=!0,window.__ikanbanAppReady=!0,window.dispatchEvent(new Event("ikanban:app-ready")))},[r,d]),dB(),VS(),TB(),IB(),hB();const v=i.useCallback(()=>{m(j=>!j)},[]);xB(v);const k=ft(j=>j.settingsAutoCreateWorktree);i.useEffect(()=>{if(!Ds())return;const j=window.__TAURI__;typeof j?.core?.invoke=="function"&&j.core.invoke("desktop_set_auto_worktree_menu",{enabled:k})},[k]),yB(),mb(),i.useEffect(()=>{const j=C=>{Lr(C)&&C.shiftKey&&C.key==="D"&&(C.preventDefault(),m(N=>!N))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]),i.useEffect(()=>{if(!Tr()||!Pr())return;let j=!1;return(async()=>{try{const N=await fetch("/health",{method:"GET"});if(!N.ok)return;const F=await N.json().catch(()=>null);if(!F||j)return;const D=F.openCodeRunning===!0,A=typeof F.lastOpenCodeError=="string"?F.lastOpenCodeError:"",E=!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(E)}catch{}})(),()=>{j=!0}},[]);const S=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(zB,{onCliAvailable:S})})}):g?(typeof window<"u"?window.__IKANBAN_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(Gs,{children:e.jsx(Id,{apis:t,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(ZI,{}),e.jsx(Vc,{})]})})}):e.jsx(Gs,{children:e.jsx(Id,{apis:t,children:e.jsx(Yp,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(HI,{}),e.jsx(Vc,{})]})})})}):e.jsx(Gs,{children:e.jsx(Id,{apis:t,children:e.jsx(RB,{children:e.jsx(Yp,{children:e.jsx(tD,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(LI,{}),e.jsx(Vc,{}),e.jsx(HB,{}),e.jsx(VB,{}),u&&e.jsx(eB,{onClose:()=>m(!1)})]})})})})})})}const Sb=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=Jt.getState();t&&r.homeDirectory!==t&&r.synchronizeHomeDirectory(t),s&&!ps()&&r.setDirectory(s,{showOverlay:!1})},kb="/auth/session",GB=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})]}),qB=({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(Ce,{type:"button",onClick:t,className:"w-full max-w-xs",children:"Retry"})]})})},KB=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},QB=()=>{try{const t=new URL(window.location.href);t.searchParams.delete("token"),window.history.replaceState({},"",t.toString())}catch{}},YB=({children:t})=>{const s=i.useMemo(()=>ps(),[]),r=s,n=i.useMemo(()=>Tr()&&!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(v=>v==="authenticated"?v:"pending");try{const v=await GB();if(v.ok){a("authenticated"),f(""),h(void 0);return}if(v.status===401){a("locked"),h(void 0);return}if(v.status===429){const k=await v.json().catch(()=>({}));h(k.retryAfter),a("rate-limited");return}a("error")}catch(v){console.warn("Failed to check session status:",v),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 v=KB();v&&(y.current=!0,QB(),u(!0),f(""),Wh(v).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 Yg(),await Jg(),await Sb()))())},[r,o]);const w=async v=>{if(v.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 S=await k.json().catch(()=>({}));h(S.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(qB,{}):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:w,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(p0,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(Ot,{id:"ikanban-ui-password",ref:g,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:l,onChange:v=>{c(v.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(Ce,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Rt,{className:"h-4 w-4 animate-spin"}):e.jsx(h0,{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(LF,{}),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})},Bd=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 JB{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(`
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),w=b!==null,v=x.filter(E=>E.type==="tool"),k=x.filter(E=>E.type==="reasoning"),S=m(v.map(E=>u(E.state?.time?.end??E.state?.time?.start))),j=m(k.map(E=>u(E.time?.end??E.time?.start))),C=m([S,j].filter(E=>E!==null)),N=v.some(E=>["pending","running","started"].includes(E.state?.status)),F=k.some(E=>typeof E.time?.end!="number");v.length>0&&(d.withTools+=1),k.length>0&&(d.withReasoning+=1),w||(d.completedMissing+=1);const D=!!(w&&typeof S=="number"&&b<S);D&&(d.completedBeforeTool+=1);const A=!!(w&&typeof j=="number"&&b<j);return A&&(d.completedBeforeReasoning+=1),w&&N&&(d.runningToolsWhenCompleted+=1),w&&F&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:b,latestToolTimestamp:S,latestReasoningTimestamp:j,latestPartTimestamp:C,completed_missing:!w,completed_before_tool:D,completed_before_reasoning:A,running_tools_when_completed:!!(w&&N),reasoning_open_when_completed:!!(w&&F),has_tools:v.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=jb,sr()&&(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 UB=({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 jb.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 qs(async()=>{const{getVersion:g}=await import("@tauri-apps/api/app");return{getVersion:g}},[]),h=await p();n(h)}catch{n("0.1.2")}})():n("0.1.2")},[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:R("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(Bg,{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(Ud,{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 Id({apis:t,children:s}){return e.jsx(Vu.Provider,{value:t,children:s})}const VB=()=>{const{isAboutDialogOpen:t,setAboutDialogOpen:s}=Me();return e.jsx(UB,{open:t,onOpenChange:s})};function WB({apis:t}){const{initializeApp:s,isInitialized:r,isConnected:n}=ft(),{error:o,clearError:a,loadSessions:l}=Ae(),c=Jt(j=>j.currentDirectory),d=Jt(j=>j.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=nb(),h=Or(j=>j.refreshStatus),[g,x]=i.useState(()=>t.runtime.isVSCode),[y,b]=i.useState(!1),w=i.useRef(!1);i.useEffect(()=>{x(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>(Em(t),()=>Em(null)),[t]),i.useEffect(()=>{h(t.github,{force:!0})},[t.github,h]),i.useEffect(()=>{if(typeof document>"u")return;const j=document.documentElement,C=lh[f]?.stack??lh[YE].stack,N=No[p]?.stack??No[Sl].stack;j.style.setProperty("--font-sans",C),j.style.setProperty("--font-heading",C),j.style.setProperty("--font-family-sans",C),j.style.setProperty("--font-mono",N),j.style.setProperty("--font-family-mono",N),j.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=C)},[f,p]),i.useEffect(()=>{if(r){const C=setTimeout(()=>{const N=document.getElementById("initial-loading");N&&(N.classList.add("fade-out"),setTimeout(()=>{N.remove()},300))},150);return()=>clearTimeout(C)}},[r]),i.useEffect(()=>{const j=setTimeout(()=>{const C=document.getElementById("initial-loading");C&&!r&&(C.classList.add("fade-out"),setTimeout(()=>{C.remove()},300))},5e3);return()=>clearTimeout(j)},[r]),i.useEffect(()=>{(async()=>g||await s())()},[s,g]),i.useEffect(()=>{if(d)return;(async()=>g||n&&(ot.setDirectory(c),await l()))()},[c,d,l,n,g]),i.useEffect(()=>{typeof window>"u"||!r||d||w.current||(w.current=!0,window.__ikanbanAppReady=!0,window.dispatchEvent(new Event("ikanban:app-ready")))},[r,d]),dB(),VS(),TB(),IB(),hB();const v=i.useCallback(()=>{m(j=>!j)},[]);xB(v);const k=ft(j=>j.settingsAutoCreateWorktree);i.useEffect(()=>{if(!Ds())return;const j=window.__TAURI__;typeof j?.core?.invoke=="function"&&j.core.invoke("desktop_set_auto_worktree_menu",{enabled:k})},[k]),yB(),mb(),i.useEffect(()=>{const j=C=>{Lr(C)&&C.shiftKey&&C.key==="D"&&(C.preventDefault(),m(N=>!N))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]),i.useEffect(()=>{if(!Tr()||!Pr())return;let j=!1;return(async()=>{try{const N=await fetch("/health",{method:"GET"});if(!N.ok)return;const F=await N.json().catch(()=>null);if(!F||j)return;const D=F.openCodeRunning===!0,A=typeof F.lastOpenCodeError=="string"?F.lastOpenCodeError:"",E=!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(E)}catch{}})(),()=>{j=!0}},[]);const S=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(zB,{onCliAvailable:S})})}):g?(typeof window<"u"?window.__IKANBAN_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(Gs,{children:e.jsx(Id,{apis:t,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(ZI,{}),e.jsx(Vc,{})]})})}):e.jsx(Gs,{children:e.jsx(Id,{apis:t,children:e.jsx(Yp,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(HI,{}),e.jsx(Vc,{})]})})})}):e.jsx(Gs,{children:e.jsx(Id,{apis:t,children:e.jsx(RB,{children:e.jsx(Yp,{children:e.jsx(tD,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(LI,{}),e.jsx(Vc,{}),e.jsx(HB,{}),e.jsx(VB,{}),u&&e.jsx(eB,{onClose:()=>m(!1)})]})})})})})})}const Sb=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=Jt.getState();t&&r.homeDirectory!==t&&r.synchronizeHomeDirectory(t),s&&!ps()&&r.setDirectory(s,{showOverlay:!1})},kb="/auth/session",GB=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})]}),qB=({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(Ce,{type:"button",onClick:t,className:"w-full max-w-xs",children:"Retry"})]})})},KB=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},QB=()=>{try{const t=new URL(window.location.href);t.searchParams.delete("token"),window.history.replaceState({},"",t.toString())}catch{}},YB=({children:t})=>{const s=i.useMemo(()=>ps(),[]),r=s,n=i.useMemo(()=>Tr()&&!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(v=>v==="authenticated"?v:"pending");try{const v=await GB();if(v.ok){a("authenticated"),f(""),h(void 0);return}if(v.status===401){a("locked"),h(void 0);return}if(v.status===429){const k=await v.json().catch(()=>({}));h(k.retryAfter),a("rate-limited");return}a("error")}catch(v){console.warn("Failed to check session status:",v),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 v=KB();v&&(y.current=!0,QB(),u(!0),f(""),Wh(v).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 Yg(),await Jg(),await Sb()))())},[r,o]);const w=async v=>{if(v.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 S=await k.json().catch(()=>({}));h(S.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(qB,{}):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:w,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(p0,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(Ot,{id:"ikanban-ui-password",ref:g,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:l,onChange:v=>{c(v.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(Ce,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Rt,{className:"h-4 w-4 animate-spin"}):e.jsx(h0,{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(LF,{}),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})},Bd=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 JB{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
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=Bd(s.colors.surface.muted),o=Bd(s.colors.surface.subtle),a=Bd(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
296
  ${r}
297
297
  }